FastBridge Contracts
Contributing
Please make sure foundry is installed:
curl -L https://foundry.paradigm.xyz | bash
foundryup
Then, run the following to make sure dependencies are installed
git submodule update --init --recursive
Testing
To run the tests, run the following:
forge test
Contents
- IAdmin
- IAdminV2
- IAdminV2Errors
- IFastBridge
- IFastBridgeV2
- IFastBridgeV2Errors
- IMulticallTarget
- ISynapseIntentPreviewer
- ISynapseIntentRouter
- ISynapseIntentRouterErrors
- IZapRecipient
IAdmin
Functions
setProtocolFeeRate
function setProtocolFeeRate(uint256 newFeeRate) external;
sweepProtocolFees
function sweepProtocolFees(address token, address recipient) external;
setChainGasAmount
function setChainGasAmount(uint256 newChainGasAmount) external;
Events
FeeRateUpdated
event FeeRateUpdated(uint256 oldFeeRate, uint256 newFeeRate);
FeesSwept
event FeesSwept(address token, address recipient, uint256 amount);
ChainGasAmountUpdated
event ChainGasAmountUpdated(uint256 oldChainGasAmount, uint256 newChainGasAmount);
IAdminV2
Functions
addProver
Allows the role admin to add a new prover to the contract.
function addProver(address prover) external;
removeProver
Allows the role admin to remove a prover from the contract.
function removeProver(address prover) external;
setCancelDelay
Allows the governor to set the cancel delay. The cancel delay is the time period after the transaction deadline during which a transaction can be permissionlessly cancelled if it hasn't been proven by any Relayer.
function setCancelDelay(uint256 newCancelDelay) external;
setDeployBlock
Allows the default admin to set the deploy block.
This is only relevant for chains like Arbitrum that implement the block.number
as the underlying L1
block number rather than the chain's native block number.
function setDeployBlock(uint256 blockNumber) external;
setDisputePenaltyTime
Allows the governor to set the dispute penalty time. The dispute penalty time is the time period used to temporarily deactivate a prover if its proof is disputed: prover will be inactive for the dispute penalty time after the dispute is submitted.
function setDisputePenaltyTime(uint256 newDisputePenaltyTime) external;
setProtocolFeeRate
Allows the governor to set the protocol fee rate. The protocol fee is taken from the origin amount and is only applied to completed and claimed transactions.
The protocol fee is abstracted away from the relayers; they always operate using the amounts after fees. The origin amount they see in the emitted log is what they get credited with.
function setProtocolFeeRate(uint256 newFeeRate) external;
sweepProtocolFees
Allows the governor to withdraw the accumulated protocol fees from the contract.
function sweepProtocolFees(address token, address recipient) external;
getActiveProverID
Returns the ID of the active prover, or zero if the prover is not currently active.
function getActiveProverID(address prover) external view returns (uint16);
getProverInfo
Returns the information about the prover with the provided address.
function getProverInfo(address prover) external view returns (uint16 proverID, uint256 activeFromTimestamp);
Returns
Name | Type | Description |
---|---|---|
proverID | uint16 | The ID of the prover if it has been added before, or zero otherwise. |
activeFromTimestamp | uint256 | The timestamp when the prover becomes active, or zero if the prover isn't active. |
getProverInfoByID
Returns the information about the prover with the provided ID.
function getProverInfoByID(uint16 proverID) external view returns (address prover, uint256 activeFromTimestamp);
Returns
Name | Type | Description |
---|---|---|
prover | address | The address of the prover with the provided ID, or zero the ID does not exist. |
activeFromTimestamp | uint256 | The timestamp when the prover becomes active, or zero if the prover isn't active. |
getProvers
Returns the list of the active provers.
function getProvers() external view returns (address[] memory);
Events
CancelDelayUpdated
event CancelDelayUpdated(uint256 oldCancelDelay, uint256 newCancelDelay);
DeployBlockSet
event DeployBlockSet(uint256 blockNumber);
DisputePenaltyTimeUpdated
event DisputePenaltyTimeUpdated(uint256 oldDisputePenaltyTime, uint256 newDisputePenaltyTime);
FeeRateUpdated
event FeeRateUpdated(uint256 oldFeeRate, uint256 newFeeRate);
FeesSwept
event FeesSwept(address token, address recipient, uint256 amount);
ProverAdded
event ProverAdded(address prover);
ProverRemoved
event ProverRemoved(address prover);
DisputePenaltyTimeApplied
event DisputePenaltyTimeApplied(address prover, uint256 inactiveUntilTimestamp);
IAdminV2Errors
Errors
CancelDelayBelowMin
error CancelDelayBelowMin();
FeeRateAboveMax
error FeeRateAboveMax();
ProverAlreadyActive
error ProverAlreadyActive();
ProverCapacityExceeded
error ProverCapacityExceeded();
ProverNotActive
error ProverNotActive();
DisputePenaltyTimeBelowMin
error DisputePenaltyTimeBelowMin();
IFastBridge
Functions
bridge
Initiates bridge on origin chain to be relayed by off-chain relayer
function bridge(BridgeParams memory params) external payable;
Parameters
Name | Type | Description |
---|---|---|
params | BridgeParams | The parameters required to bridge |
relay
Relays destination side of bridge transaction by off-chain relayer
function relay(bytes memory request) external payable;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to relay on destination chain |
prove
Provides proof on origin side that relayer provided funds on destination side of bridge transaction
function prove(bytes memory request, bytes32 destTxHash) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to prove on origin chain |
destTxHash | bytes32 | The destination tx hash proving bridge transaction was relayed |
claim
Completes bridge transaction on origin chain by claiming originally deposited capital
function claim(bytes memory request, address to) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to claim on origin chain |
to | address | The recipient address of the funds |
dispute
Disputes an outstanding proof in case relayer provided dest chain tx is invalid
function dispute(bytes32 transactionId) external;
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to dispute |
refund
Refunds an outstanding bridge transaction in case optimistic bridging failed
function refund(bytes memory request) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to refund |
getBridgeTransaction
Decodes bridge request into a bridge transaction
function getBridgeTransaction(bytes memory request) external view returns (BridgeTransaction memory);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The bridge request to decode |
canClaim
Checks if the dispute period has passed so bridge deposit can be claimed
function canClaim(bytes32 transactionId, address relayer) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to check |
relayer | address | The address of the relayer attempting to claim |
Events
BridgeRequested
event BridgeRequested(
bytes32 indexed transactionId,
address indexed sender,
bytes request,
uint32 destChainId,
address originToken,
address destToken,
uint256 originAmount,
uint256 destAmount,
bool sendChainGas
);
BridgeRelayed
event BridgeRelayed(
bytes32 indexed transactionId,
address indexed relayer,
address indexed to,
uint32 originChainId,
address originToken,
address destToken,
uint256 originAmount,
uint256 destAmount,
uint256 chainGasAmount
);
BridgeProofProvided
event BridgeProofProvided(bytes32 indexed transactionId, address indexed relayer, bytes32 transactionHash);
BridgeProofDisputed
event BridgeProofDisputed(bytes32 indexed transactionId, address indexed relayer);
BridgeDepositClaimed
event BridgeDepositClaimed(
bytes32 indexed transactionId, address indexed relayer, address indexed to, address token, uint256 amount
);
BridgeDepositRefunded
event BridgeDepositRefunded(bytes32 indexed transactionId, address indexed to, address token, uint256 amount);
Structs
BridgeTransaction
struct BridgeTransaction {
uint32 originChainId;
uint32 destChainId;
address originSender;
address destRecipient;
address originToken;
address destToken;
uint256 originAmount;
uint256 destAmount;
uint256 originFeeAmount;
bool sendChainGas;
uint256 deadline;
uint256 nonce;
}
BridgeProof
struct BridgeProof {
uint96 timestamp;
address relayer;
}
BridgeParams
struct BridgeParams {
uint32 dstChainId;
address sender;
address to;
address originToken;
address destToken;
uint256 originAmount;
uint256 destAmount;
bool sendChainGas;
uint256 deadline;
}
IFastBridgeV2
Inherits: IFastBridge
Functions
bridgeV2
Initiates bridge on origin chain to be relayed by off-chain relayer, with the ability to provide temporary exclusivity fill rights for the quote relayer.
function bridgeV2(BridgeParams memory params, BridgeParamsV2 memory paramsV2) external payable;
Parameters
Name | Type | Description |
---|---|---|
params | BridgeParams | The parameters required to bridge |
paramsV2 | BridgeParamsV2 | The parameters for exclusivity fill rights (optional, can be left empty) |
relayV2
Relays destination side of bridge transaction by off-chain relayer
function relayV2(bytes memory request, address relayer) external payable;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to relay on destination chain |
relayer | address | The address of the relaying entity which should have control of the origin funds when claimed |
proveV2
Provides proof on origin side that relayer provided funds on destination side of bridge transaction
function proveV2(bytes32 transactionId, bytes32 destTxHash, address relayer) external;
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to prove |
destTxHash | bytes32 | The destination tx hash proving bridge transaction was relayed |
relayer | address | The address of the relaying entity which should have control of the origin funds when claimed |
claimV2
Completes bridge transaction on origin chain by claiming originally deposited capital.
Can only send funds to the relayer address on the proof.
function claimV2(bytes memory request) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to claim on origin chain |
cancelV2
Cancels an outstanding bridge transaction in case optimistic bridging failed and returns the full amount to the original sender.
function cancelV2(bytes memory request) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to refund |
bridgeRelays
Checks if a transaction has been relayed
function bridgeRelays(bytes32 transactionId) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The ID of the transaction to check |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True if the transaction has been relayed, false otherwise |
bridgeStatuses
Returns the status of a bridge transaction
function bridgeStatuses(bytes32 transactionId) external view returns (BridgeStatus);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The ID of the bridge transaction |
Returns
Name | Type | Description |
---|---|---|
<none> | BridgeStatus | BridgeStatus Status of the bridge transaction |
bridgeProofs
Returns the timestamp and relayer of a bridge proof
function bridgeProofs(bytes32 transactionId) external view returns (uint96 timestamp, address relayer);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The ID of the bridge transaction |
Returns
Name | Type | Description |
---|---|---|
timestamp | uint96 | The timestamp of the bridge proof |
relayer | address | The relayer address of the bridge proof |
getBridgeTransactionV2
Decodes bridge request into a bridge transaction V2 struct used by FastBridgeV2
function getBridgeTransactionV2(bytes memory request) external view returns (BridgeTransactionV2 memory);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The bridge request to decode |
Events
BridgeQuoteDetails
event BridgeQuoteDetails(bytes32 indexed transactionId, bytes quoteId);
Structs
BridgeTxDetails
struct BridgeTxDetails {
BridgeStatus status;
uint32 destChainId;
uint16 proverID;
uint40 proofBlockTimestamp;
address proofRelayer;
}
BridgeRelay
struct BridgeRelay {
uint48 blockNumber;
uint48 blockTimestamp;
address relayer;
}
BridgeParamsV2
New params introduced in the FastBridgeV2. We are passing fields from the older BridgeParams struct outside of this struct for backwards compatibility. Note: quoteRelayer and quoteExclusivitySeconds are either both zero (indicating no exclusivity) or both non-zero (indicating exclusivity for the given period). Note: zapNative > 0 can NOT be used with destToken = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE (native token)
struct BridgeParamsV2 {
address quoteRelayer;
int256 quoteExclusivitySeconds;
bytes quoteId;
uint256 zapNative;
bytes zapData;
}
BridgeTransactionV2
Updated bridge transaction struct to include parameters introduced in FastBridgeV2.
Note: only exclusivityRelayer
can fill such a transaction until exclusivityEndTime
.
struct BridgeTransactionV2 {
uint32 originChainId;
uint32 destChainId;
address originSender;
address destRecipient;
address originToken;
address destToken;
uint256 originAmount;
uint256 destAmount;
uint256 originFeeAmount;
uint256 deadline;
uint256 nonce;
address exclusivityRelayer;
uint256 exclusivityEndTime;
uint256 zapNative;
bytes zapData;
}
Enums
BridgeStatus
enum BridgeStatus {
NULL,
REQUESTED,
RELAYER_PROVED,
RELAYER_CLAIMED,
REFUNDED
}
IFastBridgeV2Errors
Errors
AmountIncorrect
error AmountIncorrect();
ChainIncorrect
error ChainIncorrect();
ExclusivityParamsIncorrect
error ExclusivityParamsIncorrect();
MsgValueIncorrect
error MsgValueIncorrect();
SenderIncorrect
error SenderIncorrect();
StatusIncorrect
error StatusIncorrect();
TokenNotContract
error TokenNotContract();
ZapDataLengthAboveMax
error ZapDataLengthAboveMax();
ZapNativeNotSupported
error ZapNativeNotSupported();
ZeroAddress
error ZeroAddress();
RecipientIncorrectReturnValue
error RecipientIncorrectReturnValue();
RecipientNoReturnValue
error RecipientNoReturnValue();
DeadlineExceeded
error DeadlineExceeded();
DeadlineNotExceeded
error DeadlineNotExceeded();
DeadlineTooShort
error DeadlineTooShort();
DisputePeriodNotPassed
error DisputePeriodNotPassed();
DisputePeriodPassed
error DisputePeriodPassed();
ExclusivityPeriodNotPassed
error ExclusivityPeriodNotPassed();
TransactionRelayed
error TransactionRelayed();
IMulticallTarget
Interface for a contract that supports multiple calls from the same caller. Inspired by MulticallV3: https://github.com/mds1/multicall/blob/master/src/Multicall3.sol
Functions
multicallNoResults
Executes multiple calls to this contract in a single transaction while preserving msg.sender. Return data from the calls is discarded.
This method is non-payable, so only calls with msg.value of 0 can be batched. If ignoreReverts is set to true, reverted calls will be skipped. Otherwise, the entire batch will revert with the original revert reason.
function multicallNoResults(bytes[] calldata data, bool ignoreReverts) external;
Parameters
Name | Type | Description |
---|---|---|
data | bytes[] | List of ABI-encoded calldata for the calls to execute |
ignoreReverts | bool | Whether to skip calls that revert |
multicallWithResults
Executes multiple calls to this contract in a single transaction while preserving msg.sender. Return data from each call is preserved.
This method is non-payable, so only calls with msg.value of 0 can be batched. If ignoreReverts is set to true, reverted calls will be skipped. Otherwise, the entire batch will revert with the original revert reason.
function multicallWithResults(bytes[] calldata data, bool ignoreReverts) external returns (Result[] memory results);
Parameters
Name | Type | Description |
---|---|---|
data | bytes[] | List of ABI-encoded calldata for the calls to execute |
ignoreReverts | bool | Whether to skip calls that revert |
Returns
Name | Type | Description |
---|---|---|
results | Result[] | List of results from the calls, each containing (success, returnData) |
Structs
Result
struct Result {
bool success;
bytes returnData;
}
ISynapseIntentPreviewer
Functions
previewIntent
Preview the completion of a user intent.
Will not revert if the intent cannot be completed, returns empty values instead.
Returns (amountIn, []) if the intent is a no-op (tokenIn == tokenOut).
function previewIntent(
address swapQuoter,
address forwardTo,
address tokenIn,
address tokenOut,
uint256 amountIn
)
external
view
returns (uint256 amountOut, ISynapseIntentRouter.StepParams[] memory steps);
Parameters
Name | Type | Description |
---|---|---|
swapQuoter | address | Peripheral contract to use for swap quoting |
forwardTo | address | The address to which the proceeds of the intent should be forwarded to. Note: if no forwarding is required (or done within the intent), use address(0). |
tokenIn | address | Initial token for the intent |
tokenOut | address | Final token for the intent |
amountIn | uint256 | Initial amount of tokens to use for the intent |
Returns
Name | Type | Description |
---|---|---|
amountOut | uint256 | Final amount of tokens to receive. Zero if the intent cannot be completed. |
steps | ISynapseIntentRouter.StepParams[] | Steps to use in SynapseIntentRouter in order to complete the intent. Empty if the intent cannot be completed, or if intent is a no-op (tokenIn == tokenOut). |
ISynapseIntentRouter
Functions
completeIntentWithBalanceChecks
Kindly ask SIR to complete the provided intent by completing a series of Zap steps using the provided ZapRecipient contract.
- Each step is verified to be a correct Zap as per
IZapRecipient
specification. - The amounts used for each step can be predetermined or based on the proceeds from the previous steps.
- SIR does not perform any checks on the Zap Data; the user is responsible for ensuring correct encoding.
- The user is responsible for selecting the correct ZapRecipient for their intent: ZapRecipient must be able to modify the Zap Data to adjust to possible changes in the passed amount value.
- SIR checks that the ZapRecipient balance for every token in
steps
has not increased after the last step.
Typical workflow involves a series of preparation steps followed by the last step representing the user intent such as bridging, depositing, or a simple transfer to the final recipient. The ZapRecipient must be the funds recipient for the preparation steps, while the final recipient must be used for the last step.
*This function will revert in any of the following cases:
- The deadline has passed.
- The array of StepParams is empty.
- The amount of tokens to use for the last step is below the specified minimum.
- Any step fails.
msg.value
does not matchsum(steps[i].msgValue)
.*
function completeIntentWithBalanceChecks(
address zapRecipient,
uint256 amountIn,
uint256 minLastStepAmountIn,
uint256 deadline,
StepParams[] memory steps
)
external
payable;
Parameters
Name | Type | Description |
---|---|---|
zapRecipient | address | Address of the IZapRecipient contract to use for the Zap steps |
amountIn | uint256 | Initial amount of tokens (steps[0].token) to transfer into ZapRecipient |
minLastStepAmountIn | uint256 | Minimum amount of tokens (steps[N-1].token) to use for the last step |
deadline | uint256 | Deadline for the intent to be completed |
steps | StepParams[] | Parameters for each step. Use amount = type(uint256).max for steps that should use the full ZapRecipient balance. |
completeIntent
Kindly ask SIR to complete the provided intent by completing a series of Zap steps using the provided ZapRecipient contract.
This function is identical to completeIntentWithBalanceChecks
except that it does not verify that
the ZapRecipient balance for every token in steps
has not increased after the last Zap.
Anyone using this function must validate that the funds are fully spent by ZapRecipient
using other means like separate on-chain checks or off-chain simulation.
function completeIntent(
address zapRecipient,
uint256 amountIn,
uint256 minLastStepAmountIn,
uint256 deadline,
StepParams[] memory steps
)
external
payable;
Structs
StepParams
Parameters for a single Zap step.
struct StepParams {
address token;
uint256 amount;
uint256 msgValue;
bytes zapData;
}
ISynapseIntentRouterErrors
Errors
SIR__AmountInsufficient
error SIR__AmountInsufficient();
SIR__DeadlineExceeded
error SIR__DeadlineExceeded();
SIR__MsgValueIncorrect
error SIR__MsgValueIncorrect();
SIR__StepsNotProvided
error SIR__StepsNotProvided();
SIR__TokenNotContract
error SIR__TokenNotContract();
SIR__UnspentFunds
error SIR__UnspentFunds();
SIR__ZapIncorrectReturnValue
error SIR__ZapIncorrectReturnValue();
SIR__ZapNoReturnValue
error SIR__ZapNoReturnValue();
IZapRecipient
Interface for contracts that can perform Zap operations. Such contracts could be used as Recipients in a FastBridge transaction that includes a Zap operation. The Zap Data should include instructions on how exactly the Zap operation should be executed, which would typically include the target address and calldata to use. The exact implementation of the Zap Data encoding is up to the Recipient contract.
Functions
zap
Performs a Zap operation with the given token and amount according to the provided Zap data.
function zap(address token, uint256 amount, bytes memory zapData) external payable returns (bytes4);
Parameters
Name | Type | Description |
---|---|---|
token | address | The address of the token being used for the Zap operation. |
amount | uint256 | The amount of tokens to be used. |
zapData | bytes | The encoded data specifying how the Zap operation should be executed. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes4 | The function selector to indicate successful execution. |
Contents
Contents
Contents
IFastBridge
Functions
bridge
Initiates bridge on origin chain to be relayed by off-chain relayer
function bridge(BridgeParams memory params) external payable;
Parameters
Name | Type | Description |
---|---|---|
params | BridgeParams | The parameters required to bridge |
relay
Relays destination side of bridge transaction by off-chain relayer
function relay(bytes memory request) external payable;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to relay on destination chain |
prove
Provides proof on origin side that relayer provided funds on destination side of bridge transaction
function prove(bytes memory request, bytes32 destTxHash) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to prove on origin chain |
destTxHash | bytes32 | The destination tx hash proving bridge transaction was relayed |
claim
Completes bridge transaction on origin chain by claiming originally deposited capital
function claim(bytes memory request, address to) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to claim on origin chain |
to | address | The recipient address of the funds |
dispute
Disputes an outstanding proof in case relayer provided dest chain tx is invalid
function dispute(bytes32 transactionId) external;
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to dispute |
refund
Refunds an outstanding bridge transaction in case optimistic bridging failed
function refund(bytes memory request, address to) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to refund |
to | address | The recipient address of the funds |
getBridgeTransaction
Decodes bridge request into a bridge transaction
function getBridgeTransaction(bytes memory request) external pure returns (BridgeTransaction memory);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The bridge request to decode |
canClaim
Checks if the dispute period has passed so bridge deposit can be claimed
function canClaim(bytes32 transactionId, address relayer) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to check |
relayer | address | The address of the relayer attempting to claim |
Events
BridgeRequested
event BridgeRequested(bytes32 transactionId, address sender, bytes request);
BridgeRelayed
event BridgeRelayed(
bytes32 transactionId, address relayer, address to, address token, uint256 amount, uint256 chainGasAmount
);
BridgeProofProvided
event BridgeProofProvided(bytes32 transactionId, address relayer, bytes32 transactionHash);
BridgeProofDisputed
event BridgeProofDisputed(bytes32 transactionId, address relayer);
BridgeDepositClaimed
event BridgeDepositClaimed(bytes32 transactionId, address relayer, address to, address token, uint256 amount);
BridgeDepositRefunded
event BridgeDepositRefunded(bytes32 transactionId, address to, address token, uint256 amount);
Structs
BridgeTransaction
struct BridgeTransaction {
uint32 originChainId;
uint32 destChainId;
address originSender;
address destRecipient;
address originToken;
address destToken;
uint256 originAmount;
uint256 destAmount;
uint256 originFeeAmount;
bool sendChainGas;
uint256 deadline;
uint256 nonce;
}
BridgeProof
struct BridgeProof {
uint96 timestamp;
address relayer;
}
BridgeParams
struct BridgeParams {
uint32 dstChainId;
address sender;
address to;
address originToken;
address destToken;
uint256 originAmount;
uint256 destAmount;
bool sendChainGas;
uint256 deadline;
}
IFastBridgeRouter
Functions
setFastBridge
Sets the address of the FastBridge contract
This function is only callable by the owner
function setFastBridge(address fastBridge_) external;
Parameters
Name | Type | Description |
---|---|---|
fastBridge_ | address | The address of the FastBridge contract |
setSwapQuoter
Sets the address of the SwapQuoter contract
This function is only callable by the owner
function setSwapQuoter(address swapQuoter_) external;
Parameters
Name | Type | Description |
---|---|---|
swapQuoter_ | address | The address of the SwapQuoter contract |
bridge
Initiate an RFQ transaction with an optional swap on origin chain, and an optional gas rebate on destination chain.
*Note that method is payable.
If token is ETH_ADDRESS, this method should be invoked with msg.value = amountIn
.
If token is ERC20, the tokens will be pulled from msg.sender (use msg.value = 0
).
Make sure to approve this contract for spending token
beforehand.
originQuery
is supposed to be fetched using FastBridgeRouter.getOriginAmountOut().
Alternatively one could use an external adapter for more complex swaps on the origin chain.
destQuery.rawParams
signals whether the user wants to receive a gas rebate on the destination chain:
- If the first byte of
destQuery.rawParams
is GAS_REBATE_FLAG, the user wants to receive a gas rebate. - Otherwise, the user does not want to receive a gas rebate.
Cross-chain RFQ swap will be performed between tokens:
originQuery.tokenOut
anddestQuery.tokenOut
. Note: both tokens could be ETH_ADDRESS or ERC20. Full proceeds of the origin swap are considered the bid for the cross-chain swap.destQuery.minAmountOut
is considered the ask for the cross-chain swap. Note: applying slippage todestQuery.minAmountOut
will result in a worse price for the user, the full Relayer quote should be used instead.*
function bridge(
address recipient,
uint256 chainId,
address token,
uint256 amount,
SwapQuery memory originQuery,
SwapQuery memory destQuery
)
external
payable;
Parameters
Name | Type | Description |
---|---|---|
recipient | address | Address to receive tokens on destination chain |
chainId | uint256 | Destination chain id |
token | address | Initial token to be pulled from the user |
amount | uint256 | Amount of the initial tokens to be pulled from the user |
originQuery | SwapQuery | Origin swap query (see above) |
destQuery | SwapQuery | Destination swap query (see above) |
getOriginAmountOut
Finds the best path between tokenIn
and every RFQ token from the given list,
treating the swap as "origin swap", without putting any restrictions on the swap.
Check (query.minAmountOut != 0): this is true only if the swap is possible.
The returned queries with minAmountOut != 0 could be used as originQuery
with FastBridgeRouter.
Note: it is possible to form a SwapQuery off-chain using alternative SwapAdapter for the origin swap.
function getOriginAmountOut(
address tokenIn,
address[] memory rfqTokens,
uint256 amountIn
)
external
view
returns (SwapQuery[] memory originQueries);
Parameters
Name | Type | Description |
---|---|---|
tokenIn | address | Initial token that user wants to bridge/swap |
rfqTokens | address[] | List of RFQ tokens |
amountIn | uint256 | Amount of tokens user wants to bridge/swap |
Returns
Name | Type | Description |
---|---|---|
originQueries | SwapQuery[] | List of structs that could be used as originQuery in FastBridgeRouter. minAmountOut and deadline fields will need to be adjusted based on the user settings. |
GAS_REBATE_FLAG
Magic value that indicates that the user wants to receive gas rebate on the destination chain. This is the answer to the ultimate question of life, the universe, and everything.
function GAS_REBATE_FLAG() external view returns (bytes1);
fastBridge
Address of the FastBridge contract, used to initiate cross-chain RFQ swaps.
function fastBridge() external view returns (address);
swapQuoter
Address of the SwapQuoter contract, used to fetch quotes for the origin swap.
function swapQuoter() external view returns (address);
ISwapQuoter
Functions
getAmountOut
function getAmountOut(
LimitedToken memory tokenIn,
address tokenOut,
uint256 amountIn
)
external
view
returns (SwapQuery memory query);
FastBridgeRouterV2
Inherits: DefaultRouter, Ownable, IFastBridgeRouter
State Variables
GAS_REBATE_FLAG
Magic value that indicates that the user wants to receive gas rebate on the destination chain. This is the answer to the ultimate question of life, the universe, and everything.
bytes1 public constant GAS_REBATE_FLAG = 0x2A;
fastBridge
Address of the FastBridge contract, used to initiate cross-chain RFQ swaps.
address public fastBridge;
swapQuoter
Address of the SwapQuoter contract, used to fetch quotes for the origin swap.
address public swapQuoter;
Functions
constructor
constructor(address owner_);
setFastBridge
Sets the address of the FastBridge contract
This function is only callable by the owner
function setFastBridge(address fastBridge_) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
fastBridge_ | address | The address of the FastBridge contract |
setSwapQuoter
Sets the address of the SwapQuoter contract
This function is only callable by the owner
function setSwapQuoter(address swapQuoter_) external onlyOwner;
Parameters
Name | Type | Description |
---|---|---|
swapQuoter_ | address | The address of the SwapQuoter contract |
bridge
Initiate an RFQ transaction with an optional swap on origin chain, and an optional gas rebate on destination chain.
*Note that method is payable.
If token is ETH_ADDRESS, this method should be invoked with msg.value = amountIn
.
If token is ERC20, the tokens will be pulled from msg.sender (use msg.value = 0
).
Make sure to approve this contract for spending token
beforehand.
originQuery
is supposed to be fetched using FastBridgeRouter.getOriginAmountOut().
Alternatively one could use an external adapter for more complex swaps on the origin chain.
destQuery.rawParams
signals whether the user wants to receive a gas rebate on the destination chain:
- If the first byte of
destQuery.rawParams
is GAS_REBATE_FLAG, the user wants to receive a gas rebate. - Otherwise, the user does not want to receive a gas rebate.
Cross-chain RFQ swap will be performed between tokens:
originQuery.tokenOut
anddestQuery.tokenOut
. Note: both tokens could be ETH_ADDRESS or ERC20. Full proceeds of the origin swap are considered the bid for the cross-chain swap.destQuery.minAmountOut
is considered the ask for the cross-chain swap. Note: applying slippage todestQuery.minAmountOut
will result in a worse price for the user, the full Relayer quote should be used instead.*
function bridge(
address recipient,
uint256 chainId,
address token,
uint256 amount,
SwapQuery memory originQuery,
SwapQuery memory destQuery
)
external
payable;
Parameters
Name | Type | Description |
---|---|---|
recipient | address | Address to receive tokens on destination chain |
chainId | uint256 | Destination chain id |
token | address | Initial token to be pulled from the user |
amount | uint256 | Amount of the initial tokens to be pulled from the user |
originQuery | SwapQuery | Origin swap query (see above) |
destQuery | SwapQuery | Destination swap query (see above) |
getOriginAmountOut
Finds the best path between tokenIn
and every RFQ token from the given list,
treating the swap as "origin swap", without putting any restrictions on the swap.
Check (query.minAmountOut != 0): this is true only if the swap is possible.
The returned queries with minAmountOut != 0 could be used as originQuery
with FastBridgeRouter.
Note: it is possible to form a SwapQuery off-chain using alternative SwapAdapter for the origin swap.
function getOriginAmountOut(
address tokenIn,
address[] memory rfqTokens,
uint256 amountIn
)
external
view
returns (SwapQuery[] memory originQueries);
Parameters
Name | Type | Description |
---|---|---|
tokenIn | address | Initial token that user wants to bridge/swap |
rfqTokens | address[] | List of RFQ tokens |
amountIn | uint256 | Amount of tokens user wants to bridge/swap |
Returns
Name | Type | Description |
---|---|---|
originQueries | SwapQuery[] | List of structs that could be used as originQuery in FastBridgeRouter. minAmountOut and deadline fields will need to be adjusted based on the user settings. |
_getOriginSender
Retrieves the origin sender from the raw params. Note: falls back to msg.sender if origin sender is not specified in the raw params, but msg.sender is an EOA.
function _getOriginSender(bytes memory rawParams) internal view returns (address originSender);
_chainGasRequested
Checks if the explicit instruction to send gas to the destination chain was provided.
function _chainGasRequested(bytes memory rawParams) internal pure returns (bool);
Events
SwapQuoterSet
Emitted when the swap quoter is set.
event SwapQuoterSet(address newSwapQuoter);
FastBridgeSet
Emitted when the new FastBridge contract is set.
event FastBridgeSet(address newFastBridge);
Errors
FastBridgeRouterV2__OriginSenderNotSpecified
error FastBridgeRouterV2__OriginSenderNotSpecified();
Contents
Contents
DefaultAdapter
Inherits: IRouterAdapter
Functions
receive
Enable this contract to receive Ether when withdrawing from WETH.
Consider implementing rescue functions to withdraw Ether from this contract.
receive() external payable;
adapterSwap
Performs a tokenIn -> tokenOut swap, according to the provided params.
If tokenIn is ETH_ADDRESS, this method should be invoked with msg.value = amountIn
.
If tokenIn is ERC20, the tokens should be already transferred to this contract (using msg.value = 0
).
If tokenOut is ETH_ADDRESS, native ETH will be sent to the recipient (be aware of potential reentrancy).
If tokenOut is ERC20, the tokens will be transferred to the recipient.
Contracts implementing {IRouterAdapter} interface are required to enforce the above restrictions.
On top of that, they must ensure that exactly amountOut
worth of tokenOut
is transferred to the recipient.
Swap deadline and slippage is checked outside of this contract.
function adapterSwap(
address recipient,
address tokenIn,
uint256 amountIn,
address tokenOut,
bytes memory rawParams
)
external
payable
returns (uint256 amountOut);
Parameters
Name | Type | Description |
---|---|---|
recipient | address | Address to receive the swapped token |
tokenIn | address | Token to sell (use ETH_ADDRESS to start from native ETH) |
amountIn | uint256 | Amount of tokens to sell |
tokenOut | address | Token to buy (use ETH_ADDRESS to end with native ETH) |
rawParams | bytes | Additional swap parameters |
Returns
Name | Type | Description |
---|---|---|
amountOut | uint256 | Amount of bought tokens |
_adapterSwap
Internal logic for doing a tokenIn -> tokenOut swap.
Note: tokenIn
is assumed to have already been transferred to this contract.
function _adapterSwap(
address recipient,
address tokenIn,
uint256 amountIn,
address tokenOut,
bytes memory rawParams
)
internal
virtual
returns (uint256 amountOut);
_checkParams
Checks the params and decodes them into a struct.
function _checkParams(
address tokenIn,
address tokenOut,
bytes memory rawParams
)
internal
pure
returns (DefaultParams memory params);
_wrapReceivedETH
Wraps native ETH into WETH, if requested. Returns the address of the token this contract ends up with.
function _wrapReceivedETH(
address tokenIn,
uint256 amountIn,
address tokenOut,
DefaultParams memory params
)
internal
returns (address wrappedTokenIn);
_deriveTokenSwapTo
Derives the address of token to be received after an action defined in params
.
function _deriveTokenSwapTo(
address tokenIn,
address tokenOut,
DefaultParams memory params
)
internal
view
returns (address tokenSwapTo);
_performPoolAction
Performs an action defined in params
and returns the amount of tokenSwapTo
received.
function _performPoolAction(
address tokenIn,
uint256 amountIn,
address tokenSwapTo,
DefaultParams memory params
)
internal
returns (uint256 amountOut);
_swap
Performs a swap through the given pool.
Note: The pool should be already approved for spending tokenIn
.
function _swap(address pool, DefaultParams memory params, uint256 amountIn, address tokenOut) internal;
_addLiquidity
Adds liquidity in a form of a single token to the given pool.
Note: The pool should be already approved for spending tokenIn
.
function _addLiquidity(address pool, DefaultParams memory params, uint256 amountIn, address tokenOut) internal;
_removeLiquidity
Removes liquidity in a form of a single token from the given pool.
Note: The pool should be already approved for spending tokenIn
.
function _removeLiquidity(address pool, DefaultParams memory params, uint256 amountIn, address tokenOut) internal;
_getPoolLPToken
Returns the LP token address of the given pool.
function _getPoolLPToken(address pool) internal view returns (address lpToken);
_getPoolNumTokens
Returns the number of tokens in the given pool.
function _getPoolNumTokens(address pool) internal view returns (uint256 numTokens);
_getPoolTokens
Returns the tokens in the given pool.
function _getPoolTokens(address pool) internal view returns (address[] memory tokens);
_getPoolSwapQuote
Returns the quote for a swap through the given pool. Note: will return 0 on invalid swaps.
function _getPoolSwapQuote(
address pool,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 amountIn
)
internal
view
returns (uint256 amountOut);
_wrapETH
Wraps ETH into WETH.
function _wrapETH(address weth, uint256 amount) internal;
_unwrapETH
Unwraps WETH into ETH.
function _unwrapETH(address weth, uint256 amount) internal;
_deriveWethAddress
Derives WETH address from swap parameters.
function _deriveWethAddress(
address token,
DefaultParams memory params,
bool isTokenFromWeth
)
internal
view
returns (address weth);
Contents
IDefaultExtendedPool
Inherits: IDefaultPool
Functions
addLiquidity
function addLiquidity(uint256[] calldata amounts, uint256 minToMint, uint256 deadline) external returns (uint256);
removeLiquidityOneToken
function removeLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount,
uint256 deadline
)
external
returns (uint256);
calculateRemoveLiquidity
function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory);
calculateRemoveLiquidityOneToken
function calculateRemoveLiquidityOneToken(
uint256 tokenAmount,
uint8 tokenIndex
)
external
view
returns (uint256 availableTokenAmount);
getAPrecise
function getAPrecise() external view returns (uint256);
getTokenBalance
function getTokenBalance(uint8 index) external view returns (uint256);
swapStorage
function swapStorage()
external
view
returns (
uint256 initialA,
uint256 futureA,
uint256 initialATime,
uint256 futureATime,
uint256 swapFee,
uint256 adminFee,
address lpToken
);
IDefaultPool
Functions
swap
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
)
external
returns (uint256 amountOut);
calculateSwap
function calculateSwap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
)
external
view
returns (uint256 amountOut);
getToken
function getToken(uint8 index) external view returns (address token);
IRouterAdapter
Functions
adapterSwap
Performs a tokenIn -> tokenOut swap, according to the provided params.
If tokenIn is ETH_ADDRESS, this method should be invoked with msg.value = amountIn
.
If tokenIn is ERC20, the tokens should be already transferred to this contract (using msg.value = 0
).
If tokenOut is ETH_ADDRESS, native ETH will be sent to the recipient (be aware of potential reentrancy).
If tokenOut is ERC20, the tokens will be transferred to the recipient.
Contracts implementing {IRouterAdapter} interface are required to enforce the above restrictions.
On top of that, they must ensure that exactly amountOut
worth of tokenOut
is transferred to the recipient.
Swap deadline and slippage is checked outside of this contract.
function adapterSwap(
address recipient,
address tokenIn,
uint256 amountIn,
address tokenOut,
bytes calldata rawParams
)
external
payable
returns (uint256 amountOut);
Parameters
Name | Type | Description |
---|---|---|
recipient | address | Address to receive the swapped token |
tokenIn | address | Token to sell (use ETH_ADDRESS to start from native ETH) |
amountIn | uint256 | Amount of tokens to sell |
tokenOut | address | Token to buy (use ETH_ADDRESS to end with native ETH) |
rawParams | bytes | Additional swap parameters |
Returns
Name | Type | Description |
---|---|---|
amountOut | uint256 | Amount of bought tokens |
IWETH9
Functions
deposit
function deposit() external payable;
withdraw
function withdraw(uint256 wad) external;
Contents
- DeadlineExceeded
- InsufficientOutputAmount
- MsgValueIncorrect
- PoolNotFound
- TokenAddressMismatch
- TokenNotContract
- TokenNotETH
- TokensIdentical
- BridgeToken
- IndexedToken
- LimitedToken
- PoolToken
- Pool
- DestRequest
- SwapQuery
- SwapQueryLib
- DefaultParams
- Action
- ActionLib
- UniversalTokenLib
DeadlineExceeded
error DeadlineExceeded();
InsufficientOutputAmount
error InsufficientOutputAmount();
MsgValueIncorrect
error MsgValueIncorrect();
PoolNotFound
error PoolNotFound();
TokenAddressMismatch
error TokenAddressMismatch();
TokenNotContract
error TokenNotContract();
TokenNotETH
error TokenNotETH();
TokensIdentical
error TokensIdentical();
BridgeToken
Struct representing a bridge token. Used as the return value in view functions.
struct BridgeToken {
string symbol;
address token;
}
IndexedToken
Struct used by IPoolHandler to represent a token in a pool
struct IndexedToken {
uint8 index;
address token;
}
LimitedToken
Struct representing a token, and the available Actions for performing a swap.
struct LimitedToken {
uint256 actionMask;
address token;
}
PoolToken
Struct representing how pool tokens are stored by SwapQuoter
.
struct PoolToken {
bool isWeth;
address token;
}
Pool
Struct representing a liquidity pool. Used as the return value in view functions.
struct Pool {
address pool;
address lpToken;
PoolToken[] tokens;
}
DestRequest
Struct representing a quote request for swapping a bridge token. Used in destination chain's SynapseRouter, hence the name "Destination Request".
tokenOut is passed externally.
struct DestRequest {
string symbol;
uint256 amountIn;
}
SwapQuery
Struct representing a swap request for SynapseRouter.
tokenIn is supplied separately.
struct SwapQuery {
address routerAdapter;
address tokenOut;
uint256 minAmountOut;
uint256 deadline;
bytes rawParams;
}
SwapQueryLib
Functions
hasAdapter
Checks whether the router adapter was specified in the query. Query without a router adapter specifies that no action needs to be taken.
function hasAdapter(SwapQuery memory query) internal pure returns (bool);
fillAdapterAndDeadline
Fills routerAdapter
and deadline
fields in query, if it specifies one of the supported Actions,
and if a path for this action was found.
function fillAdapterAndDeadline(SwapQuery memory query, address routerAdapter) internal pure;
DefaultParams
Struct representing parameters for swapping via DefaultAdapter.
struct DefaultParams {
Action action;
address pool;
uint8 tokenIndexFrom;
uint8 tokenIndexTo;
}
Action
All possible actions that DefaultAdapter could perform.
enum Action {
Swap,
AddLiquidity,
RemoveLiquidity,
HandleEth
}
ActionLib
Library for dealing with bit masks which describe what set of Actions is available.
Functions
allActions
Returns a bitmask with all possible actions set to True.
function allActions() internal pure returns (uint256 actionMask);
isIncluded
Returns whether the given action is set to True in the bitmask.
function isIncluded(Action action, uint256 actionMask) internal pure returns (bool);
mask
Returns a bitmask with only the given action set to True.
function mask(Action action) internal pure returns (uint256);
mask
Returns a bitmask with only two given actions set to True.
function mask(Action a, Action b) internal pure returns (uint256);
UniversalTokenLib
State Variables
ETH_ADDRESS
address internal constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
Functions
universalTransfer
Transfers tokens to the given account. Reverts if transfer is not successful.
This might trigger fallback, if ETH is transferred to the contract. Make sure this can not lead to reentrancy attacks.
function universalTransfer(address token, address to, uint256 value) internal;
universalApproveInfinity
Issues an infinite allowance to the spender, if the current allowance is insufficient to spend the given amount.
Note: this can potentially lead to executing code in to
.
function universalApproveInfinity(address token, address spender, uint256 amountToSpend) internal;
universalBalanceOf
Returns the balance of the given token (or native ETH) for the given account.
function universalBalanceOf(address token, address account) internal view returns (uint256);
assertIsContract
Checks that token is a contract and not ETH_ADDRESS.
function assertIsContract(address token) internal view;
DefaultRouter
Inherits: DefaultAdapter
Base contract for all Synapse Routers, that is able to natively work with Default Pools due to the fact that it inherits from DefaultAdapter.
Functions
_doSwap
Performs a "swap from tokenIn" following instructions from query
.
query
will include the router adapter to use, and the exact type of "tokenIn -> tokenOut swap"
should be encoded in query.rawParams
.
function _doSwap(
address recipient,
address tokenIn,
uint256 amountIn,
SwapQuery memory query
)
internal
returns (address tokenOut, uint256 amountOut);
_pullToken
Pulls a requested token from the user to the requested recipient. Or, if msg.value was provided, check that ETH_ADDRESS was used and msg.value is correct.
function _pullToken(address recipient, address token, uint256 amount) internal returns (uint256 amountPulled);
Contents
- BridgeTransactionV2Lib
- DeadlineExceeded
- DeadlineNotExceeded
- DeadlineTooShort
- InsufficientOutputAmount
- MsgValueIncorrect
- PoolNotFound
- TokenAddressMismatch
- TokenNotContract
- TokenNotETH
- TokensIdentical
- ChainIncorrect
- AmountIncorrect
- ZeroAddress
- DisputePeriodNotPassed
- DisputePeriodPassed
- SenderIncorrect
- StatusIncorrect
- TransactionIdIncorrect
- TransactionRelayed
- UniversalTokenLib
- ZapDataV1
BridgeTransactionV2Lib
State Variables
VERSION
uint16 internal constant VERSION = 2;
OFFSET_ORIGIN_CHAIN_ID
uint256 private constant OFFSET_ORIGIN_CHAIN_ID = 2;
OFFSET_DEST_CHAIN_ID
uint256 private constant OFFSET_DEST_CHAIN_ID = 6;
OFFSET_ORIGIN_SENDER
uint256 private constant OFFSET_ORIGIN_SENDER = 10;
OFFSET_DEST_RECIPIENT
uint256 private constant OFFSET_DEST_RECIPIENT = 30;
OFFSET_ORIGIN_TOKEN
uint256 private constant OFFSET_ORIGIN_TOKEN = 50;
OFFSET_DEST_TOKEN
uint256 private constant OFFSET_DEST_TOKEN = 70;
OFFSET_ORIGIN_AMOUNT
uint256 private constant OFFSET_ORIGIN_AMOUNT = 90;
OFFSET_DEST_AMOUNT
uint256 private constant OFFSET_DEST_AMOUNT = 122;
OFFSET_ORIGIN_FEE_AMOUNT
uint256 private constant OFFSET_ORIGIN_FEE_AMOUNT = 154;
OFFSET_DEADLINE
uint256 private constant OFFSET_DEADLINE = 186;
OFFSET_NONCE
uint256 private constant OFFSET_NONCE = 218;
OFFSET_EXCLUSIVITY_RELAYER
uint256 private constant OFFSET_EXCLUSIVITY_RELAYER = 250;
OFFSET_EXCLUSIVITY_END_TIME
uint256 private constant OFFSET_EXCLUSIVITY_END_TIME = 270;
OFFSET_ZAP_NATIVE
uint256 private constant OFFSET_ZAP_NATIVE = 302;
OFFSET_ZAP_DATA
uint256 private constant OFFSET_ZAP_DATA = 334;
Functions
validateV2
Validates that the encoded transaction is a tightly packed encoded payload for BridgeTransactionV2.
Checks the minimum length and the version, use this function before decoding any of the fields.
function validateV2(bytes calldata encodedTx) internal pure;
encodeV2
Encodes the BridgeTransactionV2 struct by tightly packing the fields.
abi.decode
will not work as a result of the tightly packed fields. Use decodeV2
to decode instead.
function encodeV2(IFastBridgeV2.BridgeTransactionV2 memory bridgeTx) internal pure returns (bytes memory);
decodeV2
Decodes the BridgeTransactionV2 struct from the encoded transaction.
Encoded BridgeTransactionV2 struct must be tightly packed.
Use validateV2
before decoding to ensure the encoded transaction is valid.
function decodeV2(bytes calldata encodedTx) internal pure returns (IFastBridgeV2.BridgeTransactionV2 memory bridgeTx);
version
Extracts the version from the encoded transaction.
function version(bytes calldata encodedTx) internal pure returns (uint16 version_);
originChainId
Extracts the origin chain ID from the encoded transaction.
function originChainId(bytes calldata encodedTx) internal pure returns (uint32 originChainId_);
destChainId
Extracts the destination chain ID from the encoded transaction.
function destChainId(bytes calldata encodedTx) internal pure returns (uint32 destChainId_);
originSender
Extracts the origin sender from the encoded transaction.
function originSender(bytes calldata encodedTx) internal pure returns (address originSender_);
destRecipient
Extracts the destination recipient from the encoded transaction.
function destRecipient(bytes calldata encodedTx) internal pure returns (address destRecipient_);
originToken
Extracts the origin token from the encoded transaction.
function originToken(bytes calldata encodedTx) internal pure returns (address originToken_);
destToken
Extracts the destination token from the encoded transaction.
function destToken(bytes calldata encodedTx) internal pure returns (address destToken_);
originAmount
Extracts the origin amount from the encoded transaction.
function originAmount(bytes calldata encodedTx) internal pure returns (uint256 originAmount_);
destAmount
Extracts the destination amount from the encoded transaction.
function destAmount(bytes calldata encodedTx) internal pure returns (uint256 destAmount_);
originFeeAmount
Extracts the origin fee amount from the encoded transaction.
function originFeeAmount(bytes calldata encodedTx) internal pure returns (uint256 originFeeAmount_);
deadline
Extracts the deadline from the encoded transaction.
function deadline(bytes calldata encodedTx) internal pure returns (uint256 deadline_);
nonce
Extracts the nonce from the encoded transaction.
function nonce(bytes calldata encodedTx) internal pure returns (uint256 nonce_);
exclusivityRelayer
Extracts the exclusivity relayer from the encoded transaction.
function exclusivityRelayer(bytes calldata encodedTx) internal pure returns (address exclusivityRelayer_);
exclusivityEndTime
Extracts the exclusivity end time from the encoded transaction.
function exclusivityEndTime(bytes calldata encodedTx) internal pure returns (uint256 exclusivityEndTime_);
zapNative
Extracts the Zap's native value from the encoded transaction.
function zapNative(bytes calldata encodedTx) internal pure returns (uint256 zapNative_);
zapData
Extracts the Zap's data from the encoded transaction.
function zapData(bytes calldata encodedTx) internal pure returns (bytes calldata zapData_);
Errors
BridgeTransactionV2__InvalidEncodedTx
error BridgeTransactionV2__InvalidEncodedTx();
BridgeTransactionV2__UnsupportedVersion
error BridgeTransactionV2__UnsupportedVersion(uint16 version);
DeadlineExceeded
error DeadlineExceeded();
DeadlineNotExceeded
error DeadlineNotExceeded();
DeadlineTooShort
error DeadlineTooShort();
InsufficientOutputAmount
error InsufficientOutputAmount();
MsgValueIncorrect
error MsgValueIncorrect();
PoolNotFound
error PoolNotFound();
TokenAddressMismatch
error TokenAddressMismatch();
TokenNotContract
error TokenNotContract();
TokenNotETH
error TokenNotETH();
TokensIdentical
error TokensIdentical();
ChainIncorrect
error ChainIncorrect();
AmountIncorrect
error AmountIncorrect();
ZeroAddress
error ZeroAddress();
DisputePeriodNotPassed
error DisputePeriodNotPassed();
DisputePeriodPassed
error DisputePeriodPassed();
SenderIncorrect
error SenderIncorrect();
StatusIncorrect
error StatusIncorrect();
TransactionIdIncorrect
error TransactionIdIncorrect();
TransactionRelayed
error TransactionRelayed();
UniversalTokenLib
State Variables
ETH_ADDRESS
address internal constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
Functions
universalTransfer
Transfers tokens to the given account. Reverts if transfer is not successful.
This might trigger fallback, if ETH is transferred to the contract. Make sure this can not lead to reentrancy attacks.
function universalTransfer(address token, address to, uint256 value) internal;
universalApproveInfinity
Issues an infinite allowance to the spender, if the current allowance is insufficient to spend the given amount.
Note: this can potentially lead to executing code in to
.
function universalApproveInfinity(address token, address spender, uint256 amountToSpend) internal;
universalBalanceOf
Returns the balance of the given token (or native ETH) for the given account.
function universalBalanceOf(address token, address account) internal view returns (uint256);
assertIsContract
Checks that token is a contract and not ETH_ADDRESS.
function assertIsContract(address token) internal view;
ZapDataV1
State Variables
VERSION
Version of the Zap Data struct.
uint16 internal constant VERSION = 1;
AMOUNT_NOT_PRESENT
Value that indicates the amount is not present in the target function's payload.
uint16 internal constant AMOUNT_NOT_PRESENT = 0xFFFF;
OFFSET_AMOUNT_POSITION
uint256 private constant OFFSET_AMOUNT_POSITION = 2;
OFFSET_FINAL_TOKEN
uint256 private constant OFFSET_FINAL_TOKEN = 4;
OFFSET_FORWARD_TO
uint256 private constant OFFSET_FORWARD_TO = 24;
OFFSET_TARGET
uint256 private constant OFFSET_TARGET = 44;
OFFSET_PAYLOAD
uint256 private constant OFFSET_PAYLOAD = 64;
Functions
validateV1
Validates that encodedZapData is a tightly packed encoded payload for ZapData struct.
Checks that all the required fields are present and the version is correct.
function validateV1(bytes calldata encodedZapData) internal pure;
encodeV1
Encodes the ZapData struct by tightly packing the fields.
Note: we don't know the exact amount of tokens that will be used for the Zap at the time of encoding,
so we provide the reference index where the token amount is encoded within payload_
. This allows us to
hot-swap the token amount in the payload, when the Zap is performed.
abi.decode
will not work as a result of the tightly packed fields. Use decodeZapData
instead.
function encodeV1(
uint16 amountPosition_,
address finalToken_,
address forwardTo_,
address target_,
bytes memory payload_
)
internal
pure
returns (bytes memory encodedZapData);
Parameters
Name | Type | Description |
---|---|---|
amountPosition_ | uint16 | Position (start index) where the token amount is encoded within payload_ . This will usually be 4 + 32 * n , where n is the position of the token amount in the list of parameters of the target function (starting from 0). Or AMOUNT_NOT_PRESENT if the token amount is not encoded within payload_ . |
finalToken_ | address | The token produced as a result of the Zap action (ERC20 or native gas token). A zero address value signals that the Zap action doesn't result in any asset per se, like bridging or depositing into a vault without an LP token. Note: this parameter must be set to a non-zero value if the forwardTo_ parameter is set to a non-zero value. |
forwardTo_ | address | The address to which finalToken should be forwarded. This parameter is required only if the Zap action does not automatically transfer the token to the intended recipient. Otherwise, it must be set to address(0). |
target_ | address | Address of the target contract. |
payload_ | bytes | ABI-encoded calldata to be used for the target_ contract call. If the target function has the token amount as an argument, any placeholder amount value can be used for the original ABI encoding of payload_ . The placeholder amount will be replaced with the actual amount, when the Zap Data is decoded. |
version
Extracts the version from the encoded Zap Data.
function version(bytes calldata encodedZapData) internal pure returns (uint16 version_);
finalToken
Extracts the finalToken address from the encoded Zap Data.
function finalToken(bytes calldata encodedZapData) internal pure returns (address finalToken_);
forwardTo
Extracts the forwardTo address from the encoded Zap Data.
function forwardTo(bytes calldata encodedZapData) internal pure returns (address forwardTo_);
target
Extracts the target address from the encoded Zap Data.
function target(bytes calldata encodedZapData) internal pure returns (address target_);
payload
Extracts the payload from the encoded Zap Data. Replaces the token amount with the provided value, if it was present in the original data (if amountPosition is not AMOUNT_NOT_PRESENT).
This payload will be used as a calldata for the target contract.
function payload(bytes calldata encodedZapData, uint256 amount) internal pure returns (bytes memory);
_amountPosition
Extracts the amount position from the encoded Zap Data.
function _amountPosition(bytes calldata encodedZapData) private pure returns (uint16 amountPosition);
Errors
ZapDataV1__InvalidEncoding
error ZapDataV1__InvalidEncoding();
ZapDataV1__TargetZeroAddress
error ZapDataV1__TargetZeroAddress();
ZapDataV1__UnsupportedVersion
error ZapDataV1__UnsupportedVersion(uint16 version);
Contents
SynapseIntentPreviewer
Inherits: ISynapseIntentPreviewer
State Variables
NATIVE_GAS_TOKEN
The address reserved for the native gas token (ETH on Ethereum and most L2s, AVAX on Avalanche, etc.).
address public constant NATIVE_GAS_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
FULL_BALANCE
Amount value that signals that the Zap step should be performed using the full ZapRecipient balance.
uint256 internal constant FULL_BALANCE = type(uint256).max;
Functions
previewIntent
Preview the completion of a user intent.
Will not revert if the intent cannot be completed, returns empty values instead.
function previewIntent(
address swapQuoter,
address forwardTo,
address tokenIn,
address tokenOut,
uint256 amountIn
)
external
view
returns (uint256 amountOut, ISynapseIntentRouter.StepParams[] memory steps);
Parameters
Name | Type | Description |
---|---|---|
swapQuoter | address | Peripheral contract to use for swap quoting |
forwardTo | address | The address to which the proceeds of the intent should be forwarded to. Note: if no forwarding is required (or done within the intent), use address(0). |
tokenIn | address | Initial token for the intent |
tokenOut | address | Final token for the intent |
amountIn | uint256 | Initial amount of tokens to use for the intent |
Returns
Name | Type | Description |
---|---|---|
amountOut | uint256 | Final amount of tokens to receive. Zero if the intent cannot be completed. |
steps | ISynapseIntentRouter.StepParams[] | Steps to use in SynapseIntentRouter in order to complete the intent. Empty if the intent cannot be completed, or if intent is a no-op (tokenIn == tokenOut). |
_createSwapSteps
Helper function to create steps for a swap.
function _createSwapSteps(
address tokenIn,
address tokenOut,
uint256 amountIn,
DefaultParams memory params,
address forwardTo
)
internal
view
returns (ISynapseIntentRouter.StepParams[] memory steps);
_createAddLiquiditySteps
Helper function to create steps for adding liquidity.
function _createAddLiquiditySteps(
address tokenIn,
address tokenOut,
DefaultParams memory params,
address forwardTo
)
internal
view
returns (ISynapseIntentRouter.StepParams[] memory steps);
_createRemoveLiquiditySteps
Helper function to create steps for removing liquidity.
function _createRemoveLiquiditySteps(
address tokenIn,
address tokenOut,
DefaultParams memory params,
address forwardTo
)
internal
view
returns (ISynapseIntentRouter.StepParams[] memory steps);
_verifyLpToken
function _verifyLpToken(address pool, address token) internal view;
_createHandleHativeSteps
Helper function to create steps for wrapping or unwrapping native gas tokens.
function _createHandleHativeSteps(
address tokenIn,
address tokenOut,
uint256 amountIn,
address forwardTo
)
internal
pure
returns (ISynapseIntentRouter.StepParams[] memory steps);
_createSwapStep
Helper function to create a single step for a swap.
function _createSwapStep(
address tokenIn,
address tokenOut,
DefaultParams memory params,
address forwardTo
)
internal
pure
returns (ISynapseIntentRouter.StepParams memory);
_createWrapNativeStep
Helper function to create a single step for wrapping native gas tokens.
function _createWrapNativeStep(
address wrappedNative,
uint256 msgValue,
address forwardTo
)
internal
pure
returns (ISynapseIntentRouter.StepParams memory);
_createUnwrapNativeStep
Helper function to create a single step for unwrapping native gas tokens.
function _createUnwrapNativeStep(
address wrappedNative,
address forwardTo
)
internal
pure
returns (ISynapseIntentRouter.StepParams memory);
_toStepsArray
Helper function to construct an array of steps having a single step.
function _toStepsArray(ISynapseIntentRouter.StepParams memory step0)
internal
pure
returns (ISynapseIntentRouter.StepParams[] memory);
_toStepsArray
Helper function to construct an array of steps having two steps.
function _toStepsArray(
ISynapseIntentRouter.StepParams memory step0,
ISynapseIntentRouter.StepParams memory step1
)
internal
pure
returns (ISynapseIntentRouter.StepParams[] memory);
Errors
SIP__NoOpForwardNotSupported
error SIP__NoOpForwardNotSupported();
SIP__PoolTokenMismatch
error SIP__PoolTokenMismatch();
SIP__PoolZeroAddress
error SIP__PoolZeroAddress();
SIP__RawParamsEmpty
error SIP__RawParamsEmpty();
SIP__TokenNotNative
error SIP__TokenNotNative();
SynapseIntentRouter
Inherits: ISynapseIntentRouter, ISynapseIntentRouterErrors
State Variables
NATIVE_GAS_TOKEN
The address reserved for the native gas token (ETH on Ethereum and most L2s, AVAX on Avalanche, etc.).
address public constant NATIVE_GAS_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
FULL_BALANCE
Amount value that signals that the Zap step should be performed using the full ZapRecipient balance.
uint256 internal constant FULL_BALANCE = type(uint256).max;
Functions
completeIntentWithBalanceChecks
Kindly ask SIR to complete the provided intent by completing a series of Zap steps using the provided ZapRecipient contract.
- Each step is verified to be a correct Zap as per
IZapRecipient
specification. - The amounts used for each step can be predetermined or based on the proceeds from the previous steps.
- SIR does not perform any checks on the Zap Data; the user is responsible for ensuring correct encoding.
- The user is responsible for selecting the correct ZapRecipient for their intent: ZapRecipient must be able to modify the Zap Data to adjust to possible changes in the passed amount value.
- SIR checks that the ZapRecipient balance for every token in
steps
has not increased after the last step.
Typical workflow involves a series of preparation steps followed by the last step representing the user intent such as bridging, depositing, or a simple transfer to the final recipient. The ZapRecipient must be the funds recipient for the preparation steps, while the final recipient must be used for the last step.
function completeIntentWithBalanceChecks(
address zapRecipient,
uint256 amountIn,
uint256 minLastStepAmountIn,
uint256 deadline,
StepParams[] calldata steps
)
external
payable;
Parameters
Name | Type | Description |
---|---|---|
zapRecipient | address | Address of the IZapRecipient contract to use for the Zap steps |
amountIn | uint256 | Initial amount of tokens (steps[0].token) to transfer into ZapRecipient |
minLastStepAmountIn | uint256 | Minimum amount of tokens (steps[N-1].token) to use for the last step |
deadline | uint256 | Deadline for the intent to be completed |
steps | StepParams[] | Parameters for each step. Use amount = type(uint256).max for steps that should use the full ZapRecipient balance. |
completeIntent
Kindly ask SIR to complete the provided intent by completing a series of Zap steps using the provided ZapRecipient contract.
This function is identical to completeIntentWithBalanceChecks
except that it does not verify that
the ZapRecipient balance for every token in steps
has not increased after the last Zap.
Anyone using this function must validate that the funds are fully spent by ZapRecipient
using other means like separate on-chain checks or off-chain simulation.
function completeIntent(
address zapRecipient,
uint256 amountIn,
uint256 minLastStepAmountIn,
uint256 deadline,
StepParams[] calldata steps
)
public
payable;
_transferInputAsset
Transfers the input asset from the user into ZapRecipient custody. This asset will later be used to perform the zap steps.
function _transferInputAsset(address zapRecipient, address token, uint256 amount) internal;
_performZap
Performs a Zap step, using the provided msg.value and calldata.
Validates the return data from ZapRecipient as per IZapRecipient
specification.
function _performZap(address zapRecipient, uint256 msgValue, bytes memory zapRecipientCallData) internal;
Contents
MulticallTarget
Inherits: IMulticallTarget
Abstract contract template that supports batched calls while preserving msg.sender. Only calls with msg.value of 0 can be batched.
Functions
multicallNoResults
Executes multiple calls to this contract in a single transaction while preserving msg.sender. Return data from the calls is discarded.
This method is non-payable, so only calls with msg.value of 0 can be batched. If ignoreReverts is set to true, reverted calls will be skipped. Otherwise, the entire batch will revert with the original revert reason.
function multicallNoResults(bytes[] calldata data, bool ignoreReverts) external;
Parameters
Name | Type | Description |
---|---|---|
data | bytes[] | List of ABI-encoded calldata for the calls to execute |
ignoreReverts | bool | Whether to skip calls that revert |
multicallWithResults
Executes multiple calls to this contract in a single transaction while preserving msg.sender. Return data from each call is preserved.
This method is non-payable, so only calls with msg.value of 0 can be batched. If ignoreReverts is set to true, reverted calls will be skipped. Otherwise, the entire batch will revert with the original revert reason.
function multicallWithResults(bytes[] calldata data, bool ignoreReverts) external returns (Result[] memory results);
Parameters
Name | Type | Description |
---|---|---|
data | bytes[] | List of ABI-encoded calldata for the calls to execute |
ignoreReverts | bool | Whether to skip calls that revert |
Returns
Name | Type | Description |
---|---|---|
results | Result[] | List of results from the calls, each containing (success, returnData) |
_bubbleRevert
Bubbles the revert message from the underlying call. Note: preserves the same custom error or revert string, if one was used. Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v5.0.2/contracts/utils/Address.sol#L143-L158
function _bubbleRevert(bytes memory returnData) internal pure;
Errors
MulticallTarget__UndeterminedRevert
error MulticallTarget__UndeterminedRevert();
Contents
TokenZapV1
Inherits: IZapRecipient
Facilitates atomic token operations known as "Zaps", allowing the execution of predefined actions on behalf of users, such as deposits or swaps. Supports ERC20 tokens and native gas tokens (e.g., ETH).
Tokens must be transferred to the contract before execution, native tokens could be provided as msg.value
.
This contract is stateless and does not hold assets between Zaps; leftover tokens can be claimed by anyone.
Ensure that Zaps fully utilize tokens or revert to prevent the loss of funds.
State Variables
NATIVE_GAS_TOKEN
address public constant NATIVE_GAS_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
Functions
receive
Allows the contract to receive ETH.
Leftover ETH can be claimed by anyone. Ensure the full balance is spent during Zaps.
receive() external payable;
zap
Performs a Zap action using the specified token and amount. This amount must have previously been
transferred to this contract (could also be supplied as msg.value if the token is a native gas token).
Zap action will be performed forwarding full msg.value
for ERC20s or amount
for native gas tokens.
Note: all funds remaining after the Zap action is performed can be claimed by anyone.
Make sure to spend the full balance during the Zaps and avoid sending extra funds if a single Zap is performed.
The provided ZapData contains the target address and calldata for the Zap action, and must be
encoded using the encodeZapData function. Native gas token transfers could be done by using empty payload
,
this is the only case where target could be an EOA.
function zap(address token, uint256 amount, bytes calldata zapData) external payable returns (bytes4);
Parameters
Name | Type | Description |
---|---|---|
token | address | Address of the token to be used for the Zap action. |
amount | uint256 | Amount of the token to be used for the Zap action. |
zapData | bytes | Encoded Zap Data containing the target address and calldata for the Zap action. |
Returns
Name | Type | Description |
---|---|---|
<none> | bytes4 | selector Selector of this function to signal the caller about the success of the Zap action. |
encodeZapData
Encodes the ZapData for a Zap action.
At the time of encoding, we don't know the exact amount of tokens that will be used for the Zap, as we don't have a quote for performing a Zap. Therefore, a placeholder value for the amount must be used when ABI-encoding the payload. A reference index where the actual amount is encoded within the payload must be provided in order to replace the placeholder with the actual amount when the Zap is performed.
function encodeZapData(
address target,
bytes memory payload,
uint256 amountPosition,
address finalToken,
address forwardTo
)
external
pure
returns (bytes memory);
Parameters
Name | Type | Description |
---|---|---|
target | address | Address of the target contract. |
payload | bytes | ABI-encoded calldata to be used for the target contract call. If the target function has the token amount as an argument, any placeholder amount value can be used for the original ABI encoding of payload . The placeholder amount will be replaced with the actual amount when the Zap Data is decoded. |
amountPosition | uint256 | Position (start index) where the token amount is encoded within payload . This will usually be 4 + 32 * n , where n is the position of the token amount in the list of parameters of the target function (starting from 0). Any value greater than or equal to payload.length can be used if the token amount is not an argument of the target function. |
finalToken | address | The token produced as a result of the Zap action (ERC20 or native gas token). A zero address value signals that the Zap action doesn't result in any asset per se, like bridging or depositing into a vault without an LP token. Note: this parameter must be set to a non-zero value if the forwardTo parameter is set to a non-zero value. |
forwardTo | address | The address to which finalToken should be forwarded. This parameter is required only if the Zap action does not automatically transfer the token to the intended recipient. Otherwise, it must be set to address(0). |
decodeZapData
Decodes the ZapData for a Zap action. Replaces the placeholder amount with the actual amount,
if it was present in the original payload
. Otherwise, returns the original payload
as is.
function decodeZapData(
bytes calldata zapData,
uint256 amount
)
public
pure
returns (address target, bytes memory payload);
Parameters
Name | Type | Description |
---|---|---|
zapData | bytes | Encoded Zap Data containing the target address and calldata for the Zap action. |
amount | uint256 | Actual amount of the token to be used for the Zap action. |
_forwardToken
Forwards the proceeds of the Zap action to the specified non-zero recipient.
function _forwardToken(address token, address forwardTo) internal;
Errors
TokenZapV1__FinalTokenBalanceZero
error TokenZapV1__FinalTokenBalanceZero();
TokenZapV1__PayloadLengthAboveMax
error TokenZapV1__PayloadLengthAboveMax();
TokenZapV1__TargetZeroAddress
error TokenZapV1__TargetZeroAddress();
TokenZapV1__TokenZeroAddress
error TokenZapV1__TokenZeroAddress();
Admin
Inherits: IAdmin, AccessControlEnumerable
State Variables
RELAYER_ROLE
bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE");
REFUNDER_ROLE
bytes32 public constant REFUNDER_ROLE = keccak256("REFUNDER_ROLE");
GUARD_ROLE
bytes32 public constant GUARD_ROLE = keccak256("GUARD_ROLE");
GOVERNOR_ROLE
bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
FEE_BPS
uint256 public constant FEE_BPS = 1e6;
FEE_RATE_MAX
uint256 public constant FEE_RATE_MAX = 0.01e6;
protocolFeeRate
Protocol fee rate taken on origin amount deposited in origin chain
uint256 public protocolFeeRate;
protocolFees
Protocol fee amounts accumulated
mapping(address => uint256) public protocolFees;
chainGasAmount
Chain gas amount to forward as rebate if requested
uint256 public chainGasAmount;
Functions
constructor
constructor(address _owner);
setProtocolFeeRate
function setProtocolFeeRate(uint256 newFeeRate) external onlyRole(GOVERNOR_ROLE);
sweepProtocolFees
function sweepProtocolFees(address token, address recipient) external onlyRole(GOVERNOR_ROLE);
setChainGasAmount
function setChainGasAmount(uint256 newChainGasAmount) external onlyRole(GOVERNOR_ROLE);
AdminV2
Inherits: AccessControlEnumerable, IAdminV2, IAdminV2Errors
Provides administrative functions and controls for managing the FastBridgeV2 contract, including access control and configuration settings.
State Variables
NATIVE_GAS_TOKEN
The address reserved for the native gas token (ETH on Ethereum and most L2s, AVAX on Avalanche, etc.).
address public constant NATIVE_GAS_TOKEN = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
QUOTER_ROLE
The role identifier for the Quoter API's off-chain authentication.
Only addresses with this role can post FastBridge quotes to the API.
bytes32 public constant QUOTER_ROLE = keccak256("QUOTER_ROLE");
GUARD_ROLE
The role identifier for the Guard's on-chain authentication in FastBridge.
Only addresses with this role can dispute submitted relay proofs during the dispute period.
bytes32 public constant GUARD_ROLE = keccak256("GUARD_ROLE");
CANCELER_ROLE
The role identifier for the Canceler's on-chain authentication in FastBridge.
Only addresses with this role can cancel a FastBridge transaction without the cancel delay.
bytes32 public constant CANCELER_ROLE = keccak256("CANCELER_ROLE");
GOVERNOR_ROLE
The role identifier for the Governor's on-chain administrative authority.
Only addresses with this role can perform administrative tasks within the contract.
bytes32 public constant GOVERNOR_ROLE = keccak256("GOVERNOR_ROLE");
FEE_BPS
The denominator for fee rates, representing 100%.
uint256 public constant FEE_BPS = 1e6;
FEE_RATE_MAX
The maximum protocol fee rate: 1% of the origin amount.
uint256 public constant FEE_RATE_MAX = 0.01e6;
MIN_CANCEL_DELAY
The minimum cancel delay that can be set by the governor.
uint256 public constant MIN_CANCEL_DELAY = 1 hours;
DEFAULT_CANCEL_DELAY
The default cancel delay set during contract deployment.
uint256 public constant DEFAULT_CANCEL_DELAY = 1 days;
MIN_DISPUTE_PENALTY_TIME
The minimum dispute penalty time that can be set by the governor.
uint256 public constant MIN_DISPUTE_PENALTY_TIME = 1 minutes;
DEFAULT_DISPUTE_PENALTY_TIME
The default dispute penalty time set during contract deployment.
uint256 public constant DEFAULT_DISPUTE_PENALTY_TIME = 30 minutes;
protocolFeeRate
The protocol fee rate taken on the origin amount deposited in the origin chain.
uint256 public protocolFeeRate;
protocolFees
The accumulated protocol fee amounts.
mapping(address => uint256) public protocolFees;
cancelDelay
The delay period after which a transaction can be permissionlessly cancelled.
uint256 public cancelDelay;
deployBlock
The block number at which the contract was deployed.
This used to be immutable in V1, but was adjusted to be mutable in V2 for chains like Arbitrum that
implement the block.number
as the underlying L1 block number rather than the chain's native block number.
This is exposed for conveniece for off-chain indexers that need to know the deployment block.
uint256 public deployBlock;
disputePenaltyTime
The timeout period that is used to temporarily disactivate a disputed prover.
uint256 public disputePenaltyTime;
_allProvers
A list of all provers ever added to the contract. Can hold up to 2^16-1 provers.
address[] private _allProvers;
_proverInfos
A mapping of provers to their information: id and activeFromTimestamp.
mapping(address => ProverInfo) private _proverInfos;
chainGasAmount
This variable is deprecated and should not be used.
Use ZapNative V2 requests instead.
uint256 public immutable chainGasAmount = 0;
Functions
constructor
constructor(address defaultAdmin);
addProver
Allows the role admin to add a new prover to the contract.
function addProver(address prover) external onlyRole(DEFAULT_ADMIN_ROLE);
removeProver
Allows the role admin to remove a prover from the contract.
function removeProver(address prover) external onlyRole(DEFAULT_ADMIN_ROLE);
setCancelDelay
Allows the governor to set the cancel delay. The cancel delay is the time period after the transaction deadline during which a transaction can be permissionlessly cancelled if it hasn't been proven by any Relayer.
function setCancelDelay(uint256 newCancelDelay) external onlyRole(GOVERNOR_ROLE);
setDeployBlock
Allows the default admin to set the deploy block.
This is only relevant for chains like Arbitrum that implement the block.number
as the underlying L1
block number rather than the chain's native block number.
function setDeployBlock(uint256 blockNumber) external onlyRole(DEFAULT_ADMIN_ROLE);
setDisputePenaltyTime
Allows the governor to set the dispute penalty time. The dispute penalty time is the time period used to temporarily deactivate a prover if its proof is disputed: prover will be inactive for the dispute penalty time after the dispute is submitted.
function setDisputePenaltyTime(uint256 newDisputePenaltyTime) external onlyRole(GOVERNOR_ROLE);
setProtocolFeeRate
Allows the governor to set the protocol fee rate. The protocol fee is taken from the origin amount and is only applied to completed and claimed transactions.
The protocol fee is abstracted away from the relayers; they always operate using the amounts after fees. The origin amount they see in the emitted log is what they get credited with.
function setProtocolFeeRate(uint256 newFeeRate) external onlyRole(GOVERNOR_ROLE);
sweepProtocolFees
Allows the governor to withdraw the accumulated protocol fees from the contract.
function sweepProtocolFees(address token, address recipient) external onlyRole(GOVERNOR_ROLE);
getProvers
Returns the list of the active provers.
function getProvers() external view returns (address[] memory provers);
getProverInfo
Returns the information about the prover with the provided address.
function getProverInfo(address prover) external view returns (uint16 proverID, uint256 activeFromTimestamp);
Returns
Name | Type | Description |
---|---|---|
proverID | uint16 | The ID of the prover if it has been added before, or zero otherwise. |
activeFromTimestamp | uint256 | The timestamp when the prover becomes active, or zero if the prover isn't active. |
getProverInfoByID
Returns the information about the prover with the provided ID.
function getProverInfoByID(uint16 proverID) external view returns (address prover, uint256 activeFromTimestamp);
Returns
Name | Type | Description |
---|---|---|
prover | address | The address of the prover with the provided ID, or zero the ID does not exist. |
activeFromTimestamp | uint256 | The timestamp when the prover becomes active, or zero if the prover isn't active. |
getActiveProverID
Returns the ID of the active prover, or zero if the prover is not currently active.
function getActiveProverID(address prover) public view returns (uint16);
_applyDisputePenaltyTime
Internal logic to apply the dispute penalty time to a given prover. Will make the prover inactive
for disputePenaltyTime
seconds. No-op if the prover ID does not exist or prover is already inactive.
function _applyDisputePenaltyTime(uint16 proverID) internal;
_setCancelDelay
Internal logic to set the cancel delay. Security checks are performed outside of this function.
This function is marked as private to prevent child contracts from calling it directly.
function _setCancelDelay(uint256 newCancelDelay) private;
_setDeployBlock
Internal logic to set the deploy block. Security checks are performed outside of this function.
This function is marked as private to prevent child contracts from calling it directly.
function _setDeployBlock(uint256 blockNumber) private;
_setDisputePenaltyTime
Internal logic to set the dispute penalty time. Security checks are performed outside of this function.
This function is marked as private to prevent child contracts from calling it directly.
function _setDisputePenaltyTime(uint256 newDisputePenaltyTime) private;
Structs
ProverInfo
Struct for storing information about a prover.
struct ProverInfo {
uint16 id;
uint240 activeFromTimestamp;
}
FastBridge
Inherits: IFastBridge, MulticallTarget, Admin
State Variables
DISPUTE_PERIOD
Dispute period for relayed transactions
uint256 public constant DISPUTE_PERIOD = 30 minutes;
REFUND_DELAY
Delay for a transaction after which it could be permisionlessly refunded
uint256 public constant REFUND_DELAY = 7 days;
MIN_DEADLINE_PERIOD
Minimum deadline period to relay a requested bridge transaction
uint256 public constant MIN_DEADLINE_PERIOD = 30 minutes;
bridgeStatuses
Status of the bridge tx on origin chain
mapping(bytes32 => BridgeStatus) public bridgeStatuses;
bridgeProofs
Proof of relayed bridge tx on origin chain
mapping(bytes32 => BridgeProof) public bridgeProofs;
bridgeRelays
Whether bridge has been relayed on destination chain
mapping(bytes32 => bool) public bridgeRelays;
nonce
to prevent replays
uint256 public nonce;
deployBlock
uint256 public immutable deployBlock;
Functions
constructor
constructor(address _owner) Admin(_owner);
_pullToken
Pulls a requested token from the user to the requested recipient.
Be careful of re-entrancy issues when msg.value > 0 and recipient != address(this)
function _pullToken(address recipient, address token, uint256 amount) internal returns (uint256 amountPulled);
getBridgeTransaction
Decodes bridge request into a bridge transaction
function getBridgeTransaction(bytes memory request) public pure returns (BridgeTransaction memory);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The bridge request to decode |
bridge
Initiates bridge on origin chain to be relayed by off-chain relayer
function bridge(BridgeParams memory params) external payable;
Parameters
Name | Type | Description |
---|---|---|
params | BridgeParams | The parameters required to bridge |
relay
Relays destination side of bridge transaction by off-chain relayer
function relay(bytes memory request) external payable onlyRole(RELAYER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to relay on destination chain |
prove
Provides proof on origin side that relayer provided funds on destination side of bridge transaction
function prove(bytes memory request, bytes32 destTxHash) external onlyRole(RELAYER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to prove on origin chain |
destTxHash | bytes32 | The destination tx hash proving bridge transaction was relayed |
_timeSince
Calculates time since proof submitted
proof.timestamp stores casted uint96(block.timestamp) block timestamps for gas optimization _timeSince(proof) can accomodate rollover case when block.timestamp > type(uint96).max but proof.timestamp < type(uint96).max via unchecked statement
function _timeSince(BridgeProof memory proof) internal view returns (uint256 delta);
Parameters
Name | Type | Description |
---|---|---|
proof | BridgeProof | The bridge proof |
Returns
Name | Type | Description |
---|---|---|
delta | uint256 | Time delta since proof submitted |
canClaim
Checks if the dispute period has passed so bridge deposit can be claimed
function canClaim(bytes32 transactionId, address relayer) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to check |
relayer | address | The address of the relayer attempting to claim |
claim
Completes bridge transaction on origin chain by claiming originally deposited capital
function claim(bytes memory request, address to) external onlyRole(RELAYER_ROLE);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to claim on origin chain |
to | address | The recipient address of the funds |
dispute
Disputes an outstanding proof in case relayer provided dest chain tx is invalid
function dispute(bytes32 transactionId) external onlyRole(GUARD_ROLE);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to dispute |
refund
Refunds an outstanding bridge transaction in case optimistic bridging failed
function refund(bytes memory request) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to refund |
Enums
BridgeStatus
enum BridgeStatus {
NULL,
REQUESTED,
RELAYER_PROVED,
RELAYER_CLAIMED,
REFUNDED
}
FastBridgeV2
Inherits: AdminV2, MulticallTarget, IFastBridgeV2, IFastBridgeV2Errors
Core component of the SynapseRFQ protocol, enabling Relayers (Solvers) to fulfill bridge requests. Supports ERC20 and native gas tokens, along with the Zap feature for executing actions on the destination chain. Users interact with the off-chain Quoter API to obtain a current quote for a bridge transaction. They then submit the bridge request with the quote to this contract, depositing their assets in escrow. Relayers can fulfill requests by relaying them to the destination chain and must prove fulfillment to claim funds. Guards monitor proofs and can dispute discrepancies. Users can reclaim funds by cancelling their requests if it has not been fulfilled within the specified deadline.
State Variables
DISPUTE_PERIOD
The duration of the dispute period for relayed transactions.
uint256 public constant DISPUTE_PERIOD = 30 minutes;
MIN_DEADLINE_PERIOD
The minimum required time between transaction request and deadline.
uint256 public constant MIN_DEADLINE_PERIOD = 30 minutes;
MAX_ZAP_DATA_LENGTH
The maximum allowed length for zapData.
uint256 public constant MAX_ZAP_DATA_LENGTH = 2 ** 16 - 1;
bridgeTxDetails
Maps transaction IDs to bridge details (status, destination chain ID, proof timestamp, and relayer). Note: this is only stored for transactions having local chain as the origin chain.
mapping(bytes32 => BridgeTxDetails) public bridgeTxDetails;
bridgeRelayDetails
Maps transaction IDs to relay details (block number, block timestamp, and relayer). Note: this is only stored for transactions having local chain as the destination chain.
mapping(bytes32 => BridgeRelay) public bridgeRelayDetails;
senderNonces
Maps sender addresses to their unique bridge nonce.
mapping(address => uint256) public senderNonces;
nonce
This variable is deprecated and should not be used.
Replaced by senderNonces.
uint256 public immutable nonce = 0;
Functions
constructor
Initializes the FastBridgeV2 contract with the provided default admin, sets the default cancel delay, and records the deploy block number.
constructor(address defaultAdmin) AdminV2(defaultAdmin);
bridge
Initiates bridge on origin chain to be relayed by off-chain relayer
function bridge(BridgeParams memory params) external payable;
Parameters
Name | Type | Description |
---|---|---|
params | BridgeParams | The parameters required to bridge |
refund
Note: this function is deprecated and will be removed in a future version.
Replaced by cancel
.
function refund(bytes calldata request) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to refund |
relay
Relays destination side of bridge transaction by off-chain relayer
function relay(bytes calldata request) external payable;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to relay on destination chain |
prove
Provides proof on origin side that relayer provided funds on destination side of bridge transaction
function prove(bytes calldata request, bytes32 destTxHash) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to prove on origin chain |
destTxHash | bytes32 | The destination tx hash proving bridge transaction was relayed |
claimV2
Completes bridge transaction on origin chain by claiming originally deposited capital.
function claimV2(bytes calldata request) external;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to claim on origin chain |
dispute
Disputes an outstanding proof in case relayer provided dest chain tx is invalid
function dispute(bytes32 transactionId) external onlyRole(GUARD_ROLE);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to dispute |
canClaim
Checks if the dispute period has passed so bridge deposit can be claimed
function canClaim(bytes32 transactionId, address relayer) external view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to check |
relayer | address | The address of the relayer attempting to claim |
getBridgeTransaction
Decodes bridge request into a bridge transaction
*This method is added to achieve backwards compatibility with decoding requests into V1 structs:
zapNative
is partially reported as a zero/non-zero flagzapData
is ignored In order to process all kinds of requests use getBridgeTransactionV2 instead.*
function getBridgeTransaction(bytes calldata request) external view returns (BridgeTransaction memory);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The bridge request to decode |
getBridgeTransactionV2
Decodes bridge request into a bridge transaction V2 struct used by FastBridgeV2
function getBridgeTransactionV2(bytes calldata request) external pure returns (BridgeTransactionV2 memory);
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The bridge request to decode |
bridgeV2
Initiates bridge on origin chain to be relayed by off-chain relayer, with the ability to provide temporary exclusivity fill rights for the quote relayer.
function bridgeV2(BridgeParams memory params, BridgeParamsV2 memory paramsV2) public payable;
Parameters
Name | Type | Description |
---|---|---|
params | BridgeParams | The parameters required to bridge |
paramsV2 | BridgeParamsV2 | The parameters for exclusivity fill rights (optional, can be left empty) |
cancelV2
Cancels an outstanding bridge transaction in case optimistic bridging failed and returns the full amount to the original sender.
function cancelV2(bytes calldata request) public;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to refund |
relayV2
Relays destination side of bridge transaction by off-chain relayer
function relayV2(bytes calldata request, address relayer) public payable;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to relay on destination chain |
relayer | address | The address of the relaying entity which should have control of the origin funds when claimed |
proveV2
Provides proof on origin side that relayer provided funds on destination side of bridge transaction
function proveV2(bytes32 transactionId, bytes32 destTxHash, address relayer) public;
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The transaction id associated with the encoded bridge transaction to prove |
destTxHash | bytes32 | The destination tx hash proving bridge transaction was relayed |
relayer | address | The address of the relaying entity which should have control of the origin funds when claimed |
claim
Completes bridge transaction on origin chain by claiming originally deposited capital
function claim(bytes calldata request, address to) public;
Parameters
Name | Type | Description |
---|---|---|
request | bytes | The encoded bridge transaction to claim on origin chain |
to | address | The recipient address of the funds |
bridgeStatuses
Returns the status of a bridge transaction
function bridgeStatuses(bytes32 transactionId) public view returns (BridgeStatus status);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The ID of the bridge transaction |
Returns
Name | Type | Description |
---|---|---|
status | BridgeStatus | BridgeStatus Status of the bridge transaction |
bridgeProofs
Returns the timestamp and relayer of a bridge proof
function bridgeProofs(bytes32 transactionId) public view returns (uint96 timestamp, address relayer);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The ID of the bridge transaction |
Returns
Name | Type | Description |
---|---|---|
timestamp | uint96 | The timestamp of the bridge proof |
relayer | address | The relayer address of the bridge proof |
bridgeRelays
Checks if a transaction has been relayed
function bridgeRelays(bytes32 transactionId) public view returns (bool);
Parameters
Name | Type | Description |
---|---|---|
transactionId | bytes32 | The ID of the transaction to check |
Returns
Name | Type | Description |
---|---|---|
<none> | bool | True if the transaction has been relayed, false otherwise |
_takeBridgedUserAsset
Takes the bridged asset from the user into FastBridgeV2 custody. The asset will later be claimed by the relayer who completed the relay on the destination chain, or returned to the user via the cancel function if no relay is completed.
function _takeBridgedUserAsset(address token, uint256 amount) internal returns (uint256 amountTaken);
_triggerZapWithChecks
Calls the recipient's hook function with the specified zapData and validates the returned value.
function _triggerZapWithChecks(address recipient, address token, uint256 amount, bytes calldata zapData) internal;
_timeSince
Calculates the time elapsed since a proof was submitted.
The proof.timestamp stores block timestamps as uint40 for gas optimization. _timeSince(proof) handles timestamp rollover when block.timestamp > type(uint40).max but proof.timestamp < type(uint40).max via an unchecked statement.
function _timeSince(uint40 proofBlockTimestamp) internal view returns (uint256 delta);
Parameters
Name | Type | Description |
---|---|---|
proofBlockTimestamp | uint40 | The block timestamp when the proof was submitted. |
Returns
Name | Type | Description |
---|---|---|
delta | uint256 | The time elapsed since proof submission. |
_validateBridgeParams
Validates all parameters required for a bridge transaction.
This function's complexity cannot be reduced due to the number of required checks, so we disable the code-complexity rule.
function _validateBridgeParams(
BridgeParams memory params,
BridgeParamsV2 memory paramsV2,
int256 exclusivityEndTime
)
internal
view;
_validateRelayParams
Validates all parameters required for a relay transaction.
function _validateRelayParams(bytes calldata request, bytes32 transactionId, address relayer) internal view;