Superform Smart Contracts

This repository contains the core protocol smart contracts of Superform.

codecov

Table of contents

Prerequisites

See the official Foundry installation instructions.

Then, install the foundry toolchain installer (foundryup) with:

curl -L https://foundry.paradigm.xyz | bash

Now that you've installed the foundryup binary, anytime you need to get the latest forge or cast binaries, you can run foundryup.

So, simply execute:

foundryup

🎉 Foundry is installed! 🎉

Note: you should also install pre-commit and Foundry Pre-Commit Hook to format before commiting. Check https://github.com/0xYYY/foundry-pre-commit for more info

Project structure

.
├── script
├── src
  ├── crosschain-data
  ├── crosschain-liquidity
  ├── forms
  ├── interfaces
  ├── libraries
  ├── payments
  ├── settings
  ├── types
  ├── utils
  ├── vendor
├── test
├── foundry.toml
└── README.md

It makes our project structure easily scannable:

  • src are self-explanatory. All Smart Contract Codes are found inside /src
  • interfaces are where we add our custom written interfaces /src/interfaces.
  • types is where all re-used types are written and used across different smart contracts. /src/types
  • vendor is where all externally written interfaces reside. /src/vendor

Installation

Step by step instructions on setting up the project and running it

  1. Set the env variables as per the dev instructions

  2. Install submodules and dependencies:

foundryup
forge install
  1. Run forge test to run some scenario tests against the contracts

Testing

$ forge test

Documentation

Contract Architecture

Superform v1 Smart Contract Architecture (4)
  1. All external actions, except SuperForm creation, start in SuperformRouter.sol. The user has to provide a "StateRequest" containing the amounts being actioned into each vault in each chain, as well as liquidity information, about how the actual deposit/withdraw process will be handled
  2. Deposits/withdraws can be single or multiple destination, single or multi vault, cross-chain or direct chain. For deposit actions, the user can provide a different input token on a source chain and receive the actual underlying token (different than input token) on the destination chain, after swapping and bridging in a single call. Sometimes it is also needed to perform another extra swap at the destination for tokens with low bridge liquidity, through the usage of DstSwapper.sol. For withdraw actions, user can choose to receive a different token than the one redeemed for from the vault, back at the source chain.
  3. The vaults themselves are wrapped by Forms - code implementations that adapt to the needs of a given vault. This wrapping action leads to the creation of SuperForms (the triplet of superForm address, form id and chain id).
  4. Any user can wrap a vault into a SuperForm using the SuperForm Factory but only the protocol may add new Form implementations.
  5. Any individual tx must be of a specific kind, either all deposits or all withdraws, for all vaults and destinations
  6. Users are minted SuperPositions on successful deposits, a type of ERC-1155 we modified called ERC-1155S. On withdrawals these are burned.

Transaction Flow

The typical flow for a deposit xchain transaction is:

  • Validation of the input data in SuperformRouter.sol.
  • Dispatching the input tokens to the liquidity bridge using an implementation of a BridgeValidator.sol and LiquidityHandler.sol.
  • Creating the AMBMessage with the information about what is going to be deposited and by whom.
  • Messaging the information about the deposits to the vaults using CoreStateRegistry.sol. Typically this is done with the combination of two different AMBs by splitting the message and the proof for added security.
  • Receive the information on the destination chain's CoreStateRegistry.sol. At this step, a keeper updates the messaged amounts to-be deposited with the actual amounts received through the liquidity bridge using one of the updatePayload functions.
  • The keeper can then process the received message using processPayload. Here the deposit action is try-catched for errors. Should the action pass, a message is sent back to source acknowledging the action and minting SuperPositions to the user. If the action fails, no message is sent back and no SuperPositions are minted.
  • Funds bridged can be automatically recovered by the keeper in case of error catching and sent back to source using one of rescueFailedDeposit functions.

The typical flow for a withdraw xchain transaction is:

  • Validation of the input data in SuperformRouter.sol.
  • Burning the corresponding SuperPositions owned by the user in accordance to the input data.
  • Creating the AMBMessage with the information about what is going to be withdrawn and by whom.
  • Messaging the information about the withdraws to the vaults using CoreStateRegistry.sol. The process follows the same pattern as above
  • Receive the information on the destination chain's CoreStateRegistry.sol.
  • The keeper can then process the received message using processPayload. Here the withdraw action is try-catched for errors. Should the action pass, the underlying obtained is bridged back to the user in the form of the desired tokens to be received. If the action fails, a message is sent back indicating that SuperPositions need to be re-minted for the user according to the original amounts that were burned.

Read more about our protocol

Gas Costs (28 July 2023)

src/SuperFormFactory.sol:SuperFormFactory contract
Deployment CostDeployment Size
278438714142
Function Nameminavgmedianmax# calls
addFormBeacon46826431786370756589752263
changeFormBeaconPauseStatus546650567350567310058812
createSuperForm72532058731981834171820107
getAllSuperForms188561885618856188561
getAllSuperFormsFromVault19931993199319931
getBytecodeFormBeacon151701517015170151701
getFormBeacon6359306352635203
getFormCount3263263263261
getSuperForm45945945945931
getSuperFormCount3483483483481
isFormBeaconPaused13571357135713571
updateFormBeaconLogic260076816793134165
src/SuperFormRouter.sol:SuperFormRouter contract
Deployment CostDeployment Size
433855522089
Function Nameminavgmedianmax# calls
multiDstMultiVaultDeposit63042110670551012200185678611
multiDstMultiVaultWithdraw5637261190243150015115068523
multiDstSingleVaultDeposit465047781205773480137725814
multiDstSingleVaultWithdraw2971303547903313074601245
singleDirectSingleVaultDeposit20546025243725845530253412
singleDirectSingleVaultWithdraw241082967861405018820354
singleXChainMultiVaultDeposit25678444799745517865640813
singleXChainMultiVaultWithdraw2172732385342395942578845
singleXChainSingleVaultDeposit24495333182734907239760214
singleXChainSingleVaultWithdraw1423361634851623871868314
src/SuperPositions.sol:SuperPositions contract
Deployment CostDeployment Size
272097214450
Function Nameminavgmedianmax# calls
balanceOf64212186422642493
burnBatchSP689978128059921813
burnSingleSP351336973513439119
dynamicURI12991299129912991
mintBatchSP486184861848618486182
mintSingleSP2451224563245122539517
setApprovalForOne293323333249332493355
setDynamicURI29792337923546434464
stateMultiSync1029249599511019382537
stateSync701024276269102786143
supportsInterface5485485485481
updateTxHistory23495238502349525495107
uri23322332233223321
src/crosschain-liquidity/DstSwapper.sol:DstSwapper contract
Deployment CostDeployment Size
9629135020
Function Nameminavgmedianmax# calls
batchProcessTx12222516912117337522849517
processTx7150073199715008111912

Contents

Contents

Contents

HyperlaneImplementation

Git Source

Inherits: IAmbImplementation, IMessageRecipient

Author: Zeropoint Labs

allows state registries to use hyperlane for crosschain communication

State Variables

mailbox

IMailbox public mailbox;

igp

IInterchainGasPaymaster public igp;

superRegistry

ISuperRegistry public immutable superRegistry;

ambChainId

mapping(uint64 => uint32) public ambChainId;

superChainId

mapping(uint32 => uint64) public superChainId;

authorizedImpl

mapping(uint32 => address) public authorizedImpl;

processedMessages

mapping(bytes32 => bool) public processedMessages;

Functions

onlyProtocolAdmin

modifier onlyProtocolAdmin();

constructor

constructor(ISuperRegistry superRegistry_);

setHyperlaneConfig

allows protocol admin to configure hyperlane mailbox and gas paymaster

function setHyperlaneConfig(IMailbox mailbox_, IInterchainGasPaymaster igp_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
mailbox_IMailboxis the address of hyperlane mailbox
igp_IInterchainGasPaymasteris the address of hyperlane gas paymaster

dispatchPayload

allows state registry to send message via implementation.

function dispatchPayload(
    address srcSender_,
    uint64 dstChainId_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    payable
    virtual
    override;

Parameters

NameTypeDescription
srcSender_addressis the caller (used for gas refunds)
dstChainId_uint64is the identifier of the destination chain
message_bytesis the cross-chain message to be sent
extraData_bytesis message amb specific override information

setChainId

allows protocol admin to add new chain ids in future

function setChainId(uint64 superChainId_, uint32 ambChainId_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
superChainId_uint64is the identifier of the chain within superform protocol
ambChainId_uint32is the identifier of the chain given by the AMB NOTE: cannot be defined in an interface as types vary for each message bridge (amb)

setReceiver

reset old mappings

allows protocol admin to set receiver implmentation on a new chain id

function setReceiver(uint32 domain_, address authorizedImpl_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
domain_uint32is the identifier of the destination chain within hyperlane
authorizedImpl_addressis the implementation of the hyperlane message bridge on the specified destination NOTE: cannot be defined in an interface as types vary for each message bridge (amb)

handle

function handle(uint32 origin_, bytes32 sender_, bytes calldata body_) external override;

Parameters

NameTypeDescription
origin_uint32
sender_bytes32
body_bytes

estimateFees

not all AMBs will have on-chain estimation for which this function will return 0

1. validate caller

2. validate src chain sender

3. validate message uniqueness

decoding payload NOTE: experimental split of registry contracts

function estimateFees(
    uint64 dstChainId_,
    bytes memory,
    bytes memory extraData_
)
    external
    view
    override
    returns (uint256 fees);

Parameters

NameTypeDescription
dstChainId_uint64is the identifier of the destination chain
<none>bytes
extraData_bytesis any amb-specific information

Returns

NameTypeDescription
feesuint256is the native_tokens to be sent along the transaction

_castAddr

casts an address to bytes32

function _castAddr(address addr_) internal pure returns (bytes32);

Parameters

NameTypeDescription
addr_addressis the address to be casted

Returns

NameTypeDescription
<none>bytes32a bytes32 casted variable of the address passed in params

Events

MailboxAdded

event MailboxAdded(address _newMailbox);

GasPayMasterAdded

event GasPayMasterAdded(address _igp);

Contents

LayerzeroImplementation

Git Source

Inherits: IAmbImplementation, ILayerZeroUserApplicationConfig, ILayerZeroReceiver

Author: Zeropoint Labs

allows state registries to use Layerzero for crosschain communication

State Variables

RECEIVER_OFFSET

uint256 private constant RECEIVER_OFFSET = 1;

superRegistry

ISuperRegistry public immutable superRegistry;

lzEndpoint

ILayerZeroEndpoint public lzEndpoint;

isValid

prevents layerzero relayer from replaying payload

mapping(uint16 => mapping(uint64 => bool)) public isValid;

ambChainId

mapping(uint64 => uint16) public ambChainId;

superChainId

mapping(uint16 => uint64) public superChainId;

trustedRemoteLookup

mapping(uint16 => bytes) public trustedRemoteLookup;

failedMessages

mapping(uint16 => mapping(bytes => mapping(uint64 => bytes32))) public failedMessages;

Functions

onlyProtocolAdmin

modifier onlyProtocolAdmin();

constructor

constructor(ISuperRegistry superRegistry_);

Parameters

NameTypeDescription
superRegistry_ISuperRegistryis the super registry address

dispatchPayload

allows state registry to send message via implementation.

function dispatchPayload(
    address srcSender_,
    uint64 dstChainId_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    payable
    override;

Parameters

NameTypeDescription
srcSender_addressis the caller (used for gas refunds)
dstChainId_uint64is the identifier of the destination chain
message_bytesis the cross-chain message to be sent
extraData_bytesis message amb specific override information

setChainId

allows protocol admin to add new chain ids in future

function setChainId(uint64 superChainId_, uint16 ambChainId_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
superChainId_uint64is the identifier of the chain within superform protocol
ambChainId_uint16is the identifier of the chain given by the AMB NOTE: cannot be defined in an interface as types vary for each message bridge (amb)

_nonblockingLzReceive

reset old mappings

function _nonblockingLzReceive(uint16 _srcChainId, bytes memory, bytes memory _payload) internal;

lzReceive

decodes payload received NOTE: experimental split of registry contracts

function lzReceive(
    uint16 srcChainId_,
    bytes memory srcAddress_,
    uint64 nonce_,
    bytes memory payload_
)
    public
    override;

nonblockingLzReceive

function nonblockingLzReceive(uint16 srcChainId_, bytes memory srcAddress_, bytes memory payload_) public;

retryMessage

function retryMessage(
    uint16 srcChainId_,
    bytes memory srcAddress_,
    uint64 nonce_,
    bytes memory payload_
)
    public
    payable;

_lzSend

function _lzSend(
    uint16 dstChainId_,
    bytes memory payload_,
    address payable refundAddress_,
    address zroPaymentAddress_,
    bytes memory adapterParams_,
    uint256 msgValue_
)
    internal;

_blockingLzReceive

function _blockingLzReceive(
    uint16 srcChainId_,
    bytes memory srcAddress_,
    uint64 nonce_,
    bytes memory payload_
)
    internal;

setLzEndpoint

allows protocol admin to configure layerzero endpoint

function setLzEndpoint(address endpoint_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
endpoint_addressis the layerzero endpoint on the deployed network

getConfig

function getConfig(
    uint16 version_,
    uint16 chainId_,
    address,
    uint256 configType_
)
    external
    view
    returns (bytes memory);

setConfig

allows protocol admin to configure UA on layerzero

function setConfig(
    uint16 version_,
    uint16 chainId_,
    uint256 configType_,
    bytes calldata config_
)
    external
    override
    onlyProtocolAdmin;

setSendVersion

function setSendVersion(uint16 version_) external override onlyProtocolAdmin;

setReceiveVersion

function setReceiveVersion(uint16 version_) external override onlyProtocolAdmin;

forceResumeReceive

function forceResumeReceive(uint16 srcChainId_, bytes calldata srcAddress_) external override onlyProtocolAdmin;

setTrustedRemote

function setTrustedRemote(uint16 srcChainId_, bytes calldata srcAddress_) external onlyProtocolAdmin;

isTrustedRemote

function isTrustedRemote(uint16 srcChainId_, bytes calldata srcAddress_) external view returns (bool);

estimateFees

not all AMBs will have on-chain estimation for which this function will return 0

returns the gas fees estimation in native tokens

function estimateFees(
    uint64 dstChainId_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    view
    override
    returns (uint256 fees);

Parameters

NameTypeDescription
dstChainId_uint64is the identifier of the destination chain
message_bytesis the cross-chain message
extraData_bytesis any amb-specific information

Returns

NameTypeDescription
feesuint256is the native_tokens to be sent along the transaction

Events

EndpointUpdated

event EndpointUpdated(address oldEndpoint_, address newEndpoint_);

MessageFailed

event MessageFailed(uint16 srcChainId_, bytes srcAddress_, uint64 nonce_, bytes payload_);

SetTrustedRemote

event SetTrustedRemote(uint16 srcChainId_, bytes srcAddress_);

Contents

Contents

WormholeARImplementation

Git Source

Inherits: IAmbImplementation, IWormholeReceiver

Author: Zeropoint Labs

allows state registries to use wormhole for crosschain communication

uses automatic relayers of wormhole for 1:1 messaging

State Variables

superRegistry

ISuperRegistry public immutable superRegistry;

relayer

IWormholeRelayer public relayer;

ambChainId

mapping(uint64 => uint16) public ambChainId;

superChainId

mapping(uint16 => uint64) public superChainId;

authorizedImpl

mapping(uint16 => address) public authorizedImpl;

processedMessages

mapping(bytes32 => bool) public processedMessages;

Functions

onlyProtocolAdmin

modifier onlyProtocolAdmin();

constructor

constructor(ISuperRegistry superRegistry_);

Parameters

NameTypeDescription
superRegistry_ISuperRegistryis super registry address for respective chain

setWormholeRelayer

allows protocol admin to configure wormhole relayer contract

function setWormholeRelayer(address relayer_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
relayer_addressis the automatic relayer address for respective chain

dispatchPayload

allows state registry to send message via implementation.

function dispatchPayload(
    address,
    uint64 dstChainId_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    payable
    virtual
    override;

Parameters

NameTypeDescription
<none>address
dstChainId_uint64is the identifier of the destination chain
message_bytesis the cross-chain message to be sent
extraData_bytesis message amb specific override information

receiveWormholeMessages

When a send is performed with this contract as the target, this function will be invoked by the WormholeRelayer contract NOTE: This function should be restricted such that only the Wormhole Relayer contract can call it. We also recommend that this function:

  • Stores all received deliveryHashs in a mapping (bytes32 => bool), and on every call, checks that deliveryHash has not already been stored in the map (This is to prevent other users maliciously trying to relay the same message)
  • Checks that sourceChain and sourceAddress are indeed who you expect to have requested the calling of send on the source chain The invocation of this function corresponding to the send request will have msg.value equal to the receiverValue specified in the send request. If the invocation of this function reverts or exceeds the gas limit specified by the send requester, this delivery will result in a ReceiverFailure.
function receiveWormholeMessages(
    bytes memory payload_,
    bytes[] memory,
    bytes32 sourceAddress_,
    uint16 sourceChain_,
    bytes32 deliveryHash_
)
    public
    payable
    override;

Parameters

NameTypeDescription
payload_bytes
<none>bytes[]
sourceAddress_bytes32
sourceChain_uint16
deliveryHash_bytes32

setChainId

1. validate caller

2. validate src chain sender

3. validate message uniqueness

decoding payload

allows protocol admin to add new chain ids in future

function setChainId(uint64 superChainId_, uint16 ambChainId_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
superChainId_uint64is the identifier of the chain within superform protocol
ambChainId_uint16is the identifier of the chain given by the AMB NOTE: cannot be defined in an interface as types vary for each message bridge (amb)

setReceiver

reset old mappings

allows protocol admin to set receiver implmentation on a new chain id

function setReceiver(uint16 chainId_, address authorizedImpl_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
chainId_uint16is the identifier of the destination chain within wormhole
authorizedImpl_addressis the implementation of the wormhole message bridge on the specified destination NOTE: cannot be defined in an interface as types vary for each message bridge (amb)

estimateFees

not all AMBs will have on-chain estimation for which this function will return 0

returns the gas fees estimation in native tokens

function estimateFees(
    uint64 dstChainId_,
    bytes memory,
    bytes memory extraData_
)
    external
    view
    override
    returns (uint256 fees);

Parameters

NameTypeDescription
dstChainId_uint64is the identifier of the destination chain
<none>bytes
extraData_bytesis any amb-specific information

Returns

NameTypeDescription
feesuint256is the native_tokens to be sent along the transaction

_bytes32ToAddress

casts a bytes32 string to address

function _bytes32ToAddress(bytes32 buf_) internal pure returns (address);

Parameters

NameTypeDescription
buf_bytes32is the bytes32 string to be casted

Returns

NameTypeDescription
<none>addressa address variable of the address passed in params

Contents

WormholeSRImplementation

Git Source

Inherits: IBroadcastAmbImplementation

Author: Zeropoint Labs

allows broadcast state registry contracts to send messages to multiple chains

uses multicast of wormhole for broadcasting

State Variables

superRegistry

ISuperRegistry public immutable superRegistry;

wormhole

IWormhole public wormhole;

broadcastFinality

uint8 public broadcastFinality;

ambChainId

mapping(uint64 => uint16) public ambChainId;

superChainId

mapping(uint16 => uint64) public superChainId;

processedMessages

mapping(bytes32 => bool) public processedMessages;

Functions

onlyProtocolAdmin

modifier onlyProtocolAdmin();

constructor

constructor(ISuperRegistry superRegistry_);

Parameters

NameTypeDescription
superRegistry_ISuperRegistryis super registry address for respective chain

setWormholeCore

allows protocol admin to configure wormhole core contract

function setWormholeCore(address wormhole_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
wormhole_addressis wormhole address for respective chain

setFinality

allows protocol admin to set broadcast finality

function setFinality(uint8 finality_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
finality_uint8is the required finality on src chain

broadcastPayload

allows state registry to send messages to multiple dst chains

function broadcastPayload(address, bytes memory message_, bytes memory) external payable virtual;

Parameters

NameTypeDescription
<none>address
message_bytesis the cross-chain message to be broadcasted
<none>bytes

receiveMessage

is wormhole's inherent fee for sending a message batch id

function receiveMessage(bytes memory encodedMessage_) public;

setChainId

1. validate caller

2. validate src chain sender

3. validate message uniqueness

decoding payload

allows protocol admin to add new chain ids in future

function setChainId(uint64 superChainId_, uint16 ambChainId_) external onlyProtocolAdmin;

Parameters

NameTypeDescription
superChainId_uint64is the identifier of the chain within superform protocol
ambChainId_uint16is the identifier of the chain given by the AMB NOTE: cannot be defined in an interface as types vary for each message bridge (amb)

estimateFees

estimation differs for different message bridges.

reset old mappings

function estimateFees(bytes memory, bytes memory) external view override returns (uint256 fees);

Parameters

NameTypeDescription
<none>bytes
<none>bytes

Returns

NameTypeDescription
feesuint256is the native_tokens to be sent along the transaction

_bytes32ToAddress

casts a bytes32 string to address

function _bytes32ToAddress(bytes32 buf_) internal pure returns (address);

Parameters

NameTypeDescription
buf_bytes32is the bytes32 string to be casted

Returns

NameTypeDescription
<none>addressa address variable of the address passed in params

Contents

CoreStateRegistry

Git Source

Inherits: BaseStateRegistry, ICoreStateRegistry

Author: Zeropoint Labs

enables communication between Superform Core Contracts deployed on all supported networks

State Variables

failedDeposits

just stores the superformIds that failed in a specific payload id

mapping(uint256 payloadId => FailedDeposit) internal failedDeposits;

Functions

onlyCoreStateRegistryProcessor

modifier onlyCoreStateRegistryProcessor();

onlyCoreStateRegistryUpdater

modifier onlyCoreStateRegistryUpdater();

onlyCoreStateRegistryRescuer

modifier onlyCoreStateRegistryRescuer();

onlySender

modifier onlySender() override;

isValidPayloadId

modifier isValidPayloadId(uint256 payloadId_);

constructor

constructor(ISuperRegistry superRegistry_) BaseStateRegistry(superRegistry_);

updateDepositPayload

allows accounts with {CORE_STATE_REGISTRY_UPDATER_ROLE} to modify a received cross-chain deposit payload.

function updateDepositPayload(
    uint256 payloadId_,
    uint256[] calldata finalAmounts_
)
    external
    virtual
    override
    onlyCoreStateRegistryUpdater
    isValidPayloadId(payloadId_);

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload to be updated.
finalAmounts_uint256[]is the amount to be updated. NOTE: amounts cannot be updated beyond user specified safe slippage limit.

updateWithdrawPayload

set the new payload body

set new message quorum

re-set previous message quorum to 0

if payload is processed at this stage then it is failing

function updateWithdrawPayload(
    uint256 payloadId_,
    bytes[] calldata txData_
)
    external
    virtual
    override
    onlyCoreStateRegistryUpdater
    isValidPayloadId(payloadId_);

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload to be updated.
txData_bytes[]is the transaction data to be updated.

processPayload

validate payload update

set the new payload body

set new message quorum

re-set previous message quorum to 0

define the payload status as updated

function processPayload(uint256 payloadId_)
    external
    payable
    virtual
    override
    onlyCoreStateRegistryProcessor
    isValidPayloadId(payloadId_);

proposeRescueFailedDeposits

sets status as processed to prevent re-entrancy

mint superPositions for successful deposits or remint for failed withdraws

for initial payload processing

function proposeRescueFailedDeposits(
    uint256 payloadId_,
    uint256[] memory proposedAmounts_
)
    external
    override
    onlyCoreStateRegistryRescuer;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload.
proposedAmounts_uint256[]is the array of proposed rescue amounts.

disputeRescueFailedDeposits

should challenge within the delay window configured on SuperRegistry

allows refund receivers to challenge their final receiving token amounts on failed deposits

function disputeRescueFailedDeposits(uint256 payloadId_) external override;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload

finalizeRescueFailedDeposits

is an open function & can be executed by anyone

the msg sender should be the refund address (or) the disputer

the timelock is already elapsed to dispute

just can reset last proposed time here, since amounts should be updated again to pass the lastProposedTimestamp zero check in finalize

function finalizeRescueFailedDeposits(uint256 payloadId_) external override;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload

getFailedDeposits

the timelock is elapsed

deleted to prevent re-entrancy

refunds the amount to user specified refund address

function getFailedDeposits(uint256 payloadId_)
    external
    view
    override
    returns (uint256[] memory superformIds, uint256[] memory amounts);

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload.

Returns

NameTypeDescription
superformIdsuint256[]superformIds_ is the identifiers of superforms in the payloadId that got failed.
amountsuint256[]

_hasRole

returns if an address has a specific role

function _hasRole(bytes32 id_, address addressToCheck_) internal view returns (bool);

_getStateSyncer

returns the state syncer address for id

function _getStateSyncer(uint8 id_) internal view returns (address stateSyncer);

_getStateRegistryId

returns the registry address for id

function _getStateRegistryId(address registryAddress_) internal view returns (uint8 id);

_getAddress

returns the address from super registry

function _getAddress(bytes32 id_) internal view returns (address);

_getDelay

returns the current timelock delay

function _getDelay() internal view returns (uint256);

_getSuperRBAC

returns the superRBAC address

function _getSuperRBAC() internal view returns (address);

_getRequiredMessagingQuorum

returns the required quorum for the src chain id from super registry

function _getRequiredMessagingQuorum(uint64 chainId_) internal view returns (uint256);

Parameters

NameTypeDescription
chainId_uint64is the src chain id

Returns

NameTypeDescription
<none>uint256the quorum configured for the chain id

_getBridgeValidator

returns the required quorum for the src chain id from super registry

function _getBridgeValidator(uint8 bridgeId_) internal view returns (IBridgeValidator validator);

Parameters

NameTypeDescription
bridgeId_uint8is the bridge id

Returns

NameTypeDescription
validatorIBridgeValidatoris the address of the validator contract

_retrievePayloadHeaderAndBody

retrieves information associated with the payload and validates quorum

function _retrievePayloadHeaderAndBody(uint256 payloadId_)
    internal
    view
    returns (
        uint256 payloadHeader_,
        bytes memory payloadBody_,
        AMBMessage memory message,
        bytes32 payloadProof,
        uint8 txType,
        uint8 callbackType,
        uint8 isMulti,
        uint8 registryId,
        address srcSender,
        uint64 srcChainId
    );

Parameters

NameTypeDescription
payloadId_uint256is the payload id

Returns

NameTypeDescription
payloadHeader_uint256is the payload header
payloadBody_bytesis the payload body
messageAMBMessageis the AMBMessage struct
payloadProofbytes32is the payload proof
txTypeuint8is the transaction type
callbackTypeuint8is the callback type
isMultiuint8is the multi flag
registryIduint8is the registry id
srcSenderaddressis the source sender
srcChainIduint64is the source chain id

_updateMultiVaultDepositPayload

helper function to update multi vault deposit payload

function _updateMultiVaultDepositPayload(
    uint256 payloadId_,
    bytes memory prevPayloadBody_,
    uint256[] calldata finalAmounts_
)
    internal
    returns (bytes memory newPayloadBody_, PayloadState finalState_);

_updateSingleVaultDepositPayload

compare number of vaults to update with provided finalAmounts length

validate payload update

helper function to update single vault deposit payload

function _updateSingleVaultDepositPayload(
    uint256 payloadId_,
    bytes memory prevPayloadBody_,
    uint256 finalAmount_
)
    internal
    returns (bytes memory newPayloadBody_, PayloadState finalState_);

_updateWithdrawPayload

validate payload update

sets amount to zero and will mark the payload as UPDATED

sets amount to zero and will mark the payload as PROCESSED

helper function to update multi vault withdraw payload

function _updateWithdrawPayload(
    bytes memory prevPayloadBody_,
    address srcSender_,
    uint64 srcChainId_,
    bytes[] calldata txData_,
    uint8 multi
)
    internal
    view
    returns (bytes memory);

_validateAndUpdateTxData

validates the incoming update data

function _validateAndUpdateTxData(
    bytes[] calldata txData_,
    InitMultiVaultData memory multiVaultData_,
    address srcSender_,
    uint64 srcChainId_,
    uint64 dstChainId_
)
    internal
    view
    returns (InitMultiVaultData memory);

_processMultiWithdrawal

function _processMultiWithdrawal(
    uint256 payloadId_,
    bytes memory payload_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    returns (bytes memory);

_processMultiDeposit

it is critical to validate that the action is being performed to the correct chainId coming from the superform

Store destination payloadId_ & index in extraFormData (tbd: 1-step flow doesnt need this)

marks the indexes that don't require a callback re-mint of shares (successful withdraws)

detect if there is at least one failed withdraw

if at least one error happens, the shares will be re-minted for the affected superformIds

function _processMultiDeposit(
    uint256 payloadId_,
    bytes memory payload_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    returns (bytes memory);

_processSingleWithdrawal

dstAmounts has same size of the number of vaults. If a given deposit fails, we are minting 0 SPs back on source (slight gas waste)

it is critical to validate that the action is being performed to the correct chainId coming from the superform

marks the indexes that require a callback mint of shares (successful)

cleaning unused approval

if any deposit fails, we mark errors as true and add it to failedDepositSuperformIds mapping for future rescuing

issue superPositions if at least one vault deposit passed

function _processSingleWithdrawal(
    uint256 payloadId_,
    bytes memory payload_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    returns (bytes memory);

_processSingleDeposit

Withdraw from superform https://solidity-by-example.org/try-catch/

function _processSingleDeposit(
    uint256 payloadId_,
    bytes memory payload_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    returns (bytes memory);

_processAcknowledgement

deposit to superform

cleaning unused approval

if any deposit fails, add it to failedDepositSuperformIds mapping for future rescuing

function _processAcknowledgement(
    uint256 payloadId_,
    bytes32 proof_,
    uint64 srcChainId_,
    bytes memory returnMessage_
)
    internal;

_constructMultiReturnData

depositSync and withdrawSync internal method for sending message back to the source chain

if deposits succeeded or some withdrawal failed, dispatch a callback

function _constructMultiReturnData(
    address srcSender_,
    uint256 payloadId_,
    uint8 superformRouterId_,
    TransactionType txType,
    CallbackType returnType_,
    uint256[] memory superformIds_,
    uint256[] memory amounts_
)
    internal
    view
    returns (bytes memory);

_constructSingleReturnData

depositSync and withdrawSync internal method for sending message back to the source chain

Send Data to Source to issue superform positions (failed withdraws and successful deposits)

function _constructSingleReturnData(
    address srcSender_,
    uint256 payloadId_,
    uint8 superformRouterId_,
    TransactionType txType,
    CallbackType returnType_,
    uint256 superformId_,
    uint256 amount_
)
    internal
    view
    returns (bytes memory);

_dispatchAcknowledgement

Send Data to Source to issue superform positions (failed withdraws and successful deposits)

calls the appropriate dispatch function according to the ackExtraData the keeper fed initially

function _dispatchAcknowledgement(uint64 dstChainId_, uint8[] memory ambIds_, bytes memory message_) internal;

TimelockStateRegistry

Git Source

Inherits: BaseStateRegistry, ITimelockStateRegistry, ReentrancyGuard

Author: Zeropoint Labs

handles communication in two stepped forms

State Variables

WITHDRAW_COOLDOWN_PERIOD

bytes32 immutable WITHDRAW_COOLDOWN_PERIOD = keccak256(abi.encodeWithSignature("WITHDRAW_COOLDOWN_PERIOD()"));

timelockPayloadCounter

tracks the total time lock payloads

uint256 public timelockPayloadCounter;

timelockPayload

stores the timelock payloads

mapping(uint256 timelockPayloadId => TimelockPayload) public timelockPayload;

Functions

onlyTimelockStateRegistryProcessor

modifier onlyTimelockStateRegistryProcessor();

onlySender

modifier onlySender() override;

onlyForm

allows only form to write to the receive paylod

modifier onlyForm(uint256 superformId);

isValidPayloadId

modifier isValidPayloadId(uint256 payloadId_);

constructor

constructor(ISuperRegistry superRegistry_) BaseStateRegistry(superRegistry_);

receivePayload

Receives request (payload) from two steps form to process later

function receivePayload(
    uint8 type_,
    address srcSender_,
    uint64 srcChainId_,
    uint256 lockedTill_,
    InitSingleVaultData memory data_
)
    external
    override
    onlyForm(data_.superformId);

Parameters

NameTypeDescription
type_uint8is the nature of transaction (xChain: 1 or same chain: 0)
srcSender_addressis the address of the source chain caller
srcChainId_uint64is the chainId of the source chain
lockedTill_uint256is the deadline for timelock (after which we can call finalizePayload)
data_InitSingleVaultDatais the basic information of superformId, amount to withdraw of type InitSingleVaultData

finalizePayload

Form Keeper finalizes payload to process two steps withdraw fully

function finalizePayload(
    uint256 timeLockPayloadId_,
    bytes memory txData_
)
    external
    payable
    override
    onlyTimelockStateRegistryProcessor
    nonReentrant;

Parameters

NameTypeDescription
timeLockPayloadId_uint256
txData_bytesis the off-chain generated transaction data

processPayload

set status here to prevent re-entrancy

this step is used to re-feed txData to avoid using old txData that would have expired by now

validate the incoming tx data

dispatch acknowledgement to mint superPositions back because of failure

for direct chain, superPositions are minted directly

restoring state for gas saving

function processPayload(uint256 payloadId_)
    external
    payable
    virtual
    override
    onlyTimelockStateRegistryProcessor
    isValidPayloadId(payloadId_);

_getRequiredMessagingQuorum

sets status as processed to prevent re-entrancy

validates quorum

returns the required quorum for the src chain id from super registry

function _getRequiredMessagingQuorum(uint64 chainId) internal view returns (uint256);

Parameters

NameTypeDescription
chainIduint64is the src chain id

Returns

NameTypeDescription
<none>uint256the quorum configured for the chain id

getTimelockPayload

allows users to read the timeLockPayload_ stored per payloadId_

function getTimelockPayload(uint256 payloadId_) external view returns (TimelockPayload memory timelockPayload_);

Parameters

NameTypeDescription
payloadId_uint256is the unqiue payload identifier allocated on the destination chain

Returns

NameTypeDescription
timelockPayload_TimelockPayloadtimeLockPayload_ the timelock payload stored

_getDeliveryAMB

allows users to read the ids of ambs that delivered a payload

function _getDeliveryAMB(uint256 payloadId_) internal view returns (uint8[] memory ambIds_);

_constructSingleReturnData

CoreStateRegistry-like function for build message back to the source. In regular flow called after xChainWithdraw succeds.

Constructs return message in case of a FAILURE to perform redemption of already unlocked assets

function _constructSingleReturnData(
    address srcSender_,
    InitSingleVaultData memory singleVaultData_
)
    internal
    view
    returns (bytes memory returnMessage);

_dispatchAcknowledgement

Send Data to Source to issue superform positions.

In regular flow, BaseStateRegistry function for messaging back to the source

Use constructed earlier return message to send acknowledgment (msg) back to the source

function _dispatchAcknowledgement(uint64 dstChainId_, uint8[] memory ambIds_, bytes memory message_) internal;

Contents

PayloadHelper

Git Source

Inherits: IPayloadHelper

Author: ZeroPoint Labs

helps decode payload data more easily. Used for off-chain purposes

State Variables

superRegistry

ISuperRegistry public immutable superRegistry;

Functions

constructor

constructor(address superRegistry_);

decodeCoreStateRegistryPayload

reads the payload from the core state registry and decodes it in a more detailed manner.

function decodeCoreStateRegistryPayload(uint256 dstPayloadId_)
    external
    view
    override
    returns (
        uint8 txType,
        uint8 callbackType,
        address srcSender,
        uint64 srcChainId,
        uint256[] memory amounts,
        uint256[] memory slippage,
        uint256[] memory superformIds,
        uint256 srcPayloadId,
        uint8 superformRouterId
    );

Parameters

NameTypeDescription
dstPayloadId_uint256is the unique identifier of the payload received in dst core state registry

Returns

NameTypeDescription
txTypeuint8is the type of transaction. check {TransactionType} enum in DataTypes.sol
callbackTypeuint8is the type of payload. check {CallbackType} enum in DataTypes.sol
srcSenderaddressis the user who initiated the transaction on the srcChain
srcChainIduint64is the unique identifier of the srcChain
amountsuint256[]is the amount to deposit/withdraw
slippageuint256[]is the max slippage configured by the user (only for deposits)
superformIdsuint256[]is the unique identifiers of the superforms
srcPayloadIduint256is the identifier of the corresponding payload on srcChain
superformRouterIduint8is the identifier of the superform router

decodeCoreStateRegistryPayloadLiqData

reads the payload from the core state registry and decodes liqData for it (to be used in withdraw cases)

function decodeCoreStateRegistryPayloadLiqData(uint256 dstPayloadId_)
    external
    view
    override
    returns (
        uint8[] memory bridgeIds,
        bytes[] memory txDatas,
        address[] memory tokens,
        uint64[] memory liqDstChainIds,
        uint256[] memory amountsIn,
        uint256[] memory amountsOut,
        uint256[] memory nativeAmounts,
        bool[] memory hasDstSwaps,
        address dstRefundAddress
    );

Parameters

NameTypeDescription
dstPayloadId_uint256is the unique identifier of the payload received in dst core state registry

Returns

NameTypeDescription
bridgeIdsuint8[]is the ids of the bridges to be used
txDatasbytes[]is the array of txData to be sent to the bridges
tokensaddress[]is the tokens to be used in the liqData
liqDstChainIdsuint64[]are the final destination chain id for the underlying token (can be arbitrary on withdraws)
amountsInuint256[]are the from amounts to the liquidity bridge
amountsOutuint256[]are the minimum amounts to be bridged through the liquidity bridge
nativeAmountsuint256[]is the native amounts to be used in the liqData
hasDstSwapsbool[]is the array of flags indicating if the original liqData has a dstSwaps
dstRefundAddressaddressis the address to be used for refunds

decodeStateSyncerPayloadHistory

reads the payload header from a state syncer and decodes it.

function decodeStateSyncerPayloadHistory(
    uint256 srcPayloadId_,
    uint8 superformRouterId_
)
    external
    view
    override
    returns (uint8 txType, uint8 callbackType, uint8 multi, address srcSender, uint64 srcChainId);

Parameters

NameTypeDescription
srcPayloadId_uint256is the unique identifier of the payload allocated by super router
superformRouterId_uint8is the unique identifier of the superform router

Returns

NameTypeDescription
txTypeuint8is the type of transaction. check {TransactionType} enum in DataTypes.sol
callbackTypeuint8is the type of payload. check {CallbackType} enum in DataTypes.sol
multiuint8isMulti indicates if the transaction involves operations to multiple vaults
srcSenderaddressis the user who initiated the transaction on the srcChain
srcChainIduint64is the unique identifier of the srcChain

decodeTimeLockPayload

returns decoded two step form payloads

function decodeTimeLockPayload(uint256 timelockPayloadId_)
    external
    view
    override
    returns (address srcSender, uint64 srcChainId, uint256 srcPayloadId, uint256 superformId, uint256 amount);

Parameters

NameTypeDescription
timelockPayloadId_uint256is the unique identifier of payload in two step registry

decodeTimeLockFailedPayload

function decodeTimeLockFailedPayload(uint256 timelockPayloadId_)
    external
    view
    override
    returns (address srcSender, uint64 srcChainId, uint256 srcPayloadId, uint256 superformId, uint256 amount);

Structs

DecodeDstPayloadInternalVars

struct DecodeDstPayloadInternalVars {
    uint8 txType;
    uint8 callbackType;
    address srcSender;
    uint64 srcChainId;
    uint256[] amounts;
    uint256[] slippage;
    uint256[] superformIds;
    uint256 srcPayloadId;
    uint8 superformRouterId;
    uint8 multi;
    ReturnMultiData rd;
    ReturnSingleData rsd;
    InitMultiVaultData imvd;
    InitSingleVaultData isvd;
}

DecodeDstPayloadLiqDataInternalVars

struct DecodeDstPayloadLiqDataInternalVars {
    uint8 callbackType;
    uint8 multi;
    uint8[] bridgeIds;
    bytes[] txDatas;
    address[] liqDataTokens;
    uint64[] liqDataChainIds;
    uint256[] liqDataAmountsIn;
    uint256[] liqDataAmountsOut;
    uint256[] liqDataNativeAmounts;
    bool[] hasDstSwaps;
    address dstRefundAddress;
    InitMultiVaultData imvd;
    InitSingleVaultData isvd;
    uint256 i;
}

QuorumManager

Git Source

Inherits: IQuorumManager

Author: ZeroPoint Labs

separates quorum management concerns into an abstract contract. Can be re-used (currently used by superRegistry) to set different quorums per amb in different areas of the protocol

State Variables

requiredQuorum

mapping(uint64 srcChainId => uint256 quorum) internal requiredQuorum;

Functions

setRequiredMessagingQuorum

quorum is the number of extra ambs a message proof must go through and be validated

allows inheriting contracts to set the messaging quorum for a specific sender chain

function setRequiredMessagingQuorum(uint64 srcChainId_, uint256 quorum_) external virtual;

Parameters

NameTypeDescription
srcChainId_uint64is the chain id from which the message (payload) is sent
quorum_uint256the minimum number of message bridges required for processing NOTE: overriding child contracts should handle the sender validation & setting of message quorum

getRequiredMessagingQuorum

returns the required quorum for the srcChain & dstChain

function getRequiredMessagingQuorum(uint64 srcChainId_) public view returns (uint256 quorum_);

Parameters

NameTypeDescription
srcChainId_uint64is the chain id from which the message (payload) is sent

Returns

NameTypeDescription
quorum_uint256the minimum number of message bridges required for processing

BaseStateRegistry

Git Source

Inherits: IBaseStateRegistry

Author: Zeropoint Labs

contract module that allows inheriting contracts to implement crosschain messaging & processing mechanisms.

This is a lightweight version that allows only dispatching and receiving crosschain

payloads (messages). Inheriting children contracts have the flexibility to define their own processing mechanisms.

State Variables

superRegistry

ISuperRegistry public immutable superRegistry;

CHAIN_ID

uint64 public immutable CHAIN_ID;

payloadsCount

uint256 public payloadsCount;

payloadBody

stores received payload after assigning them an unique identifier upon receiving

mapping(uint256 => bytes) public payloadBody;

payloadHeader

stores received payload's header (txInfo)

mapping(uint256 => uint256) public payloadHeader;

messageQuorum

stores a proof's quorum

mapping(bytes32 => uint256) public messageQuorum;

payloadTracking

maps payloads to their current status

mapping(uint256 => PayloadState) public payloadTracking;

msgAMB

maps payloads to the amb ids that delivered them

mapping(uint256 => uint8) public msgAMB;

proofAMB

maps payloads to the amb ids that delivered them

mapping(bytes32 => uint8[]) internal proofAMB;

Functions

onlySender

inheriting contracts should override this function (else not safe)

sender varies based on functionality

modifier onlySender() virtual;

constructor

constructor(ISuperRegistry superRegistry_);

receive

receive() external payable;

dispatchPayload

allows core contracts to send payload to a destination chain.

function dispatchPayload(
    address srcSender_,
    uint8[] memory ambIds_,
    uint64 dstChainId_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    payable
    override
    onlySender;

Parameters

NameTypeDescription
srcSender_addressis the caller of the function (used for gas refunds).
ambIds_uint8[]is the identifier of the arbitrary message bridge to be used
dstChainId_uint64is the internal chainId used throughtout the protocol
message_bytesis the crosschain payload to be sent
extraData_bytesdefines all the message bridge realted overrides NOTE: dstChainId_ is mapped to message bridge's destination id inside it's implementation contract NOTE: ambIds_ are superform assigned unique identifier for arbitrary message bridges

receivePayload

allows state registry to receive messages from message bridge implementations

function receivePayload(uint64 srcChainId_, bytes memory message_) external override;

Parameters

NameTypeDescription
srcChainId_uint64is the superform chainId from which the payload is dispatched/sent
message_bytesis the crosschain payload received NOTE: Only {IMPLEMENTATION_CONTRACT} role can call this function.

processPayload

proofHash will always be 32 bytes length due to keccak256

if message, store header and body of it

function processPayload(uint256 payloadId_) external payable virtual override;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload NOTE: Only {CORE_STATE_REGISTRY_PROCESSOR_ROLE} role can call this function NOTE: this should handle reverting the state on source chain in-case of failure (or) can implement scenario based reverting like in coreStateRegistry

getProofAMB

allows users to read the amb that delivered the proof

function getProofAMB(bytes32 proof_) external view override returns (uint8[] memory);

Parameters

NameTypeDescription
proof_bytes32is the bytes32 proof

Returns

NameTypeDescription
<none>uint8[]ambIds_ is the identifier of ambs that delivered the proof

_getAmbId

returns the amb id for address

function _getAmbId(address amb_) internal view returns (uint8 ambId);

_getAmbAddress

returns the amb id for address

function _getAmbAddress(uint8 id_) internal view returns (address amb);

_dispatchPayload

dispatches the payload(message_) through individual message bridge implementations

function _dispatchPayload(
    address srcSender_,
    uint8 ambId_,
    uint64 dstChainId_,
    uint256 gasToPay_,
    bytes memory message_,
    bytes memory overrideData_
)
    internal;

_dispatchProof

revert if an unknown amb id is used

dispatches the proof(hash of the message_) through individual message bridge implementations

function _dispatchProof(
    address srcSender_,
    uint8[] memory ambIds_,
    uint64 dstChainId_,
    uint256[] memory gasToPay_,
    bytes memory message_,
    bytes[] memory overrideData_
)
    internal;

Target

Git Source

Functions

stateSyncBroadcast

function stateSyncBroadcast(bytes memory data_) external;

BroadcastRegistry

Git Source

Inherits: IBroadcastRegistry, QuorumManager

Author: ZeroPoint Labs

helps core contract communicate with multiple dst chains through supported AMBs

State Variables

superRegistry

ISuperRegistry public superRegistry;

payloadsCount

uint256 public payloadsCount;

messageQuorum

stores the message quorum

mapping(bytes32 => uint256) public messageQuorum;

payload

stores the received payload after assigning

mapping(uint256 => bytes) public payload;

srcChainId

stores the src chain of every payload

mapping(uint256 => uint64) public srcChainId;

payloadTracking

stores the status of the received payload

mapping(uint256 => PayloadState) public payloadTracking;

Functions

constructor

set up admin during deployment.

constructor(ISuperRegistry superRegistry_);

onlySender

sender should be a valid configured contract

should be factory or roles contract

modifier onlySender();

onlyProtocolAdmin

modifier onlyProtocolAdmin();

onlyProcessor

modifier onlyProcessor();

setRequiredMessagingQuorum

function setRequiredMessagingQuorum(uint64 srcChainId_, uint256 quorum_) external override onlyProtocolAdmin;

broadcastPayload

allows core contracts to send payload to all configured destination chain.

function broadcastPayload(
    address srcSender_,
    uint8[] memory ambIds_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    payable
    override
    onlySender;

Parameters

NameTypeDescription
srcSender_addressis the caller of the function (used for gas refunds).
ambIds_uint8[]is the identifier of the arbitrary message bridge to be used
message_bytesis the crosschain payload to be broadcasted
extraData_bytesdefines all the message bridge realted overrides

receiveBroadcastPayload

allows ambs to write broadcasted payloads

function receiveBroadcastPayload(uint64 srcChainId_, bytes memory message_) external override;

processPayload

allows previlaged actors to process broadcasted payloads

function processPayload(uint256 payloadId) external override onlyProcessor;

Parameters

NameTypeDescription
payloadIduint256

_broadcastPayload

The number of valid proofs (quorum) must be equal to the required messaging quorum

broadcasts the payload(message_) through individual message bridge implementations

function _broadcastPayload(
    address srcSender_,
    uint8 ambId_,
    uint256 gasToPay_,
    bytes memory message_,
    bytes memory extraData_
)
    internal;

_broadcastProof

reverts if an unknown amb id is used

broadcasts the proof(hash of the message_) through individual message bridge implementations

function _broadcastProof(
    address srcSender_,
    uint8[] memory ambIds_,
    uint256[] memory gasToPay_,
    bytes memory message_,
    bytes[] memory extraData_
)
    internal;

Contents

Contents

LiFiValidator

Git Source

Inherits: BridgeValidator, LiFiTxDataExtractor

Author: Zeropoint Labs

To assert input txData is valid

Functions

constructor

constructor(address superRegistry_) BridgeValidator(superRegistry_);

validateLiqDstChainId

function validateLiqDstChainId(bytes calldata txData_, uint64 liqDstChainId_) external pure override returns (bool);

validateReceiver

function validateReceiver(bytes calldata txData_, address receiver_) external pure override returns (bool valid_);

validateTxData

function validateTxData(ValidateTxDataArgs calldata args_) external view override;

decodeMinAmountOut

xchain actions can have bridgeData or bridgeData + swapData

direct actions with deposit, cannot have bridge data - goes into catch block

withdraw actions may have bridge data after withdrawing - goes into try block

withdraw actions without bridge data (just swap) - goes into catch block

0. Destination call validation

1. chainId validation

for deposits, liqDstChainId/toChainId will be the normal destination (where the target superform is)

for withdraws, liqDstChainId/toChainId will be the desired chain to where the underlying must be sent

to after vault redemption

2. receiver address validation

if cross chain deposits, then receiver address must be CoreStateRegistry (or) Dst Swapper

if withdraws, then receiver address must be the srcSender

remap of address 0 to NATIVE because of how LiFi produces txData

3. token validations

1. chainId validation

2. receiver address validation

If same chain deposits then receiver address must be the superform

if withdraws, then receiver address must be the srcSender

remap of address 0 to NATIVE because of how LiFi produces txData

3. token validations

function decodeMinAmountOut(
    bytes calldata txData_,
    bool genericSwapDisallowed_
)
    external
    view
    override
    returns (uint256 amount_);

decodeAmountIn

try is just used here to validate the txData. We need to always extract minAmount from bridge data

in the case of a generic swap, minAmountOut is considered to be the receivedAmount

function decodeAmountIn(
    bytes calldata txData_,
    bool genericSwapDisallowed_
)
    external
    view
    override
    returns (uint256 amount_);

decodeDstSwap

if there isn't a source swap, amountIn is minAmountOut from bridge data?

in the case of a generic swap, amountIn is the from amount

function decodeDstSwap(bytes calldata txData_) external pure override returns (address token_, uint256 amount_);

extractMainParameters

Extracts the main parameters from the calldata

function extractMainParameters(bytes calldata data_)
    public
    pure
    returns (
        string memory bridge,
        address sendingAssetId,
        address receiver,
        uint256 amount,
        uint256 minAmount,
        uint256 destinationChainId,
        bool hasSourceSwaps,
        bool hasDestinationCall
    );

Parameters

NameTypeDescription
data_bytesThe calldata to extract the main parameters from

Returns

NameTypeDescription
bridgestringThe bridge extracted from the calldata
sendingAssetIdaddressThe sending asset id extracted from the calldata
receiveraddressThe receiver extracted from the calldata
amountuint256The amount the calldata (which may be equal to bridge min amount)
minAmountuint256The min amount extracted from the bridgeData calldata
destinationChainIduint256The destination chain id extracted from the calldata
hasSourceSwapsboolWhether the calldata has source swaps
hasDestinationCallboolWhether the calldata has a destination call

extractGenericSwapParameters

Extracts the generic swap parameters from the calldata

function extractGenericSwapParameters(bytes calldata data_)
    public
    pure
    returns (
        address sendingAssetId,
        uint256 amount,
        address receiver,
        address receivingAssetId,
        uint256 receivingAmount
    );

Parameters

NameTypeDescription
data_bytesThe calldata to extract the generic swap parameters from

Returns

NameTypeDescription
sendingAssetIdaddressThe sending asset id extracted from the calldata
amountuint256The amount extracted from the calldata
receiveraddressThe receiver extracted from the calldata
receivingAssetIdaddressThe receiving asset id extracted from the calldata
receivingAmountuint256The receiving amount extracted from the calldata

Contents

SocketValidator

Git Source

Inherits: BridgeValidator

Author: Zeropoint Labs

to assert input txData is valid

Functions

constructor

constructor(address superRegistry_) BridgeValidator(superRegistry_);

validateLiqDstChainId

function validateLiqDstChainId(bytes calldata txData_, uint64 liqDstChainId_) external pure override returns (bool);

validateReceiver

function validateReceiver(bytes calldata txData_, address receiver) external pure override returns (bool);

validateTxData

function validateTxData(ValidateTxDataArgs calldata args_) external view override;

decodeMinAmountOut

function decodeMinAmountOut(
    bytes calldata txData_,
    bool genericSwapDisallowed_
)
    external
    view
    override
    returns (uint256 amount_);

decodeAmountIn

function decodeAmountIn(
    bytes calldata txData_,
    bool genericSwapDisallowed_
)
    external
    view
    override
    returns (uint256 amount_);

decodeDstSwap

function decodeDstSwap(bytes calldata txData_) external pure override returns (address token_, uint256 amount_);

_decodeTxData

helps decode socket user request returns the user request

function _decodeTxData(bytes calldata txData_)
    internal
    pure
    returns (ISocketRegistry.SocketRequest memory socketRequest);

_parseCallData

helps parsing socket calldata and return the socket request

function _parseCallData(bytes calldata callData) internal pure returns (bytes memory);

BridgeValidator

Git Source

Inherits: IBridgeValidator

Author: Zeropoint Labs

To be inherited by specific bridge handlers to verify the calldata being sent

State Variables

superRegistry

ISuperRegistry public immutable superRegistry;

NATIVE

address constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

Functions

constructor

constructor(address superRegistry_);

validateLiqDstChainId

validates the destination chainId of the liquidity request

function validateLiqDstChainId(
    bytes calldata txData_,
    uint64 liqDstChainId_
)
    external
    pure
    virtual
    override
    returns (bool);

Parameters

NameTypeDescription
txData_bytesthe txData of the deposit
liqDstChainId_uint64the chainId of the destination chain for liquidity

validateReceiver

decoded txData and returns the receiver address

function validateReceiver(
    bytes calldata txData_,
    address receiver_
)
    external
    pure
    virtual
    override
    returns (bool valid_);

Parameters

NameTypeDescription
txData_bytesis the txData of the cross chain deposit
receiver_addressis the address of the receiver to validate

Returns

NameTypeDescription
valid_boolif the address is valid

validateTxData

validates the txData of a cross chain deposit

function validateTxData(ValidateTxDataArgs calldata args_) external view virtual override;

Parameters

NameTypeDescription
args_ValidateTxDataArgsthe txData arguments to validate in txData

decodeMinAmountOut

decodes the txData and returns the minimum amount expected to receive on the destination

function decodeMinAmountOut(
    bytes calldata txData_,
    bool genericSwapDisallowed_
)
    external
    view
    virtual
    override
    returns (uint256 amount_);

Parameters

NameTypeDescription
txData_bytesis the txData of the cross chain deposit
genericSwapDisallowed_booltrue if generic swaps are disallowed

Returns

NameTypeDescription
amount_uint256the amount expected

decodeAmountIn

decodes the txData and returns the amount of external token on source

function decodeAmountIn(
    bytes calldata txData_,
    bool genericSwapDisallowed_
)
    external
    view
    virtual
    override
    returns (uint256 amount_);

Parameters

NameTypeDescription
txData_bytesis the txData of the cross chain deposit
genericSwapDisallowed_booltrue if generic swaps are disallowed

Returns

NameTypeDescription
amount_uint256the amount expected

decodeDstSwap

decodes the amount in from the txData that just involves a swap

function decodeDstSwap(bytes calldata txData_)
    external
    pure
    virtual
    override
    returns (address token_, uint256 amount_);

Parameters

NameTypeDescription
txData_bytesis the txData to be decoded

DstSwapper

Git Source

Inherits: IDstSwapper, ReentrancyGuard

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

handles all destination chain swaps.

State Variables

superRegistry

ISuperRegistry public immutable superRegistry;

CHAIN_ID

uint64 public immutable CHAIN_ID;

NATIVE

address constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

swappedAmount

mapping(uint256 payloadId => mapping(uint256 index => uint256 amount)) public swappedAmount;

Functions

onlySwapper

modifier onlySwapper();

onlyEmergencyAdmin

modifier onlyEmergencyAdmin();

constructor

constructor(address superRegistry_);

Parameters

NameTypeDescription
superRegistry_addressSuperform registry contract

receive

receive enables processing native token transfers into the smart contract.

liquidity bridge fails without a native receive function.

receive() external payable;

processTx

would interact with liquidity bridge contract to process multi-tx transactions and move the funds into destination contract.

function processTx(
    uint256 payloadId_,
    uint256 index_,
    uint8 bridgeId_,
    bytes calldata txData_
)
    public
    override
    onlySwapper
    nonReentrant;

Parameters

NameTypeDescription
payloadId_uint256represents the id of the payload
index_uint256represents the index of the superformid in the payload
bridgeId_uint8represents the id of liquidity bridge used
txData_bytesrepresents the transaction data generated by liquidity bridge API.

batchProcessTx

validates the bridge data

to enter the if-else case of the bridge validator loop

get the address of the bridge to send the txData to.

approve the bridge to spend the approvalToken_.

execute the txData_.

execute the txData_.

updates swapped amount

emits final event

function batchProcessTx(
    uint256 payloadId_,
    uint256[] calldata indices,
    uint8[] calldata bridgeIds_,
    bytes[] calldata txData_
)
    external
    override
    onlySwapper;

Parameters

NameTypeDescription
payloadId_uint256represents the array of payload ids used
indicesuint256[]
bridgeIds_uint8[]represents the array of ids of liquidity bridges used
txData_bytes[]

_getFormUnderlyingFrom

function _getFormUnderlyingFrom(uint256 payloadId_, uint256 index_) internal view returns (address underlying_);

emergencyWithdrawToken

EMERGENCY_ADMIN ONLY FUNCTION.

allows admin to withdraw lost tokens in the smart contract.

function emergencyWithdrawToken(address tokenContract_, uint256 amount_) external onlyEmergencyAdmin;

Parameters

NameTypeDescription
tokenContract_addressaddress of the token contract
amount_uint256amount of tokens to withdraw

emergencyWithdrawNativeToken

note: transfer the token from address of this contract note: to address of the user (executing the withdrawToken() function)

EMERGENCY_ADMIN ONLY FUNCTION.

allows admin to withdraw lost native tokens in the smart contract.

function emergencyWithdrawNativeToken(uint256 amount_) external onlyEmergencyAdmin;

Parameters

NameTypeDescription
amount_uint256amount of tokens to withdraw

Structs

ProcessTxVars

struct ProcessTxVars {
    address finalDst;
    address to;
    address underlying;
    uint256 expAmount;
}

LiquidityHandler

Git Source

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

bridges tokens from Chain A -> Chain B. To be inherited by contracts that move liquidity

State Variables

NATIVE

address constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

Functions

dispatchTokens

dispatches tokens via a liquidity bridge

function dispatchTokens(
    address bridge_,
    bytes memory txData_,
    address token_,
    uint256 amount_,
    uint256 nativeAmount_
)
    internal
    virtual;

Parameters

NameTypeDescription
bridge_addressBridge address to pass tokens to
txData_bytesliquidity bridge data
token_addressToken caller deposits into superform
amount_uint256Amount of tokens to deposit
nativeAmount_uint256msg.value or msg.value + native tokens

Contents

EmergencyQueue

Git Source

Inherits: IEmergencyQueue

Author: Zeropoint Labs

SPDX-License-Identifier: Apache-2.0

stores withdrawal requests when forms are paused

State Variables

CHAIN_ID

is the chain id

uint64 public immutable CHAIN_ID;

superRegistry

is the address of super registry

ISuperRegistry public immutable superRegistry;

queueCounter

is the count of actions queued

uint256 public queueCounter;

queuedWithdrawal

is the queue of pending actions

mapping(uint256 id => QueuedWithdrawal) public queuedWithdrawal;

Functions

onlySuperform

modifier onlySuperform(uint256 superformId_);

onlyEmergencyAdmin

modifier onlyEmergencyAdmin();

constructor

constructor(address superRegistry_);

Parameters

NameTypeDescription
superRegistry_addressthe superform registry contract

queueWithdrawal

called by paused forms to queue up withdrawals for exit

function queueWithdrawal(
    InitSingleVaultData memory data_,
    address srcSender_
)
    external
    override
    onlySuperform(data_.superformId);

Parameters

NameTypeDescription
data_InitSingleVaultDatais the single vault data passed by the user
srcSender_address

executeQueuedWithdrawal

alled by emergency admin to processed queued withdrawal

function executeQueuedWithdrawal(uint256 id_) public override onlyEmergencyAdmin;

Parameters

NameTypeDescription
id_uint256is the identifier of the queued action

batchExecuteQueuedWithdrawal

function batchExecuteQueuedWithdrawal(uint256[] memory ids_) external override onlyEmergencyAdmin;

queuedWithdrawalStatus

returns the execution status of an id in the emergency queue

function queuedWithdrawalStatus(uint256 id) external view override returns (bool);

Parameters

NameTypeDescription
iduint256is the identifier of the queued action

Returns

NameTypeDescription
<none>boolboolean representing the execution status

Contents

Contents

IERC4626Form

Git Source

Inherits: IERC20

Author: Zeropoint Labs

SPDX-License-Identifier: Apache-2.0

Functions

vaultSharesIsERC20

function vaultSharesIsERC20() external pure returns (bool);

vaultSharesIsERC4626

function vaultSharesIsERC4626() external pure returns (bool);

getVaultAsset

function getVaultAsset() external view returns (address);

getVaultName

function getVaultName() external view returns (string memory);

getVaultSymbol

function getVaultSymbol() external view returns (string memory);

getVaultDecimals

function getVaultDecimals() external view returns (uint256);

getPricePerVaultShare

function getPricePerVaultShare() external view returns (uint256);

getVaultShareBalance

function getVaultShareBalance() external view returns (uint256);

getTotalAssets

function getTotalAssets() external view returns (uint256);

getPreviewPricePerVaultShare

function getPreviewPricePerVaultShare() external view returns (uint256);

previewDepositTo

function previewDepositTo(uint256 assets_) external view returns (uint256);

previewWithdrawFrom

function previewWithdrawFrom(uint256 assets_) external view returns (uint256);

previewRedeemFrom

function previewRedeemFrom(uint256 shares_) external view returns (uint256);

IERC4626TimelockForm

Git Source

Inherits: IERC4626Form

Author: Zeropoint Labs

SPDX-License-Identifier: Apache-2.0

Interface used by ERC4626TimelockForm. Required by TwostepsFormStateRegistry to call processUnlock() function

Functions

withdrawAfterCoolDown

Process unlock request

function withdrawAfterCoolDown(uint256 amount_, TimelockPayload memory p_) external;

unlockId

function unlockId(uint256 unlockCounter_) external view returns (InitSingleVaultData memory singleVaultData);

ERC4626Form

Git Source

Inherits: ERC4626FormImplementation

The Form implementation for IERC4626 vaults

Functions

constructor

constructor(address superRegistry_) ERC4626FormImplementation(superRegistry_, 1);

_directDepositIntoVault

Deposits underlying tokens into a vault

function _directDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address
)
    internal
    override
    returns (uint256 dstAmount);

_directWithdrawFromVault

Withdraws underlying tokens from a vault

function _directWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    internal
    override
    returns (uint256 dstAmount);

_xChainDepositIntoVault

Deposits underlying tokens into a vault

function _xChainDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address,
    uint64 srcChainId_
)
    internal
    override
    returns (uint256 dstAmount);

_xChainWithdrawFromVault

Withdraws underlying tokens from a vault

function _xChainWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    override
    returns (uint256 dstAmount);

_emergencyWithdraw

withdraws vault shares from form during emergency

function _emergencyWithdraw(address refundAddress_, uint256 amount_) internal override;

ERC4626FormImplementation

Git Source

Inherits: BaseForm, LiquidityHandler

Has common internal functions that can be re-used by actual form implementations

State Variables

STATE_REGISTRY_ID

uint256 internal immutable STATE_REGISTRY_ID;

Functions

constructor

constructor(address superRegistry_, uint256 stateRegistryId_) BaseForm(superRegistry_);

getVaultAsset

function getVaultAsset() public view virtual override returns (address);

getVaultName

function getVaultName() public view virtual override returns (string memory);

getVaultSymbol

function getVaultSymbol() public view virtual override returns (string memory);

getVaultDecimals

function getVaultDecimals() public view virtual override returns (uint256);

getPricePerVaultShare

function getPricePerVaultShare() public view virtual override returns (uint256);

getVaultShareBalance

function getVaultShareBalance() public view virtual override returns (uint256);

getTotalAssets

function getTotalAssets() public view virtual override returns (uint256);

getPreviewPricePerVaultShare

function getPreviewPricePerVaultShare() public view virtual override returns (uint256);

previewDepositTo

function previewDepositTo(uint256 assets_) public view virtual override returns (uint256);

previewWithdrawFrom

function previewWithdrawFrom(uint256 assets_) public view virtual override returns (uint256);

previewRedeemFrom

function previewRedeemFrom(uint256 shares_) public view virtual override returns (uint256);

_processDirectDeposit

function _processDirectDeposit(InitSingleVaultData memory singleVaultData_) internal returns (uint256 dstAmount);

_processDirectWithdraw

function _processDirectWithdraw(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    internal
    returns (uint256 dstAmount);

_processXChainDeposit

if there is no txData, on withdraws the receiver is the original beneficiary (srcSender_), otherwise it is this contract (before swap)

the token we are swapping from to our desired output token (if there is txData), must be the same as the vault asset

redeem the underlying

the amount inscribed in liqData must be less or equal than the amount redeemed from the vault

validate and perform the swap to desired output token and send to beneficiary

function _processXChainDeposit(
    InitSingleVaultData memory singleVaultData_,
    uint64 srcChainId_
)
    internal
    returns (uint256 dstAmount);

_processXChainWithdraw

function _processXChainWithdraw(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    returns (uint256 dstAmount);

_processEmergencyWithdraw

a case where the withdraw req liqData has a valid token and tx data is not updated by the keeper

if there is no txData, on withdraws the receiver is the original beneficiary (srcSender_), otherwise it is this contract (before swap)

the token we are swapping from to our desired output token (if there is txData), must be the same as the vault asset

redeem vault positions (we operate only on positions, not assets)

the amount inscribed in liqData must be less or equal than the amount redeemed from the vault

validate and perform the swap to desired output token and send to beneficiary

function _processEmergencyWithdraw(address refundAddress_, uint256 amount_) internal;

superformYieldTokenName

function superformYieldTokenName() external view virtual override returns (string memory);

superformYieldTokenSymbol

function superformYieldTokenSymbol() external view virtual override returns (string memory);

getStateRegistryId

function getStateRegistryId() external view override returns (uint256);

_vaultSharesAmountToUnderlyingAmount

Converts a vault share amount into an equivalent underlying asset amount

function _vaultSharesAmountToUnderlyingAmount(
    uint256 vaultSharesAmount_,
    uint256
)
    internal
    view
    virtual
    override
    returns (uint256);

_vaultSharesAmountToUnderlyingAmountRoundingUp

Converts a vault share amount into an equivalent underlying asset amount, rounding up

function _vaultSharesAmountToUnderlyingAmountRoundingUp(
    uint256 vaultSharesAmount_,
    uint256
)
    internal
    view
    virtual
    override
    returns (uint256);

_underlyingAmountToVaultSharesAmount

Converts an underlying asset amount into an equivalent vault shares amount

function _underlyingAmountToVaultSharesAmount(
    uint256 underlyingAmount_,
    uint256
)
    internal
    view
    virtual
    override
    returns (uint256);

Structs

directDepositLocalVars

to avoid stack too deep errors

struct directDepositLocalVars {
    uint64 chainId;
    address collateral;
    address bridgeValidator;
    uint256 dstAmount;
    uint256 balanceBefore;
    uint256 balanceAfter;
    uint256 nonce;
    uint256 deadline;
    uint256 inputAmount;
    bytes signature;
}

ProcessDirectWithdawLocalVars

this is only valid if token == collateral (no txData)

handles the collateral token transfers.

transfers input token, which is the same as vault asset, to the form

non empty txData means there is a swap needed before depositing (input asset not the same as vault asset)

checks the allowance before transfer from router

transfers input token, which is different from the vault asset, to the form

the balance of vault tokens, ready to be deposited is compared with the previous balance

notice the inscribed singleVaultData_.amount is deposited regardless if txData exists or not

this is always the estimated value post any swaps (if they exist)

the balance check above implies that a certain dust may be left in the superform after depositing

the vault asset (collateral) is approved and deposited to the vault

struct ProcessDirectWithdawLocalVars {
    uint64 chainId;
    address collateral;
    address receiver;
    address bridgeValidator;
    uint256 len1;
    uint256 amount;
    IERC4626 v;
}

xChainWithdrawLocalVars

pulling from sender, to auto-send tokens back in case of failed deposits / reverts

allowance is modified inside of the IERC20.transferFrom() call

This makes ERC4626Form (address(this)) owner of v.shares

struct xChainWithdrawLocalVars {
    uint64 dstChainId;
    address receiver;
    address collateral;
    address bridgeValidator;
    uint256 balanceBefore;
    uint256 balanceAfter;
    uint256 amount;
}

ERC4626KYCDaoForm

Git Source

Inherits: ERC4626FormImplementation

The Form implementation for IERC4626 vaults with kycDAO NFT checks

This form must hold a kycDAO NFT to operate

Functions

constructor

constructor(address superRegistry_) ERC4626FormImplementation(superRegistry_, 1);

_kycCheck

this function calls the kycDAO vault kycCheck function to verify if the beneficiary holds a kycDAO token

note that this form must also be a holder of a kycDAO NFT

function _kycCheck(address srcSender_) internal view;

_directDepositIntoVault

Deposits underlying tokens into a vault

function _directDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    internal
    override
    returns (uint256 dstAmount);

_directWithdrawFromVault

Withdraws underlying tokens from a vault

function _directWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    internal
    override
    returns (uint256 dstAmount);

_xChainDepositIntoVault

function _xChainDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    override
    returns (uint256 dstAmount);

_xChainWithdrawFromVault

Withdraws underlying tokens from a vault

function _xChainWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    override
    returns (uint256 dstAmount);

_emergencyWithdraw

withdraws vault shares from form during emergency

function _emergencyWithdraw(address refundAddress_, uint256 amount_) internal override;

Errors

NO_VALID_KYC_TOKEN

error thrown when the sender doesn't the KYCDAO

error NO_VALID_KYC_TOKEN();

ERC4626TimelockForm

Git Source

Inherits: ERC4626FormImplementation

Form implementation to handle timelock extension for ERC4626 vaults

Functions

onlyTwoStepStateRegistry

modifier onlyTwoStepStateRegistry();

constructor

constructor(address superRegistry_) ERC4626FormImplementation(superRegistry_, 2);

withdrawAfterCoolDown

this function is called when the timelock deposit is ready to be withdrawn after being unlocked

function withdrawAfterCoolDown(
    uint256 amount_,
    TimelockPayload memory p_
)
    external
    onlyTwoStepStateRegistry
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
amount_uint256the amount of tokens to withdraw
p_TimelockPayloadthe payload data

_directDepositIntoVault

a case where the withdraw req liqData has a valid token and tx data is not updated by the keeper

if the txData is empty, the tokens are sent directly to the sender, otherwise sent first to this form

validate and dispatches the tokens

the amount inscribed in liqData must be less or equal than the amount redeemed from the vault

validate and perform the swap to desired output token and send to beneficiary

function _directDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address
)
    internal
    virtual
    override
    returns (uint256 dstAmount);

_directWithdrawFromVault

this is the step-1 for two step form withdrawal, direct case

will mandatorily process unlock

function _directWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    internal
    virtual
    override
    returns (uint256);

Returns

NameTypeDescription
<none>uint256dstAmount is always 0

_xChainDepositIntoVault

after requesting the unlock, the information with the time of full unlock is saved and sent to the two step

state registry for re-processing at a later date

function _xChainDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address,
    uint64 srcChainId_
)
    internal
    virtual
    override
    returns (uint256 dstAmount);

_xChainWithdrawFromVault

this is the step-1 for two step form withdrawal, xchain case

will mandatorily process unlock

function _xChainWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    virtual
    override
    returns (uint256);

Returns

NameTypeDescription
<none>uint256dstAmount is always 0

_emergencyWithdraw

after requesting the unlock, the information with the time of full unlock is saved and sent to the two step

state registry for re-processing at a later date

function _emergencyWithdraw(address refundAddress_, uint256 amount_) internal override;

_requestUnlock

superPositions are already burned at this point

calls the vault to request unlock

function _requestUnlock(uint256 amount_) internal returns (uint256 lockedTill_);

_storePayload

stores the withdrawal payload

function _storePayload(
    uint8 type_,
    address srcSender_,
    uint64 srcChainId_,
    uint256 lockedTill_,
    InitSingleVaultData memory data_
)
    internal;

Structs

withdrawAfterCoolDownLocalVars

struct withdrawAfterCoolDownLocalVars {
    uint256 len1;
    address bridgeValidator;
    uint64 chainId;
    address receiver;
    uint256 amount;
    LiqRequest liqData;
}

Contents

IAmbImplementation

Git Source

Author: ZeroPoint Labs

interface for arbitrary message bridge implementation

Functions

dispatchPayload

allows state registry to send message via implementation.

function dispatchPayload(
    address srcSender_,
    uint64 dstChainId_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    payable;

Parameters

NameTypeDescription
srcSender_addressis the caller (used for gas refunds)
dstChainId_uint64is the identifier of the destination chain
message_bytesis the cross-chain message to be sent
extraData_bytesis message amb specific override information

estimateFees

not all AMBs will have on-chain estimation for which this function will return 0

returns the gas fees estimation in native tokens

function estimateFees(
    uint64 dstChainId_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    view
    returns (uint256 fees);

Parameters

NameTypeDescription
dstChainId_uint64is the identifier of the destination chain
message_bytesis the cross-chain message
extraData_bytesis any amb-specific information

Returns

NameTypeDescription
feesuint256is the native_tokens to be sent along the transaction

Events

ChainAdded

event ChainAdded(uint64 superChainId);

AuthorizedImplAdded

event AuthorizedImplAdded(uint64 superChainId, address authImpl);

IBaseForm

Git Source

Inherits: IERC165

Author: ZeroPoint Labs

Interface for Base Form

Functions

directDepositIntoVault

process same chain id deposits

function directDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    external
    payable
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
singleVaultData_InitSingleVaultDataA bytes representation containing all the data required to make a form action
srcSender_addressThe address of the sender of the transaction

Returns

NameTypeDescription
dstAmountuint256The amount of tokens deposited in same chain action

directWithdrawFromVault

process withdrawal of collateral from a vault

function directWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    external
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
singleVaultData_InitSingleVaultDataA bytes representation containing all the data required to make a form action
srcSender_addressThe address of the sender of the transaction

Returns

NameTypeDescription
dstAmountuint256The amount of tokens withdrawn in same chain action

xChainDepositIntoVault

process same chain id deposits

is dstAmoutn is 0 then no further action/acknowledgement needs to be sent

function xChainDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    external
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
singleVaultData_InitSingleVaultDataA bytes representation containing all the data required to make a form action
srcSender_addressThe address of the sender of the transaction
srcChainId_uint64The chain id of the source chain

Returns

NameTypeDescription
dstAmountuint256The amount of tokens deposited in same chain action

xChainWithdrawFromVault

process withdrawal of collateral from a vault

function xChainWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    external
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
singleVaultData_InitSingleVaultDataA bytes representation containing all the data required to make a form action
srcSender_addressThe address of the sender of the transaction
srcChainId_uint64The chain id of the source chain

Returns

NameTypeDescription
dstAmountuint256The amount of tokens withdrawn

emergencyWithdraw

process withdrawal of shares if form is paused

function emergencyWithdraw(address refundAddress_, uint256 amount_) external;

Parameters

NameTypeDescription
refundAddress_addressThe address to refund the shares to
amount_uint256The amount of vault shares to refund

superformYieldTokenName

get Superform name of the ERC20 vault representation

function superformYieldTokenName() external view returns (string memory);

Returns

NameTypeDescription
<none>stringThe ERC20 name

superformYieldTokenSymbol

get Superform symbol of the ERC20 vault representation

function superformYieldTokenSymbol() external view returns (string memory);

Returns

NameTypeDescription
<none>stringThe ERC20 symbol

getVaultAsset

Returns the underlying token of a vault.

function getVaultAsset() external view returns (address);

Returns

NameTypeDescription
<none>addressThe asset being deposited into the vault used for accounting, depositing, and withdrawing

getVaultName

Returns the name of the vault.

function getVaultName() external view returns (string memory);

Returns

NameTypeDescription
<none>stringThe name of the vault

getVaultSymbol

Returns the symbol of a vault.

function getVaultSymbol() external view returns (string memory);

Returns

NameTypeDescription
<none>stringThe symbol associated with a vault

getVaultDecimals

Returns the number of decimals in a vault for accounting purposes

function getVaultDecimals() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The number of decimals in the vault balance

getVaultAddress

returns the vault address

function getVaultAddress() external view returns (address);

getPricePerVaultShare

Returns the amount of underlying tokens each share of a vault is worth.

function getPricePerVaultShare() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The pricePerVaultShare value

getVaultShareBalance

Returns the amount of vault shares owned by the form.

function getVaultShareBalance() external view returns (uint256);

Returns

NameTypeDescription
<none>uint256The form's vault share balance

getTotalAssets

get the total amount of underlying managed in the ERC4626 vault

function getTotalAssets() external view returns (uint256);

getPreviewPricePerVaultShare

get the total amount of assets received if shares are actually redeemed

https://eips.ethereum.org/EIPS/eip-4626

function getPreviewPricePerVaultShare() external view returns (uint256);

getStateRegistryId

get the state registry id

function getStateRegistryId() external view returns (uint256);

previewDepositTo

API may need to know state of funds deployed

function previewDepositTo(uint256 assets_) external view returns (uint256);

previewWithdrawFrom

positionBalance() -> .vaultIds&destAmounts

function previewWithdrawFrom(uint256 assets_) external view returns (uint256);

Returns

NameTypeDescription
<none>uint256how much of an asset + interest (accrued) is to withdraw from the Vault

previewRedeemFrom

API may need to know state of funds deployed

function previewRedeemFrom(uint256 shares_) external view returns (uint256);

formImplementationId

function formImplementationId() external view returns (uint32);

Events

VaultAdded

is emitted when a new vault is added by the admin.

event VaultAdded(uint256 id, IERC4626 vault);

Processed

is emitted when a payload is processed by the destination contract.

event Processed(uint64 srcChainID, uint64 dstChainId, uint256 srcPayloadId, uint256 amount, address vault);

EmergencyWithdrawalProcessed

is emitted when an emergency withdrawal is processed

event EmergencyWithdrawalProcessed(address refundAddress, uint256 amount);

IBaseRouter

Git Source

Author: Zeropoint Labs.

interface for abstract Router

Functions

multiDstSingleVaultDeposit

Performs multi destination x single vault deposits

function multiDstSingleVaultDeposit(MultiDstSingleVaultStateReq calldata req_) external payable;

Parameters

NameTypeDescription
req_MultiDstSingleVaultStateReqis the request object containing all the necessary data for the action

multiDstMultiVaultDeposit

Performs multi destination x multi vault deposits

function multiDstMultiVaultDeposit(MultiDstMultiVaultStateReq calldata req_) external payable;

Parameters

NameTypeDescription
req_MultiDstMultiVaultStateReqis the request object containing all the necessary data for the action

singleXChainSingleVaultDeposit

Performs single xchain destination x single vault deposits

function singleXChainSingleVaultDeposit(SingleXChainSingleVaultStateReq memory req_) external payable;

Parameters

NameTypeDescription
req_SingleXChainSingleVaultStateReqis the request object containing all the necessary data for the action

singleXChainMultiVaultDeposit

Performs single destination x multi vault deposits

function singleXChainMultiVaultDeposit(SingleXChainMultiVaultStateReq memory req_) external payable;

Parameters

NameTypeDescription
req_SingleXChainMultiVaultStateReqis the request object containing all the necessary data for the action

singleDirectSingleVaultDeposit

Performs single direct x single vault deposits

function singleDirectSingleVaultDeposit(SingleDirectSingleVaultStateReq memory req_) external payable;

Parameters

NameTypeDescription
req_SingleDirectSingleVaultStateReqis the request object containing all the necessary data for the action

singleDirectMultiVaultDeposit

Performs single direct x multi vault deposits

function singleDirectMultiVaultDeposit(SingleDirectMultiVaultStateReq memory req_) external payable;

Parameters

NameTypeDescription
req_SingleDirectMultiVaultStateReqis the request object containing all the necessary data for the action

multiDstSingleVaultWithdraw

Performs multi destination x single vault withdraws

function multiDstSingleVaultWithdraw(MultiDstSingleVaultStateReq calldata req_) external payable;

Parameters

NameTypeDescription
req_MultiDstSingleVaultStateReqis the request object containing all the necessary data for the action

multiDstMultiVaultWithdraw

Performs multi destination x multi vault withdraws

function multiDstMultiVaultWithdraw(MultiDstMultiVaultStateReq calldata req_) external payable;

Parameters

NameTypeDescription
req_MultiDstMultiVaultStateReqis the request object containing all the necessary data for the action

singleXChainSingleVaultWithdraw

Performs single xchain destination x single vault withdraws

function singleXChainSingleVaultWithdraw(SingleXChainSingleVaultStateReq memory req_) external payable;

Parameters

NameTypeDescription
req_SingleXChainSingleVaultStateReqis the request object containing all the necessary data for the action

singleXChainMultiVaultWithdraw

Performs single destination x multi vault withdraws

function singleXChainMultiVaultWithdraw(SingleXChainMultiVaultStateReq memory req_) external payable;

Parameters

NameTypeDescription
req_SingleXChainMultiVaultStateReqis the request object containing all the necessary data for the action

singleDirectSingleVaultWithdraw

Performs single direct x single vault withdraws

function singleDirectSingleVaultWithdraw(SingleDirectSingleVaultStateReq memory req_) external payable;

Parameters

NameTypeDescription
req_SingleDirectSingleVaultStateReqis the request object containing all the necessary data for the action

singleDirectMultiVaultWithdraw

Performs single direct x multi vault withdraws

function singleDirectMultiVaultWithdraw(SingleDirectMultiVaultStateReq memory req_) external payable;

Parameters

NameTypeDescription
req_SingleDirectMultiVaultStateReqis the request object containing all the necessary data for the action

IBaseRouterImplementation

Git Source

Inherits: IBaseRouter

Author: Zeropoint Labs.

interface for BaseRouterImplementation

Events

CrossChainInitiated

is emitted when a cross-chain transaction is initiated.

event CrossChainInitiated(uint256 indexed payloadId);

Completed

is emitted when a cross-chain transaction is completed.

event Completed(uint256 payloadId);

Structs

ActionLocalVars

For local memory variable loading and avoiding stack too deep errors

struct ActionLocalVars {
    AMBMessage ambMessage;
    LiqRequest liqRequest;
    uint64 srcChainId;
    uint256 currentPayloadId;
    uint256 liqRequestsLen;
}

DispatchAMBMessageVars

struct DispatchAMBMessageVars {
    TransactionType txType;
    bytes ambData;
    uint256[] superformIds;
    address srcSender;
    uint8[] ambIds;
    uint8 multiVaults;
    uint64 srcChainId;
    uint64 dstChainId;
    uint256 currentPayloadId;
}

IBaseStateRegistry

Git Source

Author: ZeroPoint Labs

Is the crosschain interaction point. Send, store & process crosschain messages

Functions

dispatchPayload

allows core contracts to send payload to a destination chain.

function dispatchPayload(
    address srcSender_,
    uint8[] memory ambIds_,
    uint64 dstChainId_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    payable;

Parameters

NameTypeDescription
srcSender_addressis the caller of the function (used for gas refunds).
ambIds_uint8[]is the identifier of the arbitrary message bridge to be used
dstChainId_uint64is the internal chainId used throughtout the protocol
message_bytesis the crosschain payload to be sent
extraData_bytesdefines all the message bridge realted overrides NOTE: dstChainId_ is mapped to message bridge's destination id inside it's implementation contract NOTE: ambIds_ are superform assigned unique identifier for arbitrary message bridges

receivePayload

allows state registry to receive messages from message bridge implementations

function receivePayload(uint64 srcChainId_, bytes memory message_) external;

Parameters

NameTypeDescription
srcChainId_uint64is the superform chainId from which the payload is dispatched/sent
message_bytesis the crosschain payload received NOTE: Only {IMPLEMENTATION_CONTRACT} role can call this function.

processPayload

allows previlaged actors to process cross-chain payloads

function processPayload(uint256 payloadId_) external payable;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload NOTE: Only {CORE_STATE_REGISTRY_PROCESSOR_ROLE} role can call this function NOTE: this should handle reverting the state on source chain in-case of failure (or) can implement scenario based reverting like in coreStateRegistry

payloadsCount

allows users to read the total payloads received by the registry

function payloadsCount() external view returns (uint256);

payloadTracking

allows user to read the payload state uint256 payloadId_ is the unique payload identifier allocated on the destiantion chain

function payloadTracking(uint256 payloadId_) external view returns (PayloadState payloadState_);

payloadBody

allows users to read the bytes payload_ stored per payloadId_

function payloadBody(uint256 payloadId_) external view returns (bytes memory payloadBody_);

Parameters

NameTypeDescription
payloadId_uint256is the unqiue payload identifier allocated on the destination chain

Returns

NameTypeDescription
payloadBody_bytesthe crosschain data received

payloadHeader

allows users to read the uint256 payloadHeader stored per payloadId_

function payloadHeader(uint256 payloadId_) external view returns (uint256 payloadHeader_);

Parameters

NameTypeDescription
payloadId_uint256is the unqiue payload identifier allocated on the destination chain

Returns

NameTypeDescription
payloadHeader_uint256the crosschain header received

msgAMB

allows users to read the amb that delivered the payload

function msgAMB(uint256 payloadId_) external view returns (uint8 ambId_);

Parameters

NameTypeDescription
payloadId_uint256is the unqiue payload identifier allocated on the destination chain

Returns

NameTypeDescription
ambId_uint8is the amb that delivered the payload

getProofAMB

allows users to read the amb that delivered the proof

function getProofAMB(bytes32 proof_) external view returns (uint8[] memory ambIds_);

Parameters

NameTypeDescription
proof_bytes32is the bytes32 proof

Returns

NameTypeDescription
ambIds_uint8[]is the identifier of ambs that delivered the proof

Events

PayloadReceived

is emitted when a cross-chain payload is received in the state registry

event PayloadReceived(uint64 srcChainId, uint64 dstChainId, uint256 payloadId);

ProofReceived

is emitted when a cross-chain proof is received in the state registry NOTE: comes handy if quorum required is more than 0

event ProofReceived(bytes proof);

PayloadUpdated

is emitted when a payload id gets updated

event PayloadUpdated(uint256 payloadId);

PayloadProcessed

is emitted when a payload id gets processed

event PayloadProcessed(uint256 payloadId);

SuperRegistryUpdated

is emitted when the super registry address is updated

event SuperRegistryUpdated(address indexed superRegistry);

IBridgeValidator

Git Source

Author: Zeropoint Labs

Functions

validateLiqDstChainId

validates the destination chainId of the liquidity request

function validateLiqDstChainId(bytes calldata txData_, uint64 liqDstChainId_) external pure returns (bool);

Parameters

NameTypeDescription
txData_bytesthe txData of the deposit
liqDstChainId_uint64the chainId of the destination chain for liquidity

validateReceiver

decoded txData and returns the receiver address

function validateReceiver(bytes calldata txData_, address receiver_) external pure returns (bool valid_);

Parameters

NameTypeDescription
txData_bytesis the txData of the cross chain deposit
receiver_addressis the address of the receiver to validate

Returns

NameTypeDescription
valid_boolif the address is valid

validateTxData

validates the txData of a cross chain deposit

function validateTxData(ValidateTxDataArgs calldata args_) external view;

Parameters

NameTypeDescription
args_ValidateTxDataArgsthe txData arguments to validate in txData

decodeMinAmountOut

decodes the txData and returns the minimum amount expected to receive on the destination

function decodeMinAmountOut(
    bytes calldata txData_,
    bool genericSwapDisallowed_
)
    external
    view
    returns (uint256 amount_);

Parameters

NameTypeDescription
txData_bytesis the txData of the cross chain deposit
genericSwapDisallowed_booltrue if generic swaps are disallowed

Returns

NameTypeDescription
amount_uint256the amount expected

decodeAmountIn

decodes the txData and returns the amount of external token on source

function decodeAmountIn(bytes calldata txData_, bool genericSwapDisallowed_) external view returns (uint256 amount_);

Parameters

NameTypeDescription
txData_bytesis the txData of the cross chain deposit
genericSwapDisallowed_booltrue if generic swaps are disallowed

Returns

NameTypeDescription
amount_uint256the amount expected

decodeDstSwap

decodes the amount in from the txData that just involves a swap

function decodeDstSwap(bytes calldata txData_) external pure returns (address token_, uint256 amount_);

Parameters

NameTypeDescription
txData_bytesis the txData to be decoded

Structs

ValidateTxDataArgs

struct ValidateTxDataArgs {
    bytes txData;
    uint64 srcChainId;
    uint64 dstChainId;
    uint64 liqDstChainId;
    bool deposit;
    address superform;
    address srcSender;
    address liqDataToken;
}

IBroadcastAmbImplementation

Git Source

Author: ZeroPoint Labs

interface for arbitrary message bridge implementation the supports broadcasting

Functions

broadcastPayload

allows state registry to send messages to multiple dst chains

function broadcastPayload(address srcSender_, bytes memory message_, bytes memory extraData_) external payable;

Parameters

NameTypeDescription
srcSender_addressis the caller (used for gas refunds)
message_bytesis the cross-chain message to be broadcasted
extraData_bytesis optional broadcast override information

estimateFees

estimation differs for different message bridges.

returns the gas fees estimation in native tokens

function estimateFees(bytes memory message_, bytes memory extraData_) external view returns (uint256 fees);

Parameters

NameTypeDescription
message_bytesis the cross-chain message to be broadcasted
extraData_bytesis optional broadcast override information

Returns

NameTypeDescription
feesuint256is the native_tokens to be sent along the transaction

Events

ChainAdded

event ChainAdded(uint64 superChainId);

AuthorizedImplAdded

event AuthorizedImplAdded(uint64 superChainId, address authImpl);

IBroadcastRegistry

Git Source

Author: ZeroPoint Labs

is an helper for base state registry with broadcasting abilities.

Functions

broadcastPayload

allows core contracts to send payload to all configured destination chain.

function broadcastPayload(
    address srcSender_,
    uint8[] memory ambIds_,
    bytes memory message_,
    bytes memory extraData_
)
    external
    payable;

Parameters

NameTypeDescription
srcSender_addressis the caller of the function (used for gas refunds).
ambIds_uint8[]is the identifier of the arbitrary message bridge to be used
message_bytesis the crosschain payload to be broadcasted
extraData_bytesdefines all the message bridge realted overrides

receiveBroadcastPayload

allows ambs to write broadcasted payloads

function receiveBroadcastPayload(uint64 srcChainId_, bytes memory message_) external;

processPayload

allows previlaged actors to process broadcasted payloads

function processPayload(uint256 payloadId_) external;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload

ICoreStateRegistry

Git Source

Author: ZeroPoint Labs

Interface for Core State Registry

Functions

getFailedDeposits

allows users to read the superformIds that failed in a specific payloadId_

function getFailedDeposits(uint256 payloadId_)
    external
    view
    returns (uint256[] memory superformIds_, uint256[] memory amounts);

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload.

Returns

NameTypeDescription
superformIds_uint256[]is the identifiers of superforms in the payloadId that got failed.
amountsuint256[]

updateDepositPayload

allows accounts with {CORE_STATE_REGISTRY_UPDATER_ROLE} to modify a received cross-chain deposit payload.

function updateDepositPayload(uint256 payloadId_, uint256[] calldata finalAmounts_) external;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload to be updated.
finalAmounts_uint256[]is the amount to be updated. NOTE: amounts cannot be updated beyond user specified safe slippage limit.

updateWithdrawPayload

allows accounts with {CORE_STATE_REGISTRY_UPDATER_ROLE} to modify a received cross-chain withdraw payload.

function updateWithdrawPayload(uint256 payloadId_, bytes[] calldata txData_) external;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload to be updated.
txData_bytes[]is the transaction data to be updated.

proposeRescueFailedDeposits

allows accounts with {CORE_STATE_REGISTRY_PROCESSOR_ROLE} to rescue tokens on failed deposits

function proposeRescueFailedDeposits(uint256 payloadId_, uint256[] memory proposedAmounts_) external;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload.
proposedAmounts_uint256[]is the array of proposed rescue amounts.

disputeRescueFailedDeposits

should challenge within the delay window configured on SuperRegistry

allows refund receivers to challenge their final receiving token amounts on failed deposits

function disputeRescueFailedDeposits(uint256 payloadId_) external;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload

finalizeRescueFailedDeposits

allows anyone to settle refunds for unprocessed/failed deposits past the challenge period

function finalizeRescueFailedDeposits(uint256 payloadId_) external;

Parameters

NameTypeDescription
payloadId_uint256is the identifier of the cross-chain payload

Events

FailedXChainDeposits

is emitted when any deposit fails

event FailedXChainDeposits(uint256 indexed payloadId);

RescueProposed

is emitted when a rescue is proposed for failed deposits in a payload

event RescueProposed(uint256 indexed payloadId, uint256[] superformIds, uint256[] proposedAmount, uint256 proposedTime);

RescueDisputed

is emitted when an user disputed his refund amounts

event RescueDisputed(uint256 indexed payloadId);

RescueFinalized

is emitted when deposit rescue is finalized

event RescueFinalized(uint256 indexed payloadId);

Structs

CoreProcessPayloadLocalVars

local struct to avoid stack too deep errors in processPayload

struct CoreProcessPayloadLocalVars {
    uint8 txType;
    uint8 callbackType;
    uint8 multi;
    address srcSender;
    uint64 srcChainId;
}

UpdateWithdrawPayloadVars

local struct to avoid stack too deep errors in updateWithdrawPayload

struct UpdateWithdrawPayloadVars {
    bytes32 prevPayloadProof;
    bytes prevPayloadBody;
    uint256 prevPayloadHeader;
    uint8 isMulti;
    uint64 srcChainId;
    uint64 dstChainId;
    address srcSender;
}

UpdateMultiVaultWithdrawPayloadLocalVars

local struct to avoid stack too deep errors in updateWithdrawPayload

struct UpdateMultiVaultWithdrawPayloadLocalVars {
    InitMultiVaultData multiVaultData;
    InitSingleVaultData singleVaultData;
    address superform;
    uint256[] tSuperFormIds;
    uint256[] tAmounts;
    uint256[] tMaxSlippage;
    LiqRequest[] tLiqData;
}

FailedDeposit

struct FailedDeposit {
    uint256[] superformIds;
    uint256[] amounts;
    address refundAddress;
    uint256 lastProposedTimestamp;
}

IDstSwapper

Git Source

Author: Zeropoint Labs

SPDX-License-Identifier: Apache-2.0

all write functions can only be accessed by superform keepers.

handles all destination chain swaps.

Functions

processTx

would interact with liquidity bridge contract to process multi-tx transactions and move the funds into destination contract.

function processTx(uint256 payloadId_, uint256 index_, uint8 bridgeId_, bytes calldata txData_) external;

Parameters

NameTypeDescription
payloadId_uint256represents the id of the payload
index_uint256represents the index of the superformid in the payload
bridgeId_uint8represents the id of liquidity bridge used
txData_bytesrepresents the transaction data generated by liquidity bridge API.

batchProcessTx

would interact with liquidity bridge contract to process multi-tx transactions and move the funds into destination contract.

function batchProcessTx(
    uint256 payloadId_,
    uint256[] calldata indices_,
    uint8[] calldata bridgeIds_,
    bytes[] calldata txDatas_
)
    external;

Parameters

NameTypeDescription
payloadId_uint256represents the array of payload ids used
indices_uint256[]represents the index of the superformid in the payload
bridgeIds_uint8[]represents the array of ids of liquidity bridges used
txDatas_bytes[]represents the array of transaction data generated by liquidity bridge API

swappedAmount

FIMXE: add natspec

function swappedAmount(uint256 payloadId_, uint256 index_) external view returns (uint256 amount_);

Events

SuperRegistryUpdated

is emitted when the super registry is updated.

event SuperRegistryUpdated(address indexed superRegistry);

SwapProcessed

is emitted when a dst swap transaction is processed

event SwapProcessed(uint256 payloadId, uint256 index, uint256 bridgeId, uint256 finalAmount);

IEmergencyQueue

Git Source

SPDX-License-Identifier: Apache-2.0

Functions

queueWithdrawal

called by paused forms to queue up withdrawals for exit

function queueWithdrawal(InitSingleVaultData memory data_, address srcSender_) external;

Parameters

NameTypeDescription
data_InitSingleVaultDatais the single vault data passed by the user
srcSender_address

executeQueuedWithdrawal

alled by emergency admin to processed queued withdrawal

function executeQueuedWithdrawal(uint256 id_) external;

Parameters

NameTypeDescription
id_uint256is the identifier of the queued action

batchExecuteQueuedWithdrawal

called by emergency admin to batch process queued withdrawals

function batchExecuteQueuedWithdrawal(uint256[] memory ids_) external;

Parameters

NameTypeDescription
ids_uint256[]is the array of identifiers of the queued actions

queuedWithdrawalStatus

returns the execution status of an id in the emergency queue

function queuedWithdrawalStatus(uint256 id) external view returns (bool);

Parameters

NameTypeDescription
iduint256is the identifier of the queued action

Returns

NameTypeDescription
<none>boolboolean representing the execution status

Events

WithdrawalQueued

event WithdrawalQueued(
    address indexed srcAddress,
    address indexed refundAddress,
    uint256 indexed id,
    uint256 superformId,
    uint256 amount,
    uint256 srcPayloadId
);

WithdrawalProcessed

event WithdrawalProcessed(address indexed refundAddress, uint256 indexed id, uint256 superformId, uint256 amount);

IPayMaster

Git Source

Author: ZeroPoint Labs

contract for destination transaction costs payment

Functions

withdrawTo

withdraws funds from pay master to target id from superRegistry

function withdrawTo(bytes32 superRegistryId_, uint256 nativeAmount_) external;

Parameters

NameTypeDescription
superRegistryId_bytes32is the id of the target address in superRegistry
nativeAmount_uint256is the amount to withdraw from pay master

rebalanceTo

withdraws fund from pay master to target id from superRegistry

function rebalanceTo(bytes32 superRegistryId_, LiqRequest memory req_, uint64 dstChainId_) external;

Parameters

NameTypeDescription
superRegistryId_bytes32is the id of the target address in superRegistry
req_LiqRequestis the off-chain generated liquidity request to move funds
dstChainId_uint64is the destination chain id

makePayment

accepts payment from user

function makePayment(address user_) external payable;

Parameters

NameTypeDescription
user_addressis the wallet address of the paying user

Events

Payment

is emitted when a new payment is made

event Payment(address indexed user, uint256 amount);

PaymentWithdrawn

is emitted when payments are moved out of collector

event PaymentWithdrawn(address indexed receiver, uint256 amount);

IPayloadHelper

Git Source

Author: ZeroPoint Labs

helps decoding the bytes payload and returns meaningful information

Functions

decodeCoreStateRegistryPayload

reads the payload from the core state registry and decodes it in a more detailed manner.

function decodeCoreStateRegistryPayload(uint256 dstPayloadId_)
    external
    view
    returns (
        uint8 txType,
        uint8 callbackType,
        address srcSender,
        uint64 srcChainId,
        uint256[] memory amounts,
        uint256[] memory slippage,
        uint256[] memory superformIds,
        uint256 srcPayloadId,
        uint8 superformRouterId
    );

Parameters

NameTypeDescription
dstPayloadId_uint256is the unique identifier of the payload received in dst core state registry

Returns

NameTypeDescription
txTypeuint8is the type of transaction. check {TransactionType} enum in DataTypes.sol
callbackTypeuint8is the type of payload. check {CallbackType} enum in DataTypes.sol
srcSenderaddressis the user who initiated the transaction on the srcChain
srcChainIduint64is the unique identifier of the srcChain
amountsuint256[]is the amount to deposit/withdraw
slippageuint256[]is the max slippage configured by the user (only for deposits)
superformIdsuint256[]is the unique identifiers of the superforms
srcPayloadIduint256is the identifier of the corresponding payload on srcChain
superformRouterIduint8is the identifier of the superform router

decodeCoreStateRegistryPayloadLiqData

reads the payload from the core state registry and decodes liqData for it (to be used in withdraw cases)

function decodeCoreStateRegistryPayloadLiqData(uint256 dstPayloadId_)
    external
    view
    returns (
        uint8[] memory bridgeIds,
        bytes[] memory txDatas,
        address[] memory tokens,
        uint64[] memory liqDstChainIds,
        uint256[] memory amountsIn,
        uint256[] memory amountsOut,
        uint256[] memory nativeAmounts,
        bool[] memory hasDstSwaps,
        address dstRefundAddress
    );

Parameters

NameTypeDescription
dstPayloadId_uint256is the unique identifier of the payload received in dst core state registry

Returns

NameTypeDescription
bridgeIdsuint8[]is the ids of the bridges to be used
txDatasbytes[]is the array of txData to be sent to the bridges
tokensaddress[]is the tokens to be used in the liqData
liqDstChainIdsuint64[]are the final destination chain id for the underlying token (can be arbitrary on withdraws)
amountsInuint256[]are the from amounts to the liquidity bridge
amountsOutuint256[]are the minimum amounts to be bridged through the liquidity bridge
nativeAmountsuint256[]is the native amounts to be used in the liqData
hasDstSwapsbool[]is the array of flags indicating if the original liqData has a dstSwaps
dstRefundAddressaddressis the address to be used for refunds

decodeStateSyncerPayloadHistory

reads the payload header from a state syncer and decodes it.

function decodeStateSyncerPayloadHistory(
    uint256 srcPayloadId_,
    uint8 superformRouterId_
)
    external
    view
    returns (uint8 txType, uint8 callbackType, uint8 isMulti, address srcSender, uint64 srcChainId);

Parameters

NameTypeDescription
srcPayloadId_uint256is the unique identifier of the payload allocated by super router
superformRouterId_uint8is the unique identifier of the superform router

Returns

NameTypeDescription
txTypeuint8is the type of transaction. check {TransactionType} enum in DataTypes.sol
callbackTypeuint8is the type of payload. check {CallbackType} enum in DataTypes.sol
isMultiuint8indicates if the transaction involves operations to multiple vaults
srcSenderaddressis the user who initiated the transaction on the srcChain
srcChainIduint64is the unique identifier of the srcChain

decodeTimeLockPayload

returns decoded two step form payloads

function decodeTimeLockPayload(uint256 timelockPayloadId_)
    external
    view
    returns (address srcSender, uint64 srcChainId, uint256 srcPayloadId, uint256 superformId, uint256 amount);

Parameters

NameTypeDescription
timelockPayloadId_uint256is the unique identifier of payload in two step registry

decodeTimeLockFailedPayload

returns decoded failed two step form payloads

function decodeTimeLockFailedPayload(uint256 timelockPayloadId_)
    external
    view
    returns (address srcSender, uint64 srcChainId, uint256 srcPayloadId, uint256 superformId, uint256 amount);

Parameters

NameTypeDescription
timelockPayloadId_uint256is the unique identifier of payload in two step registry

IPaymentHelper

Git Source

Author: ZeroPoint Labs

helps decoding the bytes payload and returns meaningful information

Functions

addChain

admin config destination chain config for estimation

function addChain(uint64 chainId_, PaymentHelperConfig calldata config_) external;

Parameters

NameTypeDescription
chainId_uint64is the identifier of new chain id
config_PaymentHelperConfigis the chain config

updateChainConfig

admin update remote chain config for estimation

function updateChainConfig(uint64 chainId_, uint256 configType_, bytes memory config_) external;

Parameters

NameTypeDescription
chainId_uint64is the remote chain's identifier
configType_uint256is the type of config from 1 -> 6
config_bytesis the encoded new configuration

calculateAMBData

returns the amb overrides & gas to be used

function calculateAMBData(
    uint64 dstChainId_,
    uint8[] calldata ambIds_,
    bytes memory message_
)
    external
    view
    returns (uint256 totalFees, bytes memory extraData);

Parameters

NameTypeDescription
dstChainId_uint64is the unique dst chain identifier
ambIds_uint8[]is the identifiers of arbitrary message bridges to be used
message_bytesis the encoded cross-chain payload

estimateAMBFees

returns the gas fees estimation in native tokens if we send message through a combination of AMBs

function estimateAMBFees(
    uint8[] memory ambIds_,
    uint64 dstChainId_,
    bytes memory message_,
    bytes[] memory extraData_
)
    external
    view
    returns (uint256 ambFees, uint256[] memory);

Parameters

NameTypeDescription
ambIds_uint8[]is the identifier of different AMBs
dstChainId_uint64is the identifier of the destination chain
message_bytesis the cross-chain message
extraData_bytes[]is any amb-specific information

Returns

NameTypeDescription
ambFeesuint256is the native_tokens to be sent along the transaction for all the ambIds_ included
<none>uint256[]

estimateMultiDstMultiVault

estimates the gas fees for multiple destination and multi vault operation

function estimateMultiDstMultiVault(
    MultiDstMultiVaultStateReq calldata req_,
    bool isDeposit
)
    external
    view
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_MultiDstMultiVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDepositbool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateMultiDstSingleVault

estimates the gas fees for multiple destination and single vault operation

function estimateMultiDstSingleVault(
    MultiDstSingleVaultStateReq calldata req_,
    bool isDeposit
)
    external
    view
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_MultiDstSingleVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDepositbool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateSingleXChainMultiVault

estimates the gas fees for single destination and multi vault operation

function estimateSingleXChainMultiVault(
    SingleXChainMultiVaultStateReq calldata req_,
    bool isDeposit
)
    external
    view
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_SingleXChainMultiVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter ///
isDepositbool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateSingleXChainSingleVault

estimates the gas fees for single destination and single vault operation

function estimateSingleXChainSingleVault(
    SingleXChainSingleVaultStateReq calldata req_,
    bool isDeposit
)
    external
    view
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_SingleXChainSingleVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDepositbool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateSingleDirectSingleVault

estimates the gas fees for same chain operation

function estimateSingleDirectSingleVault(
    SingleDirectSingleVaultStateReq calldata req_,
    bool isDeposit
)
    external
    view
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_SingleDirectSingleVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDepositbool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateSingleDirectMultiVault

estimates the gas fees for multiple same chain operation

function estimateSingleDirectMultiVault(
    SingleDirectMultiVaultStateReq calldata req_,
    bool isDeposit
)
    external
    view
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_SingleDirectMultiVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDepositbool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

Events

ChainConfigUpdated

event ChainConfigUpdated(uint64 chainId_, uint256 configType_, bytes config_);

Structs

PaymentHelperConfig

struct PaymentHelperConfig {
    address nativeFeedOracle;
    address gasPriceOracle;
    uint256 updateGasUsed;
    uint256 depositGasUsed;
    uint256 withdrawGasUsed;
    uint256 defaultNativePrice;
    uint256 defaultGasPrice;
    uint256 dstGasPerKB;
    uint256 ackGasCost;
    uint256 twoStepCost;
    uint256 swapGasUsed;
}

Properties

NameTypeDescription
nativeFeedOracleaddress
gasPriceOracleaddress
updateGasUseduint256
depositGasUseduint256
withdrawGasUseduint256
defaultNativePriceuint256
defaultGasPriceuint256
dstGasPerKBuint256
ackGasCostuint256
twoStepCostuint256
swapGasUseduint256

IQuorumManager

Git Source

Functions

setRequiredMessagingQuorum

quorum is the number of extra ambs a message proof must go through and be validated

allows inheriting contracts to set the messaging quorum for a specific sender chain

function setRequiredMessagingQuorum(uint64 srcChainId_, uint256 quorum_) external;

Parameters

NameTypeDescription
srcChainId_uint64is the chain id from which the message (payload) is sent
quorum_uint256the minimum number of message bridges required for processing NOTE: overriding child contracts should handle the sender validation & setting of message quorum

getRequiredMessagingQuorum

returns the required quorum for the srcChain & dstChain

function getRequiredMessagingQuorum(uint64 srcChainId_) external view returns (uint256 quorum_);

Parameters

NameTypeDescription
srcChainId_uint64is the chain id from which the message (payload) is sent

Returns

NameTypeDescription
quorum_uint256the minimum number of message bridges required for processing

Events

QuorumSet

emitted when a new quorum is set for a specific chain

event QuorumSet(uint64 indexed srcChainId, uint256 quorum);

Parameters

NameTypeDescription
srcChainIduint64the chain id from which the message (payload) is sent
quorumuint256the minimum number of message bridges required for processing

IStateSyncer

Git Source

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

interface for State Syncer

Functions

updateTxHistory

saves the message being sent together with the associated id formulated in a router

function updateTxHistory(uint256 payloadId_, uint256 txInfo_) external;

Parameters

NameTypeDescription
payloadId_uint256is the id of the message being saved
txInfo_uint256is the relevant information of the transaction being saved

mintSingle

allows minter to mint shares on source

function mintSingle(address srcSender_, uint256 id_, uint256 amount_) external;

Parameters

NameTypeDescription
srcSender_addressis the beneficiary of shares
id_uint256is the id of the shares
amount_uint256is the amount of shares to mint

mintBatch

allows minter to mint shares on source in batch

function mintBatch(address srcSender_, uint256[] memory ids_, uint256[] memory amounts_) external;

Parameters

NameTypeDescription
srcSender_addressis the beneficiary of shares
ids_uint256[]are the ids of the shares
amounts_uint256[]are the amounts of shares to mint

burnSingle

allows burner to burn shares on source

function burnSingle(address srcSender_, uint256 id_, uint256 amount_) external;

Parameters

NameTypeDescription
srcSender_addressis the address of the sender
id_uint256is the id of the shares
amount_uint256is the amount of shares to burn

burnBatch

allows burner to burn shares on source in batch

function burnBatch(address srcSender_, uint256[] memory ids_, uint256[] memory amounts_) external;

Parameters

NameTypeDescription
srcSender_addressis the address of the sender
ids_uint256[]are the ids of the shares
amounts_uint256[]are the amounts of shares to burn

stateMultiSync

allows state registry contract to mint shares on source

function stateMultiSync(AMBMessage memory data_) external returns (uint64 srcChainId_);

Parameters

NameTypeDescription
data_AMBMessageis the received information to be processed.

Returns

NameTypeDescription
srcChainId_uint64is the decoded srcChainId.

stateSync

allows state registry contract to mint shares on source

function stateSync(AMBMessage memory data_) external returns (uint64 srcChainId_);

Parameters

NameTypeDescription
data_AMBMessageis the received information to be processed.

Returns

NameTypeDescription
srcChainId_uint64is the decoded srcChainId.

txHistory

returns the payload header for a tx id on the source chain

function txHistory(uint256 txId_) external view returns (uint256);

Parameters

NameTypeDescription
txId_uint256is the identifier of the transaction issued by super router

Events

Completed

is emitted when a cross-chain transaction is completed.

event Completed(uint256 txId);

ISuperPositions

Git Source

Inherits: IStateSyncer

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

interface for Super Positions

Functions

setDynamicURI

sets the dynamic uri for NFT

function setDynamicURI(string memory dynamicURI_, bool freeze_) external;

Parameters

NameTypeDescription
dynamicURI_stringis the dynamic uri of the NFT
freeze_boolis to prevent updating the metadata once migrated to IPFS

Events

DynamicURIUpdated

is emitted when a dynamic uri is updated

event DynamicURIUpdated(string oldURI, string newURI, bool frozen);

ISuperRBAC

Git Source

Inherits: IAccessControl

Author: Zeropoint Labs.

interface for Super RBAC

Functions

setSuperRegistry

updates the super registry address

function setSuperRegistry(address superRegistry_) external;

setRoleAdmin

configures a new role in superForm

function setRoleAdmin(bytes32 role_, bytes32 adminRole_) external;

Parameters

NameTypeDescription
role_bytes32the role to set
adminRole_bytes32the admin role to set as admin

revokeRoleSuperBroadcast

revokes the role_ from superRegistryAddressId_ on all chains

function revokeRoleSuperBroadcast(
    bytes32 role_,
    address addressToRevoke_,
    bytes memory extraData_,
    bytes32 superRegistryAddressId_
)
    external
    payable;

Parameters

NameTypeDescription
role_bytes32the role to revoke
addressToRevoke_addressthe address to revoke the role from
extraData_bytesamb config if broadcasting is required
superRegistryAddressId_bytes32the super registry address id

stateSyncBroadcast

may not work for all roles

allows sync of global roles from different chains using broadcast registry

function stateSyncBroadcast(bytes memory data_) external;

PROTOCOL_ADMIN_ROLE

returns the id of the protocol admin role

function PROTOCOL_ADMIN_ROLE() external view returns (bytes32);

EMERGENCY_ADMIN_ROLE

returns the id of the emergency admin role

function EMERGENCY_ADMIN_ROLE() external view returns (bytes32);

PAYMENT_ADMIN_ROLE

returns the id of the payment admin role

function PAYMENT_ADMIN_ROLE() external view returns (bytes32);

BROADCASTER_ROLE

returns the id of the broadcaster role

function BROADCASTER_ROLE() external view returns (bytes32);

CORE_STATE_REGISTRY_PROCESSOR_ROLE

returns the id of the core state registry processor role

function CORE_STATE_REGISTRY_PROCESSOR_ROLE() external view returns (bytes32);

CORE_STATE_REGISTRY_RESCUER_ROLE

returns the id of the core state registry rescuer role

function CORE_STATE_REGISTRY_RESCUER_ROLE() external view returns (bytes32);

CORE_STATE_REGISTRY_DISPUTER_ROLE

returns the id of the core state registry rescue disputer role

function CORE_STATE_REGISTRY_DISPUTER_ROLE() external view returns (bytes32);

TIMELOCK_STATE_REGISTRY_PROCESSOR_ROLE

returns the id of the two steps state registry processor role

function TIMELOCK_STATE_REGISTRY_PROCESSOR_ROLE() external view returns (bytes32);

BROADCAST_STATE_REGISTRY_PROCESSOR_ROLE

returns the id of the broadcast state registry processor role

function BROADCAST_STATE_REGISTRY_PROCESSOR_ROLE() external view returns (bytes32);

DST_SWAPPER_ROLE

returns the id of the dst swapper role

function DST_SWAPPER_ROLE() external view returns (bytes32);

CORE_STATE_REGISTRY_UPDATER_ROLE

returns the id of the core state registry updater role

function CORE_STATE_REGISTRY_UPDATER_ROLE() external view returns (bytes32);

WORMHOLE_VAA_RELAYER_ROLE

returns the id of wormhole vaa relayer role

function WORMHOLE_VAA_RELAYER_ROLE() external view returns (bytes32);

hasProtocolAdminRole

returns whether the given address has the protocol admin role

function hasProtocolAdminRole(address admin_) external view returns (bool);

Parameters

NameTypeDescription
admin_addressthe address to check

hasEmergencyAdminRole

returns whether the given address has the emergency admin role

function hasEmergencyAdminRole(address admin_) external view returns (bool);

Parameters

NameTypeDescription
admin_addressthe address to check

Structs

InitialRoleSetup

struct InitialRoleSetup {
    address admin;
    address emergencyAdmin;
    address paymentAdmin;
    address csrProcessor;
    address tlProcessor;
    address brProcessor;
    address csrUpdater;
    address srcVaaRelayer;
    address dstSwapper;
    address csrRescuer;
    address csrDisputer;
}

ISuperRegistry

Git Source

Author: Zeropoint Labs.

interface for Super Registry

Functions

setDelay

sets the deposit rescue delay

function setDelay(uint256 delay_) external;

Parameters

NameTypeDescription
delay_uint256the delay in seconds before the deposit rescue can be finalized

setPermit2

sets the permit2 address

function setPermit2(address permit2_) external;

Parameters

NameTypeDescription
permit2_addressthe address of the permit2 contract

setAddress

sets a new address on a specific chain.

function setAddress(bytes32 id_, address newAddress_, uint64 chainId_) external;

Parameters

NameTypeDescription
id_bytes32the identifier of the address on that chain
newAddress_addressthe new address on that chain
chainId_uint64the chain id of that chain

setBridgeAddresses

this function operates in an APPEND-ONLY fashion.

allows admin to set the bridge address for an bridge id.

function setBridgeAddresses(
    uint8[] memory bridgeId_,
    address[] memory bridgeAddress_,
    address[] memory bridgeValidator_
)
    external;

Parameters

NameTypeDescription
bridgeId_uint8[]represents the bridge unqiue identifier.
bridgeAddress_address[]represents the bridge address.
bridgeValidator_address[]represents the bridge validator address.

setAmbAddress

this function operates in an APPEND-ONLY fashion.

allows admin to set the amb address for an amb id.

function setAmbAddress(uint8[] memory ambId_, address[] memory ambAddress_, bool[] memory isBroadcastAMB_) external;

Parameters

NameTypeDescription
ambId_uint8[]represents the bridge unqiue identifier.
ambAddress_address[]represents the bridge address.
isBroadcastAMB_bool[]represents whether the amb implementation supports broadcasting

setStateRegistryAddress

this function operates in an APPEND-ONLY fashion.

allows admin to set the state registry address for an state registry id.

function setStateRegistryAddress(uint8[] memory registryId_, address[] memory registryAddress_) external;

Parameters

NameTypeDescription
registryId_uint8[]represents the state registry's unqiue identifier.
registryAddress_address[]represents the state registry's address.

setRouterInfo

this function operates in an APPEND-ONLY fashion.

allows admin to set the superform routers info

function setRouterInfo(
    uint8[] memory superformRouterIds_,
    address[] memory stateSyncers_,
    address[] memory routers_
)
    external;

Parameters

NameTypeDescription
superformRouterIds_uint8[]represents the superform router's unqiue identifier.
stateSyncers_address[]represents the state syncer's address.
routers_address[]represents the router's address.

delay

gets the deposit rescue delay

function delay() external view returns (uint256);

PERMIT2

returns the permit2 address

function PERMIT2() external view returns (address);

SUPERFORM_ROUTER

returns the id of the super router module

function SUPERFORM_ROUTER() external view returns (bytes32);

SUPERFORM_FACTORY

returns the id of the superform factory module

function SUPERFORM_FACTORY() external view returns (bytes32);

SUPER_TRANSMUTER

returns the id of the superform transmuter

function SUPER_TRANSMUTER() external view returns (bytes32);

PAYMASTER

returns the id of the superform paymaster contract

function PAYMASTER() external view returns (bytes32);

PAYMENT_HELPER

returns the id of the superform payload helper contract

function PAYMENT_HELPER() external view returns (bytes32);

CORE_STATE_REGISTRY

returns the id of the core state registry module

function CORE_STATE_REGISTRY() external view returns (bytes32);

TIMELOCK_STATE_REGISTRY

returns the id of the two steps form state registry module

function TIMELOCK_STATE_REGISTRY() external view returns (bytes32);

BROADCAST_REGISTRY

returns the id of the broadcast state registry module

function BROADCAST_REGISTRY() external view returns (bytes32);

SUPER_POSITIONS

returns the id of the super positions module

function SUPER_POSITIONS() external view returns (bytes32);

SUPER_RBAC

returns the id of the super rbac module

function SUPER_RBAC() external view returns (bytes32);

PAYLOAD_HELPER

returns the id of the payload helper module

function PAYLOAD_HELPER() external view returns (bytes32);

DST_SWAPPER

returns the id of the dst swapper keeper

function DST_SWAPPER() external view returns (bytes32);

EMERGENCY_QUEUE

returns the id of the emergency queue

function EMERGENCY_QUEUE() external view returns (bytes32);

PAYMENT_ADMIN

returns the id of the payment admin keeper

function PAYMENT_ADMIN() external view returns (bytes32);

CORE_REGISTRY_PROCESSOR

returns the id of the core state registry processor keeper

function CORE_REGISTRY_PROCESSOR() external view returns (bytes32);

BROADCAST_REGISTRY_PROCESSOR

returns the id of the broadcast registry processor keeper

function BROADCAST_REGISTRY_PROCESSOR() external view returns (bytes32);

TIMELOCK_REGISTRY_PROCESSOR

returns the id of the two steps form state registry processor keeper

function TIMELOCK_REGISTRY_PROCESSOR() external view returns (bytes32);

CORE_REGISTRY_UPDATER

returns the id of the core state registry updater keeper

function CORE_REGISTRY_UPDATER() external view returns (bytes32);

CORE_REGISTRY_RESCUER

returns the id of the core state registry updater keeper

function CORE_REGISTRY_RESCUER() external view returns (bytes32);

CORE_REGISTRY_DISPUTER

returns the id of the core state registry updater keeper

function CORE_REGISTRY_DISPUTER() external view returns (bytes32);

DST_SWAPPER_PROCESSOR

returns the id of the core state registry updater keeper

function DST_SWAPPER_PROCESSOR() external view returns (bytes32);

getAddress

gets the address of a contract on current chain

function getAddress(bytes32 id_) external view returns (address);

Parameters

NameTypeDescription
id_bytes32is the id of the contract

getAddressByChainId

gets the address of a contract on a target chain

function getAddressByChainId(bytes32 id_, uint64 chainId_) external view returns (address);

Parameters

NameTypeDescription
id_bytes32is the id of the contract
chainId_uint64is the chain id of that chain

getBridgeAddress

gets the address of a bridge

function getBridgeAddress(uint8 bridgeId_) external view returns (address bridgeAddress_);

Parameters

NameTypeDescription
bridgeId_uint8is the id of a bridge

Returns

NameTypeDescription
bridgeAddress_addressis the address of the form

getStateRegistry

gets the address of the registry

function getStateRegistry(uint8 registryId_) external view returns (address registryAddress_);

Parameters

NameTypeDescription
registryId_uint8is the id of the state registry

Returns

NameTypeDescription
registryAddress_addressis the address of the state registry

getAmbId

gets the id of the amb

function getAmbId(address ambAddress_) external view returns (uint8 ambId_);

Parameters

NameTypeDescription
ambAddress_addressis the address of an amb

Returns

NameTypeDescription
ambId_uint8is the identifier of an amb

getStateRegistryId

reverts if the id is not found

gets the id of the registry

function getStateRegistryId(address registryAddress_) external view returns (uint8 registryId_);

Parameters

NameTypeDescription
registryAddress_addressis the address of the state registry

Returns

NameTypeDescription
registryId_uint8is the id of the state registry

getStateSyncer

gets the address of a state syncer

function getStateSyncer(uint8 superformRouterId_) external view returns (address stateSyncer_);

Parameters

NameTypeDescription
superformRouterId_uint8is the id of a state syncer

Returns

NameTypeDescription
stateSyncer_addressis the address of a state syncer

getRouter

gets the address of a router

function getRouter(uint8 superformRouterId_) external view returns (address router_);

Parameters

NameTypeDescription
superformRouterId_uint8is the id of a state syncer

Returns

NameTypeDescription
router_addressis the address of a router

getSuperformRouterId

gets the id of a router

function getSuperformRouterId(address router_) external view returns (uint8 superformRouterId_);

Parameters

NameTypeDescription
router_addressis the address of a router

Returns

NameTypeDescription
superformRouterId_uint8is the id of a superform router / state syncer

isValidStateRegistry

helps validate if an address is a valid state registry

function isValidStateRegistry(address registryAddress_) external view returns (bool valid_);

Parameters

NameTypeDescription
registryAddress_addressis the address of the state registry

Returns

NameTypeDescription
valid_boola flag indicating if its valid.

isValidAmbImpl

helps validate if an address is a valid amb implementation

function isValidAmbImpl(address ambAddress_) external view returns (bool valid_);

Parameters

NameTypeDescription
ambAddress_addressis the address of the amb implementation

Returns

NameTypeDescription
valid_boola flag indicating if its valid.

isValidBroadcastAmbImpl

helps validate if an address is a valid broadcast amb implementation

function isValidBroadcastAmbImpl(address ambAddress_) external view returns (bool valid_);

Parameters

NameTypeDescription
ambAddress_addressis the address of the broadcast amb implementation

Returns

NameTypeDescription
valid_boola flag indicating if its valid.

getBridgeValidator

gets the address of a bridge validator

function getBridgeValidator(uint8 bridgeId_) external view returns (address bridgeValidator_);

Parameters

NameTypeDescription
bridgeId_uint8is the id of a bridge

Returns

NameTypeDescription
bridgeValidator_addressis the address of the form

getAmbAddress

gets the address of a amb

function getAmbAddress(uint8 ambId_) external view returns (address ambAddress_);

Parameters

NameTypeDescription
ambId_uint8is the id of a bridge

Returns

NameTypeDescription
ambAddress_addressis the address of the form

Events

SetPermit2

emitted when permit2 is set.

event SetPermit2(address indexed permit2);

AddressUpdated

is emitted when an address is set.

event AddressUpdated(
    bytes32 indexed protocolAddressId, uint64 indexed chainId, address indexed oldAddress, address newAddress
);

SetBridgeAddress

is emitted when a new token bridge is configured.

event SetBridgeAddress(uint256 indexed bridgeId, address indexed bridgeAddress);

SetBridgeValidator

is emitted when a new bridge validator is configured.

event SetBridgeValidator(uint256 indexed bridgeId, address indexed bridgeValidator);

SetAmbAddress

is emitted when a new amb is configured.

event SetAmbAddress(uint8 ambId_, address ambAddress_, bool isBroadcastAMB_);

SetStateRegistryAddress

is emitted when a new state registry is configured.

event SetStateRegistryAddress(uint8 registryId_, address registryAddress_);

SetRouterInfo

is emitted when a new router/state syncer is configured.

event SetRouterInfo(uint8 superFormRouterId_, address stateSyncer_, address router_);

SetDelay

is emitted when a new delay is configured.

event SetDelay(uint256 oldDelay_, uint256 newDelay_);

ISuperTransmuter

Git Source

Inherits: IStateSyncer

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

interface for Super Transmuter

Functions

registerTransmuter

this overrides registerTransmuter from original transmuter implementation so that users cannot insert name, symbol, and decimals

anyone can register a transmuter for an existent superform

function registerTransmuter(uint256 superformId, bytes memory extraData_) external returns (address);

Parameters

NameTypeDescription
superformIduint256the superform to register a transmuter for
extraData_bytesis an optional param to broadcast changes to all chains

stateSyncBroadcast

allows sync register new superform ids using broadcast state registry

function stateSyncBroadcast(bytes memory data_) external payable;

Parameters

NameTypeDescription
data_bytesis the crosschain payload

ISuperformFactory

Git Source

Author: ZeroPoint Labs

Interface for Superform Factory

Functions

addFormImplementation

allows an admin to add a Form implementation to the factory

function addFormImplementation(address formImplementation_, uint32 formImplementationId_) external;

Parameters

NameTypeDescription
formImplementation_addressis the address of a form implementation
formImplementationId_uint32is the id of the form implementation (generated off-chain and equal in all chains)

createSuperform

To add new vaults to Form implementations, fusing them together into Superforms

function createSuperform(
    uint32 formImplementationId_,
    address vault_
)
    external
    returns (uint256 superformId_, address superform_);

Parameters

NameTypeDescription
formImplementationId_uint32is the form implementation we want to attach the vault to
vault_addressis the address of the vault

Returns

NameTypeDescription
superformId_uint256is the id of the created superform
superform_addressis the address of the created superform

stateSyncBroadcast

to synchronize superforms added to different chains using broadcast registry

function stateSyncBroadcast(bytes memory data_) external payable;

Parameters

NameTypeDescription
data_bytesis the cross-chain superform id

changeFormImplementationPauseStatus

allows an admin to change the status of a form

function changeFormImplementationPauseStatus(
    uint32 formImplementationId_,
    bool status_,
    bytes memory extraData_
)
    external
    payable;

Parameters

NameTypeDescription
formImplementationId_uint32is the id of the form implementation
status_boolis the new status
extraData_bytesis optional & passed when broadcasting of status is needed

getFormImplementation

returns the address of a form implementation

function getFormImplementation(uint32 formImplementationId_) external view returns (address formImplementation_);

Parameters

NameTypeDescription
formImplementationId_uint32is the id of the form implementation

Returns

NameTypeDescription
formImplementation_addressis the address of the form implementation

isFormImplementationPaused

returns the paused status of form implementation

function isFormImplementationPaused(uint32 formImplementationId_) external view returns (bool paused_);

Parameters

NameTypeDescription
formImplementationId_uint32is the id of the form implementation

Returns

NameTypeDescription
paused_boolis the current paused status of the form formImplementationId_

getSuperform

returns the address of a superform

function getSuperform(uint256 superformId_)
    external
    pure
    returns (address superform_, uint32 formImplementationId_, uint64 chainId_);

Parameters

NameTypeDescription
superformId_uint256is the id of the superform

Returns

NameTypeDescription
superform_addressis the address of the superform
formImplementationId_uint32is the id of the form implementation
chainId_uint64is the chain id

getAllSuperformsFromVault

Reverse query of getSuperform, returns all superforms for a given vault

function getAllSuperformsFromVault(address vault_)
    external
    view
    returns (uint256[] memory superformIds_, address[] memory superforms_);

Parameters

NameTypeDescription
vault_addressis the address of a vault

Returns

NameTypeDescription
superformIds_uint256[]is the id of the superform
superforms_address[]is the address of the superform

getAllSuperforms

Returns all Superforms

function getAllSuperforms() external view returns (uint256[] memory superformIds_, address[] memory vaults_);

Returns

NameTypeDescription
superformIds_uint256[]is the id of the superform
vaults_address[]is the address of the vault

getFormCount

returns the number of forms

function getFormCount() external view returns (uint256 forms_);

Returns

NameTypeDescription
forms_uint256is the number of forms

getSuperformCount

returns the number of superforms

function getSuperformCount() external view returns (uint256 superforms_);

Returns

NameTypeDescription
superforms_uint256is the number of superforms

Events

FormImplementationAdded

emitted when a new formImplementation is entered into the factory

event FormImplementationAdded(address indexed formImplementation, uint256 indexed formImplementationId);

Parameters

NameTypeDescription
formImplementationaddressis the address of the new form implementation
formImplementationIduint256is the id of the formImplementation

SuperformCreated

emitted when a new Superform is created

event SuperformCreated(
    uint256 indexed formImplementationId, address indexed vault, uint256 indexed superformId, address superform
);

Parameters

NameTypeDescription
formImplementationIduint256is the id of the form implementation
vaultaddressis the address of the vault
superformIduint256is the id of the superform
superformaddressis the address of the superform

SuperRegistrySet

emitted when a new SuperRegistry is set

event SuperRegistrySet(address indexed superRegistry);

Parameters

NameTypeDescription
superRegistryaddressis the address of the super registry

ITimelockStateRegistry

Git Source

Author: ZeroPoint Labs

Interface for Two Steps Form State Registry

Functions

receivePayload

Receives request (payload) from two steps form to process later

function receivePayload(
    uint8 type_,
    address srcSender_,
    uint64 srcChainId_,
    uint256 lockedTill_,
    InitSingleVaultData memory data_
)
    external;

Parameters

NameTypeDescription
type_uint8is the nature of transaction (xChain: 1 or same chain: 0)
srcSender_addressis the address of the source chain caller
srcChainId_uint64is the chainId of the source chain
lockedTill_uint256is the deadline for timelock (after which we can call finalizePayload)
data_InitSingleVaultDatais the basic information of superformId, amount to withdraw of type InitSingleVaultData

finalizePayload

Form Keeper finalizes payload to process two steps withdraw fully

function finalizePayload(uint256 payloadId_, bytes memory txData_) external payable;

Parameters

NameTypeDescription
payloadId_uint256is the id of the payload to finalize
txData_bytesis the off-chain generated transaction data

getTimelockPayload

allows users to read the timeLockPayload_ stored per payloadId_

function getTimelockPayload(uint256 payloadId_) external view returns (TimelockPayload memory timeLockPayload_);

Parameters

NameTypeDescription
payloadId_uint256is the unqiue payload identifier allocated on the destination chain

Returns

NameTypeDescription
timeLockPayload_TimelockPayloadthe timelock payload stored

timelockPayloadCounter

allows users to read the timelockPayloadCounter

function timelockPayloadCounter() external view returns (uint256);

Contents

ArrayCastLib

Git Source

not gas optimized, suggested for usage only in view/pure functions

library to cast single values into array for streamlining helper functions

Functions

castToArray

function castToArray(LiqRequest memory value_) internal pure returns (LiqRequest[] memory values);

DataLib

Git Source

rationale for "memory-safe" assembly: https://docs.soliditylang.org/en/v0.8.20/assembly.html#memory-safety

Functions

packTxInfo

function packTxInfo(
    uint8 txType_,
    uint8 callbackType_,
    uint8 multi_,
    uint8 registryId_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    pure
    returns (uint256 txInfo);

decodeTxInfo

function decodeTxInfo(uint256 txInfo_)
    internal
    pure
    returns (uint8 txType, uint8 callbackType, uint8 multi, uint8 registryId, address srcSender, uint64 srcChainId);

getSuperform

returns the vault-form-chain pair of a superform

function getSuperform(uint256 superformId_)
    internal
    pure
    returns (address superform_, uint32 formImplementationId_, uint64 chainId_);

Parameters

NameTypeDescription
superformId_uint256is the id of the superform

Returns

NameTypeDescription
superform_addressis the address of the superform
formImplementationId_uint32is the form id
chainId_uint64is the chain id

getSuperforms

returns the vault-form-chain pair of an array of superforms

function getSuperforms(uint256[] memory superformIds_)
    internal
    pure
    returns (address[] memory superforms_, uint32[] memory formIds_, uint64[] memory chainIds_);

Parameters

NameTypeDescription
superformIds_uint256[]array of superforms

Returns

NameTypeDescription
superforms_address[]are the address of the vaults
formIds_uint32[]are the form ids
chainIds_uint64[]are the chain ids

validateSuperformChainId

pointer to the end of the superformIds_ array (shl(5, mload(superformIds_)) == mul(32, mload(superformIds_))

initialize pointers for all the 4 arrays

execute what getSuperform() does on a single superformId and store the results in the respective arrays

increment pointers

check if we've reached the end of the array

validates if the superformId_ belongs to the chainId_

function validateSuperformChainId(uint256 superformId_, uint64 chainId_) internal pure;

Parameters

NameTypeDescription
superformId_uint256to validate
chainId_uint64is the chainId to check if the superform id belongs to

getDestinationChain

validates if superformId exists on factory

returns the destination chain of a given superform

function getDestinationChain(uint256 superformId_) internal pure returns (uint64 chainId_);

Parameters

NameTypeDescription
superformId_uint256is the id of the superform

Returns

NameTypeDescription
chainId_uint64is the chain id

packSuperform

generates the superformId

function packSuperform(
    address superform_,
    uint32 formImplementationId_,
    uint64 chainId_
)
    internal
    pure
    returns (uint256 superformId_);

Parameters

NameTypeDescription
superform_addressis the address of the superform
formImplementationId_uint32is the type of the form
chainId_uint64is the chain id on which the superform is deployed

PayloadUpdaterLib

Git Source

library to validate slippage updation

Functions

validateSlippage

function validateSlippage(
    uint256 newAmount_,
    uint256 maxAmount_,
    uint256 slippage_
)
    internal
    pure
    returns (bool valid_);

strictValidateSlippage

args validation

amount must fall within the slippage bounds

function strictValidateSlippage(
    uint256 newAmount_,
    uint256 maxAmount_,
    uint256 slippage_
)
    internal
    pure
    returns (bool valid_);

validateLiqReq

args validation

amount must fall within the slippage bounds

function validateLiqReq(LiqRequest memory req_) internal pure;

validateDepositPayloadUpdate

req token should be address(0) req tx data length should be 0

function validateDepositPayloadUpdate(
    uint256 txInfo_,
    PayloadState currentPayloadState_,
    uint8 isMulti_
)
    internal
    pure;

validateWithdrawPayloadUpdate

function validateWithdrawPayloadUpdate(
    uint256 txInfo_,
    PayloadState currentPayloadState_,
    uint8 isMulti_
)
    internal
    pure;

ProofLib

Git Source

generates proof for amb message and bytes encoded message

Functions

computeProof

function computeProof(AMBMessage memory message_) internal pure returns (bytes32);

computeProofBytes

function computeProofBytes(AMBMessage memory message_) internal pure returns (bytes memory);

computeProof

function computeProof(bytes memory message_) internal pure returns (bytes32);

computeProofBytes

function computeProofBytes(bytes memory message_) internal pure returns (bytes memory);

Contents

PayMaster

Git Source

Inherits: IPayMaster, LiquidityHandler

Author: ZeroPoint Labs

State Variables

superRegistry

ISuperRegistry public superRegistry;

totalFeesPaid

mapping(address => uint256) public totalFeesPaid;

Functions

onlyPaymentAdmin

modifier onlyPaymentAdmin();

constructor

constructor(address superRegistry_);

withdrawTo

withdraws funds from pay master to target id from superRegistry

function withdrawTo(bytes32 superRegistryId_, uint256 nativeAmount_) external override onlyPaymentAdmin;

Parameters

NameTypeDescription
superRegistryId_bytes32is the id of the target address in superRegistry
nativeAmount_uint256is the amount to withdraw from pay master

rebalanceTo

withdraws fund from pay master to target id from superRegistry

function rebalanceTo(
    bytes32 superRegistryId_,
    LiqRequest memory req_,
    uint64 dstChainId_
)
    external
    override
    onlyPaymentAdmin;

Parameters

NameTypeDescription
superRegistryId_bytes32is the id of the target address in superRegistry
req_LiqRequestis the off-chain generated liquidity request to move funds
dstChainId_uint64is the destination chain id

makePayment

accepts payment from user

function makePayment(address user_) external payable override;

Parameters

NameTypeDescription
user_addressis the wallet address of the paying user

_withdrawNative

helper to move native tokens same chain

function _withdrawNative(address receiver_, uint256 amount_) internal;

_validateAndDispatchTokens

helper to move native tokens cross-chain

function _validateAndDispatchTokens(LiqRequest memory liqRequest_, address receiver_) internal;

ReadOnlyBaseRegistry

Git Source

Inherits: IBaseStateRegistry

interface to read public variable from state registry

Functions

payloadsCount

function payloadsCount() external view returns (uint256);

PaymentHelper

Git Source

Inherits: IPaymentHelper

Author: ZeroPoint Labs

helps estimating the cost for the entire transaction lifecycle

State Variables

superRegistry

is the address of the superRegistry on the chain

ISuperRegistry public immutable superRegistry;

CHAIN_ID

uint64 public immutable CHAIN_ID;

NATIVE

address constant NATIVE = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

TIMELOCK_FORM_ID

uint32 public constant TIMELOCK_FORM_ID = 1;

nativeFeedOracle

xchain params

mapping(uint64 chainId => AggregatorV3Interface) public nativeFeedOracle;

gasPriceOracle

mapping(uint64 chainId => AggregatorV3Interface) public gasPriceOracle;

swapGasUsed

mapping(uint64 chainId => uint256 gasForSwap) public swapGasUsed;

updateGasUsed

mapping(uint64 chainId => uint256 gasForUpdate) public updateGasUsed;

depositGasUsed

mapping(uint64 chainId => uint256 gasForOps) public depositGasUsed;

withdrawGasUsed

mapping(uint64 chainId => uint256 gasForOps) public withdrawGasUsed;

nativePrice

mapping(uint64 chainId => uint256 defaultNativePrice) public nativePrice;

gasPrice

mapping(uint64 chainId => uint256 defaultGasPrice) public gasPrice;

gasPerKB

mapping(uint64 chainId => uint256 gasPerKB) public gasPerKB;

ackGasCost

mapping(uint64 chainId => uint256 gasForOps) public ackGasCost;

twoStepCost

mapping(uint64 chainId => uint256 gasForOps) public twoStepCost;

Functions

onlyProtocolAdmin

modifier onlyProtocolAdmin();

onlyEmergencyAdmin

modifier onlyEmergencyAdmin();

constructor

constructor(address superRegistry_);

addChain

admin config destination chain config for estimation

function addChain(uint64 chainId_, PaymentHelperConfig calldata config_) external override onlyProtocolAdmin;

Parameters

NameTypeDescription
chainId_uint64is the identifier of new chain id
config_PaymentHelperConfigis the chain config

updateChainConfig

admin update remote chain config for estimation

function updateChainConfig(
    uint64 chainId_,
    uint256 configType_,
    bytes memory config_
)
    external
    override
    onlyEmergencyAdmin;

Parameters

NameTypeDescription
chainId_uint64is the remote chain's identifier
configType_uint256is the type of config from 1 -> 6
config_bytesis the encoded new configuration

calculateAMBData

Type 1: DST TOKEN PRICE FEED ORACLE

Type 2: DST GAS PRICE ORACLE

Type 3: PAYLOAD UPDATE GAS COST PER TX FOR DEPOSIT

Type 4: DEPOSIT GAS COST PER TX

Type 5: WITHDRAW GAS COST PER TX

Type 6: DEFAULT NATIVE PRICE

Type 7: DEFAULT GAS PRICE

Type 8: GAS PRICE PER KB of Message

Type 9: ACK GAS COST

Type 10: TWO STEP PROCESSING COST

Type 11: SWAP GAS USED

function calculateAMBData(
    uint64 dstChainId_,
    uint8[] calldata ambIds_,
    bytes memory message_
)
    external
    view
    override
    returns (uint256 totalFees, bytes memory extraData);

Parameters

NameTypeDescription
dstChainId_uint64is the unique dst chain identifier
ambIds_uint8[]is the identifiers of arbitrary message bridges to be used
message_bytesis the encoded cross-chain payload

estimateMultiDstMultiVault

estimates the gas fees for multiple destination and multi vault operation

function estimateMultiDstMultiVault(
    MultiDstMultiVaultStateReq calldata req_,
    bool isDeposit_
)
    external
    view
    override
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_MultiDstMultiVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDeposit_bool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateMultiDstSingleVault

optimistically estimating. (Ideal case scenario: no failed deposits / withdrawals)

step 1: estimate amb costs

step 2: estimate update cost (only for deposit)

step 3: estimation processing cost of acknowledgement

step 4: estimate liq amount

step 5: estimate dst swap cost if it exists

step 6: estimate execution costs in dst (withdraw / deposit) note: execution cost includes acknowledgement messaging cost

step 7: convert all dst gas estimates to src chain estimate (withdraw / deposit)

function estimateMultiDstSingleVault(
    MultiDstSingleVaultStateReq calldata req_,
    bool isDeposit_
)
    external
    view
    override
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_MultiDstSingleVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDeposit_bool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateSingleXChainMultiVault

step 1: estimate amb costs

step 2: estimate update cost (only for deposit)

step 3: estimation execution cost of acknowledgement

step 4: estimate the liqAmount

step 5: estimate if swap costs are involved

step 5: estimate execution costs in dst note: execution cost includes acknowledgement messaging cost

step 6: convert all dst gas estimates to src chain estimate

function estimateSingleXChainMultiVault(
    SingleXChainMultiVaultStateReq calldata req_,
    bool isDeposit_
)
    external
    view
    override
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_SingleXChainMultiVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter ///
isDeposit_bool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateSingleXChainSingleVault

step 1: estimate amb costs

step 2: estimate update cost (only for deposit)

step 3: estimate execution costs in dst note: execution cost includes acknowledgement messaging cost

step 4: estimation execution cost of acknowledgement

step 5: estimate liq amount

step 6: estimate if swap costs are involved

step 7: convert all dst gas estimates to src chain estimate

function estimateSingleXChainSingleVault(
    SingleXChainSingleVaultStateReq calldata req_,
    bool isDeposit_
)
    external
    view
    override
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_SingleXChainSingleVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDeposit_bool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateSingleDirectSingleVault

step 1: estimate amb costs

step 2: estimate update cost (only for deposit)

step 3: estimate execution costs in dst note: execution cost includes acknowledgement messaging cost

step 4: estimation execution cost of acknowledgement

step 5: estimate the liq amount

step 6: estimate if swap costs are involved

step 7: convert all dst gas estimates to src chain estimate

function estimateSingleDirectSingleVault(
    SingleDirectSingleVaultStateReq calldata req_,
    bool isDeposit_
)
    external
    view
    override
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_SingleDirectSingleVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDeposit_bool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateSingleDirectMultiVault

only if timelock form withdrawal is involved

not adding dstAmount to save some GAS

function estimateSingleDirectMultiVault(
    SingleDirectMultiVaultStateReq calldata req_,
    bool isDeposit_
)
    external
    view
    override
    returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);

Parameters

NameTypeDescription
req_SingleDirectMultiVaultStateReqis the request object containing all necessary data for the actual operation on SuperRouter
isDeposit_bool

Returns

NameTypeDescription
liqAmountuint256is the amount of liquidity to be provided in native tokens
srcAmountuint256is the gas expense on source chain in native tokens
dstAmountuint256is the gas expense on dst chain in terms of src chain's native tokens
totalAmountuint256is the native_tokens to be sent along the transaction

estimateAMBFees

only if timelock form withdrawal is involved

not adding dstAmount to save some GAS

function estimateAMBFees(
    uint8[] memory ambIds_,
    uint64 dstChainId_,
    bytes memory message_,
    bytes[] memory extraData_
)
    public
    view
    returns (uint256 totalFees, uint256[] memory);

Parameters

NameTypeDescription
ambIds_uint8[]is the identifier of different AMBs
dstChainId_uint64is the identifier of the destination chain
message_bytesis the cross-chain message
extraData_bytes[]is any amb-specific information

Returns

NameTypeDescription
totalFeesuint256ambFees is the native_tokens to be sent along the transaction for all the ambIds_ included
<none>uint256[]

_generateExtraData

just checks the estimate for sending message from src -> dst

helps generate extra data per amb

function _generateExtraData(
    uint64 dstChainId_,
    uint8[] calldata ambIds_,
    bytes memory message_
)
    public
    view
    returns (bytes[] memory extraDataPerAMB);

_estimateAMBFees

helps estimate the cross-chain message costs

function _estimateAMBFees(
    uint8[] calldata ambIds_,
    uint64 dstChainId_,
    bytes memory message_
)
    public
    view
    returns (uint256[] memory feeSplitUp, uint256 totalFees);

_estimateAMBFeesReturnExtraData

just checks the estimate for sending message from src -> dst

only ambIds_[0] = primary amb (rest of the ambs send only the proof)

helps estimate the cross-chain message costs

function _estimateAMBFeesReturnExtraData(
    uint64 dstChainId_,
    uint8[] calldata ambIds_,
    bytes memory message_
)
    public
    view
    returns (uint256[] memory feeSplitUp, bytes[] memory extraDataPerAMB, uint256 totalFees);

_estimateLiqAmount

just checks the estimate for sending message from src -> dst

helps estimate the liq amount involved in the tx

function _estimateLiqAmount(LiqRequest[] memory req_) internal view returns (uint256 liqAmount);

_estimateSwapFees

helps estimate the dst chain swap gas limit (if multi-tx is involved)

function _estimateSwapFees(uint64 dstChainId_, LiqRequest[] memory liqReq_) internal view returns (uint256 gasUsed);

_estimateUpdateCost

checks if tx_data receiver is dstSwapProcessor

helps estimate the dst chain update payload gas limit

function _estimateUpdateCost(uint64 dstChainId_, uint256 vaultsCount_) internal view returns (uint256 gasUsed);

_estimateDstExecutionCost

helps estimate the dst chain processing gas limit

function _estimateDstExecutionCost(
    bool isDeposit_,
    uint64 dstChainId_,
    uint256 vaultsCount_
)
    internal
    view
    returns (uint256 gasUsed);

_estimateAckProcessingCost

helps estimate the src chain processing fee

function _estimateAckProcessingCost(
    uint256 dstChainCount_,
    uint256 vaultsCount_
)
    internal
    view
    returns (uint256 nativeFee);

_generateSingleVaultMessage

generates the amb message for single vault data

function _generateSingleVaultMessage(SingleVaultSFData memory sfData_) internal view returns (bytes memory message_);

_generateMultiVaultMessage

sample router id for estimation

generates the amb message for multi vault data

function _generateMultiVaultMessage(MultiVaultSFData memory sfData_) internal view returns (bytes memory message_);

_convertToNativeFee

sample router id for estimation

helps convert the dst gas fee into src chain native fee

https://docs.soliditylang.org/en/v0.8.4/units-and-global-variables.html#ether-units

all native tokens should be 18 decimals across all EVMs

function _convertToNativeFee(uint64 dstChainId_, uint256 dstGas_) internal view returns (uint256 nativeFee);

_getNextPayloadId

gas fee * gas price (to get the gas amounts in dst chain's native token)

gas price is 9 decimal (in gwei)

assumption: all evm native tokens are 18 decimals

converts the gas to pay in terms of native token to usd value

native token price is 8 decimal

converts the usd value to source chain's native token

native token price is 8 decimal which cancels the 8 decimal multiplied in previous step

helps generate the new payload id

next payload id = current payload id + 1

function _getNextPayloadId() internal view returns (uint256 nextPayloadId);

_getGasPrice

helps return the current gas price of different networks

function _getGasPrice(uint64 chainId_) internal view returns (uint256);

Returns

NameTypeDescription
<none>uint256native token price

_getNativeTokenPrice

helps return the dst chain token price of different networks

function _getNativeTokenPrice(uint64 chainId_) internal view returns (uint256);

Returns

NameTypeDescription
<none>uint256native token price

Contents

SuperRBAC

Git Source

Inherits: ISuperRBAC, AccessControlEnumerable

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

Contract to manage roles in the entire superform protocol

State Variables

SYNC_REVOKE

bytes32 public constant SYNC_REVOKE = keccak256("SYNC_REVOKE");

PROTOCOL_ADMIN_ROLE

used in many areas of the codebase to perform config operations

could be worth to have this changeable in case it gets compromised (but without ability to revoke itself)

changeable by which role?

single address

bytes32 public constant override PROTOCOL_ADMIN_ROLE = keccak256("PROTOCOL_ADMIN_ROLE");

EMERGENCY_ADMIN_ROLE

used in a few areas of the code

could be worth to have this changeable in case it gets compromised (but without ability to revoke itself)

changeable by which role?

single address

bytes32 public constant override EMERGENCY_ADMIN_ROLE = keccak256("EMERGENCY_ADMIN_ROLE");

PAYMENT_ADMIN_ROLE

used to extract funds from PayMaster

could be allowed to be changed

single address

bytes32 public constant override PAYMENT_ADMIN_ROLE = keccak256("PAYMENT_ADMIN_ROLE");

BROADCASTER_ROLE

used so that certain contracts can broadcast state changes to all connected remote chains

currently SUPERFORM_FACTORY, SUPERTRANSMUTER and SUPER_RBAC have this role. SUPER_RBAC doesn't need it

should NOT be allowed to be changed (maps to more than 1 address)

multi address (revoke broadcast should be restricted)

bytes32 public constant override BROADCASTER_ROLE = keccak256("BROADCASTER_ROLE");

CORE_STATE_REGISTRY_PROCESSOR_ROLE

keeper role, should be allowed to be changed

single address

bytes32 public constant override CORE_STATE_REGISTRY_PROCESSOR_ROLE = keccak256("CORE_STATE_REGISTRY_PROCESSOR_ROLE");

TIMELOCK_STATE_REGISTRY_PROCESSOR_ROLE

keeper role, should be allowed to be changed

single address

bytes32 public constant override TIMELOCK_STATE_REGISTRY_PROCESSOR_ROLE =
    keccak256("TIMELOCK_STATE_REGISTRY_PROCESSOR_ROLE");

BROADCAST_STATE_REGISTRY_PROCESSOR_ROLE

keeper role, should be allowed to be changed

single address

bytes32 public constant override BROADCAST_STATE_REGISTRY_PROCESSOR_ROLE =
    keccak256("BROADCAST_STATE_REGISTRY_PROCESSOR_ROLE");

CORE_STATE_REGISTRY_UPDATER_ROLE

keeper role, should be allowed to be changed

single address

bytes32 public constant override CORE_STATE_REGISTRY_UPDATER_ROLE = keccak256("CORE_STATE_REGISTRY_UPDATER_ROLE");

CORE_STATE_REGISTRY_RESCUER_ROLE

keeper role, should be allowed to be changed

single address

bytes32 public constant override CORE_STATE_REGISTRY_RESCUER_ROLE = keccak256("CORE_STATE_REGISTRY_RESCUER_ROLE");

CORE_STATE_REGISTRY_DISPUTER_ROLE

keeper role, should be allowed to be changed

single address

bytes32 public constant override CORE_STATE_REGISTRY_DISPUTER_ROLE = keccak256("CORE_STATE_REGISTRY_DISPUTER_ROLE");

WORMHOLE_VAA_RELAYER_ROLE

this is a role so that we could run multiple relayers

should be allowed to be changed

multi address (revoke broadcast should be restricted)

bytes32 public constant override WORMHOLE_VAA_RELAYER_ROLE = keccak256("WORMHOLE_VAA_RELAYER_ROLE");

DST_SWAPPER_ROLE

keeper role, should be allowed to be changed

single address

bytes32 public constant override DST_SWAPPER_ROLE = keccak256("DST_SWAPPER_ROLE");

superRegistry

ISuperRegistry public superRegistry;

Functions

constructor

constructor(InitialRoleSetup memory roles);

setSuperRegistry

manually set role admin to PROTOCOL_ADMIN_ROLE on all roles

function setSuperRegistry(address superRegistry_) external override onlyRole(PROTOCOL_ADMIN_ROLE);

setRoleAdmin

configures a new role in superForm

function setRoleAdmin(bytes32 role_, bytes32 adminRole_) external override onlyRole(PROTOCOL_ADMIN_ROLE);

Parameters

NameTypeDescription
role_bytes32the role to set
adminRole_bytes32the admin role to set as admin

revokeRoleSuperBroadcast

revokes the role_ from superRegistryAddressId_ on all chains

function revokeRoleSuperBroadcast(
    bytes32 role_,
    address addressToRevoke_,
    bytes memory extraData_,
    bytes32 superRegistryAddressId_
)
    external
    payable
    override
    onlyRole(PROTOCOL_ADMIN_ROLE);

Parameters

NameTypeDescription
role_bytes32the role to revoke
addressToRevoke_addressthe address to revoke the role from
extraData_bytesamb config if broadcasting is required
superRegistryAddressId_bytes32the super registry address id

stateSyncBroadcast

may not work for all roles

revokeRoleSuperBroadcast cannot update the PROTOCOL_ADMIN_ROLE and EMERGENCY_ADMIN_ROLE

function stateSyncBroadcast(bytes memory data_) external override;

hasProtocolAdminRole

broadcasting cannot update the PROTOCOL_ADMIN_ROLE and EMERGENCY_ADMIN_ROLE

function hasProtocolAdminRole(address admin_) external view override returns (bool);

Parameters

NameTypeDescription
admin_addressthe address to check

hasEmergencyAdminRole

returns whether the given address has the emergency admin role

function hasEmergencyAdminRole(address emergencyAdmin_) external view override returns (bool);

Parameters

NameTypeDescription
emergencyAdmin_address

_revokeRole

Overload _revokeRole to track enumerable memberships

function _revokeRole(bytes32 role_, address account_) internal override;

_broadcast

interacts with role state registry to broadcasting state changes to all connected remote chains

function _broadcast(bytes memory message_, bytes memory extraData_) internal;

Parameters

NameTypeDescription
message_bytesis the crosschain message to be sent.
extraData_bytesis the amb override information.

SuperRegistry

Git Source

Inherits: ISuperRegistry, QuorumManager

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

Keeps information on all addresses used in the Superforms ecosystem.

State Variables

MIN_DELAY

uint256 public constant MIN_DELAY = 1 hours;

MAX_DELAY

uint256 public constant MAX_DELAY = 24 hours;

PERMIT2

canonical permit2 contract

address public PERMIT2;

delay

rescue timelock delay config

uint256 public delay;

CHAIN_ID

uint64 public immutable CHAIN_ID;

registry

mapping(bytes32 id => mapping(uint64 chainid => address moduleAddress)) private registry;

bridgeAddresses

bridge id is mapped to a bridge address (to prevent interaction with unauthorized bridges)

mapping(uint8 bridgeId => address bridgeAddress) public bridgeAddresses;

bridgeValidator

mapping(uint8 bridgeId => address bridgeValidator) public bridgeValidator;

ambAddresses

mapping(uint8 bridgeId => address ambAddresses) public ambAddresses;

isBroadcastAMB

mapping(uint8 bridgeId => bool isBroadcastAMB) public isBroadcastAMB;

stateSyncers

mapping(uint8 superformRouterId => address stateSyncer) public stateSyncers;

routers

mapping(uint8 superformRouterId => address router) public routers;

registryAddresses

mapping(uint8 registryId => address registryAddress) public registryAddresses;

stateRegistryIds

is the reverse mapping of registryAddresses

mapping(address registryAddress => uint8 registryId) public stateRegistryIds;

ambIds

is the reverse mapping of ambAddresses

mapping(address ambAddress => uint8 bridgeId) public ambIds;

superformRouterIds

is the reverse mapping of routers

mapping(address router => uint8 superformRouterId) public superformRouterIds;

SUPERFORM_ROUTER

SUPERFORM_FACTORY, CORE_STATE_REGISTRY, TIMELOCK_STATE_REGISTRY, BROADCAST_REGISTRY, SUPER_RBAC, DST_SWAPPER

should not be allowed to be changed

core protocol - identifiers

not accessed in protocol

could be allowed to be changed

bytes32 public constant override SUPERFORM_ROUTER = keccak256("SUPERFORM_ROUTER");

SUPERFORM_FACTORY

can be used to set a new factory that has form ids paused

probably should NOT be allowed to be changed

bytes32 public constant override SUPERFORM_FACTORY = keccak256("SUPERFORM_FACTORY");

SUPER_TRANSMUTER

not accessed in protocol

could be allowed to be changed

bytes32 public constant override SUPER_TRANSMUTER = keccak256("SUPER_TRANSMUTER");

PAYMASTER

can be used to set a new paymaster to forward payments to

could be allowed to be changed

bytes32 public constant override PAYMASTER = keccak256("PAYMASTER");

PAYMENT_HELPER

accessed in some areas of the protocol to calculate AMB fees. Already has a function to alter the configuration

could be allowed to be changed

bytes32 public constant override PAYMENT_HELPER = keccak256("PAYMENT_HELPER");

CORE_STATE_REGISTRY

accessed in many areas of the protocol. has direct access to superforms

should NOT be allowed to be changed

bytes32 public constant override CORE_STATE_REGISTRY = keccak256("CORE_STATE_REGISTRY");

TIMELOCK_STATE_REGISTRY

accessed in many areas of the protocol. has direct access to timelock form

should NOT be allowed to be changed

bytes32 public constant override TIMELOCK_STATE_REGISTRY = keccak256("TIMELOCK_STATE_REGISTRY");

BROADCAST_REGISTRY

used to sync messages for pausing superforms or deploying transmuters

probably should NOT be allowed to be changed

bytes32 public constant override BROADCAST_REGISTRY = keccak256("BROADCAST_REGISTRY");

SUPER_POSITIONS

not accessed in protocol

could be allowed to be changed

bytes32 public constant override SUPER_POSITIONS = keccak256("SUPER_POSITIONS");

SUPER_RBAC

accessed in many areas of the protocol

probably should NOT be allowed to be changed

bytes32 public constant override SUPER_RBAC = keccak256("SUPER_RBAC");

PAYLOAD_HELPER

not accessed in protocol

could be allowed to be changed

bytes32 public constant override PAYLOAD_HELPER = keccak256("PAYLOAD_HELPER");

DST_SWAPPER

accessed in CSR and validators. can be used to alter behaviour of update deposit payloads

probably should NOT be allowed to be changed

bytes32 public constant override DST_SWAPPER = keccak256("DST_SWAPPER");

EMERGENCY_QUEUE

accessed in base form to send payloads to emergency queue

probably should NOT be allowed to be changed

bytes32 public constant override EMERGENCY_QUEUE = keccak256("EMERGENCY_QUEUE");

PAYMENT_ADMIN

default keepers - identifiers

could be allowed to be changed

bytes32 public constant override PAYMENT_ADMIN = keccak256("PAYMENT_ADMIN");

CORE_REGISTRY_PROCESSOR

bytes32 public constant override CORE_REGISTRY_PROCESSOR = keccak256("CORE_REGISTRY_PROCESSOR");

BROADCAST_REGISTRY_PROCESSOR

bytes32 public constant override BROADCAST_REGISTRY_PROCESSOR = keccak256("BROADCAST_REGISTRY_PROCESSOR");

TIMELOCK_REGISTRY_PROCESSOR

bytes32 public constant override TIMELOCK_REGISTRY_PROCESSOR = keccak256("TIMELOCK_REGISTRY_PROCESSOR");

CORE_REGISTRY_UPDATER

bytes32 public constant override CORE_REGISTRY_UPDATER = keccak256("CORE_REGISTRY_UPDATER");

CORE_REGISTRY_RESCUER

bytes32 public constant override CORE_REGISTRY_RESCUER = keccak256("CORE_REGISTRY_RESCUER");

CORE_REGISTRY_DISPUTER

bytes32 public constant override CORE_REGISTRY_DISPUTER = keccak256("CORE_REGISTRY_DISPUTER");

DST_SWAPPER_PROCESSOR

bytes32 public constant override DST_SWAPPER_PROCESSOR = keccak256("DST_SWAPPER_PROCESSOR");

Functions

onlyProtocolAdmin

modifier onlyProtocolAdmin();

constructor

constructor(address superRBAC_);

setDelay

sets the deposit rescue delay

function setDelay(uint256 delay_) external override onlyProtocolAdmin;

Parameters

NameTypeDescription
delay_uint256the delay in seconds before the deposit rescue can be finalized

setPermit2

sets the permit2 address

function setPermit2(address permit2_) external override onlyProtocolAdmin;

Parameters

NameTypeDescription
permit2_addressthe address of the permit2 contract

setAddress

sets a new address on a specific chain.

function setAddress(bytes32 id_, address newAddress_, uint64 chainId_) external override onlyProtocolAdmin;

Parameters

NameTypeDescription
id_bytes32the identifier of the address on that chain
newAddress_addressthe new address on that chain
chainId_uint64the chain id of that chain

setBridgeAddresses

SUPERFORM_FACTORY, CORE_STATE_REGISTRY, TIMELOCK_STATE_REGISTRY, BROADCAST_REGISTRY, SUPER_RBAC, DST_SWAPPER cannot be changed once set

allows admin to set the bridge address for an bridge id.

function setBridgeAddresses(
    uint8[] memory bridgeId_,
    address[] memory bridgeAddress_,
    address[] memory bridgeValidator_
)
    external
    override
    onlyProtocolAdmin;

Parameters

NameTypeDescription
bridgeId_uint8[]represents the bridge unqiue identifier.
bridgeAddress_address[]represents the bridge address.
bridgeValidator_address[]represents the bridge validator address.

setAmbAddress

this function operates in an APPEND-ONLY fashion.

allows admin to set the amb address for an amb id.

function setAmbAddress(
    uint8[] memory ambId_,
    address[] memory ambAddress_,
    bool[] memory isBroadcastAMB_
)
    external
    override
    onlyProtocolAdmin;

Parameters

NameTypeDescription
ambId_uint8[]represents the bridge unqiue identifier.
ambAddress_address[]represents the bridge address.
isBroadcastAMB_bool[]represents whether the amb implementation supports broadcasting

setStateRegistryAddress

this function operates in an APPEND-ONLY fashion.

allows admin to set the state registry address for an state registry id.

function setStateRegistryAddress(
    uint8[] memory registryId_,
    address[] memory registryAddress_
)
    external
    override
    onlyProtocolAdmin;

Parameters

NameTypeDescription
registryId_uint8[]represents the state registry's unqiue identifier.
registryAddress_address[]represents the state registry's address.

setRouterInfo

this function operates in an APPEND-ONLY fashion.

allows admin to set the superform routers info

function setRouterInfo(
    uint8[] memory superformRouterIds_,
    address[] memory stateSyncers_,
    address[] memory routers_
)
    external
    override
    onlyProtocolAdmin;

Parameters

NameTypeDescription
superformRouterIds_uint8[]represents the superform router's unqiue identifier.
stateSyncers_address[]represents the state syncer's address.
routers_address[]represents the router's address.

setRequiredMessagingQuorum

function setRequiredMessagingQuorum(uint64 srcChainId_, uint256 quorum_) external override onlyProtocolAdmin;

getAddress

function getAddress(bytes32 id_) external view override returns (address);

getAddressByChainId

function getAddressByChainId(bytes32 id_, uint64 chainId_) external view override returns (address);

getBridgeAddress

gets the address of a bridge

function getBridgeAddress(uint8 bridgeId_) external view override returns (address bridgeAddress_);

Parameters

NameTypeDescription
bridgeId_uint8is the id of a bridge

Returns

NameTypeDescription
bridgeAddress_addressis the address of the form

getBridgeValidator

gets the address of a bridge validator

function getBridgeValidator(uint8 bridgeId_) external view override returns (address bridgeValidator_);

Parameters

NameTypeDescription
bridgeId_uint8is the id of a bridge

Returns

NameTypeDescription
bridgeValidator_addressis the address of the form

getAmbAddress

gets the address of a amb

function getAmbAddress(uint8 ambId_) external view override returns (address ambAddress_);

Parameters

NameTypeDescription
ambId_uint8is the id of a bridge

Returns

NameTypeDescription
ambAddress_addressis the address of the form

getAmbId

gets the id of the amb

function getAmbId(address ambAddress_) external view override returns (uint8 ambId_);

Parameters

NameTypeDescription
ambAddress_addressis the address of an amb

Returns

NameTypeDescription
ambId_uint8is the identifier of an amb

getStateRegistry

gets the address of the registry

function getStateRegistry(uint8 registryId_) external view override returns (address registryAddress_);

Parameters

NameTypeDescription
registryId_uint8is the id of the state registry

Returns

NameTypeDescription
registryAddress_addressis the address of the state registry

getStateRegistryId

reverts if the id is not found

gets the id of the registry

function getStateRegistryId(address registryAddress_) external view override returns (uint8 registryId_);

Parameters

NameTypeDescription
registryAddress_addressis the address of the state registry

Returns

NameTypeDescription
registryId_uint8is the id of the state registry

getStateSyncer

gets the address of a state syncer

function getStateSyncer(uint8 superformRouterId_) external view override returns (address stateSyncer_);

Parameters

NameTypeDescription
superformRouterId_uint8is the id of a state syncer

Returns

NameTypeDescription
stateSyncer_addressis the address of a state syncer

getRouter

gets the address of a router

function getRouter(uint8 superformRouterId_) external view override returns (address router_);

Parameters

NameTypeDescription
superformRouterId_uint8is the id of a state syncer

Returns

NameTypeDescription
router_addressis the address of a router

getSuperformRouterId

gets the id of a router

function getSuperformRouterId(address router_) external view override returns (uint8 superformRouterId_);

Parameters

NameTypeDescription
router_addressis the address of a router

Returns

NameTypeDescription
superformRouterId_uint8is the id of a superform router / state syncer

isValidStateRegistry

helps validate if an address is a valid state registry

function isValidStateRegistry(address registryAddress_) external view override returns (bool valid_);

Parameters

NameTypeDescription
registryAddress_addressis the address of the state registry

Returns

NameTypeDescription
valid_boola flag indicating if its valid.

isValidAmbImpl

helps validate if an address is a valid amb implementation

function isValidAmbImpl(address ambAddress_) external view override returns (bool valid_);

Parameters

NameTypeDescription
ambAddress_addressis the address of the amb implementation

Returns

NameTypeDescription
valid_boola flag indicating if its valid.

isValidBroadcastAmbImpl

helps validate if an address is a valid broadcast amb implementation

function isValidBroadcastAmbImpl(address ambAddress_) external view override returns (bool valid_);

Parameters

NameTypeDescription
ambAddress_addressis the address of the broadcast amb implementation

Returns

NameTypeDescription
valid_boola flag indicating if its valid.

Contents

TransactionType

Git Source

contains all the common struct and enums used for data communication between chains.

There are two transaction types in Superform Protocol

enum TransactionType {
    DEPOSIT,
    WITHDRAW
}

CallbackType

Git Source

Message types can be INIT, RETURN (for successful Deposits) and FAIL (for failed withdraws)

enum CallbackType {
    INIT,
    RETURN,
    FAIL
}

PayloadState

Git Source

Used only in withdraw flow now

Payloads are stored, updated (deposits) or processed (finalized)

enum PayloadState {
    STORED,
    UPDATED,
    PROCESSED
}

MultiVaultSFData

Git Source

main struct that holds required multi vault data for an action

struct MultiVaultSFData {
    uint256[] superformIds;
    uint256[] amounts;
    uint256[] maxSlippages;
    bool[] hasDstSwaps;
    LiqRequest[] liqRequests;
    bytes permit2data;
    address dstRefundAddress;
    bytes extraFormData;
}

SingleVaultSFData

Git Source

main struct that holds required single vault data for an action

struct SingleVaultSFData {
    uint256 superformId;
    uint256 amount;
    uint256 maxSlippage;
    bool hasDstSwap;
    LiqRequest liqRequest;
    bytes permit2data;
    address dstRefundAddress;
    bytes extraFormData;
}

MultiDstMultiVaultStateReq

Git Source

overarching struct for multiDst requests with multi vaults

struct MultiDstMultiVaultStateReq {
    uint8[][] ambIds;
    uint64[] dstChainIds;
    MultiVaultSFData[] superformsData;
}

SingleXChainMultiVaultStateReq

Git Source

overarching struct for single cross chain requests with multi vaults

struct SingleXChainMultiVaultStateReq {
    uint8[] ambIds;
    uint64 dstChainId;
    MultiVaultSFData superformsData;
}

MultiDstSingleVaultStateReq

Git Source

overarching struct for multiDst requests with single vaults

struct MultiDstSingleVaultStateReq {
    uint8[][] ambIds;
    uint64[] dstChainIds;
    SingleVaultSFData[] superformsData;
}

SingleXChainSingleVaultStateReq

Git Source

overarching struct for single cross chain requests with single vaults

struct SingleXChainSingleVaultStateReq {
    uint8[] ambIds;
    uint64 dstChainId;
    SingleVaultSFData superformData;
}

SingleDirectSingleVaultStateReq

Git Source

overarching struct for single direct chain requests with single vaults

struct SingleDirectSingleVaultStateReq {
    SingleVaultSFData superformData;
}

SingleDirectMultiVaultStateReq

Git Source

overarching struct for single direct chain requests with multi vaults

struct SingleDirectMultiVaultStateReq {
    MultiVaultSFData superformData;
}

InitMultiVaultData

Git Source

struct for SuperRouter with re-arranged data for the message (contains the payloadId)

struct InitMultiVaultData {
    uint8 superformRouterId;
    uint256 payloadId;
    uint256[] superformIds;
    uint256[] amounts;
    uint256[] maxSlippage;
    bool[] hasDstSwaps;
    LiqRequest[] liqData;
    address dstRefundAddress;
    bytes extraFormData;
}

InitSingleVaultData

Git Source

struct for SuperRouter with re-arranged data for the message (contains the payloadId)

struct InitSingleVaultData {
    uint8 superformRouterId;
    uint256 payloadId;
    uint256 superformId;
    uint256 amount;
    uint256 maxSlippage;
    bool hasDstSwap;
    LiqRequest liqData;
    address dstRefundAddress;
    bytes extraFormData;
}

QueuedWithdrawal

Git Source

struct for Emergency Queue

struct QueuedWithdrawal {
    address refundAddress;
    uint256 superformId;
    uint256 amount;
    uint256 srcPayloadId;
    bool isProcessed;
}

TwoStepsStatus

Git Source

all statuses of the two steps payload

enum TwoStepsStatus {
    UNAVAILABLE,
    PENDING,
    PROCESSED
}

TimelockPayload

Git Source

holds information about the two-steps payload

struct TimelockPayload {
    uint8 isXChain;
    address srcSender;
    uint64 srcChainId;
    uint256 lockedTill;
    InitSingleVaultData data;
    TwoStepsStatus status;
}

AMBMessage

Git Source

struct that contains the type of transaction, callback flags and other identification, as well as the vaults data in params

struct AMBMessage {
    uint256 txInfo;
    bytes params;
}

BroadcastMessage

Git Source

struct that contains the information required for broadcasting changes

struct BroadcastMessage {
    bytes target;
    bytes32 messageType;
    bytes message;
}

ReturnMultiData

Git Source

struct that contains info on returned data from destination

struct ReturnMultiData {
    uint8 superformRouterId;
    uint256 payloadId;
    uint256[] superformIds;
    uint256[] amounts;
}

ReturnSingleData

Git Source

struct that contains info on returned data from destination

struct ReturnSingleData {
    uint8 superformRouterId;
    uint256 payloadId;
    uint256 superformId;
    uint256 amount;
}

SingleDstAMBParams

Git Source

struct that contains the data on the fees to pay

struct SingleDstAMBParams {
    uint256 gasToPay;
    bytes encodedAMBExtraData;
}

AMBExtraData

Git Source

struct that contains the data on the fees to pay to the AMBs

struct AMBExtraData {
    uint256[] gasPerAMB;
    bytes[] extraDataPerAMB;
}

BroadCastAMBExtraData

Git Source

struct that contains the data on the fees to pay to the AMBs on broadcasts

struct BroadCastAMBExtraData {
    uint256[] gasPerDst;
    bytes[] extraDataPerDst;
}

AckAMBData

Git Source

acknowledgement extra data (contains gas information from dst to src callbacks)

struct AckAMBData {
    uint8[] ambIds;
    bytes extraData;
}

LiqRequest

Git Source

contains all the common struct used for interchain token transfers.

struct LiqRequest {
    uint8 bridgeId;
    bytes txData;
    address token;
    uint64 liqDstChainId;
    uint256 nativeAmount;
}

Contents

Error

Git Source

Errors

INVALID_INPUT_CHAIN_ID

is emitted when the chain id input is invalid.

error INVALID_INPUT_CHAIN_ID();

ZERO_ADDRESS

error thrown when address input is address 0

error ZERO_ADDRESS();

ZERO_AMOUNT

error thrown when address input is address 0

error ZERO_AMOUNT();

FORM_IMPLEMENTATION_ID_ALREADY_EXISTS

error thrown when beacon id already exists

error FORM_IMPLEMENTATION_ID_ALREADY_EXISTS();

NOT_CORE_STATE_REGISTRY

thrown when msg.sender is not core state registry

error NOT_CORE_STATE_REGISTRY();

NOT_EMERGENCY_QUEUE

thrown when msg.sender is not emergency queue

error NOT_EMERGENCY_QUEUE();

NOT_SUPERFORM

thrown when msg.sender is not form

error NOT_SUPERFORM();

NOT_TWO_STEP_SUPERFORM

thrown when msg.sender is not two step form

error NOT_TWO_STEP_SUPERFORM();

NOT_AMB_IMPLEMENTATION

thrown when msg.sender is not a valid amb implementation

error NOT_AMB_IMPLEMENTATION();

NOT_STATE_REGISTRY

thrown when msg.sender is not state registry

error NOT_STATE_REGISTRY();

NOT_ALLOWED_BROADCASTER

thrown when msg.sender is not an allowed broadcaster

error NOT_ALLOWED_BROADCASTER();

NOT_BROADCAST_REGISTRY

thrown when msg.sender is not broadcast state registry

error NOT_BROADCAST_REGISTRY();

NOT_BROADCAST_AMB_IMPLEMENTATION

thrown when msg.sender is not broadcast amb implementation

error NOT_BROADCAST_AMB_IMPLEMENTATION();

INVALID_BROADCAST_PAYLOAD

thrown if the broadcast payload is invalid

error INVALID_BROADCAST_PAYLOAD();

INVALID_DEPOSIT_TOKEN

thrown if the underlying collateral mismatches

error INVALID_DEPOSIT_TOKEN();

NOT_TWO_STEP_STATE_REGISTRY

thrown when msg.sender is not two step state registry

error NOT_TWO_STEP_STATE_REGISTRY();

NOT_PROTOCOL_ADMIN

thrown when msg.sender is not protocol admin

error NOT_PROTOCOL_ADMIN();

NOT_EMERGENCY_ADMIN

thrown when msg.sender is not emergency admin

error NOT_EMERGENCY_ADMIN();

NOT_SUPER_ROUTER

thrown when msg.sender is not super router

error NOT_SUPER_ROUTER();

NOT_MINTER

thrown when msg.sender is not minter

error NOT_MINTER();

NOT_BURNER

thrown when msg.sender is not burner

error NOT_BURNER();

NOT_MINTER_STATE_REGISTRY_ROLE

thrown when msg.sender is not minter state registry

error NOT_MINTER_STATE_REGISTRY_ROLE();

NOT_SUPERFORM_FACTORY

if the msg-sender is not super form factory

error NOT_SUPERFORM_FACTORY();

NOT_SUPER_REGISTRY

thrown if the msg-sender is not super registry

error NOT_SUPER_REGISTRY();

NOT_SWAPPER

thrown if the msg-sender does not have SWAPPER role

error NOT_SWAPPER();

NOT_PROCESSOR

thrown if the msg-sender does not have PROCESSOR role

error NOT_PROCESSOR();

NOT_UPDATER

thrown if the msg-sender does not have UPDATER role

error NOT_UPDATER();

NOT_RESCUER

thrown if the msg-sender does not have RESCUER role

error NOT_RESCUER();

BRIDGE_TOKENS_PENDING

thrown when the bridge tokens haven't arrived to destination

error BRIDGE_TOKENS_PENDING();

DISABLED

thrown when trying to set again pseudo immutables in SuperRegistry

error DISABLED();

NATIVE_TOKEN_TRANSFER_FAILURE

thrown when the native tokens transfer has failed

error NATIVE_TOKEN_TRANSFER_FAILURE();

CANNOT_REVOKE_LAST_ADMIN

thrown when not possible to revoke last admin

error CANNOT_REVOKE_LAST_ADMIN();

CANNOT_REVOKE_BROADCAST

thrown when not possible to revoke last admin

error CANNOT_REVOKE_BROADCAST();

INVALID_TIMELOCK_DELAY

thrown if the delay is invalid

error INVALID_TIMELOCK_DELAY();

RESCUE_ALREADY_PROPOSED

thrown if rescue is already proposed

error RESCUE_ALREADY_PROPOSED();

INVALID_TXDATA_CHAIN_ID

is emitted when the chain id in the txdata is invalid

error INVALID_TXDATA_CHAIN_ID();

INVALID_TXDATA_RECEIVER

thrown the when validation of bridge txData fails due to wrong receiver

error INVALID_TXDATA_RECEIVER();

INVALID_TXDATA_TOKEN

thrown when the validation of bridge txData fails due to wrong token

error INVALID_TXDATA_TOKEN();

INVALID_DEPOSIT_LIQ_DST_CHAIN_ID

thrown when in deposits, the liqDstChainId doesn't match the stateReq dstChainId

error INVALID_DEPOSIT_LIQ_DST_CHAIN_ID();

INVALID_ACTION

when a certain action of the user is not allowed given the txData provided

error INVALID_ACTION();

INVALID_TXDATA_NO_DESTINATIONCALL_ALLOWED

thrown when the validation of bridge txData fails due to a destination call present

error INVALID_TXDATA_NO_DESTINATIONCALL_ALLOWED();

INVALID_SWAP_OUTPUT

thrown when dst swap output is less than minimum expected

error INVALID_SWAP_OUTPUT();

DST_SWAP_ALREADY_PROCESSED

thrown when try to process dst swap for same payload id

error DST_SWAP_ALREADY_PROCESSED();

INVALID_INDEX

thrown if index is invalid

error INVALID_INDEX();

INVALID_DISUPTER

thrown if msg.sender is not the refund address to dispute

error INVALID_DISUPTER();

DISPUTE_TIME_ELAPSED

thrown if the rescue passed dispute deadline

error DISPUTE_TIME_ELAPSED();

RESCUE_LOCKED

thrown if the rescue is still in timelocked state

error RESCUE_LOCKED();

NO_TXDATA_PRESENT

error thrown when txData must be present (in case of xChain acitons)

error NO_TXDATA_PRESENT();

CALLER_NOT_MAILBOX

hyperlane adapter specific error, when caller not hyperlane mailbox

error CALLER_NOT_MAILBOX();

CALLER_NOT_RELAYER

wormhole relayer specific error, when caller not wormhole relayer

error CALLER_NOT_RELAYER();

CALLER_NOT_ENDPOINT

layerzero adapter specific error, when caller not layerzero endpoint

error CALLER_NOT_ENDPOINT();

INVALID_SRC_SENDER

thrown when src chain sender is not valid

error INVALID_SRC_SENDER();

INVALID_BROADCAST_FINALITY

thrown when broadcast finality for wormhole is invalid

error INVALID_BROADCAST_FINALITY();

INVALID_SRC_CHAIN_ID

thrown when src chain is blocked from messaging

error INVALID_SRC_CHAIN_ID();

DUPLICATE_PAYLOAD

thrown when payload is not unique

error DUPLICATE_PAYLOAD();

INVALID_CHAIN_ID

is emitted when the chain id brought in the cross chain message is invalid

error INVALID_CHAIN_ID();

INVALID_BRIDGE_ID

thrown if ambId is not valid leading to an address 0 of the implementation

error INVALID_BRIDGE_ID();

INVALID_PAYLOAD_ID

thrown if payload id does not exist

error INVALID_PAYLOAD_ID();

PAYLOAD_ALREADY_UPDATED

is thrown is payload is already updated (during xChain deposits)

error PAYLOAD_ALREADY_UPDATED();

PAYLOAD_ALREADY_PROCESSED

is thrown is payload is already processed

error PAYLOAD_ALREADY_PROCESSED();

ZERO_PAYLOAD_HASH

is thrown if the payload hash is zero during retryMessage on Layezero implementation

error ZERO_PAYLOAD_HASH();

INVALID_PAYLOAD_HASH

is thrown if the payload hash is invalid during retryMessage on Layezero implementation

error INVALID_PAYLOAD_HASH();

INVALID_PAYLOAD_UPDATE_REQUEST

thrown if update payload function was called on a wrong payload

error INVALID_PAYLOAD_UPDATE_REQUEST();

INVALID_DST_SWAP_AMOUNT

thrown if payload update amount mismatch with dst swapper amount

error INVALID_DST_SWAP_AMOUNT();

DIFFERENT_PAYLOAD_UPDATE_AMOUNTS_LENGTH

thrown if payload is being updated with final amounts length different than amounts length

error DIFFERENT_PAYLOAD_UPDATE_AMOUNTS_LENGTH();

DIFFERENT_PAYLOAD_UPDATE_TX_DATA_LENGTH

thrown if payload is being updated with tx data length different than liq data length

error DIFFERENT_PAYLOAD_UPDATE_TX_DATA_LENGTH();

NEGATIVE_SLIPPAGE

thrown if the amounts being sent in update payload mean a negative slippage

error NEGATIVE_SLIPPAGE();

PAYLOAD_NOT_UPDATED

thrown if payload is not in UPDATED state

error PAYLOAD_NOT_UPDATED();

CANNOT_UPDATE_WITHDRAW_TX_DATA

thrown if withdrawal TX_DATA cannot be updated

error CANNOT_UPDATE_WITHDRAW_TX_DATA();

WITHDRAW_TX_DATA_NOT_UPDATED

thrown if withdrawal TX_DATA is not updated

error WITHDRAW_TX_DATA_NOT_UPDATED();

QUORUM_NOT_REACHED

thrown if message hasn't reached the specified level of quorum needed

error QUORUM_NOT_REACHED();

INVALID_PROOF_BRIDGE_ID

thrown if message amb and proof amb are the same

error INVALID_PROOF_BRIDGE_ID();

DUPLICATE_PROOF_BRIDGE_ID

thrown if a duplicate proof amb is found

error DUPLICATE_PROOF_BRIDGE_ID();

INVALID_RESCUE_DATA

thrown if the rescue data lengths are invalid

error INVALID_RESCUE_DATA();

CROSS_CHAIN_TX_UNDERPAID

thrown if not enough native fees is paid for amb to send the message

error CROSS_CHAIN_TX_UNDERPAID();

ERC165_UNSUPPORTED

thrown when a form is not ERC165 compatible

error ERC165_UNSUPPORTED();

FORM_INTERFACE_UNSUPPORTED

thrown when a form is not FORM interface compatible

error FORM_INTERFACE_UNSUPPORTED();

FORM_DOES_NOT_EXIST

thrown when a form does not exist

error FORM_DOES_NOT_EXIST();

VAULT_FORM_IMPLEMENTATION_COMBINATION_EXISTS

thrown when same vault and beacon is used to create new superform

error VAULT_FORM_IMPLEMENTATION_COMBINATION_EXISTS();

ARRAY_LENGTH_MISMATCH

thrown when there is an array length mismatch

error ARRAY_LENGTH_MISMATCH();

SLIPPAGE_OUT_OF_BOUNDS

thrown slippage is outside of bounds

error SLIPPAGE_OUT_OF_BOUNDS();

INVALID_FORM_ID

thrown when form id is larger than max uint16

error INVALID_FORM_ID();

INVALID_SUPERFORMS_DATA

thrown when the vaults data is invalid

error INVALID_SUPERFORMS_DATA();

INVALID_CHAIN_IDS

thrown when the chain ids data is invalid

error INVALID_CHAIN_IDS();

INVALID_PAYLOAD

thrown when the payload is invalid

error INVALID_PAYLOAD();

SRC_SENDER_MISMATCH

thrown if src senders mismatch in state sync

error SRC_SENDER_MISMATCH();

SRC_TX_TYPE_MISMATCH

thrown if src tx types mismatch in state sync

error SRC_TX_TYPE_MISMATCH();

INVALID_PAYLOAD_STATUS

thrown if the payload status is invalid

error INVALID_PAYLOAD_STATUS();

FAILED_TO_EXECUTE_TXDATA

thrown if liquidity bridge fails for erc20 tokens

error FAILED_TO_EXECUTE_TXDATA();

FAILED_TO_EXECUTE_TXDATA_NATIVE

thrown if liquidity bridge fails for native tokens

error FAILED_TO_EXECUTE_TXDATA_NATIVE();

INSUFFICIENT_NATIVE_AMOUNT

thrown if native amount is not at least equal to the amount in the request

error INSUFFICIENT_NATIVE_AMOUNT();

EMERGENCY_WITHDRAW_INSUFFICIENT_BALANCE

thrown when the form has insufficient balance for emergency withdraw

error EMERGENCY_WITHDRAW_INSUFFICIENT_BALANCE();

EMERGENCY_WITHDRAW_PROCESSED_ALREADY

thrown when emergency withdraw is already processed

error EMERGENCY_WITHDRAW_PROCESSED_ALREADY();

DIRECT_DEPOSIT_INSUFFICIENT_ALLOWANCE

thrown when the allowance in direct deposit is not correct

error DIRECT_DEPOSIT_INSUFFICIENT_ALLOWANCE();

DIRECT_DEPOSIT_INVALID_DATA

thrown when the amount in direct deposit is not correct

error DIRECT_DEPOSIT_INVALID_DATA();

DIRECT_WITHDRAW_INVALID_COLLATERAL

thrown when the collateral in direct withdraw is not correct

error DIRECT_WITHDRAW_INVALID_COLLATERAL();

DIRECT_WITHDRAW_INVALID_LIQ_REQUEST

thrown when the amount in direct withdraw is not correct

error DIRECT_WITHDRAW_INVALID_LIQ_REQUEST();

XCHAIN_WITHDRAW_INVALID_LIQ_REQUEST

thrown when the amount in xchain withdraw is not correct

error XCHAIN_WITHDRAW_INVALID_LIQ_REQUEST();

WITHDRAW_COOLDOWN_PERIOD

thrown when unlock has already been requested - cooldown period didn't pass yet

error WITHDRAW_COOLDOWN_PERIOD();

LOCKED

thrown when trying to finalize the payload but the withdraw is still locked

error LOCKED();

EMPTY_TOKEN_NON_EMPTY_TXDATA

thrown when liqData token is empty but txData is not

error EMPTY_TOKEN_NON_EMPTY_TXDATA();

PAUSED

if implementation formBeacon is PAUSED then users cannot perform any action

error PAUSED();

NOT_PAYMENT_ADMIN

- when msg.sender is not payment admin

error NOT_PAYMENT_ADMIN();

ZERO_MSG_VALUE

thrown when user pays zero

error ZERO_MSG_VALUE();

FAILED_WITHDRAW

thrown when payment withdrawal fails

error FAILED_WITHDRAW();

DYNAMIC_URI_FROZEN

thrown when the uri cannot be updated

error DYNAMIC_URI_FROZEN();

thrown when chainlink is reporting an improper price

error CHAINLINK_MALFUNCTION();

thrown when chainlink is reporting an incomplete round

error CHAINLINK_INCOMPLETE_ROUND();

Contents

Contents

AggregatorV3Interface

Git Source

Functions

decimals

function decimals() external view returns (uint8);

description

function description() external view returns (string memory);

version

function version() external view returns (uint256);

getRoundData

function getRoundData(uint80 _roundId)
    external
    view
    returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

latestRoundData

function latestRoundData()
    external
    view
    returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);

Contents

IPermit2

Git Source

Author: https://github.com/dragonfly-xyz/useful-solidity-patterns/blob/main/patterns/permit2/Permit2Vault.sol

SPDX-License-Identifier: Apache-2.0

Minimal Permit2 interface, derived from

https://github.com/Uniswap/permit2/blob/main/src/interfaces/ISignatureTransfer.sol

Functions

permitTransferFrom

function permitTransferFrom(
    PermitTransferFrom calldata permit,
    SignatureTransferDetails calldata transferDetails,
    address owner,
    bytes calldata signature
)
    external;

Structs

TokenPermissions

struct TokenPermissions {
    IERC20 token;
    uint256 amount;
}

PermitTransferFrom

struct PermitTransferFrom {
    TokenPermissions permitted;
    uint256 nonce;
    uint256 deadline;
}

SignatureTransferDetails

struct SignatureTransferDetails {
    address to;
    uint256 requestedAmount;
}

Contents

IInterchainGasPaymaster

Git Source

is imported from (https://github.com/hyperlane-xyz/hyperlane-monorepo/blob/main/solidity/contracts/interfaces/IInterchainGasPaymaster.sol)

Functions

payForGas

function payForGas(
    bytes32 _messageId,
    uint32 _destinationDomain,
    uint256 _gasAmount,
    address _refundAddress
)
    external
    payable;

quoteGasPayment

function quoteGasPayment(uint32 _destinationDomain, uint256 _gasAmount) external view returns (uint256);

Events

GasPayment

Emitted when a payment is made for a message's gas costs.

event GasPayment(bytes32 indexed messageId, uint256 gasAmount, uint256 payment);

Parameters

NameTypeDescription
messageIdbytes32The ID of the message to pay for.
gasAmountuint256The amount of destination gas paid for.
paymentuint256The amount of native tokens paid.

IMailbox

Git Source

is imported from (https://github.com/hyperlane-xyz/hyperlane-monorepo/blob/main/solidity/contracts/interfaces/IMailbox.sol)

Functions

localDomain

function localDomain() external view returns (uint32);

delivered

function delivered(bytes32 messageId) external view returns (bool);

dispatch

function dispatch(
    uint32 _destinationDomain,
    bytes32 _recipientAddress,
    bytes calldata _messageBody
)
    external
    returns (bytes32);

process

function process(bytes calldata _metadata, bytes calldata _message) external;

count

function count() external view returns (uint32);

root

function root() external view returns (bytes32);

latestCheckpoint

function latestCheckpoint() external view returns (bytes32, uint32);

Events

Dispatch

Emitted when a new message is dispatched via Hyperlane

event Dispatch(address indexed sender, uint32 indexed destination, bytes32 indexed recipient, bytes message);

Parameters

NameTypeDescription
senderaddressThe address that dispatched the message
destinationuint32The destination domain of the message
recipientbytes32The message recipient address on destination
messagebytesRaw bytes of message

DispatchId

Emitted when a new message is dispatched via Hyperlane

event DispatchId(bytes32 indexed messageId);

Parameters

NameTypeDescription
messageIdbytes32The unique message identifier

ProcessId

Emitted when a Hyperlane message is processed

event ProcessId(bytes32 indexed messageId);

Parameters

NameTypeDescription
messageIdbytes32The unique message identifier

Process

Emitted when a Hyperlane message is delivered

event Process(uint32 indexed origin, bytes32 indexed sender, address indexed recipient);

Parameters

NameTypeDescription
originuint32The origin domain of the message
senderbytes32The message sender address on origin
recipientaddressThe address that handled the message

IMessageRecipient

Git Source

is imported from (https://github.com/hyperlane-xyz/hyperlane-monorepo/blob/main/solidity/contracts/interfaces/IMessageRecipient.sol)

Functions

handle

function handle(uint32 _origin, bytes32 _sender, bytes calldata _message) external;

Parameters

NameTypeDescription
_originuint32Domain ID of the chain from which the message came
_senderbytes32Address of the message sender on the origin chain as bytes32
_messagebytesRaw bytes content of message body

Contents

IKycValidity

Git Source

Functions

hasValidToken

Check whether a given address has a valid kycNFT token

function hasValidToken(address _addr) external view returns (bool valid);

Parameters

NameTypeDescription
_addraddressAddress to check for tokens

Returns

NameTypeDescription
validboolWhether the address has a valid token

Contents

ILayerZeroEndpoint

Git Source

Inherits: ILayerZeroUserApplicationConfig

is imported from (https://github.com/LayerZero-Labs/LayerZero/blob/main/contracts/interfaces/ILayerZeroEndpoint.sol)

Functions

send

function send(
    uint16 dstChainId_,
    bytes calldata destination_,
    bytes calldata payload_,
    address payable refundAddress_,
    address zroPaymentAddress_,
    bytes calldata adapterParams_
)
    external
    payable;

receivePayload

function receivePayload(
    uint16 srcChainId_,
    bytes calldata srcAddress_,
    address dstAddress_,
    uint64 nonce_,
    uint256 gasLimit_,
    bytes calldata payload_
)
    external;

getInboundNonce

function getInboundNonce(uint16 srcChainId_, bytes calldata srcAddress_) external view returns (uint64);

getOutboundNonce

function getOutboundNonce(uint16 dstChainId_, address srcAddress_) external view returns (uint64);

estimateFees

function estimateFees(
    uint16 dstChainId_,
    address userApplication_,
    bytes calldata payload_,
    bool _payInZRO,
    bytes calldata _adapterParam
)
    external
    view
    returns (uint256 nativeFee, uint256 zroFee);

getChainId

function getChainId() external view returns (uint16);

retryPayload

function retryPayload(uint16 srcChainId_, bytes calldata srcAddress_, bytes calldata payload_) external;

hasStoredPayload

function hasStoredPayload(uint16 srcChainId_, bytes calldata srcAddress_) external view returns (bool);

getSendLibraryAddress

function getSendLibraryAddress(address userApplication_) external view returns (address);

getReceiveLibraryAddress

function getReceiveLibraryAddress(address userApplication_) external view returns (address);

isSendingPayload

function isSendingPayload() external view returns (bool);

isReceivingPayload

function isReceivingPayload() external view returns (bool);

getConfig

function getConfig(
    uint16 version_,
    uint16 chainId_,
    address userApplication_,
    uint256 configType_
)
    external
    view
    returns (bytes memory);

getSendVersion

function getSendVersion(address userApplication_) external view returns (uint16);

getReceiveVersion

function getReceiveVersion(address userApplication_) external view returns (uint16);

ILayerZeroReceiver

Git Source

is imported from (https://github.com/LayerZero-Labs/LayerZero/blob/main/contracts/interfaces/ILayerZeroReceiver.sol)

Functions

lzReceive

function lzReceive(uint16 _srcChainId, bytes calldata _srcAddress, uint64 _nonce, bytes calldata _payload) external;

ILayerZeroUserApplicationConfig

Git Source

is imported from (https://github.com/LayerZero-Labs/LayerZero/blob/main/contracts/interfaces/ILayerZeroUserApplicationConfig.sol)

Functions

setConfig

function setConfig(uint16 _version, uint16 _chainId, uint256 _configType, bytes calldata _config) external;

setSendVersion

function setSendVersion(uint16 _version) external;

setReceiveVersion

function setReceiveVersion(uint16 _version) external;

forceResumeReceive

function forceResumeReceive(uint16 _srcChainId, bytes calldata _srcAddress) external;

Contents

ILiFi

Git Source

Interface containing useful structs when using LiFi as a bridge

taken from LiFi contracts https://github.com/lifinance/contracts

Structs

BridgeData

struct BridgeData {
    bytes32 transactionId;
    string bridge;
    string integrator;
    address referrer;
    address sendingAssetId;
    address receiver;
    uint256 minAmount;
    uint256 destinationChainId;
    bool hasSourceSwaps;
    bool hasDestinationCall;
}

LiFiTxDataExtractor

Git Source

Author: LI.FI (https://li.fi)

Provides functionality for extracting calldata

upgraded to solidity 0.8.19 and adapted from CalldataVerificationFacet and LibBytes without any changes to used functions (just stripped down functionality and renamed contract name)

taken from LiFi contracts https://github.com/lifinance/contracts

Note: version: 1.1.0

Functions

_extractBridgeData

Extracts the bridge data from the calldata

function _extractBridgeData(bytes calldata data) internal pure returns (ILiFi.BridgeData memory bridgeData);

Parameters

NameTypeDescription
databytesThe calldata to extract the bridge data from

Returns

NameTypeDescription
bridgeDataILiFi.BridgeDataThe bridge data extracted from the calldata

_extractSwapData

Extracts the swap data from the calldata

function _extractSwapData(bytes calldata data) internal pure returns (LibSwap.SwapData[] memory swapData);

Parameters

NameTypeDescription
databytesThe calldata to extract the swap data from

Returns

NameTypeDescription
swapDataLibSwap.SwapData[]The swap data extracted from the calldata

_slice

function _slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory);

Errors

SliceOverflow

error SliceOverflow();

SliceOutOfBounds

error SliceOutOfBounds();

LibSwap

Git Source

Structs

SwapData

struct SwapData {
    address callTo;
    address approveTo;
    address sendingAssetId;
    address receivingAssetId;
    uint256 fromAmount;
    bytes callData;
    bool requiresDeposit;
}

Contents

ISocketRegistry

Git Source

Interface for socket's Router contract

taken from https://github.com/SocketDotTech/socket-gateway-verifier

Structs

SocketRequest

struct SocketRequest {
    uint256 amount;
    address recipient;
    uint256 toChainId;
    address token;
    bytes4 signature;
}

UserRequest

struct UserRequest {
    uint32 routeId;
    bytes socketRequest;
}

UserRequestValidation

struct UserRequestValidation {
    uint32 routeId;
    SocketRequest socketRequest;
}

Contents

IWormhole

Git Source

Functions

publishMessage

function publishMessage(
    uint32 nonce,
    bytes memory payload,
    uint8 consistencyLevel
)
    external
    payable
    returns (uint64 sequence);

initialize

function initialize() external;

parseAndVerifyVM

function parseAndVerifyVM(bytes calldata encodedVM)
    external
    view
    returns (VM memory vm, bool valid, string memory reason);

verifyVM

function verifyVM(VM memory vm) external view returns (bool valid, string memory reason);

verifySignatures

function verifySignatures(
    bytes32 hash,
    Signature[] memory signatures,
    GuardianSet memory guardianSet
)
    external
    pure
    returns (bool valid, string memory reason);

parseVM

function parseVM(bytes memory encodedVM) external pure returns (VM memory vm);

quorum

function quorum(uint256 numGuardians) external pure returns (uint256 numSignaturesRequiredForQuorum);

getGuardianSet

function getGuardianSet(uint32 index) external view returns (GuardianSet memory);

getCurrentGuardianSetIndex

function getCurrentGuardianSetIndex() external view returns (uint32);

getGuardianSetExpiry

function getGuardianSetExpiry() external view returns (uint32);

governanceActionIsConsumed

function governanceActionIsConsumed(bytes32 hash) external view returns (bool);

isInitialized

function isInitialized(address impl) external view returns (bool);

chainId

function chainId() external view returns (uint16);

isFork

function isFork() external view returns (bool);

governanceChainId

function governanceChainId() external view returns (uint16);

governanceContract

function governanceContract() external view returns (bytes32);

messageFee

function messageFee() external view returns (uint256);

evmChainId

function evmChainId() external view returns (uint256);

nextSequence

function nextSequence(address emitter) external view returns (uint64);

parseContractUpgrade

function parseContractUpgrade(bytes memory encodedUpgrade) external pure returns (ContractUpgrade memory cu);

parseGuardianSetUpgrade

function parseGuardianSetUpgrade(bytes memory encodedUpgrade) external pure returns (GuardianSetUpgrade memory gsu);

parseSetMessageFee

function parseSetMessageFee(bytes memory encodedSetMessageFee) external pure returns (SetMessageFee memory smf);

parseTransferFees

function parseTransferFees(bytes memory encodedTransferFees) external pure returns (TransferFees memory tf);

parseRecoverChainId

function parseRecoverChainId(bytes memory encodedRecoverChainId) external pure returns (RecoverChainId memory rci);

submitContractUpgrade

function submitContractUpgrade(bytes memory _vm) external;

submitSetMessageFee

function submitSetMessageFee(bytes memory _vm) external;

submitNewGuardianSet

function submitNewGuardianSet(bytes memory _vm) external;

submitTransferFees

function submitTransferFees(bytes memory _vm) external;

submitRecoverChainId

function submitRecoverChainId(bytes memory _vm) external;

Events

LogMessagePublished

event LogMessagePublished(address indexed sender, uint64 sequence, uint32 nonce, bytes payload, uint8 consistencyLevel);

ContractUpgraded

event ContractUpgraded(address indexed oldContract, address indexed newContract);

GuardianSetAdded

event GuardianSetAdded(uint32 indexed index);

Structs

GuardianSet

struct GuardianSet {
    address[] keys;
    uint32 expirationTime;
}

Signature

struct Signature {
    bytes32 r;
    bytes32 s;
    uint8 v;
    uint8 guardianIndex;
}

VM

struct VM {
    uint8 version;
    uint32 timestamp;
    uint32 nonce;
    uint16 emitterChainId;
    bytes32 emitterAddress;
    uint64 sequence;
    uint8 consistencyLevel;
    bytes payload;
    uint32 guardianSetIndex;
    Signature[] signatures;
    bytes32 hash;
}

ContractUpgrade

struct ContractUpgrade {
    bytes32 module;
    uint8 action;
    uint16 chain;
    address newContract;
}

GuardianSetUpgrade

struct GuardianSetUpgrade {
    bytes32 module;
    uint8 action;
    uint16 chain;
    GuardianSet newGuardianSet;
    uint32 newGuardianSetIndex;
}

SetMessageFee

struct SetMessageFee {
    bytes32 module;
    uint8 action;
    uint16 chain;
    uint256 messageFee;
}

TransferFees

struct TransferFees {
    bytes32 module;
    uint8 action;
    uint16 chain;
    uint256 amount;
    bytes32 recipient;
}

RecoverChainId

struct RecoverChainId {
    bytes32 module;
    uint8 action;
    uint256 evmChainId;
    uint16 newChainId;
}

IWormholeReceiver

Git Source

Interface for a contract which can receive Wormhole messages.

Functions

receiveWormholeMessages

When a send is performed with this contract as the target, this function will be invoked by the WormholeRelayer contract NOTE: This function should be restricted such that only the Wormhole Relayer contract can call it. We also recommend that this function:

  • Stores all received deliveryHashs in a mapping (bytes32 => bool), and on every call, checks that deliveryHash has not already been stored in the map (This is to prevent other users maliciously trying to relay the same message)
  • Checks that sourceChain and sourceAddress are indeed who you expect to have requested the calling of send on the source chain The invocation of this function corresponding to the send request will have msg.value equal to the receiverValue specified in the send request. If the invocation of this function reverts or exceeds the gas limit specified by the send requester, this delivery will result in a ReceiverFailure.
function receiveWormholeMessages(
    bytes memory payload,
    bytes[] memory additionalVaas,
    bytes32 sourceAddress,
    uint16 sourceChain,
    bytes32 deliveryHash
)
    external
    payable;

Parameters

NameTypeDescription
payloadbytes- an arbitrary message which was included in the delivery by the requester.
additionalVaasbytes[]- Additional VAAs which were requested to be included in this delivery. They are guaranteed to all be included and in the same order as was specified in the delivery request.
sourceAddressbytes32- the (wormhole format) address on the sending chain which requested this delivery.
sourceChainuint16- the wormhole chain ID where this delivery was requested.
deliveryHashbytes32- the VAA hash of the deliveryVAA. NOTE: These signedVaas are NOT verified by the Wormhole core contract prior to being provided to this call. Always make sure parseAndVerify() is called on the Wormhole core contract before trusting the content of a raw VAA, otherwise the VAA may be invalid or malicious.

VaaKey

Git Source

Author:

This project allows developers to build cross-chain applications powered by Wormhole without needing to write and run their own relaying infrastructure We implement the IWormholeRelayer interface that allows users to request a delivery provider to relay a payload (and/or additional VAAs) to a chain and address of their choice.

VaaKey identifies a wormhole message

Notes:

  • member: chainId Wormhole chain ID of the chain where this VAA was emitted from

  • member: emitterAddress Address of the emitter of the VAA, in Wormhole bytes32 format

  • member: sequence Sequence number of the VAA

struct VaaKey {
    uint16 chainId;
    bytes32 emitterAddress;
    uint64 sequence;
}

IWormholeRelayerBase

Git Source

Functions

getRegisteredWormholeRelayerContract

function getRegisteredWormholeRelayerContract(uint16 chainId) external view returns (bytes32);

Events

SendEvent

event SendEvent(uint64 indexed sequence, uint256 deliveryQuote, uint256 paymentForExtraReceiverValue);

IWormholeRelayerSend

Git Source

Inherits: IWormholeRelayerBase

The interface to request deliveries

Functions

sendPayloadToEvm

Publishes an instruction for the default delivery provider to relay a payload to the address targetAddress on chain targetChain with gas limit gasLimit and msg.value equal to receiverValue targetAddress must implement the IWormholeReceiver interface This function must be called with msg.value equal to quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit) Any refunds (from leftover gas) will be paid to the delivery provider. In order to receive the refunds, use the sendPayloadToEvm function with refundChain and refundAddress as parameters

function sendPayloadToEvm(
    uint16 targetChain,
    address targetAddress,
    bytes memory payload,
    uint256 receiverValue,
    uint256 gasLimit
)
    external
    payable
    returns (uint64 sequence);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
targetAddressaddressaddress to call on targetChain (that implements IWormholeReceiver)
payloadbytesarbitrary bytes to pass in as parameter in call to targetAddress
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
gasLimituint256gas limit with which to call targetAddress.

Returns

NameTypeDescription
sequenceuint64sequence number of published VAA containing delivery instructions

sendPayloadToEvm

Publishes an instruction for the default delivery provider to relay a payload to the address targetAddress on chain targetChain with gas limit gasLimit and msg.value equal to receiverValue Any refunds (from leftover gas) will be sent to refundAddress on chain refundChain targetAddress must implement the IWormholeReceiver interface This function must be called with msg.value equal to quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit)

function sendPayloadToEvm(
    uint16 targetChain,
    address targetAddress,
    bytes memory payload,
    uint256 receiverValue,
    uint256 gasLimit,
    uint16 refundChain,
    address refundAddress
)
    external
    payable
    returns (uint64 sequence);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
targetAddressaddressaddress to call on targetChain (that implements IWormholeReceiver)
payloadbytesarbitrary bytes to pass in as parameter in call to targetAddress
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
gasLimituint256gas limit with which to call targetAddress. Any units of gas unused will be refunded according to the targetChainRefundPerGasUnused rate quoted by the delivery provider
refundChainuint16The chain to deliver any refund to, in Wormhole Chain ID format
refundAddressaddressThe address on refundChain to deliver any refund to

Returns

NameTypeDescription
sequenceuint64sequence number of published VAA containing delivery instructions

sendVaasToEvm

Publishes an instruction for the default delivery provider to relay a payload and VAAs specified by vaaKeys to the address targetAddress on chain targetChain with gas limit gasLimit and msg.value equal to receiverValue targetAddress must implement the IWormholeReceiver interface This function must be called with msg.value equal to quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit) Any refunds (from leftover gas) will be paid to the delivery provider. In order to receive the refunds, use the sendVaasToEvm function with refundChain and refundAddress as parameters

function sendVaasToEvm(
    uint16 targetChain,
    address targetAddress,
    bytes memory payload,
    uint256 receiverValue,
    uint256 gasLimit,
    VaaKey[] memory vaaKeys
)
    external
    payable
    returns (uint64 sequence);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
targetAddressaddressaddress to call on targetChain (that implements IWormholeReceiver)
payloadbytesarbitrary bytes to pass in as parameter in call to targetAddress
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
gasLimituint256gas limit with which to call targetAddress.
vaaKeysVaaKey[]Additional VAAs to pass in as parameter in call to targetAddress

Returns

NameTypeDescription
sequenceuint64sequence number of published VAA containing delivery instructions

sendVaasToEvm

Publishes an instruction for the default delivery provider to relay a payload and VAAs specified by vaaKeys to the address targetAddress on chain targetChain with gas limit gasLimit and msg.value equal to receiverValue Any refunds (from leftover gas) will be sent to refundAddress on chain refundChain targetAddress must implement the IWormholeReceiver interface This function must be called with msg.value equal to quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit)

function sendVaasToEvm(
    uint16 targetChain,
    address targetAddress,
    bytes memory payload,
    uint256 receiverValue,
    uint256 gasLimit,
    VaaKey[] memory vaaKeys,
    uint16 refundChain,
    address refundAddress
)
    external
    payable
    returns (uint64 sequence);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
targetAddressaddressaddress to call on targetChain (that implements IWormholeReceiver)
payloadbytesarbitrary bytes to pass in as parameter in call to targetAddress
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
gasLimituint256gas limit with which to call targetAddress. Any units of gas unused will be refunded according to the targetChainRefundPerGasUnused rate quoted by the delivery provider
vaaKeysVaaKey[]Additional VAAs to pass in as parameter in call to targetAddress
refundChainuint16The chain to deliver any refund to, in Wormhole Chain ID format
refundAddressaddressThe address on refundChain to deliver any refund to

Returns

NameTypeDescription
sequenceuint64sequence number of published VAA containing delivery instructions

sendToEvm

Publishes an instruction for the delivery provider at deliveryProviderAddress to relay a payload and VAAs specified by vaaKeys to the address targetAddress on chain targetChain with gas limit gasLimit and msg.value equal to receiverValue + (arbitrary amount that is paid for by paymentForExtraReceiverValue of this chain's wei) in targetChain wei. Any refunds (from leftover gas) will be sent to refundAddress on chain refundChain targetAddress must implement the IWormholeReceiver interface This function must be called with msg.value equal to quoteEVMDeliveryPrice(targetChain, receiverValue, gasLimit, deliveryProviderAddress) + paymentForExtraReceiverValue

function sendToEvm(
    uint16 targetChain,
    address targetAddress,
    bytes memory payload,
    uint256 receiverValue,
    uint256 paymentForExtraReceiverValue,
    uint256 gasLimit,
    uint16 refundChain,
    address refundAddress,
    address deliveryProviderAddress,
    VaaKey[] memory vaaKeys,
    uint8 consistencyLevel
)
    external
    payable
    returns (uint64 sequence);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
targetAddressaddressaddress to call on targetChain (that implements IWormholeReceiver)
payloadbytesarbitrary bytes to pass in as parameter in call to targetAddress
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
paymentForExtraReceiverValueuint256amount (in current chain currency units) to spend on extra receiverValue (in addition to the receiverValue specified)
gasLimituint256gas limit with which to call targetAddress. Any units of gas unused will be refunded according to the targetChainRefundPerGasUnused rate quoted by the delivery provider
refundChainuint16The chain to deliver any refund to, in Wormhole Chain ID format
refundAddressaddressThe address on refundChain to deliver any refund to
deliveryProviderAddressaddressThe address of the desired delivery provider's implementation of IDeliveryProvider
vaaKeysVaaKey[]Additional VAAs to pass in as parameter in call to targetAddress
consistencyLeveluint8Consistency level with which to publish the delivery instructions - see https://book.wormhole.com/wormhole/3_coreLayerContracts.html?highlight=consistency#consistency-levels

Returns

NameTypeDescription
sequenceuint64sequence number of published VAA containing delivery instructions

send

Publishes an instruction for the delivery provider at deliveryProviderAddress to relay a payload and VAAs specified by vaaKeys to the address targetAddress on chain targetChain with msg.value equal to receiverValue + (arbitrary amount that is paid for by paymentForExtraReceiverValue of this chain's wei) in targetChain wei. Any refunds (from leftover gas) will be sent to refundAddress on chain refundChain targetAddress must implement the IWormholeReceiver interface This function must be called with msg.value equal to quoteDeliveryPrice(targetChain, receiverValue, encodedExecutionParameters, deliveryProviderAddress) + paymentForExtraReceiverValue

function send(
    uint16 targetChain,
    bytes32 targetAddress,
    bytes memory payload,
    uint256 receiverValue,
    uint256 paymentForExtraReceiverValue,
    bytes memory encodedExecutionParameters,
    uint16 refundChain,
    bytes32 refundAddress,
    address deliveryProviderAddress,
    VaaKey[] memory vaaKeys,
    uint8 consistencyLevel
)
    external
    payable
    returns (uint64 sequence);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
targetAddressbytes32address to call on targetChain (that implements IWormholeReceiver), in Wormhole bytes32 format
payloadbytesarbitrary bytes to pass in as parameter in call to targetAddress
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
paymentForExtraReceiverValueuint256amount (in current chain currency units) to spend on extra receiverValue (in addition to the receiverValue specified)
encodedExecutionParametersbytesencoded information on how to execute delivery that may impact pricing e.g. for version EVM_V1, this is a struct that encodes the gasLimit with which to call targetAddress
refundChainuint16The chain to deliver any refund to, in Wormhole Chain ID format
refundAddressbytes32The address on refundChain to deliver any refund to, in Wormhole bytes32 format
deliveryProviderAddressaddressThe address of the desired delivery provider's implementation of IDeliveryProvider
vaaKeysVaaKey[]Additional VAAs to pass in as parameter in call to targetAddress
consistencyLeveluint8Consistency level with which to publish the delivery instructions - see https://book.wormhole.com/wormhole/3_coreLayerContracts.html?highlight=consistency#consistency-levels

Returns

NameTypeDescription
sequenceuint64sequence number of published VAA containing delivery instructions

resendToEvm

Requests a previously published delivery instruction to be redelivered (e.g. with a different delivery provider) This function must be called with msg.value equal to quoteEVMDeliveryPrice(targetChain, newReceiverValue, newGasLimit, newDeliveryProviderAddress)

*** This will only be able to succeed if the following is true **

  • newGasLimit >= gas limit of the old instruction
  • newReceiverValue >= receiver value of the old instruction
  • newDeliveryProvider's targetChainRefundPerGasUnused >= old relay provider's targetChainRefundPerGasUnused

*** This will only be able to succeed if the following is true **

  • newGasLimit >= gas limit of the old instruction
  • newReceiverValue >= receiver value of the old instruction
  • newDeliveryProvider's targetChainRefundPerGasUnused >= old relay provider's targetChainRefundPerGasUnused
function resendToEvm(
    VaaKey memory deliveryVaaKey,
    uint16 targetChain,
    uint256 newReceiverValue,
    uint256 newGasLimit,
    address newDeliveryProviderAddress
)
    external
    payable
    returns (uint64 sequence);

Parameters

NameTypeDescription
deliveryVaaKeyVaaKeyVaaKey identifying the wormhole message containing the previously published delivery instructions
targetChainuint16The target chain that the original delivery targeted. Must match targetChain from original delivery instructions
newReceiverValueuint256new msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
newGasLimituint256gas limit with which to call targetAddress. Any units of gas unused will be refunded according to the targetChainRefundPerGasUnused rate quoted by the delivery provider, to the refund chain and address specified in the original request
newDeliveryProviderAddressaddressThe address of the desired delivery provider's implementation of IDeliveryProvider

Returns

NameTypeDescription
sequenceuint64sequence number of published VAA containing redelivery instructions

resend

Requests a previously published delivery instruction to be redelivered This function must be called with msg.value equal to quoteDeliveryPrice(targetChain, newReceiverValue, newEncodedExecutionParameters, newDeliveryProviderAddress)

*** This will only be able to succeed if the following is true **

  • (For EVM_V1) newGasLimit >= gas limit of the old instruction
  • newReceiverValue >= receiver value of the old instruction
  • (For EVM_V1) newDeliveryProvider's targetChainRefundPerGasUnused >= old relay provider's targetChainRefundPerGasUnused
function resend(
    VaaKey memory deliveryVaaKey,
    uint16 targetChain,
    uint256 newReceiverValue,
    bytes memory newEncodedExecutionParameters,
    address newDeliveryProviderAddress
)
    external
    payable
    returns (uint64 sequence);

Parameters

NameTypeDescription
deliveryVaaKeyVaaKeyVaaKey identifying the wormhole message containing the previously published delivery instructions
targetChainuint16The target chain that the original delivery targeted. Must match targetChain from original delivery instructions
newReceiverValueuint256new msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
newEncodedExecutionParametersbytesnew encoded information on how to execute delivery that may impact pricing e.g. for version EVM_V1, this is a struct that encodes the gasLimit with which to call targetAddress
newDeliveryProviderAddressaddressThe address of the desired delivery provider's implementation of IDeliveryProvider

Returns

NameTypeDescription
sequenceuint64sequence number of published VAA containing redelivery instructions

quoteEVMDeliveryPrice

Returns the price to request a relay to chain targetChain, using the default delivery provider

function quoteEVMDeliveryPrice(
    uint16 targetChain,
    uint256 receiverValue,
    uint256 gasLimit
)
    external
    view
    returns (uint256 nativePriceQuote, uint256 targetChainRefundPerGasUnused);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
gasLimituint256gas limit with which to call targetAddress.

Returns

NameTypeDescription
nativePriceQuoteuint256Price, in units of current chain currency, that the delivery provider charges to perform the relay
targetChainRefundPerGasUnuseduint256amount of target chain currency that will be refunded per unit of gas unused, if a refundAddress is specified

quoteEVMDeliveryPrice

Returns the price to request a relay to chain targetChain, using delivery provider deliveryProviderAddress

function quoteEVMDeliveryPrice(
    uint16 targetChain,
    uint256 receiverValue,
    uint256 gasLimit,
    address deliveryProviderAddress
)
    external
    view
    returns (uint256 nativePriceQuote, uint256 targetChainRefundPerGasUnused);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
gasLimituint256gas limit with which to call targetAddress.
deliveryProviderAddressaddressThe address of the desired delivery provider's implementation of IDeliveryProvider

Returns

NameTypeDescription
nativePriceQuoteuint256Price, in units of current chain currency, that the delivery provider charges to perform the relay
targetChainRefundPerGasUnuseduint256amount of target chain currency that will be refunded per unit of gas unused, if a refundAddress is specified

quoteDeliveryPrice

Returns the price to request a relay to chain targetChain, using delivery provider deliveryProviderAddress

function quoteDeliveryPrice(
    uint16 targetChain,
    uint256 receiverValue,
    bytes memory encodedExecutionParameters,
    address deliveryProviderAddress
)
    external
    view
    returns (uint256 nativePriceQuote, bytes memory encodedExecutionInfo);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
receiverValueuint256msg.value that delivery provider should pass in for call to targetAddress (in targetChain currency units)
encodedExecutionParametersbytesencoded information on how to execute delivery that may impact pricing e.g. for version EVM_V1, this is a struct that encodes the gasLimit with which to call targetAddress
deliveryProviderAddressaddressThe address of the desired delivery provider's implementation of IDeliveryProvider

Returns

NameTypeDescription
nativePriceQuoteuint256Price, in units of current chain currency, that the delivery provider charges to perform the relay
encodedExecutionInfobytesencoded information on how the delivery will be executed e.g. for version EVM_V1, this is a struct that encodes the gasLimit and targetChainRefundPerGasUnused (which is the amount of target chain currency that will be refunded per unit of gas unused, if a refundAddress is specified)

quoteNativeForChain

Returns the (extra) amount of target chain currency that targetAddress will be called with, if the paymentForExtraReceiverValue field is set to currentChainAmount

function quoteNativeForChain(
    uint16 targetChain,
    uint256 currentChainAmount,
    address deliveryProviderAddress
)
    external
    view
    returns (uint256 targetChainAmount);

Parameters

NameTypeDescription
targetChainuint16in Wormhole Chain ID format
currentChainAmountuint256The value that paymentForExtraReceiverValue will be set to
deliveryProviderAddressaddressThe address of the desired delivery provider's implementation of IDeliveryProvider

Returns

NameTypeDescription
targetChainAmountuint256The amount such that if targetAddress will be called with msg.value equal to receiverValue + targetChainAmount

getDefaultDeliveryProvider

Returns the address of the current default delivery provider

function getDefaultDeliveryProvider() external view returns (address deliveryProvider);

Returns

NameTypeDescription
deliveryProvideraddressThe address of (the default delivery provider)'s contract on this source chain. This must be a contract that implements IDeliveryProvider.

IWormholeRelayerDelivery

Git Source

Inherits: IWormholeRelayerBase

The interface to execute deliveries. Only relevant for Delivery Providers

Functions

deliver

The delivery provider calls deliver to relay messages as described by one delivery instruction The delivery provider must pass in the specified (by VaaKeys[]) signed wormhole messages (VAAs) from the source chain as well as the signed wormhole message with the delivery instructions (the delivery VAA) The messages will be relayed to the target address (with the specified gas limit and receiver value) iff the following checks are met:

  • the delivery VAA has a valid signature
  • the delivery VAA's emitter is one of these WormholeRelayer contracts
  • the delivery provider passed in at least enough of this chain's currency as msg.value (enough meaning the maximum possible refund)
  • the instruction's target chain is this chain
  • the relayed signed VAAs match the descriptions in container.messages (the VAA hashes match, or the emitter address, sequence number pair matches, depending on the description given)
function deliver(
    bytes[] memory encodedVMs,
    bytes memory encodedDeliveryVAA,
    address payable relayerRefundAddress,
    bytes memory deliveryOverrides
)
    external
    payable;

Parameters

NameTypeDescription
encodedVMsbytes[]- An array of signed wormhole messages (all from the same source chain transaction)
encodedDeliveryVAAbytes- Signed wormhole message from the source chain's WormholeRelayer contract with payload being the encoded delivery instruction container
relayerRefundAddressaddress payable- The address to which any refunds to the delivery provider should be sent
deliveryOverridesbytes- Optional overrides field which must be either an empty bytes array or an encoded DeliveryOverride struct

Events

Delivery

Notes:

  • member: recipientContract - The target contract address

  • member: sourceChain - The chain which this delivery was requested from (in wormhole ChainID format)

  • member: sequence - The wormhole sequence number of the delivery VAA on the source chain corresponding to this delivery request

  • member: deliveryVaaHash - The hash of the delivery VAA corresponding to this delivery request

  • member: gasUsed - The amount of gas that was used to call your target contract

  • member: status:

  • RECEIVER_FAILURE, if the target contract reverts

  • SUCCESS, if the target contract doesn't revert

  • member: additionalStatusInfo:

  • If status is SUCCESS, then this is empty.

  • If status is RECEIVER_FAILURE, this is RETURNDATA_TRUNCATION_THRESHOLD bytes of the return data (i.e. potentially truncated revert reason information).

  • member: refundStatus - Result of the refund. REFUND_SUCCESS or REFUND_FAIL are for refunds where targetChain=refundChain; the others are for targetChain!=refundChain, where a cross chain refund is necessary

  • member: overridesInfo:

  • If not an override: empty bytes array

  • Otherwise: An encoded DeliveryOverride

event Delivery(
    address indexed recipientContract,
    uint16 indexed sourceChain,
    uint64 indexed sequence,
    bytes32 deliveryVaaHash,
    DeliveryStatus status,
    uint256 gasUsed,
    RefundStatus refundStatus,
    bytes additionalStatusInfo,
    bytes overridesInfo
);

Enums

DeliveryStatus

enum DeliveryStatus {
    SUCCESS,
    RECEIVER_FAILURE
}

RefundStatus

enum RefundStatus {
    REFUND_SENT,
    REFUND_FAIL,
    CROSS_CHAIN_REFUND_SENT,
    CROSS_CHAIN_REFUND_FAIL_PROVIDER_NOT_SUPPORTED,
    CROSS_CHAIN_REFUND_FAIL_NOT_ENOUGH
}

IWormholeRelayer

Git Source

Inherits: IWormholeRelayerDelivery, IWormholeRelayerSend

InvalidMsgValue

Git Source

error InvalidMsgValue(uint256 msgValue, uint256 totalFee);

RequestedGasLimitTooLow

Git Source

error RequestedGasLimitTooLow();

DeliveryProviderDoesNotSupportTargetChain

Git Source

error DeliveryProviderDoesNotSupportTargetChain(address relayer, uint16 chainId);

DeliveryProviderCannotReceivePayment

Git Source

error DeliveryProviderCannotReceivePayment();

ReentrantDelivery

Git Source

error ReentrantDelivery(address msgSender, address lockedBy);

InvalidPayloadId

Git Source

error InvalidPayloadId(uint8 parsed, uint8 expected);

InvalidPayloadLength

Git Source

error InvalidPayloadLength(uint256 received, uint256 expected);

InvalidVaaKeyType

Git Source

error InvalidVaaKeyType(uint8 parsed);

InvalidDeliveryVaa

Git Source

error InvalidDeliveryVaa(string reason);

InvalidEmitter

Git Source

error InvalidEmitter(bytes32 emitter, bytes32 registered, uint16 chainId);

VaaKeysLengthDoesNotMatchVaasLength

Git Source

error VaaKeysLengthDoesNotMatchVaasLength(uint256 keys, uint256 vaas);

VaaKeysDoNotMatchVaas

Git Source

error VaaKeysDoNotMatchVaas(uint8 index);

RequesterNotWormholeRelayer

Git Source

error RequesterNotWormholeRelayer();

TargetChainIsNotThisChain

Git Source

error TargetChainIsNotThisChain(uint16 targetChain);

InvalidOverrideGasLimit

Git Source

error InvalidOverrideGasLimit();

InvalidOverrideReceiverValue

Git Source

error InvalidOverrideReceiverValue();

InvalidOverrideRefundPerGasUnused

Git Source

error InvalidOverrideRefundPerGasUnused();

InsufficientRelayerFunds

Git Source

error InsufficientRelayerFunds(uint256 msgValue, uint256 minimum);

NotAnEvmAddress

Git Source

error NotAnEvmAddress(bytes32);

Constants

Git Source

RETURNDATA_TRUNCATION_THRESHOLD

uint256 constant RETURNDATA_TRUNCATION_THRESHOLD = 132;

BaseForm

Git Source

Inherits: Initializable, ERC165, IBaseForm

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

Abstract contract to be inherited by different form implementations

State Variables

PRECISION_DECIMALS

uint256 internal constant PRECISION_DECIMALS = 27;

PRECISION

uint256 internal constant PRECISION = 10 ** PRECISION_DECIMALS;

CHAIN_ID

uint64 public immutable CHAIN_ID;

superRegistry

The superRegistry address is used to access relevant protocol addresses

ISuperRegistry public immutable superRegistry;

vault

the vault this form pertains to

address public vault;

formImplementationId

uint32 public formImplementationId;

Functions

notPaused

modifier notPaused(InitSingleVaultData memory singleVaultData_);

onlySuperRouter

modifier onlySuperRouter();

onlyCoreStateRegistry

modifier onlyCoreStateRegistry();

onlyEmergencyQueue

modifier onlyEmergencyQueue();

constructor

constructor(address superRegistry_);

initialize

sets caller as the admin of the contract.

function initialize(address superRegistry_, address vault_, uint32 formImplementationId_) external initializer;

Parameters

NameTypeDescription
superRegistry_addressISuperRegistry address deployed
vault_addressThe vault address this form pertains to
formImplementationId_uint32

receive

receive() external payable;

supportsInterface

function supportsInterface(bytes4 interfaceId_) public view virtual override(ERC165, IERC165) returns (bool);

directDepositIntoVault

process same chain id deposits

function directDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    external
    payable
    override
    onlySuperRouter
    notPaused(singleVaultData_)
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
singleVaultData_InitSingleVaultDataA bytes representation containing all the data required to make a form action
srcSender_addressThe address of the sender of the transaction

Returns

NameTypeDescription
dstAmountuint256The amount of tokens deposited in same chain action

directWithdrawFromVault

process withdrawal of collateral from a vault

function directWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    external
    override
    onlySuperRouter
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
singleVaultData_InitSingleVaultDataA bytes representation containing all the data required to make a form action
srcSender_addressThe address of the sender of the transaction

Returns

NameTypeDescription
dstAmountuint256The amount of tokens withdrawn in same chain action

xChainDepositIntoVault

process same chain id deposits

function xChainDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    external
    override
    onlyCoreStateRegistry
    notPaused(singleVaultData_)
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
singleVaultData_InitSingleVaultDataA bytes representation containing all the data required to make a form action
srcSender_addressThe address of the sender of the transaction
srcChainId_uint64The chain id of the source chain

Returns

NameTypeDescription
dstAmountuint256The amount of tokens deposited in same chain action

xChainWithdrawFromVault

process withdrawal of collateral from a vault

function xChainWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    external
    override
    onlyCoreStateRegistry
    returns (uint256 dstAmount);

Parameters

NameTypeDescription
singleVaultData_InitSingleVaultDataA bytes representation containing all the data required to make a form action
srcSender_addressThe address of the sender of the transaction
srcChainId_uint64The chain id of the source chain

Returns

NameTypeDescription
dstAmountuint256The amount of tokens withdrawn

emergencyWithdraw

process withdrawal of shares if form is paused

function emergencyWithdraw(address refundAddress_, uint256 amount_) external override onlyEmergencyQueue;

Parameters

NameTypeDescription
refundAddress_addressThe address to refund the shares to
amount_uint256The amount of vault shares to refund

superformYieldTokenName

get Superform name of the ERC20 vault representation

function superformYieldTokenName() external view virtual override returns (string memory);

Returns

NameTypeDescription
<none>stringThe ERC20 name

superformYieldTokenSymbol

get Superform symbol of the ERC20 vault representation

function superformYieldTokenSymbol() external view virtual override returns (string memory);

Returns

NameTypeDescription
<none>stringThe ERC20 symbol

getVaultAsset

Returns the underlying token of a vault.

function getVaultAsset() public view virtual override returns (address);

Returns

NameTypeDescription
<none>addressThe asset being deposited into the vault used for accounting, depositing, and withdrawing

getVaultName

Returns the name of the vault.

function getVaultName() public view virtual override returns (string memory);

Returns

NameTypeDescription
<none>stringThe name of the vault

getVaultSymbol

Returns the symbol of a vault.

function getVaultSymbol() public view virtual override returns (string memory);

Returns

NameTypeDescription
<none>stringThe symbol associated with a vault

getVaultDecimals

Returns the number of decimals in a vault for accounting purposes

function getVaultDecimals() public view virtual override returns (uint256);

Returns

NameTypeDescription
<none>uint256The number of decimals in the vault balance

getVaultAddress

function getVaultAddress() external view override returns (address);

getPricePerVaultShare

Returns the amount of underlying tokens each share of a vault is worth.

function getPricePerVaultShare() public view virtual override returns (uint256);

Returns

NameTypeDescription
<none>uint256The pricePerVaultShare value

getVaultShareBalance

Returns the amount of vault shares owned by the form.

function getVaultShareBalance() public view virtual override returns (uint256);

Returns

NameTypeDescription
<none>uint256The form's vault share balance

getTotalAssets

get the total amount of underlying managed in the ERC4626 vault

function getTotalAssets() public view virtual override returns (uint256);

getStateRegistryId

get the state registry id

function getStateRegistryId() external view virtual override returns (uint256);

getPreviewPricePerVaultShare

function getPreviewPricePerVaultShare() public view virtual override returns (uint256);

previewDepositTo

API may need to know state of funds deployed

function previewDepositTo(uint256 assets_) public view virtual override returns (uint256);

previewWithdrawFrom

positionBalance() -> .vaultIds&destAmounts

function previewWithdrawFrom(uint256 assets_) public view virtual override returns (uint256);

Returns

NameTypeDescription
<none>uint256how much of an asset + interest (accrued) is to withdraw from the Vault

previewRedeemFrom

API may need to know state of funds deployed

function previewRedeemFrom(uint256 shares_) public view virtual override returns (uint256);

_directDepositIntoVault

Deposits underlying tokens into a vault

function _directDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    internal
    virtual
    returns (uint256 dstAmount);

_directWithdrawFromVault

Withdraws underlying tokens from a vault

function _directWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_
)
    internal
    virtual
    returns (uint256 dstAmount_);

_xChainDepositIntoVault

Deposits underlying tokens into a vault

function _xChainDepositIntoVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    virtual
    returns (uint256 dstAmount);

_xChainWithdrawFromVault

Withdraws underlying tokens from a vault

function _xChainWithdrawFromVault(
    InitSingleVaultData memory singleVaultData_,
    address srcSender_,
    uint64 srcChainId_
)
    internal
    virtual
    returns (uint256 dstAmount);

_emergencyWithdraw

withdraws vault shares from form during emergency

function _emergencyWithdraw(address refundAddress_, uint256 amount_) internal virtual;

_isPaused

returns if a form id is paused

function _isPaused(uint256 superformId) internal view returns (bool);

_vaultSharesAmountToUnderlyingAmount

Converts a vault share amount into an equivalent underlying asset amount

function _vaultSharesAmountToUnderlyingAmount(
    uint256 vaultSharesAmount_,
    uint256 pricePerVaultShare_
)
    internal
    view
    virtual
    returns (uint256);

_vaultSharesAmountToUnderlyingAmountRoundingUp

Converts a vault share amount into an equivalent underlying asset amount, rounding up

function _vaultSharesAmountToUnderlyingAmountRoundingUp(
    uint256 vaultSharesAmount_,
    uint256 pricePerVaultShare_
)
    internal
    view
    virtual
    returns (uint256);

_underlyingAmountToVaultSharesAmount

Converts an underlying asset amount into an equivalent vault shares amount

function _underlyingAmountToVaultSharesAmount(
    uint256 underlyingAmount_,
    uint256 pricePerVaultShare_
)
    internal
    view
    virtual
    returns (uint256);

BaseRouter

Git Source

Inherits: IBaseRouter

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

Routes users funds and action information to a remote execution chain.

abstract implementation that allows inheriting routers to implement their own logic

State Variables

STATE_REGISTRY_TYPE

uint8 public immutable STATE_REGISTRY_TYPE;

ROUTER_TYPE

uint8 public immutable ROUTER_TYPE;

CHAIN_ID

uint64 public immutable CHAIN_ID;

superRegistry

ISuperRegistry public immutable superRegistry;

Functions

constructor

constructor(address superRegistry_, uint8 stateRegistryType_, uint8 routerType_);

Parameters

NameTypeDescription
superRegistry_addressthe superform registry contract
stateRegistryType_uint8the state registry type
routerType_uint8the router type

receive

receive enables processing native token transfers into the smart contract.

liquidity bridge fails without a native receive function.

receive() external payable;

multiDstMultiVaultDeposit

Performs multi destination x multi vault deposits

function multiDstMultiVaultDeposit(MultiDstMultiVaultStateReq calldata req_) external payable virtual override;

Parameters

NameTypeDescription
req_MultiDstMultiVaultStateReqis the request object containing all the necessary data for the action

multiDstSingleVaultDeposit

Performs multi destination x single vault deposits

function multiDstSingleVaultDeposit(MultiDstSingleVaultStateReq calldata req_) external payable virtual override;

Parameters

NameTypeDescription
req_MultiDstSingleVaultStateReqis the request object containing all the necessary data for the action

singleXChainMultiVaultDeposit

Performs single destination x multi vault deposits

function singleXChainMultiVaultDeposit(SingleXChainMultiVaultStateReq memory req_) external payable virtual override;

Parameters

NameTypeDescription
req_SingleXChainMultiVaultStateReqis the request object containing all the necessary data for the action

singleXChainSingleVaultDeposit

Performs single xchain destination x single vault deposits

function singleXChainSingleVaultDeposit(SingleXChainSingleVaultStateReq memory req_)
    external
    payable
    virtual
    override;

Parameters

NameTypeDescription
req_SingleXChainSingleVaultStateReqis the request object containing all the necessary data for the action

singleDirectMultiVaultDeposit

Performs single direct x multi vault deposits

function singleDirectMultiVaultDeposit(SingleDirectMultiVaultStateReq memory req_) external payable virtual override;

Parameters

NameTypeDescription
req_SingleDirectMultiVaultStateReqis the request object containing all the necessary data for the action

singleDirectSingleVaultDeposit

Performs single direct x single vault deposits

function singleDirectSingleVaultDeposit(SingleDirectSingleVaultStateReq memory req_)
    external
    payable
    virtual
    override;

Parameters

NameTypeDescription
req_SingleDirectSingleVaultStateReqis the request object containing all the necessary data for the action

multiDstMultiVaultWithdraw

Performs multi destination x multi vault withdraws

function multiDstMultiVaultWithdraw(MultiDstMultiVaultStateReq calldata req_) external payable virtual override;

Parameters

NameTypeDescription
req_MultiDstMultiVaultStateReqis the request object containing all the necessary data for the action

multiDstSingleVaultWithdraw

Performs multi destination x single vault withdraws

function multiDstSingleVaultWithdraw(MultiDstSingleVaultStateReq calldata req_) external payable virtual override;

Parameters

NameTypeDescription
req_MultiDstSingleVaultStateReqis the request object containing all the necessary data for the action

singleXChainMultiVaultWithdraw

Performs single destination x multi vault withdraws

function singleXChainMultiVaultWithdraw(SingleXChainMultiVaultStateReq memory req_) external payable virtual override;

Parameters

NameTypeDescription
req_SingleXChainMultiVaultStateReqis the request object containing all the necessary data for the action

singleXChainSingleVaultWithdraw

Performs single xchain destination x single vault withdraws

function singleXChainSingleVaultWithdraw(SingleXChainSingleVaultStateReq memory req_)
    external
    payable
    virtual
    override;

Parameters

NameTypeDescription
req_SingleXChainSingleVaultStateReqis the request object containing all the necessary data for the action

singleDirectMultiVaultWithdraw

Performs single direct x multi vault withdraws

function singleDirectMultiVaultWithdraw(SingleDirectMultiVaultStateReq memory req_) external payable virtual override;

Parameters

NameTypeDescription
req_SingleDirectMultiVaultStateReqis the request object containing all the necessary data for the action

singleDirectSingleVaultWithdraw

Performs single direct x single vault withdraws

function singleDirectSingleVaultWithdraw(SingleDirectSingleVaultStateReq memory req_)
    external
    payable
    virtual
    override;

Parameters

NameTypeDescription
req_SingleDirectSingleVaultStateReqis the request object containing all the necessary data for the action

BaseRouterImplementation

Git Source

Inherits: IBaseRouterImplementation, BaseRouter, LiquidityHandler

Author: Zeropoint Labs

SPDX-License-Identifier: Apache-2.0

Extends BaseRouter with standard internal execution functions (based on SuperPositions)

State Variables

payloadIds

tracks the total payloads

uint256 public payloadIds;

Functions

constructor

constructor(
    address superRegistry_,
    uint8 stateRegistryType_,
    uint8 routerType_
)
    BaseRouter(superRegistry_, stateRegistryType_, routerType_);

Parameters

NameTypeDescription
superRegistry_addressthe superform registry contract
stateRegistryType_uint8the state registry type
routerType_uint8the router type

_singleXChainMultiVaultDeposit

handles cross-chain multi vault deposit

function _singleXChainMultiVaultDeposit(SingleXChainMultiVaultStateReq memory req_) internal virtual;

_singleXChainSingleVaultDeposit

validate superformsData

this loop is what allows to deposit to >1 different underlying on destination

if a loop fails in a validation the whole chain should be reverted

dispatch liquidity data

dispatch message information, notice multiVaults is set to 1

handles cross-chain single vault deposit

function _singleXChainSingleVaultDeposit(SingleXChainSingleVaultStateReq memory req_) internal virtual;

_singleDirectSingleVaultDeposit

disallow direct chain actions

this step validates and returns ambData from the state request

dispatch liquidity data

dispatch message information, notice multiVaults is set to 0

handles same-chain single vault deposit

function _singleDirectSingleVaultDeposit(SingleDirectSingleVaultStateReq memory req_) internal virtual;

_singleDirectMultiVaultDeposit

same chain action & forward residual payment to payment collector

handles same-chain multi vault deposit

function _singleDirectMultiVaultDeposit(SingleDirectMultiVaultStateReq memory req_) internal virtual;

_singleXChainMultiVaultWithdraw

same chain action & forward residual payment to payment collector

handles cross-chain multi vault withdraw

function _singleXChainMultiVaultWithdraw(SingleXChainMultiVaultStateReq memory req_) internal virtual;

_singleXChainSingleVaultWithdraw

validate superformsData

write packed txData

dispatch message information, notice multiVaults is set to 1

handles cross-chain single vault withdraw

function _singleXChainSingleVaultWithdraw(SingleXChainSingleVaultStateReq memory req_) internal virtual;

_singleDirectSingleVaultWithdraw

this step validates and returns ambData from the state request

dispatch message information, notice multiVaults is set to 0

handles same-chain single vault withdraw

function _singleDirectSingleVaultWithdraw(SingleDirectSingleVaultStateReq memory req_) internal virtual;

_singleDirectMultiVaultWithdraw

same chain action

handles same-chain multi vault withdraw

function _singleDirectMultiVaultWithdraw(SingleDirectMultiVaultStateReq memory req_) internal virtual;

_buildDepositAmbData

SuperPositions are burnt optimistically here

same chain action & forward residual payment to payment collector

internal function used for validation and ambData building across different entry points

function _buildDepositAmbData(
    uint64 dstChainId_,
    SingleVaultSFData memory superformData_
)
    internal
    virtual
    returns (InitSingleVaultData memory ambData, uint256 currentPayloadId);

_buildWithdrawAmbData

validate superformsData

function _buildWithdrawAmbData(
    address srcSender_,
    uint64 dstChainId_,
    SingleVaultSFData memory superformData_
)
    internal
    virtual
    returns (InitSingleVaultData memory ambData, uint256 currentPayloadId);

_validateAndDispatchTokens

function _validateAndDispatchTokens(ValidateAndDispatchTokensArgs memory args_) internal virtual;

_dispatchAmbMessage

validates remaining params of txData

dispatches tokens through the selected liquidity bridge to the destination contract

function _dispatchAmbMessage(DispatchAMBMessageVars memory vars_) internal virtual;

_directSingleDeposit

deposits to single vault on the same chain

this call dispatches the message to the AMB bridge through dispatchPayload

calls _directDeposit

function _directSingleDeposit(
    address srcSender_,
    bytes memory permit2data_,
    InitSingleVaultData memory vaultData_
)
    internal
    virtual;

_directMultiDeposit

deposits to multiple vaults on the same chain

loops and call _directDeposit

function _directMultiDeposit(
    address srcSender_,
    bytes memory permit2data_,
    InitMultiVaultData memory vaultData_
)
    internal
    virtual;

_directDeposit

fulfils the final stage of same chain deposit action

decode superforms

deposits collateral to a given vault and mint vault positions.

in direct deposits, SuperPositions are minted right after depositing to vaults

function _directDeposit(
    address superform_,
    uint8 superformRouterId_,
    uint256 payloadId_,
    uint256 superformId_,
    uint256 amount_,
    uint256 maxSlippage_,
    LiqRequest memory liqData_,
    bytes memory extraFormData_,
    uint256 msgValue_,
    address srcSender_
)
    internal
    virtual
    returns (uint256 dstAmount);

_directSingleWithdraw

withdraws from single vault on the same chain

validates if superformId exists on factory

deposits collateral to a given vault and mint vault positions directly through the form no need for a refund address

call _directWithdraw

function _directSingleWithdraw(InitSingleVaultData memory vaultData_, address srcSender_) internal virtual;

_directMultiWithdraw

withdraws from multiple vaults on the same chain

decode superforms

loops and call _directWithdraw

function _directMultiWithdraw(InitMultiVaultData memory vaultData_, address srcSender_) internal virtual;

_directWithdraw

fulfils the final stage of same chain withdrawal action

decode superforms

deposits collateral to a given vault and mint vault positions.

function _directWithdraw(
    address superform_,
    uint8 superformRouterId_,
    uint256 payloadId_,
    uint256 superformId_,
    uint256 amount_,
    uint256 maxSlippage_,
    LiqRequest memory liqData_,
    bytes memory extraFormData_,
    address srcSender_,
    address refundAddress_
)
    internal
    virtual;

_validateSuperformData

validates if superformId exists on factory

in direct withdraws, form is called directly

function _validateSuperformData(
    uint64 dstChainId_,
    SingleVaultSFData memory superformData_
)
    internal
    view
    virtual
    returns (bool);

_validateSuperformsDepositData

the dstChainId_ (in the state request) must match the superforms' chainId (superform must exist on destinatiom)

10000 = 100% slippage if it reaches this point then is valid

function _validateSuperformsDepositData(
    MultiVaultSFData memory superformsData_,
    uint64 dstChainId_
)
    internal
    view
    virtual
    returns (bool);

_validateSuperformsWithdrawData

empty requests are not allowed, as well as requests with length mismatch

superformIds/amounts/slippages array sizes validation

slippage and paused status validation

10000 = 100% slippage

function _validateSuperformsWithdrawData(
    MultiVaultSFData memory superformsData_,
    uint64 dstChainId_
)
    internal
    view
    virtual
    returns (bool);

_forwardPayment

empty requests are not allowed, as well as requests with length mismatch

superformIds/amounts/slippages array sizes validation

slippage and paused status validation

10000 = 100% slippage

forwards the residual payment to payment collector

function _forwardPayment(uint256 _balanceBefore) internal virtual;

_singleVaultTokenForward

deducts what's already available sends what's left in msg.value to payment collector

function _singleVaultTokenForward(
    address srcSender_,
    address superform_,
    bytes memory permit2data_,
    InitSingleVaultData memory vaultData_
)
    internal
    virtual;

_multiVaultTokenForward

function _multiVaultTokenForward(
    address srcSender_,
    address[] memory targets_,
    bytes memory permit2data_,
    InitMultiVaultData memory vaultData_,
    bool xChain
)
    internal
    virtual;

Structs

ValidateAndDispatchTokensArgs

validate superformsData

struct ValidateAndDispatchTokensArgs {
    LiqRequest liqRequest;
    address permit2;
    address superform;
    uint64 srcChainId;
    uint64 dstChainId;
    address srcSender;
    bool deposit;
}

MultiDepositLocalVars

decode superforms

deposits collateral to a given vault and mint vault positions.

mint super positions at the end of the deposit action

struct MultiDepositLocalVars {
    uint256 len;
    address[] superforms;
    uint256[] dstAmounts;
    bool mint;
}

MultiTokenForwardLocalVars

e.g asset in is USDC (6 decimals), we use this amount to approve the transfer to superform

moves the tokens from the user to the router

moves the tokens from the user to the router

approves the input amount to the superform

struct MultiTokenForwardLocalVars {
    IERC20 token;
    uint256 len;
    uint256 totalAmount;
    uint256 permit2dataLen;
    address permit2;
    uint256[] approvalAmounts;
}

StateSyncer

Git Source

Inherits: IStateSyncer

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

base contract for stateSync functions

State Variables

superRegistry

is the super registry address

ISuperRegistry public immutable superRegistry;

ROUTER_TYPE

uint8 public immutable ROUTER_TYPE;

CHAIN_ID

uint64 public immutable CHAIN_ID;

txHistory

maps all transaction data routed through the smart contract.

mapping(uint256 transactionId => uint256 txInfo) public override txHistory;

Functions

onlyRouter

modifier onlyRouter();

onlyMinter

modifier onlyMinter(uint256 id) virtual;

onlyBatchMinter

modifier onlyBatchMinter(uint256[] memory ids) virtual;

onlyBurner

modifier onlyBurner() virtual;

onlyProtocolAdmin

modifier onlyProtocolAdmin();

constructor

constructor(address superRegistry_, uint8 routerType_);

Parameters

NameTypeDescription
superRegistry_addressthe superform registry contract
routerType_uint8the router type

updateTxHistory

saves the message being sent together with the associated id formulated in a router

function updateTxHistory(uint256 payloadId_, uint256 txInfo_) external override onlyRouter;

Parameters

NameTypeDescription
payloadId_uint256is the id of the message being saved
txInfo_uint256is the relevant information of the transaction being saved

mintSingle

allows minter to mint shares on source

function mintSingle(address srcSender_, uint256 id_, uint256 amount_) external virtual override;

Parameters

NameTypeDescription
srcSender_addressis the beneficiary of shares
id_uint256is the id of the shares
amount_uint256is the amount of shares to mint

mintBatch

allows minter to mint shares on source in batch

function mintBatch(address srcSender_, uint256[] memory ids_, uint256[] memory amounts_) external virtual override;

Parameters

NameTypeDescription
srcSender_addressis the beneficiary of shares
ids_uint256[]are the ids of the shares
amounts_uint256[]are the amounts of shares to mint

burnSingle

allows burner to burn shares on source

function burnSingle(address srcSender_, uint256 id_, uint256 amount_) external virtual override;

Parameters

NameTypeDescription
srcSender_addressis the address of the sender
id_uint256is the id of the shares
amount_uint256is the amount of shares to burn

burnBatch

allows burner to burn shares on source in batch

function burnBatch(address srcSender_, uint256[] memory ids_, uint256[] memory amounts_) external virtual override;

Parameters

NameTypeDescription
srcSender_addressis the address of the sender
ids_uint256[]are the ids of the shares
amounts_uint256[]are the amounts of shares to burn

stateMultiSync

allows state registry contract to mint shares on source

function stateMultiSync(AMBMessage memory data_) external virtual override returns (uint64 srcChainId_);

Parameters

NameTypeDescription
data_AMBMessageis the received information to be processed.

Returns

NameTypeDescription
srcChainId_uint64is the decoded srcChainId.

stateSync

allows state registry contract to mint shares on source

function stateSync(AMBMessage memory data_) external virtual override returns (uint64 srcChainId_);

Parameters

NameTypeDescription
data_AMBMessageis the received information to be processed.

Returns

NameTypeDescription
srcChainId_uint64is the decoded srcChainId.

_validateStateSyncer

helps validate the state registry id for minting superform id

function _validateStateSyncer(uint256 superformId_) internal view;

_validateStateSyncer

helps validate the state registry id for minting superform id

function _validateStateSyncer(uint256[] memory superformIds_) internal view;

_isValidStateSyncer

function _isValidStateSyncer(uint8 registryId_, uint256 superformId_) internal pure;

SuperPositions

Git Source

Inherits: ISuperPositions, ERC1155A, StateSyncer

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

State Variables

dynamicURI

is the base uri set by admin

string public dynamicURI;

dynamicURIFrozen

is the base uri frozen status

bool public dynamicURIFrozen;

Functions

onlyMinter

minters can be router with id 1 (or) state registry for that beacon

modifier onlyMinter(uint256 superformId) override;

onlyBatchMinter

if registry id is 1 (or) corresponding state registry can mint

minters can be router with id 1 (or) state registry for that beacon

modifier onlyBatchMinter(uint256[] memory superformIds) override;

onlyBurner

if registry id is 1 (or) corresponding state registry can mint

only routers with id 1 can burn super positions

modifier onlyBurner() override;

constructor

constructor(
    string memory dynamicURI_,
    address superRegistry_,
    uint8 routerType_
)
    StateSyncer(superRegistry_, routerType_);

Parameters

NameTypeDescription
dynamicURI_stringURL for external metadata of ERC1155 SuperPositions
superRegistry_addressthe superform registry contract
routerType_uint8the router type

mintSingle

allows minter to mint shares on source

function mintSingle(
    address srcSender_,
    uint256 id_,
    uint256 amount_
)
    external
    override(IStateSyncer, StateSyncer)
    onlyMinter(id_);

Parameters

NameTypeDescription
srcSender_addressis the beneficiary of shares
id_uint256is the id of the shares
amount_uint256is the amount of shares to mint

mintBatch

allows minter to mint shares on source in batch

function mintBatch(
    address srcSender_,
    uint256[] memory ids_,
    uint256[] memory amounts_
)
    external
    override(IStateSyncer, StateSyncer)
    onlyBatchMinter(ids_);

Parameters

NameTypeDescription
srcSender_addressis the beneficiary of shares
ids_uint256[]are the ids of the shares
amounts_uint256[]are the amounts of shares to mint

burnSingle

allows burner to burn shares on source

function burnSingle(
    address srcSender_,
    uint256 id_,
    uint256 amount_
)
    external
    override(IStateSyncer, StateSyncer)
    onlyBurner;

Parameters

NameTypeDescription
srcSender_addressis the address of the sender
id_uint256is the id of the shares
amount_uint256is the amount of shares to burn

burnBatch

allows burner to burn shares on source in batch

function burnBatch(
    address srcSender_,
    uint256[] memory ids_,
    uint256[] memory amounts_
)
    external
    override(IStateSyncer, StateSyncer)
    onlyBurner;

Parameters

NameTypeDescription
srcSender_addressis the address of the sender
ids_uint256[]are the ids of the shares
amounts_uint256[]are the amounts of shares to burn

stateMultiSync

allows state registry contract to mint shares on source

function stateMultiSync(AMBMessage memory data_)
    external
    override(IStateSyncer, StateSyncer)
    returns (uint64 srcChainId_);

Parameters

NameTypeDescription
data_AMBMessageis the received information to be processed.

Returns

NameTypeDescription
srcChainId_uint64is the decoded srcChainId.

stateSync

here we decode the txInfo and params from the data brought back from destination

decode remaining info on superPositions to mint from destination

decode initial payload info stored on source chain in this contract

verify this is a single vault mint

compare final shares beneficiary to be the same (dst/src)

compare txType to be the same (dst/src)

mint super positions accordingly

function stateSync(AMBMessage memory data_) external override(IStateSyncer, StateSyncer) returns (uint64 srcChainId_);

Parameters

NameTypeDescription
data_AMBMessageis the received information to be processed.

Returns

NameTypeDescription
srcChainId_uint64is the decoded srcChainId.

setDynamicURI

here we decode the txInfo and params from the data brought back from destination

decode remaining info on superPositions to mint from destination

decode initial payload info stored on source chain in this contract

verify this is a multi vault mint

compare final shares beneficiary to be the same (dst/src)

compare txType to be the same (dst/src)

mint super positions accordingly

function setDynamicURI(string memory dynamicURI_, bool freeze_) external override onlyProtocolAdmin;

Parameters

NameTypeDescription
dynamicURI_stringis the dynamic uri of the NFT
freeze_boolis to prevent updating the metadata once migrated to IPFS

supportsInterface

Implementation copied from solmate/ERC1155

function supportsInterface(bytes4 interfaceId_) public view virtual override(ERC1155A) returns (bool);

_baseURI

Used to construct return url

function _baseURI() internal view override returns (string memory);

SuperTransmuter

Git Source

Inherits: ISuperTransmuter, Transmuter, StateSyncer

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

This contract inherits from ERC1155A transmuter, changing the way transmuters are registered to only require a superformId. Metadata is fetched from underlying vault

State Variables

DEPLOY_NEW_TRANSMUTER

bytes32 constant DEPLOY_NEW_TRANSMUTER = keccak256("DEPLOY_NEW_TRANSMUTER");

xChainPayloadCounter

uint256 public xChainPayloadCounter;

Functions

onlyMinter

minters can be router with id 2 (or) state registry for that beacon

modifier onlyMinter(uint256 superformId) override;

onlyBatchMinter

if registry id is 2 (or) corresponding state registry can mint

minters can be router with id 2 (or) state registry for that beacon

modifier onlyBatchMinter(uint256[] memory superformIds) override;

onlyBurner

if registry id is 1 (or) corresponding state registry can mint

only routers with id 2 can burn sERC20

modifier onlyBurner() override;

constructor

constructor(
    IERC1155A superPositions_,
    address superRegistry_,
    uint8 routerType_
)
    Transmuter(superPositions_)
    StateSyncer(superRegistry_, routerType_);

Parameters

NameTypeDescription
superPositions_IERC1155Athe super positions contract
superRegistry_addressthe superform registry contract
routerType_uint8the router type

registerTransmuter

explicity revert on register transmuter

function registerTransmuter(uint256, string memory, string memory, uint8) external pure override returns (address);

registerTransmuter

this overrides registerTransmuter from original transmuter implementation so that users cannot insert name, symbol, and decimals

anyone can register a transmuter for an existent superform

function registerTransmuter(uint256 superformId_, bytes memory extraData_) external override returns (address);

Parameters

NameTypeDescription
superformId_uint256
extraData_bytesis an optional param to broadcast changes to all chains

mintSingle

broadcast and deploy to the other destination chains

function mintSingle(
    address srcSender_,
    uint256 id_,
    uint256 amount_
)
    external
    override(IStateSyncer, StateSyncer)
    onlyMinter(id_);

Parameters

NameTypeDescription
srcSender_addressis the beneficiary of shares
id_uint256is the id of the shares
amount_uint256is the amount of shares to mint

mintBatch

allows minter to mint shares on source in batch

function mintBatch(
    address srcSender_,
    uint256[] memory ids_,
    uint256[] memory amounts_
)
    external
    override(IStateSyncer, StateSyncer)
    onlyBatchMinter(ids_);

Parameters

NameTypeDescription
srcSender_addressis the beneficiary of shares
ids_uint256[]are the ids of the shares
amounts_uint256[]are the amounts of shares to mint

burnSingle

allows burner to burn shares on source

function burnSingle(
    address srcSender_,
    uint256 id_,
    uint256 amount_
)
    external
    override(IStateSyncer, StateSyncer)
    onlyBurner;

Parameters

NameTypeDescription
srcSender_addressis the address of the sender
id_uint256is the id of the shares
amount_uint256is the amount of shares to burn

burnBatch

allows burner to burn shares on source in batch

function burnBatch(
    address srcSender_,
    uint256[] memory ids_,
    uint256[] memory amounts_
)
    external
    override(IStateSyncer, StateSyncer)
    onlyBurner;

Parameters

NameTypeDescription
srcSender_addressis the address of the sender
ids_uint256[]are the ids of the shares
amounts_uint256[]are the amounts of shares to burn

stateMultiSync

note each allowance check in burn needs to pass. Since we burn atomically (on SuperformRouter level), if this loop fails, tx reverts right in the 1st stage

function stateMultiSync(AMBMessage memory data_)
    external
    override(IStateSyncer, StateSyncer)
    returns (uint64 srcChainId_);

Parameters

NameTypeDescription
data_AMBMessageis the received information to be processed.

Returns

NameTypeDescription
srcChainId_uint64is the decoded srcChainId.

stateSync

here we decode the txInfo and params from the data brought back from destination

decode remaining info on superPositions to mint from destination

decode initial payload info stored on source chain in this contract

verify this is a single vault mint

compare final shares beneficiary to be the same (dst/src)

compare txType to be the same (dst/src)

mint super positions accordingly

function stateSync(AMBMessage memory data_) external override(IStateSyncer, StateSyncer) returns (uint64 srcChainId_);

Parameters

NameTypeDescription
data_AMBMessageis the received information to be processed.

Returns

NameTypeDescription
srcChainId_uint64is the decoded srcChainId.

stateSyncBroadcast

here we decode the txInfo and params from the data brought back from destination

decode remaining info on superPositions to mint from destination

decode initial payload info stored on source chain in this contract

verify this is a multi vault mint

compare final shares beneficiary to be the same (dst/src)

compare txType to be the same (dst/src)

mint super positions accordingly

function stateSyncBroadcast(bytes memory data_) external payable override;

Parameters

NameTypeDescription
data_bytesis the crosschain payload

_broadcast

this function is only accessible through broadcast registry

interacts with broadcast state registry to broadcasting state changes to all connected remote chains

function _broadcast(bytes memory message_, bytes memory extraData_) internal;

Parameters

NameTypeDescription
message_bytesis the crosschain message to be sent.
extraData_bytesis the amb override information.

_deployTransmuter

ambIds are validated inside the broadcast state registry

broadcastParams if wrong will revert in the amb implementation

deploys new transmuter on broadcasting

function _deployTransmuter(bytes memory message_) internal;

SuperformFactory

Git Source

Inherits: ISuperformFactory

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

A secure, and easily queryable central point of access for all Superforms on any given chain,

State Variables

SYNC_IMPLEMENTATION_STATUS

bytes32 constant SYNC_IMPLEMENTATION_STATUS = keccak256("SYNC_IMPLEMENTATION_STATUS");

CHAIN_ID

uint64 public immutable CHAIN_ID;

xChainPayloadCounter

uint256 public xChainPayloadCounter;

superRegistry

ISuperRegistry public immutable superRegistry;

formImplementations

all form beacon addresses

address[] public formImplementations;

superforms

all superform ids

uint256[] public superforms;

formImplementation

If formImplementationId is 0, formImplementation is not part of the protocol

mapping(uint32 formImplementationId => address formBeaconAddress) public formImplementation;

formImplementationPaused

mapping(uint32 formImplementationId => bool paused) public formImplementationPaused;

vaultToSuperforms

mapping(address vault => uint256[] superformIds) public vaultToSuperforms;

vaultToFormImplementationId

mapping(address vault => uint256[] formImplementationId) public vaultToFormImplementationId;

vaultFormImplCombinationToSuperforms

mapping(bytes32 vaultFormImplementationCombination => uint256 superformIds) public vaultFormImplCombinationToSuperforms;

Functions

onlyEmergencyAdmin

modifier onlyEmergencyAdmin();

onlyProtocolAdmin

modifier onlyProtocolAdmin();

constructor

constructor(address superRegistry_);

Parameters

NameTypeDescription
superRegistry_addressthe superform registry contract

addFormImplementation

allows an admin to add a Form implementation to the factory

function addFormImplementation(
    address formImplementation_,
    uint32 formImplementationId_
)
    public
    override
    onlyProtocolAdmin;

Parameters

NameTypeDescription
formImplementation_addressis the address of a form implementation
formImplementationId_uint32is the id of the form implementation (generated off-chain and equal in all chains)

createSuperform

save the newly added address in the mapping and array registry

function createSuperform(
    uint32 formImplementationId_,
    address vault_
)
    public
    override
    returns (uint256 superformId_, address superform_);

Parameters

NameTypeDescription
formImplementationId_uint32is the form implementation we want to attach the vault to
vault_addressis the address of the vault

Returns

NameTypeDescription
superformId_uint256is the id of the created superform
superform_addressis the address of the created superform

changeFormImplementationPauseStatus

Same vault and beacon can be used only once to create superform

instantiate the superform.

this will always be unique because all chainIds are unique

Mapping vaults to formImplementationId for use in Backend

function changeFormImplementationPauseStatus(
    uint32 formImplementationId_,
    bool paused_,
    bytes memory extraData_
)
    external
    payable
    override
    onlyEmergencyAdmin;

Parameters

NameTypeDescription
formImplementationId_uint32is the id of the form implementation
paused_bool
extraData_bytesis optional & passed when broadcasting of status is needed

stateSyncBroadcast

broadcast the change in status to the other destination chains

function stateSyncBroadcast(bytes memory data_) external payable override;

Parameters

NameTypeDescription
data_bytesis the cross-chain superform id

getFormImplementation

this function is only accessible through broadcast registry

function getFormImplementation(uint32 formImplementationId_) external view override returns (address);

Parameters

NameTypeDescription
formImplementationId_uint32is the id of the form implementation

Returns

NameTypeDescription
<none>addressformImplementation_ is the address of the form implementation

isFormImplementationPaused

returns the paused status of form implementation

function isFormImplementationPaused(uint32 formImplementationId_) external view override returns (bool);

Parameters

NameTypeDescription
formImplementationId_uint32is the id of the form implementation

Returns

NameTypeDescription
<none>boolpaused_ is the current paused status of the form formImplementationId_

getAllSuperformsFromVault

Reverse query of getSuperform, returns all superforms for a given vault

function getAllSuperformsFromVault(address vault_)
    external
    view
    override
    returns (uint256[] memory superformIds_, address[] memory superforms_);

Parameters

NameTypeDescription
vault_addressis the address of a vault

Returns

NameTypeDescription
superformIds_uint256[]is the id of the superform
superforms_address[]is the address of the superform

getSuperform

returns the address of a superform

function getSuperform(uint256 superformId_)
    external
    pure
    override
    returns (address superform_, uint32 formImplementationId_, uint64 chainId_);

Parameters

NameTypeDescription
superformId_uint256is the id of the superform

Returns

NameTypeDescription
superform_addressis the address of the superform
formImplementationId_uint32is the id of the form implementation
chainId_uint64is the chain id

getAllSuperforms

Returns all Superforms

function getAllSuperforms()
    external
    view
    override
    returns (uint256[] memory superformIds_, address[] memory superforms_);

Returns

NameTypeDescription
superformIds_uint256[]is the id of the superform
superforms_address[]vaults_ is the address of the vault

getFormCount

returns the number of forms

function getFormCount() external view override returns (uint256 forms_);

Returns

NameTypeDescription
forms_uint256is the number of forms

getSuperformCount

returns the number of superforms

function getSuperformCount() external view override returns (uint256 superforms_);

Returns

NameTypeDescription
superforms_uint256is the number of superforms

_broadcast

interacts with broadcast state registry to broadcasting state changes to all connected remote chains

function _broadcast(bytes memory message_, bytes memory extraData_) internal;

Parameters

NameTypeDescription
message_bytesis the crosschain message to be sent.
extraData_bytesis the amb override information.

_syncFormPausedStatus

is a part of broadcasting / dispatching through factory state registry

ambIds are validated inside the broadcast state registry

broadcastParams if wrong will revert in the amb implementation

synchronize paused status update message from remote chain

function _syncFormPausedStatus(bytes memory message_) internal;

Parameters

NameTypeDescription
message_bytesis the crosschain message received.

SuperformRouter

Git Source

Inherits: BaseRouterImplementation

Author: Zeropoint Labs.

SPDX-License-Identifier: Apache-2.0

SuperformRouter users funds and action information to a remote execution chain.

Uses standard BaseRouterImplementation without any overrides to internal execution functions

Functions

constructor

constructor(
    address superRegistry_,
    uint8 stateRegistryType_,
    uint8 routerType_
)
    BaseRouterImplementation(superRegistry_, stateRegistryType_, routerType_);

Parameters

NameTypeDescription
superRegistry_addressthe superform registry contract
stateRegistryType_uint8the state registry type
routerType_uint8the router type

multiDstMultiVaultDeposit

Performs multi destination x multi vault deposits

function multiDstMultiVaultDeposit(MultiDstMultiVaultStateReq calldata req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_MultiDstMultiVaultStateReqis the request object containing all the necessary data for the action

multiDstSingleVaultDeposit

Performs multi destination x single vault deposits

function multiDstSingleVaultDeposit(MultiDstSingleVaultStateReq calldata req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_MultiDstSingleVaultStateReqis the request object containing all the necessary data for the action

singleXChainMultiVaultDeposit

Performs single destination x multi vault deposits

function singleXChainMultiVaultDeposit(SingleXChainMultiVaultStateReq memory req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_SingleXChainMultiVaultStateReqis the request object containing all the necessary data for the action

singleXChainSingleVaultDeposit

Performs single xchain destination x single vault deposits

function singleXChainSingleVaultDeposit(SingleXChainSingleVaultStateReq memory req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_SingleXChainSingleVaultStateReqis the request object containing all the necessary data for the action

singleDirectMultiVaultDeposit

Performs single direct x multi vault deposits

function singleDirectMultiVaultDeposit(SingleDirectMultiVaultStateReq memory req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_SingleDirectMultiVaultStateReqis the request object containing all the necessary data for the action

singleDirectSingleVaultDeposit

Performs single direct x single vault deposits

function singleDirectSingleVaultDeposit(SingleDirectSingleVaultStateReq memory req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_SingleDirectSingleVaultStateReqis the request object containing all the necessary data for the action

multiDstMultiVaultWithdraw

Performs multi destination x multi vault withdraws

function multiDstMultiVaultWithdraw(MultiDstMultiVaultStateReq calldata req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_MultiDstMultiVaultStateReqis the request object containing all the necessary data for the action

multiDstSingleVaultWithdraw

Performs multi destination x single vault withdraws

function multiDstSingleVaultWithdraw(MultiDstSingleVaultStateReq calldata req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_MultiDstSingleVaultStateReqis the request object containing all the necessary data for the action

singleXChainMultiVaultWithdraw

Performs single destination x multi vault withdraws

function singleXChainMultiVaultWithdraw(SingleXChainMultiVaultStateReq memory req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_SingleXChainMultiVaultStateReqis the request object containing all the necessary data for the action

singleXChainSingleVaultWithdraw

Performs single xchain destination x single vault withdraws

function singleXChainSingleVaultWithdraw(SingleXChainSingleVaultStateReq memory req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_SingleXChainSingleVaultStateReqis the request object containing all the necessary data for the action

singleDirectMultiVaultWithdraw

Performs single direct x multi vault withdraws

function singleDirectMultiVaultWithdraw(SingleDirectMultiVaultStateReq memory req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_SingleDirectMultiVaultStateReqis the request object containing all the necessary data for the action

singleDirectSingleVaultWithdraw

Performs single direct x single vault withdraws

function singleDirectSingleVaultWithdraw(SingleDirectSingleVaultStateReq memory req_)
    external
    payable
    override(BaseRouter, IBaseRouter);

Parameters

NameTypeDescription
req_SingleDirectSingleVaultStateReqis the request object containing all the necessary data for the action