// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import { IBroadcastRegistry } from "src/interfaces/IBroadcastRegistry.sol";
import { Error } from "src/libraries/Error.sol";
/// @title Broadcastable
/// @dev Can be inherited in contracts that wish to support broadcasting
/// @author ZeroPoint Labs
abstract contract Broadcastable {
//////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev broadcasts state changes to all connected remote chains
/// @param broadcastRegistry_ is the address of the broadcast registry contract.
/// @param payMaster_ is the address of the paymaster contract.
/// @param message_ is the crosschain message to be sent.
/// @param extraData_ is the amb override information.
function _broadcast(
address broadcastRegistry_,
address payMaster_,
bytes memory message_,
bytes memory extraData_
)
internal
{
(uint8 ambId, bytes memory broadcastParams) = abi.decode(extraData_, (uint8, bytes));
/// @dev if the broadcastParams are wrong this will revert
(uint256 gasFee, bytes memory extraData) = abi.decode(broadcastParams, (uint256, bytes));
if (msg.value < gasFee) {
revert Error.INVALID_BROADCAST_FEE();
}
/// @dev ambIds are validated inside the broadcast state registry
IBroadcastRegistry(broadcastRegistry_).broadcastPayload{ value: gasFee }(
msg.sender, ambId, gasFee, message_, extraData
);
if (msg.value > gasFee) {
/// @dev forwards the rest to paymaster
(bool success,) = payable(payMaster_).call{ value: msg.value - gasFee }("");
if (!success) {
revert Error.FAILED_TO_SEND_NATIVE();
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import { Error } from "src/libraries/Error.sol";
library DataLib {
function packTxInfo(
uint8 txType_,
uint8 callbackType_,
uint8 multi_,
uint8 registryId_,
address srcSender_,
uint64 srcChainId_
)
internal
pure
returns (uint256 txInfo)
{
txInfo = uint256(txType_);
txInfo |= uint256(callbackType_) << 8;
txInfo |= uint256(multi_) << 16;
txInfo |= uint256(registryId_) << 24;
txInfo |= uint256(uint160(srcSender_)) << 32;
txInfo |= uint256(srcChainId_) << 192;
}
function decodeTxInfo(uint256 txInfo_)
internal
pure
returns (uint8 txType, uint8 callbackType, uint8 multi, uint8 registryId, address srcSender, uint64 srcChainId)
{
txType = uint8(txInfo_);
callbackType = uint8(txInfo_ >> 8);
multi = uint8(txInfo_ >> 16);
registryId = uint8(txInfo_ >> 24);
srcSender = address(uint160(txInfo_ >> 32));
srcChainId = uint64(txInfo_ >> 192);
}
/// @dev returns the vault-form-chain pair of a superform
/// @param superformId_ is the id of the superform
/// @return superform_ is the address of the superform
/// @return formImplementationId_ is the form id
/// @return chainId_ is the chain id
function getSuperform(uint256 superformId_)
internal
pure
returns (address superform_, uint32 formImplementationId_, uint64 chainId_)
{
superform_ = address(uint160(superformId_));
formImplementationId_ = uint32(superformId_ >> 160);
chainId_ = uint64(superformId_ >> 192);
if (chainId_ == 0) {
revert Error.INVALID_CHAIN_ID();
}
}
/// @dev returns the vault-form-chain pair of an array of superforms
/// @param superformIds_ array of superforms
/// @return superforms_ are the address of the vaults
function getSuperforms(uint256[] memory superformIds_) internal pure returns (address[] memory superforms_) {
uint256 len = superformIds_.length;
superforms_ = new address[](len);
for (uint256 i; i < len; ++i) {
(superforms_[i],,) = getSuperform(superformIds_[i]);
}
}
/// @dev returns the destination chain of a given superform
/// @param superformId_ is the id of the superform
/// @return chainId_ is the chain id
function getDestinationChain(uint256 superformId_) internal pure returns (uint64 chainId_) {
chainId_ = uint64(superformId_ >> 192);
if (chainId_ == 0) {
revert Error.INVALID_CHAIN_ID();
}
}
/// @dev generates the superformId
/// @param superform_ is the address of the superform
/// @param formImplementationId_ is the type of the form
/// @param chainId_ is the chain id on which the superform is deployed
function packSuperform(
address superform_,
uint32 formImplementationId_,
uint64 chainId_
)
internal
pure
returns (uint256 superformId_)
{
superformId_ = uint256(uint160(superform_));
superformId_ |= uint256(formImplementationId_) << 160;
superformId_ |= uint256(chainId_) << 192;
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
/// @dev contains all the common struct and enums used for data communication between chains.
/// @dev There are two transaction types in Superform Protocol
enum TransactionType {
DEPOSIT,
WITHDRAW
}
/// @dev Message types can be INIT, RETURN (for successful Deposits) and FAIL (for failed withdraws)
enum CallbackType {
INIT,
RETURN,
FAIL
}
/// @dev Payloads are stored, updated (deposits) or processed (finalized)
enum PayloadState {
STORED,
UPDATED,
PROCESSED
}
/// @dev contains all the common struct used for interchain token transfers.
struct LiqRequest {
/// @dev generated data
bytes txData;
/// @dev input token for deposits, desired output token on target liqDstChainId for withdraws. Must be set for
/// txData to be updated on destination for withdraws
address token;
/// @dev intermediary token on destination. Relevant for xChain deposits where a destination swap is needed for
/// validation purposes
address interimToken;
/// @dev what bridge to use to move tokens
uint8 bridgeId;
/// @dev dstChainId = liqDstchainId for deposits. For withdraws it is the target chain id for where the underlying
/// is to be delivered
uint64 liqDstChainId;
/// @dev currently this amount is used as msg.value in the txData call.
uint256 nativeAmount;
}
/// @dev main struct that holds required multi vault data for an action
struct MultiVaultSFData {
// superformids must have same destination. Can have different underlyings
uint256[] superformIds;
uint256[] amounts; // on deposits, amount of token to deposit on dst, on withdrawals, superpositions to burn
uint256[] outputAmounts; // on deposits, amount of shares to receive, on withdrawals, amount of assets to receive
uint256[] maxSlippages;
LiqRequest[] liqRequests; // if length = 1; amount = sum(amounts) | else amounts must match the amounts being sent
bytes permit2data;
bool[] hasDstSwaps;
bool[] retain4626s; // if true, we don't mint SuperPositions, and send the 4626 back to the user instead
address receiverAddress;
/// this address must always be an EOA otherwise funds may be lost
address receiverAddressSP;
/// this address can be a EOA or a contract that implements onERC1155Receiver. must always be set for deposits
bytes extraFormData; // extraFormData
}
/// @dev main struct that holds required single vault data for an action
struct SingleVaultSFData {
// superformids must have same destination. Can have different underlyings
uint256 superformId;
uint256 amount;
uint256 outputAmount; // on deposits, amount of shares to receive, on withdrawals, amount of assets to receive
uint256 maxSlippage;
LiqRequest liqRequest; // if length = 1; amount = sum(amounts)| else amounts must match the amounts being sent
bytes permit2data;
bool hasDstSwap;
bool retain4626; // if true, we don't mint SuperPositions, and send the 4626 back to the user instead
address receiverAddress;
/// this address must always be an EOA otherwise funds may be lost
address receiverAddressSP;
/// this address can be a EOA or a contract that implements onERC1155Receiver. must always be set for deposits
bytes extraFormData; // extraFormData
}
/// @dev overarching struct for multiDst requests with multi vaults
struct MultiDstMultiVaultStateReq {
uint8[][] ambIds;
uint64[] dstChainIds;
MultiVaultSFData[] superformsData;
}
/// @dev overarching struct for single cross chain requests with multi vaults
struct SingleXChainMultiVaultStateReq {
uint8[] ambIds;
uint64 dstChainId;
MultiVaultSFData superformsData;
}
/// @dev overarching struct for multiDst requests with single vaults
struct MultiDstSingleVaultStateReq {
uint8[][] ambIds;
uint64[] dstChainIds;
SingleVaultSFData[] superformsData;
}
/// @dev overarching struct for single cross chain requests with single vaults
struct SingleXChainSingleVaultStateReq {
uint8[] ambIds;
uint64 dstChainId;
SingleVaultSFData superformData;
}
/// @dev overarching struct for single direct chain requests with single vaults
struct SingleDirectSingleVaultStateReq {
SingleVaultSFData superformData;
}
/// @dev overarching struct for single direct chain requests with multi vaults
struct SingleDirectMultiVaultStateReq {
MultiVaultSFData superformData;
}
/// @dev struct for SuperRouter with re-arranged data for the message (contains the payloadId)
/// @dev realize that receiverAddressSP is not passed, only needed on source chain to mint
struct InitMultiVaultData {
uint256 payloadId;
uint256[] superformIds;
uint256[] amounts;
uint256[] outputAmounts;
uint256[] maxSlippages;
LiqRequest[] liqData;
bool[] hasDstSwaps;
bool[] retain4626s;
address receiverAddress;
bytes extraFormData;
}
/// @dev struct for SuperRouter with re-arranged data for the message (contains the payloadId)
struct InitSingleVaultData {
uint256 payloadId;
uint256 superformId;
uint256 amount;
uint256 outputAmount;
uint256 maxSlippage;
LiqRequest liqData;
bool hasDstSwap;
bool retain4626;
address receiverAddress;
bytes extraFormData;
}
/// @dev struct for Emergency Queue
struct QueuedWithdrawal {
address receiverAddress;
uint256 superformId;
uint256 amount;
uint256 srcPayloadId;
bool isProcessed;
}
/// @dev all statuses of the timelock payload
enum TimelockStatus {
UNAVAILABLE,
PENDING,
PROCESSED
}
/// @dev holds information about the timelock payload
struct TimelockPayload {
uint8 isXChain;
uint64 srcChainId;
uint256 lockedTill;
InitSingleVaultData data;
TimelockStatus status;
}
/// @dev struct that contains the type of transaction, callback flags and other identification, as well as the vaults
/// data in params
struct AMBMessage {
uint256 txInfo; // tight packing of TransactionType txType, CallbackType flag if multi/single vault, registry id,
// srcSender and srcChainId
bytes params; // decoding txInfo will point to the right datatype of params. Refer PayloadHelper.sol
}
/// @dev struct that contains the information required for broadcasting changes
struct BroadcastMessage {
bytes target;
bytes32 messageType;
bytes message;
}
/// @dev struct that contains info on returned data from destination
struct ReturnMultiData {
uint256 payloadId;
uint256[] superformIds;
uint256[] amounts;
}
/// @dev struct that contains info on returned data from destination
struct ReturnSingleData {
uint256 payloadId;
uint256 superformId;
uint256 amount;
}
/// @dev struct that contains the data on the fees to pay to the AMBs
struct AMBExtraData {
uint256[] gasPerAMB;
bytes[] extraDataPerAMB;
}
/// @dev struct that contains the data on the fees to pay to the AMBs on broadcasts
struct BroadCastAMBExtraData {
uint256[] gasPerDst;
bytes[] extraDataPerDst;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import { IERC1155A } from "./interfaces/IERC1155A.sol";
import { IaERC20 } from "./interfaces/IaERC20.sol";
import { Strings } from "openzeppelin-contracts/contracts/utils/Strings.sol";
import { IERC165 } from "openzeppelin-contracts/contracts/interfaces/IERC165.sol";
import { IERC1155 } from "openzeppelin-contracts/contracts/interfaces/IERC1155.sol";
import { IERC1155MetadataURI } from "openzeppelin-contracts/contracts/interfaces/IERC1155MetadataURI.sol";
import { IERC1155Errors } from "openzeppelin-contracts/contracts/interfaces/draft-IERC6093.sol";
import { IERC1155Receiver } from "openzeppelin-contracts/contracts/token/ERC1155/IERC1155Receiver.sol";
/// @title ERC1155A
/// @dev Single/range based id approve capability with conversion to ERC20s
/// @author Zeropoint Labs
abstract contract ERC1155A is IERC1155A, IERC1155Errors {
//////////////////////////////////////////////////////////////
// CONSTANTS //
//////////////////////////////////////////////////////////////
bytes private constant EMPTY_BYTES = bytes("");
//////////////////////////////////////////////////////////////
// STATE VARIABLES //
//////////////////////////////////////////////////////////////
/// @dev ERC20-like mapping for single id supply.
mapping(uint256 => uint256) private _totalSupply;
/// @dev ERC20-like mapping for single id approvals.
mapping(address owner => mapping(address operator => mapping(uint256 id => uint256 amount))) private allowances;
/// @dev Implementation copied from solmate/ERC1155
mapping(address => mapping(uint256 => uint256)) public balanceOf;
/// @dev Implementation copied from solmate/ERC1155
mapping(address => mapping(address => bool)) public isApprovedForAll;
/// @dev mapping of token ids to aErc20 token addresses
mapping(uint256 id => address aErc20Token) public aErc20TokenId;
/// @dev ERC1155A name
string public name;
/// @dev ERC1155A symbol
string public symbol;
//////////////////////////////////////////////////////////////
// CONSTRUCTOR //
//////////////////////////////////////////////////////////////
/// @dev Initializes ERC1155A
/// @param name_ ERC1155A name
/// @param symbol_ ERC1155A symbol
constructor(string memory name_, string memory symbol_) {
name = name_;
symbol = symbol_;
}
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
// Basic Token Information
// --------------------------
/// @inheritdoc IERC1155A
function totalSupply(uint256 id) external view virtual returns (uint256) {
return _totalSupply[id];
}
/// @inheritdoc IERC1155A
function exists(uint256 id) external view virtual returns (bool) {
return _totalSupply[id] != 0;
}
/// @inheritdoc IERC1155
function balanceOfBatch(
address[] memory owners,
uint256[] memory ids
)
public
view
virtual
returns (uint256[] memory balances)
{
if (owners.length != ids.length) revert LENGTH_MISMATCH();
balances = new uint256[](owners.length);
for (uint256 i; i < owners.length; ++i) {
balances[i] = balanceOf[owners[i]][ids[i]];
}
}
// Allowance and Approval Checking
// --------------------------------
/// @inheritdoc IERC1155A
function allowance(address owner, address operator, uint256 id) public view virtual returns (uint256) {
return allowances[owner][operator][id];
}
// aERC20 Token Management
// ------------------------
/// @inheritdoc IERC1155A
function aERC20Exists(uint256 id) external view virtual returns (bool) {
return aErc20TokenId[id] != address(0);
}
/// @inheritdoc IERC1155A
function getERC20TokenAddress(uint256 id) external view virtual override returns (address) {
return aErc20TokenId[id];
}
// Metadata and Interface Support
// ------------------------------
/// @inheritdoc IERC1155A
function uri(uint256 id) public view virtual returns (string memory) {
return string.concat(_baseURI(), Strings.toString(id));
}
/// @dev return interface checks
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId // ERC165 Interface ID for ERC165
|| interfaceId == type(IERC1155).interfaceId // ERC165 Interface ID for ERC1155
|| interfaceId == type(IERC1155MetadataURI).interfaceId; // ERC165 Interface ID for ERC1155MetadataURI
}
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
// Token Approval Management
// --------------------------
/// @inheritdoc IERC1155A
function setApprovalForOne(address operator, uint256 id, uint256 amount) public virtual {
_setAllowance(msg.sender, operator, id, amount, true);
}
/// @inheritdoc IERC1155A
function setApprovalForMany(address operator, uint256[] memory ids, uint256[] memory amounts) public virtual {
uint256 idsLength = ids.length;
if (idsLength != amounts.length) revert LENGTH_MISMATCH();
for (uint256 i; i < idsLength; ++i) {
_setAllowance(msg.sender, operator, ids[i], amounts[i], true);
}
}
/// @inheritdoc IERC1155
function setApprovalForAll(address operator, bool approved) public virtual {
if (operator == address(0)) revert ZERO_ADDRESS();
isApprovedForAll[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
// Allowance Modification
// -----------------------
/// @inheritdoc IERC1155A
function increaseAllowance(address operator, uint256 id, uint256 addedValue) public virtual returns (bool) {
_setAllowance(msg.sender, operator, id, allowance(msg.sender, operator, id) + addedValue, true);
return true;
}
/// @inheritdoc IERC1155A
function decreaseAllowance(address operator, uint256 id, uint256 subtractedValue) public virtual returns (bool) {
return _decreaseAllowance(msg.sender, operator, id, subtractedValue, true);
}
/// @inheritdoc IERC1155A
function increaseAllowanceForMany(
address operator,
uint256[] memory ids,
uint256[] memory addedValues
)
public
virtual
returns (bool)
{
uint256 idsLength = ids.length;
if (idsLength != addedValues.length) revert LENGTH_MISMATCH();
for (uint256 i; i < idsLength; ++i) {
_setAllowance(msg.sender, operator, ids[i], allowance(msg.sender, operator, ids[i]) + addedValues[i], true);
}
return true;
}
/// @inheritdoc IERC1155A
function decreaseAllowanceForMany(
address operator,
uint256[] memory ids,
uint256[] memory subtractedValues
)
public
virtual
returns (bool)
{
uint256 idsLength = ids.length;
if (idsLength != subtractedValues.length) revert LENGTH_MISMATCH();
for (uint256 i; i < idsLength; ++i) {
_decreaseAllowance(msg.sender, operator, ids[i], subtractedValues[i], true);
}
return true;
}
// Token Transfer Functions
// -------------------------
/// @notice see {IERC1155-safeTransferFrom}
/// @dev adds supports for user to not have called setApprovalForAll
/// @dev single id approval is senior in execution flow
/// @dev if approved for all, function executes without reducing allowance
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
if (from == address(0) || to == address(0)) revert ZERO_ADDRESS();
address operator = msg.sender;
/// @dev message sender is not from and is not approved for all
if (from != operator && !isApprovedForAll[from][operator]) {
_decreaseAllowance(from, operator, id, amount, false);
_safeTransferFrom(from, to, id, amount);
} else {
/// @dev message sender is from || is approved for all
_safeTransferFrom(from, to, id, amount);
}
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/// @notice see {IERC1155-safeBatchTransferFrom}
/// @dev adds supports for user to not have called setApprovalForAll
/// @dev single id approvals are senior in execution flow
/// @dev if approved for all, function executes without reducing allowance
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
if (from == address(0) || to == address(0)) revert ZERO_ADDRESS();
uint256 len = ids.length;
if (len != amounts.length) revert LENGTH_MISMATCH();
address operator = msg.sender;
/// @dev case to handle single id / multi id approvals
if (operator != from && !isApprovedForAll[from][operator]) {
uint256 id;
uint256 amount;
for (uint256 i; i < len; ++i) {
id = ids[i];
amount = amounts[i];
_decreaseAllowance(from, operator, id, amount, false);
_safeTransferFrom(from, to, id, amount);
}
} else {
for (uint256 i; i < len; ++i) {
_safeTransferFrom(from, to, ids[i], amounts[i]);
}
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
// Token Transmutation
// --------------------
/// @inheritdoc IERC1155A
function transmuteToERC20(address owner, uint256 id, uint256 amount, address receiver) external override {
if (owner == address(0) || receiver == address(0)) revert ZERO_ADDRESS();
/// @dev an approval is needed to burn
_burn(owner, msg.sender, id, amount);
address aERC20Token = aErc20TokenId[id];
if (aERC20Token == address(0)) revert AERC20_NOT_REGISTERED();
IaERC20(aERC20Token).mint(receiver, amount);
emit TransmutedToERC20(owner, id, amount, receiver);
}
/// @inheritdoc IERC1155A
function transmuteToERC1155A(address owner, uint256 id, uint256 amount, address receiver) external override {
if (owner == address(0) || receiver == address(0)) revert ZERO_ADDRESS();
address aERC20Token = aErc20TokenId[id];
if (aERC20Token == address(0)) revert AERC20_NOT_REGISTERED();
/// @dev an approval is needed to burn
IaERC20(aERC20Token).burn(owner, msg.sender, amount);
_mint(receiver, msg.sender, id, amount, EMPTY_BYTES);
emit TransmutedToERC1155A(owner, id, amount, receiver);
}
/// @inheritdoc IERC1155A
function transmuteBatchToERC20(
address owner,
uint256[] memory ids,
uint256[] memory amounts,
address receiver
)
external
override
{
if (owner == address(0) || receiver == address(0)) revert ZERO_ADDRESS();
uint256 idsLength = ids.length; // Saves MLOADs.
if (idsLength != amounts.length) revert LENGTH_MISMATCH();
/// @dev an approval is needed to burn
_batchBurn(owner, msg.sender, ids, amounts);
for (uint256 i; i < idsLength; ++i) {
address aERC20Token = aErc20TokenId[ids[i]];
if (aERC20Token == address(0)) revert AERC20_NOT_REGISTERED();
IaERC20(aERC20Token).mint(receiver, amounts[i]);
}
emit TransmutedBatchToERC20(owner, ids, amounts, receiver);
}
/// @inheritdoc IERC1155A
function transmuteBatchToERC1155A(
address owner,
uint256[] memory ids,
uint256[] memory amounts,
address receiver
)
external
override
{
if (owner == address(0) || receiver == address(0)) revert ZERO_ADDRESS();
uint256 idsLength = ids.length; // Saves MLOADs.
if (idsLength != amounts.length) revert LENGTH_MISMATCH();
uint256 id;
uint256 amount;
for (uint256 i; i < ids.length; ++i) {
id = ids[i];
amount = amounts[i];
address aERC20Token = aErc20TokenId[id];
if (aERC20Token == address(0)) revert AERC20_NOT_REGISTERED();
/// @dev an approval is needed on each aERC20 to burn
IaERC20(aERC20Token).burn(owner, msg.sender, amount);
}
_batchMint(receiver, msg.sender, ids, amounts, EMPTY_BYTES);
emit TransmutedBatchToERC1155A(owner, ids, amounts, receiver);
}
// aERC20 Registration
// --------------------
/// @inheritdoc IERC1155A
function registerAERC20(uint256 id) external payable override returns (address) {
if (_totalSupply[id] == 0) revert ID_NOT_MINTED_YET();
if (aErc20TokenId[id] != address(0)) revert AERC20_ALREADY_REGISTERED();
address aErc20Token = _registerAERC20(id);
aErc20TokenId[id] = aErc20Token;
return aErc20TokenId[id];
}
//////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS //
//////////////////////////////////////////////////////////////
// Token Transfer and Balance Management
// --------------------------------------
/// @notice Internal safeTranferFrom function called after all checks from the public function are done
/// @dev Notice `operator` param. It's msg.sender to the safeTransferFrom function. Function is specific to
/// @dev singleId approve logic.
function _safeTransferFrom(address from, address to, uint256 id, uint256 amount) internal virtual {
balanceOf[from][id] -= amount;
balanceOf[to][id] += amount;
}
/// @dev Implementation copied from solmate/ERC1155 and adapted with operator logic
function _mint(address to, address operator, uint256 id, uint256 amount, bytes memory data) internal virtual {
balanceOf[to][id] += amount;
_totalSupply[id] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/// @dev Implementation copied from solmate/ERC1155 and adapted with operator logic
function _batchMint(
address to,
address operator,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{
uint256 idsLength = ids.length; // Saves MLOADs.
if (idsLength != amounts.length) revert LENGTH_MISMATCH();
uint256 id;
uint256 amount;
for (uint256 i; i < idsLength; ++i) {
id = ids[i];
amount = amounts[i];
balanceOf[to][id] += amount;
_totalSupply[id] += amount;
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/// @dev Implementation copied from solmate/ERC1155 and adapted with operator logic
function _burn(address from, address operator, uint256 id, uint256 amount) internal virtual {
// Check if the msg.sender is the owner or is approved for all tokens
/// Most implementations of _burn don't use allowance, but it is a good practice to check for it
/// Otherwise it could allow to burn tokens on which no explicit allowance is given
if (operator != from && !isApprovedForAll[from][operator]) {
_decreaseAllowance(from, operator, id, amount, false);
}
// Update the balances and total supply
_safeTransferFrom(from, address(0), id, amount);
_totalSupply[id] -= amount;
emit TransferSingle(operator, from, address(0), id, amount);
}
/// @dev Implementation copied from solmate/ERC1155 and adapted with operator logic
function _batchBurn(
address from,
address operator,
uint256[] memory ids,
uint256[] memory amounts
)
internal
virtual
{
uint256 idsLength = ids.length; // Saves MLOADs.
if (idsLength != amounts.length) revert LENGTH_MISMATCH();
uint256 id;
uint256 amount;
/// @dev case to handle single id / multi id approvals
if (operator != from && !isApprovedForAll[from][operator]) {
for (uint256 i; i < idsLength; ++i) {
id = ids[i];
amount = amounts[i];
_decreaseAllowance(from, operator, id, amount, false);
_safeTransferFrom(from, address(0), id, amount);
_totalSupply[ids[i]] -= amounts[i];
}
} else {
for (uint256 i; i < idsLength; ++i) {
id = ids[i];
amount = amounts[i];
_safeTransferFrom(from, address(0), id, amount);
_totalSupply[ids[i]] -= amounts[i];
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
// Allowance and Approval Handling
// --------------------------------
/// @notice Internal function for decreasing single id approval amount
/// @dev Only to be used by address(this)
/// @dev Notice `owner` param, only contract functions should be able to define it
/// @dev Re-adapted from ERC20
function _decreaseAllowance(
address owner,
address operator,
uint256 id,
uint256 subtractedValue,
bool emitEvent
)
internal
virtual
returns (bool)
{
uint256 currentAllowance = allowance(owner, operator, id);
if (currentAllowance < subtractedValue) revert DECREASED_ALLOWANCE_BELOW_ZERO();
_setAllowance(owner, operator, id, currentAllowance - subtractedValue, emitEvent);
return true;
}
/// @notice Internal function for setting single id approval
/// @dev Used for fine-grained control over approvals with increase/decrease allowance
/// @dev Notice `owner` param, only contract functions should be able to define it
function _setAllowance(
address owner,
address operator,
uint256 id,
uint256 amount,
bool emitEvent
)
internal
virtual
{
if (owner == address(0)) revert ZERO_ADDRESS();
if (operator == address(0)) revert ZERO_ADDRESS();
allowances[owner][operator][id] = amount;
if (emitEvent) {
emit ApprovalForOne(owner, operator, id, amount);
}
}
// ERC1155A Transfer Checks
// ------------------------
/// @dev Implementation copied from openzeppelin-contracts/ERC1155 with new custom error logic
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
)
private
{
if (to.code.length != 0) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
// Tokens rejected
revert ERC1155InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-ERC1155Receiver implementer
revert ERC1155InvalidReceiver(to);
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
if (to == address(0)) revert TRANSFER_TO_ADDRESS_ZERO();
}
}
/// @dev Implementation copied from openzeppelin-contracts/ERC1155 with new custom error logic and revert on
/// transfer to address 0
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
)
private
{
if (to.code.length != 0) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (bytes4 response)
{
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
// Tokens rejected
revert ERC1155InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-ERC1155Receiver implementer
revert ERC1155InvalidReceiver(to);
} else {
/// @solidity memory-safe-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
if (to == address(0)) revert TRANSFER_TO_ADDRESS_ZERO();
}
}
// aERC20 Token Creation
// ----------------------
/// @dev allows a developer to integrate their logic to create an aERC20
function _registerAERC20(uint256 id) internal virtual returns (address aErc20Token);
// Metadata and URI Handling
// --------------------------
/// @dev Used to construct return url
function _baseURI() internal view virtual returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the ERC may not emit
* these events, as it isn't required by the specification.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the ERC. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
* ```
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
library Error {
//////////////////////////////////////////////////////////////
// CONFIGURATION ERRORS //
//////////////////////////////////////////////////////////////
///@notice errors thrown in protocol setup
/// @dev thrown if chain id exceeds max(uint64)
error BLOCK_CHAIN_ID_OUT_OF_BOUNDS();
/// @dev thrown if not possible to revoke a role in broadcasting
error CANNOT_REVOKE_NON_BROADCASTABLE_ROLES();
/// @dev thrown if not possible to revoke last admin
error CANNOT_REVOKE_LAST_ADMIN();
/// @dev thrown if trying to set again pseudo immutables in super registry
error DISABLED();
/// @dev thrown if rescue delay is not yet set for a chain
error DELAY_NOT_SET();
/// @dev thrown if get native token price estimate in paymentHelper is 0
error INVALID_NATIVE_TOKEN_PRICE();
/// @dev thrown if wormhole refund chain id is not set
error REFUND_CHAIN_ID_NOT_SET();
/// @dev thrown if wormhole relayer is not set
error RELAYER_NOT_SET();
/// @dev thrown if a role to be revoked is not assigned
error ROLE_NOT_ASSIGNED();
//////////////////////////////////////////////////////////////
// AUTHORIZATION ERRORS //
//////////////////////////////////////////////////////////////
///@notice errors thrown if functions cannot be called
/// COMMON AUTHORIZATION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if caller is not address(this), internal call
error INVALID_INTERNAL_CALL();
/// @dev thrown if msg.sender is not a valid amb implementation
error NOT_AMB_IMPLEMENTATION();
/// @dev thrown if msg.sender is not an allowed broadcaster
error NOT_ALLOWED_BROADCASTER();
/// @dev thrown if msg.sender is not broadcast amb implementation
error NOT_BROADCAST_AMB_IMPLEMENTATION();
/// @dev thrown if msg.sender is not broadcast state registry
error NOT_BROADCAST_REGISTRY();
/// @dev thrown if msg.sender is not core state registry
error NOT_CORE_STATE_REGISTRY();
/// @dev thrown if msg.sender is not emergency admin
error NOT_EMERGENCY_ADMIN();
/// @dev thrown if msg.sender is not emergency queue
error NOT_EMERGENCY_QUEUE();
/// @dev thrown if msg.sender is not minter
error NOT_MINTER();
/// @dev thrown if msg.sender is not minter state registry
error NOT_MINTER_STATE_REGISTRY_ROLE();
/// @dev thrown if msg.sender is not paymaster
error NOT_PAYMASTER();
/// @dev thrown if msg.sender is not payment admin
error NOT_PAYMENT_ADMIN();
/// @dev thrown if msg.sender is not protocol admin
error NOT_PROTOCOL_ADMIN();
/// @dev thrown if msg.sender is not state registry
error NOT_STATE_REGISTRY();
/// @dev thrown if msg.sender is not super registry
error NOT_SUPER_REGISTRY();
/// @dev thrown if msg.sender is not superform router
error NOT_SUPERFORM_ROUTER();
/// @dev thrown if msg.sender is not a superform
error NOT_SUPERFORM();
/// @dev thrown if msg.sender is not superform factory
error NOT_SUPERFORM_FACTORY();
/// @dev thrown if msg.sender is not timelock form
error NOT_TIMELOCK_SUPERFORM();
/// @dev thrown if msg.sender is not timelock state registry
error NOT_TIMELOCK_STATE_REGISTRY();
/// @dev thrown if msg.sender is not user or disputer
error NOT_VALID_DISPUTER();
/// @dev thrown if the msg.sender is not privileged caller
error NOT_PRIVILEGED_CALLER(bytes32 role);
/// STATE REGISTRY AUTHORIZATION ERRORS
/// ---------------------------------------------------------
/// @dev layerzero adapter specific error, thrown if caller not layerzero endpoint
error CALLER_NOT_ENDPOINT();
/// @dev hyperlane adapter specific error, thrown if caller not hyperlane mailbox
error CALLER_NOT_MAILBOX();
/// @dev wormhole relayer specific error, thrown if caller not wormhole relayer
error CALLER_NOT_RELAYER();
/// @dev thrown if src chain sender is not valid
error INVALID_SRC_SENDER();
//////////////////////////////////////////////////////////////
// INPUT VALIDATION ERRORS //
//////////////////////////////////////////////////////////////
///@notice errors thrown if input variables are not valid
/// COMMON INPUT VALIDATION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if there is an array length mismatch
error ARRAY_LENGTH_MISMATCH();
/// @dev thrown if payload id does not exist
error INVALID_PAYLOAD_ID();
/// @dev error thrown when msg value should be zero in certain payable functions
error MSG_VALUE_NOT_ZERO();
/// @dev thrown if amb ids length is 0
error ZERO_AMB_ID_LENGTH();
/// @dev thrown if address input is address 0
error ZERO_ADDRESS();
/// @dev thrown if amount input is 0
error ZERO_AMOUNT();
/// @dev thrown if final token is address 0
error ZERO_FINAL_TOKEN();
/// @dev thrown if value input is 0
error ZERO_INPUT_VALUE();
/// SUPERFORM ROUTER INPUT VALIDATION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if the vaults data is invalid
error INVALID_SUPERFORMS_DATA();
/// @dev thrown if receiver address is not set
error RECEIVER_ADDRESS_NOT_SET();
/// SUPERFORM FACTORY INPUT VALIDATION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if a form is not ERC165 compatible
error ERC165_UNSUPPORTED();
/// @dev thrown if a form is not form interface compatible
error FORM_INTERFACE_UNSUPPORTED();
/// @dev error thrown if form implementation address already exists
error FORM_IMPLEMENTATION_ALREADY_EXISTS();
/// @dev error thrown if form implementation id already exists
error FORM_IMPLEMENTATION_ID_ALREADY_EXISTS();
/// @dev thrown if a form does not exist
error FORM_DOES_NOT_EXIST();
/// @dev thrown if form id is larger than max uint16
error INVALID_FORM_ID();
/// @dev thrown if superform not on factory
error SUPERFORM_ID_NONEXISTENT();
/// @dev thrown if same vault and form implementation is used to create new superform
error VAULT_FORM_IMPLEMENTATION_COMBINATION_EXISTS();
/// FORM INPUT VALIDATION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if in case of no txData, if liqData.token != vault.asset()
/// in case of txData, if token output of swap != vault.asset()
error DIFFERENT_TOKENS();
/// @dev thrown if the amount in direct withdraw is not correct
error DIRECT_WITHDRAW_INVALID_LIQ_REQUEST();
/// @dev thrown if the amount in xchain withdraw is not correct
error XCHAIN_WITHDRAW_INVALID_LIQ_REQUEST();
/// LIQUIDITY BRIDGE INPUT VALIDATION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if route id is blacklisted in socket
error BLACKLISTED_ROUTE_ID();
/// @dev thrown if route id is not blacklisted in socket
error NOT_BLACKLISTED_ROUTE_ID();
/// @dev error thrown when txData selector of lifi bridge is a blacklisted selector
error BLACKLISTED_SELECTOR();
/// @dev error thrown when txData selector of lifi bridge is not a blacklisted selector
error NOT_BLACKLISTED_SELECTOR();
/// @dev thrown if a certain action of the user is not allowed given the txData provided
error INVALID_ACTION();
/// @dev thrown if in deposits, the liqDstChainId doesn't match the stateReq dstChainId
error INVALID_DEPOSIT_LIQ_DST_CHAIN_ID();
/// @dev thrown if index is invalid
error INVALID_INDEX();
/// @dev thrown if the chain id in the txdata is invalid
error INVALID_TXDATA_CHAIN_ID();
/// @dev thrown if the validation of bridge txData fails due to a destination call present
error INVALID_TXDATA_NO_DESTINATIONCALL_ALLOWED();
/// @dev thrown if the validation of bridge txData fails due to wrong receiver
error INVALID_TXDATA_RECEIVER();
/// @dev thrown if the validation of bridge txData fails due to wrong token
error INVALID_TXDATA_TOKEN();
/// @dev thrown if txData is not present (in case of xChain actions)
error NO_TXDATA_PRESENT();
/// STATE REGISTRY INPUT VALIDATION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if payload is being updated with final amounts length different than amounts length
error DIFFERENT_PAYLOAD_UPDATE_AMOUNTS_LENGTH();
/// @dev thrown if payload is being updated with tx data length different than liq data length
error DIFFERENT_PAYLOAD_UPDATE_TX_DATA_LENGTH();
/// @dev thrown if keeper update final token is different than the vault underlying
error INVALID_UPDATE_FINAL_TOKEN();
/// @dev thrown if broadcast finality for wormhole is invalid
error INVALID_BROADCAST_FINALITY();
/// @dev thrown if amb id is not valid leading to an address 0 of the implementation
error INVALID_BRIDGE_ID();
/// @dev thrown if chain id involved in xchain message is invalid
error INVALID_CHAIN_ID();
/// @dev thrown if payload update amount isn't equal to dst swapper amount
error INVALID_DST_SWAP_AMOUNT();
/// @dev thrown if message amb and proof amb are the same
error INVALID_PROOF_BRIDGE_ID();
/// @dev thrown if order of proof AMBs is incorrect, either duplicated or not incrementing
error INVALID_PROOF_BRIDGE_IDS();
/// @dev thrown if rescue data lengths are invalid
error INVALID_RESCUE_DATA();
/// @dev thrown if delay is invalid
error INVALID_TIMELOCK_DELAY();
/// @dev thrown if amounts being sent in update payload mean a negative slippage
error NEGATIVE_SLIPPAGE();
/// @dev thrown if slippage is outside of bounds
error SLIPPAGE_OUT_OF_BOUNDS();
/// SUPERPOSITION INPUT VALIDATION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if src senders mismatch in state sync
error SRC_SENDER_MISMATCH();
/// @dev thrown if src tx types mismatch in state sync
error SRC_TX_TYPE_MISMATCH();
//////////////////////////////////////////////////////////////
// EXECUTION ERRORS //
//////////////////////////////////////////////////////////////
///@notice errors thrown due to function execution logic
/// COMMON EXECUTION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if the swap in a direct deposit resulted in insufficient tokens
error DIRECT_DEPOSIT_SWAP_FAILED();
/// @dev thrown if payload is not unique
error DUPLICATE_PAYLOAD();
/// @dev thrown if native tokens fail to be sent to superform contracts
error FAILED_TO_SEND_NATIVE();
/// @dev thrown if allowance is not correct to deposit
error INSUFFICIENT_ALLOWANCE_FOR_DEPOSIT();
/// @dev thrown if contract has insufficient balance for operations
error INSUFFICIENT_BALANCE();
/// @dev thrown if native amount is not at least equal to the amount in the request
error INSUFFICIENT_NATIVE_AMOUNT();
/// @dev thrown if payload cannot be decoded
error INVALID_PAYLOAD();
/// @dev thrown if payload status is invalid
error INVALID_PAYLOAD_STATUS();
/// @dev thrown if payload type is invalid
error INVALID_PAYLOAD_TYPE();
/// LIQUIDITY BRIDGE EXECUTION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if we try to decode the final swap output token in a xChain liquidity bridging action
error CANNOT_DECODE_FINAL_SWAP_OUTPUT_TOKEN();
/// @dev thrown if liquidity bridge fails for erc20 or native tokens
error FAILED_TO_EXECUTE_TXDATA(address token);
/// @dev thrown if asset being used for deposit mismatches in multivault deposits
error INVALID_DEPOSIT_TOKEN();
/// STATE REGISTRY EXECUTION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if bridge tokens haven't arrived to destination
error BRIDGE_TOKENS_PENDING();
/// @dev thrown if withdrawal tx data cannot be updated
error CANNOT_UPDATE_WITHDRAW_TX_DATA();
/// @dev thrown if rescue passed dispute deadline
error DISPUTE_TIME_ELAPSED();
/// @dev thrown if message failed to reach the specified level of quorum needed
error INSUFFICIENT_QUORUM();
/// @dev thrown if broadcast payload is invalid
error INVALID_BROADCAST_PAYLOAD();
/// @dev thrown if broadcast fee is invalid
error INVALID_BROADCAST_FEE();
/// @dev thrown if retry fees is less than required
error INVALID_RETRY_FEE();
/// @dev thrown if broadcast message type is wrong
error INVALID_MESSAGE_TYPE();
/// @dev thrown if payload hash is invalid during `retryMessage` on Layezero implementation
error INVALID_PAYLOAD_HASH();
/// @dev thrown if update payload function was called on a wrong payload
error INVALID_PAYLOAD_UPDATE_REQUEST();
/// @dev thrown if a state registry id is 0
error INVALID_REGISTRY_ID();
/// @dev thrown if a form state registry id is 0
error INVALID_FORM_REGISTRY_ID();
/// @dev thrown if trying to finalize the payload but the withdraw is still locked
error LOCKED();
/// @dev thrown if payload is already updated (during xChain deposits)
error PAYLOAD_ALREADY_UPDATED();
/// @dev thrown if payload is already processed
error PAYLOAD_ALREADY_PROCESSED();
/// @dev thrown if payload is not in UPDATED state
error PAYLOAD_NOT_UPDATED();
/// @dev thrown if rescue is still in timelocked state
error RESCUE_LOCKED();
/// @dev thrown if rescue is already proposed
error RESCUE_ALREADY_PROPOSED();
/// @dev thrown if payload hash is zero during `retryMessage` on Layezero implementation
error ZERO_PAYLOAD_HASH();
/// DST SWAPPER EXECUTION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if process dst swap is tried for processed payload id
error DST_SWAP_ALREADY_PROCESSED();
/// @dev thrown if indices have duplicates
error DUPLICATE_INDEX();
/// @dev thrown if failed dst swap is already updated
error FAILED_DST_SWAP_ALREADY_UPDATED();
/// @dev thrown if indices are out of bounds
error INDEX_OUT_OF_BOUNDS();
/// @dev thrown if failed swap token amount is 0
error INVALID_DST_SWAPPER_FAILED_SWAP();
/// @dev thrown if failed swap token amount is not 0 and if token balance is less than amount (non zero)
error INVALID_DST_SWAPPER_FAILED_SWAP_NO_TOKEN_BALANCE();
/// @dev thrown if failed swap token amount is not 0 and if native amount is less than amount (non zero)
error INVALID_DST_SWAPPER_FAILED_SWAP_NO_NATIVE_BALANCE();
/// @dev forbid xChain deposits with destination swaps without interim token set (for user protection)
error INVALID_INTERIM_TOKEN();
/// @dev thrown if dst swap output is less than minimum expected
error INVALID_SWAP_OUTPUT();
/// FORM EXECUTION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if try to forward 4626 share from the superform
error CANNOT_FORWARD_4646_TOKEN();
/// @dev thrown in KYCDAO form if no KYC token is present
error NO_VALID_KYC_TOKEN();
/// @dev thrown in forms where a certain functionality is not allowed or implemented
error NOT_IMPLEMENTED();
/// @dev thrown if form implementation is PAUSED, users cannot perform any action
error PAUSED();
/// @dev thrown if shares != deposit output or assets != redeem output when minting SuperPositions
error VAULT_IMPLEMENTATION_FAILED();
/// @dev thrown if withdrawal tx data is not updated
error WITHDRAW_TOKEN_NOT_UPDATED();
/// @dev thrown if withdrawal tx data is not updated
error WITHDRAW_TX_DATA_NOT_UPDATED();
/// @dev thrown when redeeming from vault yields zero collateral
error WITHDRAW_ZERO_COLLATERAL();
/// PAYMENT HELPER EXECUTION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if chainlink is reporting an improper price
error CHAINLINK_MALFUNCTION();
/// @dev thrown if chainlink is reporting an incomplete round
error CHAINLINK_INCOMPLETE_ROUND();
/// @dev thrown if feed decimals is not 8
error CHAINLINK_UNSUPPORTED_DECIMAL();
/// EMERGENCY QUEUE EXECUTION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if emergency withdraw is not queued
error EMERGENCY_WITHDRAW_NOT_QUEUED();
/// @dev thrown if emergency withdraw is already processed
error EMERGENCY_WITHDRAW_PROCESSED_ALREADY();
/// SUPERPOSITION EXECUTION ERRORS
/// ---------------------------------------------------------
/// @dev thrown if uri cannot be updated
error DYNAMIC_URI_FROZEN();
/// @dev thrown if tx history is not found while state sync
error TX_HISTORY_NOT_FOUND();
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import { InitSingleVaultData } from "src/types/DataTypes.sol";
import { IERC165 } from "openzeppelin-contracts/contracts/utils/introspection/IERC165.sol";
import { IERC4626 } from "openzeppelin-contracts/contracts/interfaces/IERC4626.sol";
/// @title IBaseForm
/// @dev Interface for BaseForm
/// @author ZeroPoint Labs
interface IBaseForm is IERC165 {
//////////////////////////////////////////////////////////////
// EVENTS //
//////////////////////////////////////////////////////////////
/// @dev is emitted when a new vault is added by the admin.
event VaultAdded(uint256 indexed id, IERC4626 indexed vault);
/// @dev is emitted when a payload is processed by the destination contract.
event Processed(
uint64 indexed srcChainID,
uint64 indexed dstChainId,
uint256 indexed srcPayloadId,
uint256 amount,
address vault
);
/// @dev is emitted when an emergency withdrawal is processed
event EmergencyWithdrawalProcessed(address indexed refundAddress, uint256 indexed amount);
/// @dev is emitted when dust is forwarded to the paymaster
event FormDustForwardedToPaymaster(address indexed token, uint256 indexed amount);
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @notice get Superform name of the ERC20 vault representation
/// @return The ERC20 name
function superformYieldTokenName() external view returns (string memory);
/// @notice get Superform symbol of the ERC20 vault representation
/// @return The ERC20 symbol
function superformYieldTokenSymbol() external view returns (string memory);
/// @notice get the state registry id associated with the vault
function getStateRegistryId() external view returns (uint8);
/// @notice Returns the vault address
/// @return The address of the vault
function getVaultAddress() external view returns (address);
/// @notice Returns the vault address
/// @return The address of the vault asset
function getVaultAsset() external view returns (address);
/// @notice Returns the name of the vault.
/// @return The name of the vault
function getVaultName() external view returns (string memory);
/// @notice Returns the symbol of a vault.
/// @return The symbol associated with a vault
function getVaultSymbol() external view returns (string memory);
/// @notice Returns the number of decimals in a vault for accounting purposes
/// @return The number of decimals in the vault balance
function getVaultDecimals() external view returns (uint256);
/// @notice Returns the amount of underlying tokens each share of a vault is worth.
/// @return The pricePerVaultShare value
function getPricePerVaultShare() external view returns (uint256);
/// @notice Returns the amount of vault shares owned by the form.
/// @return The form's vault share balance
function getVaultShareBalance() external view returns (uint256);
/// @notice get the total amount of underlying managed in the ERC4626 vault
function getTotalAssets() external view returns (uint256);
/// @notice get the total amount of unredeemed vault shares in circulation
function getTotalSupply() external view returns (uint256);
/// @notice get the total amount of assets received if shares are actually redeemed
/// @notice https://eips.ethereum.org/EIPS/eip-4626
function getPreviewPricePerVaultShare() external view returns (uint256);
/// @dev API may need to know state of funds deployed
function previewDepositTo(uint256 assets_) external view returns (uint256);
/// @notice positionBalance() -> .vaultIds&destAmounts
/// @return how much of an asset + interest (accrued) is to withdraw from the Vault
function previewWithdrawFrom(uint256 assets_) external view returns (uint256);
/// @dev API may need to know state of funds deployed
function previewRedeemFrom(uint256 shares_) external view returns (uint256);
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev process same chain id deposits
/// @param singleVaultData_ A bytes representation containing all the data required to make a form action
/// @param srcSender_ The address of the sender of the transaction
/// @return shares The amount of vault shares received
function directDepositIntoVault(
InitSingleVaultData memory singleVaultData_,
address srcSender_
)
external
payable
returns (uint256 shares);
/// @dev process same chain id deposits
/// @param singleVaultData_ A bytes representation containing all the data required to make a form action
/// @param srcSender_ The address of the sender of the transaction
/// @param srcChainId_ The chain id of the source chain
/// @return shares The amount of vault shares received
/// @dev is shares is `0` then no further action/acknowledgement needs to be sent
function xChainDepositIntoVault(
InitSingleVaultData memory singleVaultData_,
address srcSender_,
uint64 srcChainId_
)
external
returns (uint256 shares);
/// @dev process withdrawal of asset from a vault
/// @param singleVaultData_ A bytes representation containing all the data required to make a form action
/// @param srcSender_ The address of the sender of the transaction
/// @return assets The amount of assets received
function directWithdrawFromVault(
InitSingleVaultData memory singleVaultData_,
address srcSender_
)
external
returns (uint256 assets);
/// @dev process withdrawal of asset from a vault
/// @param singleVaultData_ A bytes representation containing all the data required to make a form action
/// @param srcSender_ The address of the sender of the transaction
/// @param srcChainId_ The chain id of the source chain
/// @return assets The amount of assets received
function xChainWithdrawFromVault(
InitSingleVaultData memory singleVaultData_,
address srcSender_,
uint64 srcChainId_
)
external
returns (uint256 assets);
/// @dev process withdrawal of shares if form is paused
/// @param receiverAddress_ The address to refund the shares to
/// @param amount_ The amount of vault shares to refund
function emergencyWithdraw(address receiverAddress_, uint256 amount_) external;
/// @dev moves all dust in the contract to Paymaster contract
/// @param token_ The address of the token to forward
function forwardDustToPaymaster(address token_) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
/// @title IBroadcastRegistry
/// @dev Interface for BroadcastRegistry
/// @author ZeroPoint Labs
interface IBroadcastRegistry {
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev emitted when a payload is broadcasted
event PayloadSent(address indexed sender);
/// @dev emitted when a broadcast payload is received
event PayloadReceived(uint256 indexed payloadId, uint64 indexed srcChainId);
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev allows core contracts to send payload to all configured destination chain.
/// @param srcSender_ is the caller of the function (used for gas refunds).
/// @param ambId_ is the identifier of the arbitrary message bridge to be used
/// @param gasFee_ is the gas fee to be used for broadcasting
/// @param message_ is the crosschain payload to be broadcasted
/// @param extraData_ defines all the message bridge related overrides
function broadcastPayload(
address srcSender_,
uint8 ambId_,
uint256 gasFee_,
bytes memory message_,
bytes memory extraData_
)
external
payable;
/// @dev allows ambs to write broadcasted payloads
function receiveBroadcastPayload(uint64 srcChainId_, bytes memory message_) external;
/// @dev allows privileged actors to process broadcasted payloads
/// @param payloadId_ is the identifier of the cross-chain payload
function processPayload(uint256 payloadId_) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1155.sol)
pragma solidity ^0.8.20;
import {IERC1155} from "../token/ERC1155/IERC1155.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import { IERC1155 } from "openzeppelin-contracts/contracts/token/ERC1155/IERC1155.sol";
/// @title IERC1155A
/// @author Zeropoint Labs
/// @dev Single/range based id approve capability with conversion to ERC20s
interface IERC1155A is IERC1155 {
//////////////////////////////////////////////////////////////
// EVENTS //
//////////////////////////////////////////////////////////////
/// @dev emitted when single id approval is set
event ApprovalForOne(address indexed owner, address indexed spender, uint256 id, uint256 amount);
/// @dev emitted when an ERC1155A id is transmuted to an aERC20
event TransmutedToERC20(address indexed user, uint256 id, uint256 amount, address indexed receiver);
/// @dev emitted when an aERC20 is transmuted to an ERC1155 id
event TransmutedToERC1155A(address indexed user, uint256 id, uint256 amount, address indexed receiver);
/// @dev emitted when multiple ERC1155A ids are transmuted to aERC20s
event TransmutedBatchToERC20(address indexed user, uint256[] ids, uint256[] amounts, address indexed receiver);
/// @dev emitted when multiple aERC20s are transmuted to ERC1155A ids
event TransmutedBatchToERC1155A(address indexed user, uint256[] ids, uint256[] amounts, address indexed receiver);
//////////////////////////////////////////////////////////////
// ERRORS //
//////////////////////////////////////////////////////////////
/// @dev thrown if aERC20 was already registered
error AERC20_ALREADY_REGISTERED();
/// @dev thrown if aERC20 was not registered
error AERC20_NOT_REGISTERED();
/// @dev thrown if allowance amount will be decreased below zero
error DECREASED_ALLOWANCE_BELOW_ZERO();
/// @dev thrown if the associated ERC1155A id has not been minted before registering an aERC20
error ID_NOT_MINTED_YET();
/// @dev thrown if there is a length mismatch in batch operations
error LENGTH_MISMATCH();
/// @dev thrown if transfer is made to address 0
error TRANSFER_TO_ADDRESS_ZERO();
/// @dev thrown if address is 0
error ZERO_ADDRESS();
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @notice Public getter for existing single id total supply
/// @param id id of the ERC1155
function totalSupply(uint256 id) external view returns (uint256);
/// @notice Public getter to know if a token id exists
/// @dev determines based on total supply for the id
/// @param id id of the ERC1155
function exists(uint256 id) external view returns (bool);
/// @notice Public getter for existing single id approval
/// @param owner address of the owner of the ERC1155A id
/// @param spender address of the contract to approve
/// @param id id of the ERC1155A to approve
function allowance(address owner, address spender, uint256 id) external returns (uint256);
/// @notice handy helper to check if a AERC20 is registered
/// @param id id of the ERC1155
function aERC20Exists(uint256 id) external view returns (bool);
/// @notice Public getter for the address of the aErc20 token for a given ERC1155 id
/// @param id id of the ERC1155 to get the aErc20 token address for
/// @return aERC20 address of the aErc20 token for the given ERC1155 id
function getERC20TokenAddress(uint256 id) external view returns (address aERC20);
/// @notice Compute return string from baseURI set for this contract and unique vaultId
/// @param id id of the ERC1155
function uri(uint256 id) external view returns (string memory);
/// @notice ERC1155A name
function name() external view returns (string memory);
/// @notice ERC1155A symbol
function symbol() external view returns (string memory);
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @notice Public function for setting single id approval
/// @dev Notice `owner` param, it will always be msg.sender, see _setApprovalForOne()
/// @param spender address of the contract to approve
/// @param id id of the ERC1155A to approve
/// @param amount amount of the ERC1155A to approve
function setApprovalForOne(address spender, uint256 id, uint256 amount) external;
/// @notice Public function for setting multiple id approval
/// @dev extension of sigle id approval
/// @param spender address of the contract to approve
/// @param ids ids of the ERC1155A to approve
/// @param amounts amounts of the ERC1155A to approve
function setApprovalForMany(address spender, uint256[] memory ids, uint256[] memory amounts) external;
/// @notice Public function for increasing single id approval amount
/// @dev Re-adapted from ERC20
/// @param spender address of the contract to approve
/// @param id id of the ERC1155A to approve
/// @param addedValue amount of the allowance to increase by
function increaseAllowance(address spender, uint256 id, uint256 addedValue) external returns (bool);
/// @notice Public function for decreasing single id approval amount
/// @dev Re-adapted from ERC20
/// @param spender address of the contract to approve
/// @param id id of the ERC1155A to approve
/// @param subtractedValue amount of the allowance to decrease by
function decreaseAllowance(address spender, uint256 id, uint256 subtractedValue) external returns (bool);
/// @notice Public function for increasing multiple id approval amount at once
/// @dev extension of single id increase allowance
/// @param spender address of the contract to approve
/// @param ids ids of the ERC1155A to approve
/// @param addedValues amounts of the allowance to increase by
function increaseAllowanceForMany(
address spender,
uint256[] memory ids,
uint256[] memory addedValues
)
external
returns (bool);
/// @notice Public function for decreasing multiple id approval amount at once
/// @dev extension of single id decrease allowance
/// @param spender address of the contract to approve
/// @param ids ids of the ERC1155A to approve
/// @param subtractedValues amounts of the allowance to decrease by
function decreaseAllowanceForMany(
address spender,
uint256[] memory ids,
uint256[] memory subtractedValues
)
external
returns (bool);
/// @notice Turn ERC1155A id into an aERC20
/// @dev allows owner to send ERC1155A id as an aERC20 to receiver
/// @param owner address of the user on whose behalf this transmutation is happening
/// @param id id of the ERC20s to transmute to aERC20
/// @param amount amount of the ERC20s to transmute to aERC20
/// @param receiver address of the user to receive the aERC20 token
function transmuteToERC20(address owner, uint256 id, uint256 amount, address receiver) external;
/// @notice Turn aERC20 into an ERC1155A id
/// @dev allows owner to send ERC20 as an ERC1155A id to receiver
/// @param owner address of the user on whose behalf this transmutation is happening
/// @param id id of the ERC20s to transmute to erc1155
/// @param amount amount of the ERC20s to transmute to erc1155
/// @param receiver address of the user to receive the erc1155 token id
function transmuteToERC1155A(address owner, uint256 id, uint256 amount, address receiver) external;
/// @notice Turn ERC1155A ids into aERC20s
/// @dev allows owner to send ERC1155A ids as aERC20s to receiver
/// @param owner address of the user on whose behalf this transmutation is happening
/// @param ids ids of the ERC1155A to transmute
/// @param amounts amounts of the ERC1155A to transmute
/// @param receiver address of the user to receive the aERC20 tokens
function transmuteBatchToERC20(
address owner,
uint256[] memory ids,
uint256[] memory amounts,
address receiver
)
external;
/// @notice Turn aERC20s into ERC1155A ids
/// @dev allows owner to send aERC20s as ERC1155A ids to receiver
/// @param owner address of the user on whose behalf this transmutation is happening
/// @param ids ids of the ERC20 to transmute
/// @param amounts amounts of the ERC20 to transmute
/// @param receiver address of the user to receive the ERC1155 token ids
function transmuteBatchToERC1155A(
address owner,
uint256[] memory ids,
uint256[] memory amounts,
address receiver
)
external;
/// @notice payable to allow any implementing cross-chain protocol to be paid for fees for broadcasting
/// @dev should emit any required events inside _registerAERC20 internal function
/// @param id of the ERC1155 to create a ERC20 for
function registerAERC20(uint256 id) external payable returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.20;
import {IERC1155} from "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[ERC].
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC-1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC-1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC-4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import {
MultiDstMultiVaultStateReq,
MultiDstSingleVaultStateReq,
SingleXChainMultiVaultStateReq,
SingleXChainSingleVaultStateReq,
SingleDirectSingleVaultStateReq,
SingleDirectMultiVaultStateReq
} from "src/types/DataTypes.sol";
/// @title IPaymentHelper
/// @dev Interface for PaymentHelper
/// @author ZeroPoint Labs
interface IPaymentHelper {
//////////////////////////////////////////////////////////////
// STRUCTS //
//////////////////////////////////////////////////////////////
/// @param nativeFeedOracle is the native price feed oracle
/// @param gasPriceOracle is the gas price oracle
/// @param swapGasUsed is the swap gas params
/// @param updateGasUsed is the update gas params
/// @param depositGasUsed is the deposit per vault gas on the chain
/// @param withdrawGasUsed is the withdraw per vault gas on the chain
/// @param defaultNativePrice is the native price on the specified chain
/// @param defaultGasPrice is the gas price on the specified chain
/// @param dstGasPerByte is the gas per size of data on the specified chain
/// @param ackGasCost is the gas cost for sending and processing from dst->src
/// @param timelockCost is the extra cost for processing timelocked payloads
/// @param emergencyCost is the extra cost for processing emergency payloads
struct PaymentHelperConfig {
address nativeFeedOracle;
address gasPriceOracle;
uint256 swapGasUsed;
uint256 updateGasUsed;
uint256 depositGasUsed;
uint256 withdrawGasUsed;
uint256 defaultNativePrice;
uint256 defaultGasPrice;
uint256 dstGasPerByte;
uint256 ackGasCost;
uint256 timelockCost;
uint256 emergencyCost;
}
//////////////////////////////////////////////////////////////
// EVENTS //
//////////////////////////////////////////////////////////////
event ChainConfigUpdated(uint64 indexed chainId_, uint256 indexed configType_, bytes config_);
event ChainConfigAdded(uint64 chainId_, PaymentHelperConfig config_);
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev returns the amb overrides & gas to be used
/// @param dstChainId_ is the unique dst chain identifier
/// @param ambIds_ is the identifiers of arbitrary message bridges to be used
/// @param message_ is the encoded cross-chain payload
function calculateAMBData(
uint64 dstChainId_,
uint8[] calldata ambIds_,
bytes memory message_
)
external
view
returns (uint256 totalFees, bytes memory extraData);
/// @dev returns the amb overrides & gas to be used
/// @return extraData the amb specific override information
function getRegisterTransmuterAMBData() external view returns (bytes memory extraData);
/// @dev estimates the gas fees for multiple destination and multi vault operation
/// @param req_ is the request object containing all necessary data for the actual operation on SuperRouter
/// @param isDeposit_ indicated if the datatype will be used for a deposit
/// @return liqAmount is the amount of liquidity to be provided in native tokens
/// @return srcAmount is the gas expense on source chain in native tokens
/// @return dstAmount is the gas expense on dst chain in terms of src chain's native tokens
/// @return totalAmount is the native_tokens to be sent along the transaction
function estimateMultiDstMultiVault(
MultiDstMultiVaultStateReq calldata req_,
bool isDeposit_
)
external
view
returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);
/// @dev estimates the gas fees for multiple destination and single vault operation
/// @param req_ is the request object containing all necessary data for the actual operation on SuperRouter
/// @param isDeposit_ indicated if the datatype will be used for a deposit
/// @return liqAmount is the amount of liquidity to be provided in native tokens
/// @return srcAmount is the gas expense on source chain in native tokens
/// @return dstAmount is the gas expense on dst chain in terms of src chain's native tokens
/// @return totalAmount is the native_tokens to be sent along the transaction
function estimateMultiDstSingleVault(
MultiDstSingleVaultStateReq calldata req_,
bool isDeposit_
)
external
view
returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);
/// @dev estimates the gas fees for single destination and multi vault operation
/// @param req_ is the request object containing all necessary data for the actual operation on SuperRouter
/// @param isDeposit_ indicated if the datatype will be used for a deposit
/// @return liqAmount is the amount of liquidity to be provided in native tokens
/// @return srcAmount is the gas expense on source chain in native tokens
/// @return dstAmount is the gas expense on dst chain in terms of src chain's native tokens
/// @return totalAmount is the native_tokens to be sent along the transaction
function estimateSingleXChainMultiVault(
SingleXChainMultiVaultStateReq calldata req_,
bool isDeposit_
)
external
view
returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);
/// @dev estimates the gas fees for single destination and single vault operation
/// @param req_ is the request object containing all necessary data for the actual operation on SuperRouter
/// @param isDeposit_ indicated if the datatype will be used for a deposit
/// @return liqAmount is the amount of liquidity to be provided in native tokens
/// @return srcAmount is the gas expense on source chain in native tokens
/// @return dstAmount is the gas expense on dst chain in terms of src chain's native tokens
/// @return totalAmount is the native_tokens to be sent along the transaction
function estimateSingleXChainSingleVault(
SingleXChainSingleVaultStateReq calldata req_,
bool isDeposit_
)
external
view
returns (uint256 liqAmount, uint256 srcAmount, uint256 dstAmount, uint256 totalAmount);
/// @dev estimates the gas fees for same chain operation
/// @param req_ is the request object containing all necessary data for the actual operation on SuperRouter
/// @param isDeposit_ indicated if the datatype will be used for a deposit
/// @return liqAmount is the amount of liquidity to be provided in native tokens
/// @return srcAmount is the gas expense on source chain in native tokens
/// @return totalAmount is the native_tokens to be sent along the transaction
function estimateSingleDirectSingleVault(
SingleDirectSingleVaultStateReq calldata req_,
bool isDeposit_
)
external
view
returns (uint256 liqAmount, uint256 srcAmount, uint256 totalAmount);
/// @dev estimates the gas fees for multiple same chain operation
/// @param req_ is the request object containing all necessary data for the actual operation on SuperRouter
/// @param isDeposit_ indicated if the datatype will be used for a deposit
/// @return liqAmount is the amount of liquidity to be provided in native tokens
/// @return srcAmount is the gas expense on source chain in native tokens
/// @return totalAmount is the native_tokens to be sent along the transaction
function estimateSingleDirectMultiVault(
SingleDirectMultiVaultStateReq calldata req_,
bool isDeposit_
)
external
view
returns (uint256 liqAmount, uint256 srcAmount, uint256 totalAmount);
/// @dev returns the gas fees estimation in native tokens if we send message through a combination of AMBs
/// @param ambIds_ is the identifier of different AMBs
/// @param dstChainId_ is the identifier of the destination chain
/// @param message_ is the cross-chain message
/// @param extraData_ is any amb-specific information
/// @return ambFees is the native_tokens to be sent along the transaction for all the ambIds_ included
function estimateAMBFees(
uint8[] memory ambIds_,
uint64 dstChainId_,
bytes memory message_,
bytes[] memory extraData_
)
external
view
returns (uint256 ambFees, uint256[] memory);
/// @dev helps estimate the acknowledgement costs for amb processing
/// @param payloadId_ is the payload identifier
/// @return totalFees is the total fees to be paid in native tokens
function estimateAckCost(uint256 payloadId_) external view returns (uint256 totalFees);
/// @dev helps estimate the acknowledgement costs for amb processing without relying on payloadId (using max values)
/// @param multi is the flag indicating if the payload is multi or single
/// @param ackAmbIds is the list of ambIds to be used for acknowledgement
/// @param srcChainId is the source chain identifier
/// @return totalFees is the total fees to be paid in native tokens
function estimateAckCostDefault(
bool multi,
uint8[] memory ackAmbIds,
uint64 srcChainId
)
external
view
returns (uint256 totalFees);
/// @dev helps estimate the acknowledgement costs for amb processing without relying on payloadId (using max values)
/// with source native amounts
/// @param multi is the flag indicating if the payload is multi or single
/// @param ackAmbIds is the list of ambIds to be used for acknowledgement
/// @param srcChainId is the source chain identifier
/// @return totalFees is the total fees to be paid in native tokens
function estimateAckCostDefaultNativeSource(
bool multi,
uint8[] memory ackAmbIds,
uint64 srcChainId
)
external
view
returns (uint256 totalFees);
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev admin can configure a remote chain for first time
/// @param chainId_ is the identifier of new chain id
/// @param config_ is the chain config
function addRemoteChain(uint64 chainId_, PaymentHelperConfig calldata config_) external;
/// @dev admin can specifically configure/update certain configuration of a remote chain
/// @param chainId_ is the remote chain's identifier
/// @param configType_ is the type of config from 1 -> 6
/// @param config_ is the encoded new configuration
function updateRemoteChain(uint64 chainId_, uint256 configType_, bytes memory config_) external;
/// @dev admin updates config for register transmuter amb params
/// @param extraDataForTransmuter_ is the broadcast extra data
function updateRegisterAERC20Params(bytes memory extraDataForTransmuter_) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import { IERC1155A } from "ERC1155A/interfaces/IERC1155A.sol";
import { AMBMessage } from "../types/DataTypes.sol";
/// @title ISuperPositions
/// @dev Interface for SuperPositions
/// @author Zeropoint Labs
interface ISuperPositions is IERC1155A {
//////////////////////////////////////////////////////////////
// STRUCTS //
//////////////////////////////////////////////////////////////
struct TxHistory {
uint256 txInfo;
address receiverAddressSP;
}
//////////////////////////////////////////////////////////////
// EVENTS //
//////////////////////////////////////////////////////////////
/// @dev is emitted when a dynamic uri is updated
event DynamicURIUpdated(string indexed oldURI, string indexed newURI, bool indexed frozen);
/// @dev is emitted when a cross-chain transaction is completed.
event Completed(uint256 indexed txId);
/// @dev is emitted when a aErc20 token is registered
event AERC20TokenRegistered(uint256 indexed tokenId, address indexed tokenAddress);
/// @dev is emitted when a tx info is saved
event TxHistorySet(uint256 indexed payloadId, uint256 txInfo, address indexed receiverAddress);
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev returns the payload header and the receiver address for a tx id on the source chain
/// @param txId_ is the identifier of the transaction issued by superform router
/// @return txInfo is the header of the payload
/// @return receiverAddressSP is the address of the receiver of superPositions
function txHistory(uint256 txId_) external view returns (uint256 txInfo, address receiverAddressSP);
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev saves the message being sent together with the associated id formulated in a router
/// @param payloadId_ is the id of the message being saved
/// @param txInfo_ is the header of the AMBMessage of the transaction being saved
/// @param receiverAddressSP_ is the address of the receiver of superPositions
function updateTxHistory(uint256 payloadId_, uint256 txInfo_, address receiverAddressSP_) external;
/// @dev allows minter to mint shares on source
/// @param receiverAddress_ is the beneficiary of shares
/// @param id_ is the id of the shares
/// @param amount_ is the amount of shares to mint
function mintSingle(address receiverAddress_, uint256 id_, uint256 amount_) external;
/// @dev allows minter to mint shares on source in batch
/// @param receiverAddress_ is the beneficiary of shares
/// @param ids_ are the ids of the shares
/// @param amounts_ are the amounts of shares to mint
function mintBatch(address receiverAddress_, uint256[] memory ids_, uint256[] memory amounts_) external;
/// @dev allows superformRouter to burn shares on source
/// @notice burn is done optimistically by the router in the beginning of the withdraw transactions
/// @notice in case the withdraw tx fails on the destination, shares are reminted through stateSync
/// @param srcSender_ is the address of the sender
/// @param id_ is the id of the shares
/// @param amount_ is the amount of shares to burn
function burnSingle(address srcSender_, uint256 id_, uint256 amount_) external;
/// @dev allows burner to burn shares on source in batch
/// @param srcSender_ is the address of the sender
/// @param ids_ are the ids of the shares
/// @param amounts_ are the amounts of shares to burn
function burnBatch(address srcSender_, uint256[] memory ids_, uint256[] memory amounts_) external;
/// @dev allows state registry contract to mint shares on source
/// @param data_ is the received information to be processed.
/// @return srcChainId_ is the decoded srcChainId.
function stateMultiSync(AMBMessage memory data_) external returns (uint64 srcChainId_);
/// @dev allows state registry contract to mint shares on source
/// @param data_ is the received information to be processed.
/// @return srcChainId_ is the decoded srcChainId.
function stateSync(AMBMessage memory data_) external returns (uint64 srcChainId_);
/// @dev sets the dynamic uri for NFT
/// @param dynamicURI_ is the dynamic uri of the NFT
/// @param freeze_ is to prevent updating the metadata once migrated to IPFS
function setDynamicURI(string memory dynamicURI_, bool freeze_) external;
/// @dev allows to create sERC0 using broadcast state registry
/// @param data_ is the crosschain payload
function stateSyncBroadcast(bytes memory data_) external payable;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import { IAccessControl } from "openzeppelin-contracts/contracts/access/IAccessControl.sol";
/// @title ISuperRBAC
/// @dev Interface for SuperRBAC
/// @author Zeropoint Labs
interface ISuperRBAC is IAccessControl {
//////////////////////////////////////////////////////////////
// STRUCTS //
//////////////////////////////////////////////////////////////
struct InitialRoleSetup {
address admin;
address emergencyAdmin;
address paymentAdmin;
address csrProcessor;
address tlProcessor;
address brProcessor;
address csrUpdater;
address srcVaaRelayer;
address dstSwapper;
address csrRescuer;
address csrDisputer;
}
//////////////////////////////////////////////////////////////
// EVENTS //
//////////////////////////////////////////////////////////////
/// @dev is emitted when superRegistry is set
event SuperRegistrySet(address indexed superRegistry);
/// @dev is emitted when an admin is set for a role
event RoleAdminSet(bytes32 role, bytes32 adminRole);
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev returns the id of the protocol admin role
function PROTOCOL_ADMIN_ROLE() external view returns (bytes32);
/// @dev returns the id of the emergency admin role
function EMERGENCY_ADMIN_ROLE() external view returns (bytes32);
/// @dev returns the id of the payment admin role
function PAYMENT_ADMIN_ROLE() external view returns (bytes32);
/// @dev returns the id of the broadcaster role
function BROADCASTER_ROLE() external view returns (bytes32);
/// @dev returns the id of the core state registry processor role
function CORE_STATE_REGISTRY_PROCESSOR_ROLE() external view returns (bytes32);
/// @dev returns the id of the timelock state registry processor role
function TIMELOCK_STATE_REGISTRY_PROCESSOR_ROLE() external view returns (bytes32);
/// @dev returns the id of the broadcast state registry processor role
function BROADCAST_STATE_REGISTRY_PROCESSOR_ROLE() external view returns (bytes32);
/// @dev returns the id of the core state registry updater role
function CORE_STATE_REGISTRY_UPDATER_ROLE() external view returns (bytes32);
/// @dev returns the id of the dst swapper role
function DST_SWAPPER_ROLE() external view returns (bytes32);
/// @dev returns the id of the core state registry rescuer role
function CORE_STATE_REGISTRY_RESCUER_ROLE() external view returns (bytes32);
/// @dev returns the id of the core state registry rescue disputer role
function CORE_STATE_REGISTRY_DISPUTER_ROLE() external view returns (bytes32);
/// @dev returns the id of wormhole vaa relayer role
function WORMHOLE_VAA_RELAYER_ROLE() external view returns (bytes32);
/// @dev returns whether the given address has the protocol admin role
/// @param admin_ the address to check
function hasProtocolAdminRole(address admin_) external view returns (bool);
/// @dev returns whether the given address has the emergency admin role
/// @param admin_ the address to check
function hasEmergencyAdminRole(address admin_) external view returns (bool);
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev updates the super registry address
function setSuperRegistry(address superRegistry_) external;
/// @dev configures a new role in superForm
/// @param role_ the role to set
/// @param adminRole_ the admin role to set as admin
function setRoleAdmin(bytes32 role_, bytes32 adminRole_) external;
/// @dev revokes the role_ from superRegistryAddressId_ on all chains
/// @param role_ the role to revoke
/// @param extraData_ amb config if broadcasting is required
/// @param superRegistryAddressId_ the super registry address id
function revokeRoleSuperBroadcast(
bytes32 role_,
bytes memory extraData_,
bytes32 superRegistryAddressId_
)
external
payable;
/// @dev allows sync of global roles from different chains using broadcast registry
/// @notice may not work for all roles
function stateSyncBroadcast(bytes memory data_) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
/// @title ISuperRegistry
/// @dev Interface for SuperRegistry
/// @author Zeropoint Labs
interface ISuperRegistry {
//////////////////////////////////////////////////////////////
// EVENTS //
//////////////////////////////////////////////////////////////
/// @dev emitted when permit2 is set.
event SetPermit2(address indexed permit2);
/// @dev is emitted when an address is set.
event AddressUpdated(
bytes32 indexed protocolAddressId, uint64 indexed chainId, address indexed oldAddress, address newAddress
);
/// @dev is emitted when a new token bridge is configured.
event SetBridgeAddress(uint256 indexed bridgeId, address indexed bridgeAddress);
/// @dev is emitted when a new bridge validator is configured.
event SetBridgeValidator(uint256 indexed bridgeId, address indexed bridgeValidator);
/// @dev is emitted when a new amb is configured.
event SetAmbAddress(uint8 indexed ambId_, address indexed ambAddress_, bool indexed isBroadcastAMB_);
/// @dev is emitted when a new state registry is configured.
event SetStateRegistryAddress(uint8 indexed registryId_, address indexed registryAddress_);
/// @dev is emitted when a new delay is configured.
event SetDelay(uint256 indexed oldDelay_, uint256 indexed newDelay_);
/// @dev is emitted when a new vault limit is configured
event SetVaultLimitPerDestination(uint64 indexed chainId_, uint256 indexed vaultLimit_);
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev gets the deposit rescue delay
function delay() external view returns (uint256);
/// @dev returns the permit2 address
function PERMIT2() external view returns (address);
/// @dev returns the id of the superform router module
function SUPERFORM_ROUTER() external view returns (bytes32);
/// @dev returns the id of the superform factory module
function SUPERFORM_FACTORY() external view returns (bytes32);
/// @dev returns the id of the superform paymaster contract
function PAYMASTER() external view returns (bytes32);
/// @dev returns the id of the superform payload helper contract
function PAYMENT_HELPER() external view returns (bytes32);
/// @dev returns the id of the core state registry module
function CORE_STATE_REGISTRY() external view returns (bytes32);
/// @dev returns the id of the timelock form state registry module
function TIMELOCK_STATE_REGISTRY() external view returns (bytes32);
/// @dev returns the id of the broadcast state registry module
function BROADCAST_REGISTRY() external view returns (bytes32);
/// @dev returns the id of the super positions module
function SUPER_POSITIONS() external view returns (bytes32);
/// @dev returns the id of the super rbac module
function SUPER_RBAC() external view returns (bytes32);
/// @dev returns the id of the payload helper module
function PAYLOAD_HELPER() external view returns (bytes32);
/// @dev returns the id of the dst swapper keeper
function DST_SWAPPER() external view returns (bytes32);
/// @dev returns the id of the emergency queue
function EMERGENCY_QUEUE() external view returns (bytes32);
/// @dev returns the id of the superform receiver
function SUPERFORM_RECEIVER() external view returns (bytes32);
/// @dev returns the id of the payment admin keeper
function PAYMENT_ADMIN() external view returns (bytes32);
/// @dev returns the id of the core state registry processor keeper
function CORE_REGISTRY_PROCESSOR() external view returns (bytes32);
/// @dev returns the id of the broadcast registry processor keeper
function BROADCAST_REGISTRY_PROCESSOR() external view returns (bytes32);
/// @dev returns the id of the timelock form state registry processor keeper
function TIMELOCK_REGISTRY_PROCESSOR() external view returns (bytes32);
/// @dev returns the id of the core state registry updater keeper
function CORE_REGISTRY_UPDATER() external view returns (bytes32);
/// @dev returns the id of the core state registry updater keeper
function CORE_REGISTRY_RESCUER() external view returns (bytes32);
/// @dev returns the id of the core state registry updater keeper
function CORE_REGISTRY_DISPUTER() external view returns (bytes32);
/// @dev returns the id of the core state registry updater keeper
function DST_SWAPPER_PROCESSOR() external view returns (bytes32);
/// @dev gets the address of a contract on current chain
/// @param id_ is the id of the contract
function getAddress(bytes32 id_) external view returns (address);
/// @dev gets the address of a contract on a target chain
/// @param id_ is the id of the contract
/// @param chainId_ is the chain id of that chain
function getAddressByChainId(bytes32 id_, uint64 chainId_) external view returns (address);
/// @dev gets the address of a bridge
/// @param bridgeId_ is the id of a bridge
/// @return bridgeAddress_ is the address of the form
function getBridgeAddress(uint8 bridgeId_) external view returns (address bridgeAddress_);
/// @dev gets the address of a bridge validator
/// @param bridgeId_ is the id of a bridge
/// @return bridgeValidator_ is the address of the form
function getBridgeValidator(uint8 bridgeId_) external view returns (address bridgeValidator_);
/// @dev gets the address of a amb
/// @param ambId_ is the id of a bridge
/// @return ambAddress_ is the address of the form
function getAmbAddress(uint8 ambId_) external view returns (address ambAddress_);
/// @dev gets the id of the amb
/// @param ambAddress_ is the address of an amb
/// @return ambId_ is the identifier of an amb
function getAmbId(address ambAddress_) external view returns (uint8 ambId_);
/// @dev gets the address of the registry
/// @param registryId_ is the id of the state registry
/// @return registryAddress_ is the address of the state registry
function getStateRegistry(uint8 registryId_) external view returns (address registryAddress_);
/// @dev gets the id of the registry
/// @notice reverts if the id is not found
/// @param registryAddress_ is the address of the state registry
/// @return registryId_ is the id of the state registry
function getStateRegistryId(address registryAddress_) external view returns (uint8 registryId_);
/// @dev gets the safe vault limit
/// @param chainId_ is the id of the remote chain
/// @return vaultLimitPerDestination_ is the safe number of vaults to deposit
/// without hitting out of gas error
function getVaultLimitPerDestination(uint64 chainId_) external view returns (uint256 vaultLimitPerDestination_);
/// @dev helps validate if an address is a valid state registry
/// @param registryAddress_ is the address of the state registry
/// @return valid_ a flag indicating if its valid.
function isValidStateRegistry(address registryAddress_) external view returns (bool valid_);
/// @dev helps validate if an address is a valid amb implementation
/// @param ambAddress_ is the address of the amb implementation
/// @return valid_ a flag indicating if its valid.
function isValidAmbImpl(address ambAddress_) external view returns (bool valid_);
/// @dev helps validate if an address is a valid broadcast amb implementation
/// @param ambAddress_ is the address of the broadcast amb implementation
/// @return valid_ a flag indicating if its valid.
function isValidBroadcastAmbImpl(address ambAddress_) external view returns (bool valid_);
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev sets the deposit rescue delay
/// @param delay_ the delay in seconds before the deposit rescue can be finalized
function setDelay(uint256 delay_) external;
/// @dev sets the permit2 address
/// @param permit2_ the address of the permit2 contract
function setPermit2(address permit2_) external;
/// @dev sets the safe vault limit
/// @param chainId_ is the remote chain identifier
/// @param vaultLimit_ is the max limit of vaults per transaction
function setVaultLimitPerDestination(uint64 chainId_, uint256 vaultLimit_) external;
/// @dev sets new addresses on specific chains.
/// @param ids_ are the identifiers of the address on that chain
/// @param newAddresses_ are the new addresses on that chain
/// @param chainIds_ are the chain ids of that chain
function batchSetAddress(
bytes32[] calldata ids_,
address[] calldata newAddresses_,
uint64[] calldata chainIds_
)
external;
/// @dev sets a new address on a specific chain.
/// @param id_ the identifier of the address on that chain
/// @param newAddress_ the new address on that chain
/// @param chainId_ the chain id of that chain
function setAddress(bytes32 id_, address newAddress_, uint64 chainId_) external;
/// @dev allows admin to set the bridge address for an bridge id.
/// @notice this function operates in an APPEND-ONLY fashion.
/// @param bridgeId_ represents the bridge unique identifier.
/// @param bridgeAddress_ represents the bridge address.
/// @param bridgeValidator_ represents the bridge validator address.
function setBridgeAddresses(
uint8[] memory bridgeId_,
address[] memory bridgeAddress_,
address[] memory bridgeValidator_
)
external;
/// @dev allows admin to set the amb address for an amb id.
/// @notice this function operates in an APPEND-ONLY fashion.
/// @param ambId_ represents the bridge unique identifier.
/// @param ambAddress_ represents the bridge address.
/// @param isBroadcastAMB_ represents whether the amb implementation supports broadcasting
function setAmbAddress(
uint8[] memory ambId_,
address[] memory ambAddress_,
bool[] memory isBroadcastAMB_
)
external;
/// @dev allows admin to set the state registry address for an state registry id.
/// @notice this function operates in an APPEND-ONLY fashion.
/// @param registryId_ represents the state registry's unique identifier.
/// @param registryAddress_ represents the state registry's address.
function setStateRegistryAddress(uint8[] memory registryId_, address[] memory registryAddress_) external;
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
/// @title ISuperformFactory
/// @dev Interface for SuperformFactory
/// @author ZeroPoint Labs
interface ISuperformFactory {
//////////////////////////////////////////////////////////////
// CONSTANTS //
//////////////////////////////////////////////////////////////
enum PauseStatus {
NON_PAUSED,
PAUSED
}
//////////////////////////////////////////////////////////////
// EVENTS //
//////////////////////////////////////////////////////////////
/// @dev emitted when a new formImplementation is entered into the factory
/// @param formImplementation is the address of the new form implementation
/// @param formImplementationId is the id of the formImplementation
/// @param formStateRegistryId is any additional state registry id of the formImplementation
event FormImplementationAdded(
address indexed formImplementation, uint256 indexed formImplementationId, uint8 indexed formStateRegistryId
);
/// @dev emitted when a new Superform is created
/// @param formImplementationId is the id of the form implementation
/// @param vault is the address of the vault
/// @param superformId is the id of the superform
/// @param superform is the address of the superform
event SuperformCreated(
uint256 indexed formImplementationId, address indexed vault, uint256 indexed superformId, address superform
);
/// @dev emitted when a new SuperRegistry is set
/// @param superRegistry is the address of the super registry
event SuperRegistrySet(address indexed superRegistry);
/// @dev emitted when a form implementation is paused
/// @param formImplementationId is the id of the form implementation
/// @param paused is the new paused status
event FormImplementationPaused(uint256 indexed formImplementationId, PauseStatus indexed paused);
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev returns the number of forms
/// @return forms_ is the number of forms
function getFormCount() external view returns (uint256 forms_);
/// @dev returns the number of superforms
/// @return superforms_ is the number of superforms
function getSuperformCount() external view returns (uint256 superforms_);
/// @dev returns the address of a form implementation
/// @param formImplementationId_ is the id of the form implementation
/// @return formImplementation_ is the address of the form implementation
function getFormImplementation(uint32 formImplementationId_) external view returns (address formImplementation_);
/// @dev returns the form state registry id of a form implementation
/// @param formImplementationId_ is the id of the form implementation
/// @return stateRegistryId_ is the additional state registry id of the form
function getFormStateRegistryId(uint32 formImplementationId_) external view returns (uint8 stateRegistryId_);
/// @dev returns the paused status of form implementation
/// @param formImplementationId_ is the id of the form implementation
/// @return paused_ is the current paused status of the form formImplementationId_
function isFormImplementationPaused(uint32 formImplementationId_) external view returns (bool paused_);
/// @dev returns the address of a superform
/// @param superformId_ is the id of the superform
/// @return superform_ is the address of the superform
/// @return formImplementationId_ is the id of the form implementation
/// @return chainId_ is the chain id
function getSuperform(uint256 superformId_)
external
pure
returns (address superform_, uint32 formImplementationId_, uint64 chainId_);
/// @dev returns if an address has been added to a Form
/// @param superformId_ is the id of the superform
/// @return isSuperform_ bool if it exists
function isSuperform(uint256 superformId_) external view returns (bool isSuperform_);
/// @dev Reverse query of getSuperform, returns all superforms for a given vault
/// @param vault_ is the address of a vault
/// @return superformIds_ is the id of the superform
/// @return superforms_ is the address of the superform
function getAllSuperformsFromVault(address vault_)
external
view
returns (uint256[] memory superformIds_, address[] memory superforms_);
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @dev allows an admin to add a Form implementation to the factory
/// @param formImplementation_ is the address of a form implementation
/// @param formImplementationId_ is the id of the form implementation (generated off-chain and equal in all chains)
/// @param formStateRegistryId_ is the id of any additional state registry for that form
/// @dev formStateRegistryId_ 1 is default for all form implementations, pass in formStateRegistryId_ only if an
/// additional state registry is required
function addFormImplementation(
address formImplementation_,
uint32 formImplementationId_,
uint8 formStateRegistryId_
)
external;
/// @dev To add new vaults to Form implementations, fusing them together into Superforms
/// @param formImplementationId_ is the form implementation we want to attach the vault to
/// @param vault_ is the address of the vault
/// @return superformId_ is the id of the created superform
/// @return superform_ is the address of the created superform
function createSuperform(
uint32 formImplementationId_,
address vault_
)
external
returns (uint256 superformId_, address superform_);
/// @dev to synchronize superforms added to different chains using broadcast registry
/// @param data_ is the cross-chain superform id
function stateSyncBroadcast(bytes memory data_) external payable;
/// @dev allows an admin to change the status of a form
/// @param formImplementationId_ is the id of the form implementation
/// @param status_ is the new status
/// @param extraData_ is optional & passed when broadcasting of status is needed
function changeFormImplementationPauseStatus(
uint32 formImplementationId_,
PauseStatus status_,
bytes memory extraData_
)
external
payable;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import { IERC20 } from "openzeppelin-contracts/contracts/token/ERC20/IERC20.sol";
/// @title IaERC20
/// @author Zeropoint Labs
/// @dev ERC20 tokens out of 1155A
interface IaERC20 is IERC20 {
/// @dev thrown if ERC1155A is not caller for mint/burn in transmute
error ONLY_ERC1155A();
/// @dev allows msg.sender set in constructor to mint
/// @param owner address of the owner of the tokens
/// @param amount amount of tokens to mint
function mint(address owner, uint256 amount) external;
/// @dev allows msg.sender set in constructor to burn
/// @param owner address of the owner of the tokens
/// @param operator address of the operator of the tokens
/// @param amount amount of tokens to burn
function burn(address owner, address operator, uint256 amount) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
return a / b;
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return a == 0 ? 0 : (a - 1) / b + 1;
}
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.23;
import { ERC1155A } from "ERC1155A/ERC1155A.sol";
import { aERC20 } from "ERC1155A/aERC20.sol";
import { Broadcastable } from "src/crosschain-data/utils/Broadcastable.sol";
import { ISuperPositions } from "src/interfaces/ISuperPositions.sol";
import { ISuperRegistry } from "src/interfaces/ISuperRegistry.sol";
import { ISuperRBAC } from "src/interfaces/ISuperRBAC.sol";
import { ISuperformFactory } from "src/interfaces/ISuperformFactory.sol";
import { IBaseForm } from "src/interfaces/IBaseForm.sol";
import { IPaymentHelper } from "./interfaces/IPaymentHelper.sol";
import { Error } from "src/libraries/Error.sol";
import { DataLib } from "src/libraries/DataLib.sol";
import {
TransactionType,
ReturnMultiData,
ReturnSingleData,
CallbackType,
AMBMessage,
BroadcastMessage
} from "src/types/DataTypes.sol";
import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/// @title SuperPositions
/// @dev Cross-chain LP token minted on source chain
/// @author Zeropoint Labs
contract SuperPositions is ISuperPositions, ERC1155A, Broadcastable {
using DataLib for uint256;
//////////////////////////////////////////////////////////////
// CONSTANTS //
//////////////////////////////////////////////////////////////
ISuperRegistry public immutable superRegistry;
uint64 public immutable CHAIN_ID;
uint8 internal constant CORE_STATE_REGISTRY_ID = 1;
bytes32 internal constant DEPLOY_NEW_AERC20 = keccak256("DEPLOY_NEW_AERC20");
//////////////////////////////////////////////////////////////
// STATE VARIABLES //
//////////////////////////////////////////////////////////////
/// @dev maps all transaction data routed through the smart contract.
mapping(uint256 transactionId => TxHistory txHistory) public override txHistory;
/// @dev is the base uri set by admin
string public dynamicURI;
/// @dev is the base uri frozen status
bool public dynamicURIFrozen;
/// @dev nonce for aERC20 broadcast
uint256 public xChainPayloadCounter;
//////////////////////////////////////////////////////////////
// MODIFIERS //
//////////////////////////////////////////////////////////////
modifier onlyRouter() {
if (msg.sender != superRegistry.getAddress(keccak256("SUPERFORM_ROUTER"))) revert Error.NOT_SUPERFORM_ROUTER();
_;
}
modifier onlyProtocolAdmin() {
if (!ISuperRBAC(superRegistry.getAddress(keccak256("SUPER_RBAC"))).hasProtocolAdminRole(msg.sender)) {
revert Error.NOT_PROTOCOL_ADMIN();
}
_;
}
/// @dev is used in same chain case (as superform is available on the chain to validate caller)
modifier onlyMinter(uint256 superformId) {
address router = superRegistry.getAddress(keccak256("SUPERFORM_ROUTER"));
/// if msg.sender isn't superformRouter then it must be state registry of that form
if (msg.sender != router) {
uint8 registryId = superRegistry.getStateRegistryId(msg.sender);
(address superform,,) = DataLib.getSuperform(superformId);
uint8 formRegistryId = IBaseForm(superform).getStateRegistryId();
if (registryId != formRegistryId) {
revert Error.NOT_MINTER();
}
}
_;
}
modifier onlyBroadcastRegistry() {
if (msg.sender != superRegistry.getAddress(keccak256("BROADCAST_REGISTRY"))) {
revert Error.NOT_BROADCAST_REGISTRY();
}
_;
}
modifier onlyBatchMinter(uint256[] memory superformIds) {
address router = superRegistry.getAddress(keccak256("SUPERFORM_ROUTER"));
/// if msg.sender isn't superformRouter then it must be state registry for that superform
if (msg.sender != router) {
uint256 len = superformIds.length;
for (uint256 i; i < len; ++i) {
(, uint32 formImplementationId,) = DataLib.getSuperform(superformIds[i]);
uint8 registryId = superRegistry.getStateRegistryId(msg.sender);
if (uint32(registryId) != formImplementationId) {
revert Error.NOT_MINTER();
}
}
}
_;
}
//////////////////////////////////////////////////////////////
// CONSTRUCTOR //
//////////////////////////////////////////////////////////////
/// @param dynamicURI_ URL for external metadata of ERC1155 SuperPositions
/// @param superRegistry_ the superform registry contract
constructor(
string memory dynamicURI_,
address superRegistry_,
string memory name_,
string memory symbol_
)
ERC1155A(name_, symbol_)
{
if (block.chainid > type(uint64).max) {
revert Error.BLOCK_CHAIN_ID_OUT_OF_BOUNDS();
}
CHAIN_ID = uint64(block.chainid);
superRegistry = ISuperRegistry(superRegistry_);
dynamicURI = dynamicURI_;
}
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @inheritdoc ERC1155A
function supportsInterface(bytes4 interfaceId_) public view virtual override(ERC1155A, IERC165) returns (bool) {
return super.supportsInterface(interfaceId_);
}
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @inheritdoc ISuperPositions
function updateTxHistory(
uint256 payloadId_,
uint256 txInfo_,
address receiverAddressSP_
)
external
override
onlyRouter
{
txHistory[payloadId_] = TxHistory({ txInfo: txInfo_, receiverAddressSP: receiverAddressSP_ });
emit TxHistorySet(payloadId_, txInfo_, receiverAddressSP_);
}
/// @inheritdoc ISuperPositions
function mintSingle(address receiverAddressSP_, uint256 id_, uint256 amount_) external override onlyMinter(id_) {
_mint(receiverAddressSP_, msg.sender, id_, amount_, "");
}
/// @inheritdoc ISuperPositions
function mintBatch(
address receiverAddressSP_,
uint256[] memory ids_,
uint256[] memory amounts_
)
external
override
onlyBatchMinter(ids_)
{
if (ids_.length != amounts_.length) revert Error.ARRAY_LENGTH_MISMATCH();
_batchMint(receiverAddressSP_, msg.sender, ids_, amounts_, "");
}
/// @inheritdoc ISuperPositions
function burnSingle(address srcSender_, uint256 id_, uint256 amount_) external override onlyRouter {
_burn(srcSender_, msg.sender, id_, amount_);
}
/// @inheritdoc ISuperPositions
function burnBatch(
address srcSender_,
uint256[] memory ids_,
uint256[] memory amounts_
)
external
override
onlyRouter
{
if (ids_.length != amounts_.length) revert Error.ARRAY_LENGTH_MISMATCH();
_batchBurn(srcSender_, msg.sender, ids_, amounts_);
}
/// @inheritdoc ISuperPositions
function stateMultiSync(AMBMessage memory data_) external override returns (uint64 srcChainId_) {
/// @dev here we decode the txInfo and params from the data brought back from destination
(uint256 returnTxType, uint256 callbackType, uint8 multi,,,) = data_.txInfo.decodeTxInfo();
if (callbackType != uint256(CallbackType.RETURN) && callbackType != uint256(CallbackType.FAIL)) {
revert Error.INVALID_PAYLOAD_TYPE();
}
/// @dev decode remaining info on superPositions to mint from destination
ReturnMultiData memory returnData = abi.decode(data_.params, (ReturnMultiData));
_validateStateSyncer(returnData.superformIds);
uint256 txInfo = txHistory[returnData.payloadId].txInfo;
/// @dev if txInfo is zero then the payloadId is invalid for ack
if (txInfo == 0) {
revert Error.TX_HISTORY_NOT_FOUND();
}
uint256 txType;
/// @dev decode initial payload info stored on source chain in this contract
(txType,,,,, srcChainId_) = txInfo.decodeTxInfo();
/// @dev verify this is a not single vault mint
if (multi != 1) revert Error.INVALID_PAYLOAD_TYPE();
/// @dev compare txType to be the same (dst/src)
if (returnTxType != txType) revert Error.SRC_TX_TYPE_MISMATCH();
/// @dev mint super positions accordingly
if (
(txType == uint256(TransactionType.DEPOSIT) && callbackType == uint256(CallbackType.RETURN))
|| (txType == uint256(TransactionType.WITHDRAW) && callbackType == uint256(CallbackType.FAIL))
) {
_batchMint(
txHistory[returnData.payloadId].receiverAddressSP,
msg.sender,
returnData.superformIds,
returnData.amounts,
""
);
} else {
revert Error.INVALID_PAYLOAD_TYPE();
}
emit Completed(returnData.payloadId);
}
/// @inheritdoc ISuperPositions
function stateSync(AMBMessage memory data_) external override returns (uint64 srcChainId_) {
/// @dev here we decode the txInfo and params from the data brought back from destination
(uint256 returnTxType, uint256 callbackType, uint8 multi,,,) = data_.txInfo.decodeTxInfo();
if (callbackType != uint256(CallbackType.RETURN) && callbackType != uint256(CallbackType.FAIL)) {
revert Error.INVALID_PAYLOAD_TYPE();
}
/// @dev decode remaining info on superPositions to mint from destination
ReturnSingleData memory returnData = abi.decode(data_.params, (ReturnSingleData));
_validateStateSyncer(returnData.superformId);
uint256 txInfo = txHistory[returnData.payloadId].txInfo;
/// @dev if txInfo is zero then the payloadId is invalid for ack
if (txInfo == 0) {
revert Error.TX_HISTORY_NOT_FOUND();
}
uint256 txType;
/// @dev decode initial payload info stored on source chain in this contract
(txType,,,,, srcChainId_) = txInfo.decodeTxInfo();
/// @dev this is a not multi vault mint
if (multi != 0) revert Error.INVALID_PAYLOAD_TYPE();
/// @dev compare txType to be the same (dst/src)
if (returnTxType != txType) revert Error.SRC_TX_TYPE_MISMATCH();
/// @dev mint super positions accordingly
if (
(txType == uint256(TransactionType.DEPOSIT) && callbackType == uint256(CallbackType.RETURN))
|| (txType == uint256(TransactionType.WITHDRAW) && callbackType == uint256(CallbackType.FAIL))
) {
_mint(
txHistory[returnData.payloadId].receiverAddressSP,
msg.sender,
returnData.superformId,
returnData.amount,
""
);
} else {
revert Error.INVALID_PAYLOAD_TYPE();
}
emit Completed(returnData.payloadId);
}
/// @inheritdoc ISuperPositions
function stateSyncBroadcast(bytes memory data_) external payable override onlyBroadcastRegistry {
BroadcastMessage memory transmuterPayload = abi.decode(data_, (BroadcastMessage));
if (transmuterPayload.messageType != DEPLOY_NEW_AERC20) {
revert Error.INVALID_MESSAGE_TYPE();
}
_deployTransmuter(transmuterPayload.message);
}
/// @inheritdoc ISuperPositions
function setDynamicURI(string memory dynamicURI_, bool freeze_) external override onlyProtocolAdmin {
if (dynamicURIFrozen) {
revert Error.DYNAMIC_URI_FROZEN();
}
string memory oldURI = dynamicURI;
dynamicURI = dynamicURI_;
dynamicURIFrozen = freeze_;
emit DynamicURIUpdated(oldURI, dynamicURI_, freeze_);
}
//////////////////////////////////////////////////////////////
// INTERNAL FUNCTIONS //
//////////////////////////////////////////////////////////////
/// @notice Used to construct return url
function _baseURI() internal view override returns (string memory) {
return dynamicURI;
}
/// @dev helps validate the state registry id for minting superform id
/// @dev is used in cross chain case (as superform is not available on the chain to validate caller)
function _validateStateSyncer(uint256 superformId_) internal view {
uint8 registryId = superRegistry.getStateRegistryId(msg.sender);
_isValidStateSyncer(registryId, superformId_);
}
/// @dev helps validate the state registry id for minting superform id
function _validateStateSyncer(uint256[] memory superformIds_) internal view {
uint8 registryId = superRegistry.getStateRegistryId(msg.sender);
for (uint256 i; i < superformIds_.length; ++i) {
_isValidStateSyncer(registryId, superformIds_[i]);
}
}
function _isValidStateSyncer(uint8 registryId_, uint256 superformId_) internal view {
/// @dev registryId_ zero check is done in superRegistry.getStateRegistryId()
/// @dev If registryId is 1, meaning CoreStateRegistry, no further checks are necessary.
/// @dev This is because CoreStateRegistry is the default minter for all kinds of forms
/// @dev In case registryId is > 1, we need to check if the registryId matches the formImplementationId
if (registryId_ == CORE_STATE_REGISTRY_ID) {
return;
}
(, uint32 formImplementationId,) = DataLib.getSuperform(superformId_);
uint8 formRegistryId = ISuperformFactory(superRegistry.getAddress(keccak256("SUPERFORM_FACTORY")))
.getFormStateRegistryId(formImplementationId);
if (registryId_ != formRegistryId) {
revert Error.NOT_MINTER_STATE_REGISTRY_ROLE();
}
}
function _registerAERC20(uint256 id) internal override returns (address aErc20Token) {
if (!ISuperformFactory(superRegistry.getAddress(keccak256("SUPERFORM_FACTORY"))).isSuperform(id)) {
revert Error.SUPERFORM_ID_NONEXISTENT();
}
(address superform,,) = id.getSuperform();
string memory name = IBaseForm(superform).superformYieldTokenName();
string memory symbol = IBaseForm(superform).superformYieldTokenSymbol();
uint8 decimal = uint8(IBaseForm(superform).getVaultDecimals());
aErc20Token = address(new aERC20(name, symbol, decimal));
/// @dev broadcast and deploy to the other destination chains
BroadcastMessage memory transmuterPayload = BroadcastMessage(
"SUPER_POSITIONS",
DEPLOY_NEW_AERC20,
abi.encode(CHAIN_ID, ++xChainPayloadCounter, id, name, symbol, decimal)
);
_broadcast(
superRegistry.getAddress(keccak256("BROADCAST_REGISTRY")),
superRegistry.getAddress(keccak256("PAYMASTER")),
abi.encode(transmuterPayload),
IPaymentHelper(superRegistry.getAddress(keccak256("PAYMENT_HELPER"))).getRegisterTransmuterAMBData()
);
emit AERC20TokenRegistered(id, aErc20Token);
return aErc20Token;
}
/// @dev deploys new transmuter on broadcasting
function _deployTransmuter(bytes memory message_) internal {
(,, uint256 superformId, string memory name, string memory symbol, uint8 decimal) =
abi.decode(message_, (uint64, uint256, uint256, string, string, uint8));
if (aErc20TokenId[superformId] != address(0)) revert AERC20_ALREADY_REGISTERED();
address aErc20Token = address(new aERC20(name, symbol, decimal));
aErc20TokenId[superformId] = aErc20Token;
emit AERC20TokenRegistered(superformId, aErc20Token);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.23;
import { IaERC20 } from "./interfaces/IaERC20.sol";
import { ERC20 } from "openzeppelin-contracts/contracts/token/ERC20/ERC20.sol";
/// @title aERC20
/// @dev ERC20 tokens out of 1155A
/// @author Zeropoint Labs
contract aERC20 is ERC20, IaERC20 {
//////////////////////////////////////////////////////////////
// CONSTANTS //
//////////////////////////////////////////////////////////////
address public immutable ERC1155A;
uint8 private immutable TOKEN_DECIMALS;
//////////////////////////////////////////////////////////////
// MODIFIERS //
//////////////////////////////////////////////////////////////
modifier onlyTokenTransmuter() {
if (msg.sender != ERC1155A) {
revert ONLY_ERC1155A();
}
_;
}
//////////////////////////////////////////////////////////////
// CONSTRUCTOR //
//////////////////////////////////////////////////////////////
constructor(string memory name_, string memory symbol_, uint8 decimals_) ERC20(name_, symbol_) {
ERC1155A = msg.sender;
TOKEN_DECIMALS = decimals_;
}
//////////////////////////////////////////////////////////////
// EXTERNAL VIEW FUNCTIONS //
//////////////////////////////////////////////////////////////
/// inheritdoc IaERC20
function decimals() public view override returns (uint8) {
return TOKEN_DECIMALS;
}
//////////////////////////////////////////////////////////////
// EXTERNAL WRITE FUNCTIONS //
//////////////////////////////////////////////////////////////
/// inheritdoc IaERC20
function mint(address owner, uint256 amount) external override onlyTokenTransmuter {
_mint(owner, amount);
}
/// inheritdoc IaERC20
function burn(address owner, address operator, uint256 amount) external override onlyTokenTransmuter {
if (owner != operator) _spendAllowance(owner, operator, amount);
_burn(owner, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
{
"compilationTarget": {
"src/SuperPositions.sol": "SuperPositions"
},
"evmVersion": "paris",
"libraries": {},
"metadata": {
"bytecodeHash": "ipfs"
},
"optimizer": {
"enabled": true,
"runs": 200
},
"remappings": [
":@openzeppelin/contracts/=lib/ERC1155A/lib/openzeppelin-contracts/contracts/",
":ERC1155A/=lib/ERC1155A/src/",
":ds-test/=lib/ds-test/src/",
":erc4626-tests/=lib/ERC1155A/lib/openzeppelin-contracts/lib/erc4626-tests/",
":forge-std/=lib/forge-std/src/",
":openzeppelin-contracts/=lib/ERC1155A/lib/openzeppelin-contracts/",
":pigeon/=lib/pigeon/src/",
":solady/=lib/pigeon/lib/solady/",
":solmate/=lib/ERC1155A/lib/solmate/src/",
":super-vaults/=lib/super-vaults/src/",
":v2-core/=lib/super-vaults/lib/v2-core/contracts/",
":v2-periphery/=lib/super-vaults/lib/v2-periphery/contracts/",
":v3-core/=lib/super-vaults/lib/v3-core/"
]
}
[{"inputs":[{"internalType":"string","name":"dynamicURI_","type":"string"},{"internalType":"address","name":"superRegistry_","type":"address"},{"internalType":"string","name":"name_","type":"string"},{"internalType":"string","name":"symbol_","type":"string"}],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"AERC20_ALREADY_REGISTERED","type":"error"},{"inputs":[],"name":"AERC20_NOT_REGISTERED","type":"error"},{"inputs":[],"name":"ARRAY_LENGTH_MISMATCH","type":"error"},{"inputs":[],"name":"BLOCK_CHAIN_ID_OUT_OF_BOUNDS","type":"error"},{"inputs":[],"name":"DECREASED_ALLOWANCE_BELOW_ZERO","type":"error"},{"inputs":[],"name":"DYNAMIC_URI_FROZEN","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"},{"internalType":"uint256","name":"balance","type":"uint256"},{"internalType":"uint256","name":"needed","type":"uint256"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"ERC1155InsufficientBalance","type":"error"},{"inputs":[{"internalType":"address","name":"approver","type":"address"}],"name":"ERC1155InvalidApprover","type":"error"},{"inputs":[{"internalType":"uint256","name":"idsLength","type":"uint256"},{"internalType":"uint256","name":"valuesLength","type":"uint256"}],"name":"ERC1155InvalidArrayLength","type":"error"},{"inputs":[{"internalType":"address","name":"operator","type":"address"}],"name":"ERC1155InvalidOperator","type":"error"},{"inputs":[{"internalType":"address","name":"receiver","type":"address"}],"name":"ERC1155InvalidReceiver","type":"error"},{"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"ERC1155InvalidSender","type":"error"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"address","name":"owner","type":"address"}],"name":"ERC1155MissingApprovalForAll","type":"error"},{"inputs":[],"name":"FAILED_TO_SEND_NATIVE","type":"error"},{"inputs":[],"name":"ID_NOT_MINTED_YET","type":"error"},{"inputs":[],"name":"INVALID_BROADCAST_FEE","type":"error"},{"inputs":[],"name":"INVALID_CHAIN_ID","type":"error"},{"inputs":[],"name":"INVALID_MESSAGE_TYPE","type":"error"},{"inputs":[],"name":"INVALID_PAYLOAD_TYPE","type":"error"},{"inputs":[],"name":"LENGTH_MISMATCH","type":"error"},{"inputs":[],"name":"NOT_BROADCAST_REGISTRY","type":"error"},{"inputs":[],"name":"NOT_MINTER","type":"error"},{"inputs":[],"name":"NOT_MINTER_STATE_REGISTRY_ROLE","type":"error"},{"inputs":[],"name":"NOT_PROTOCOL_ADMIN","type":"error"},{"inputs":[],"name":"NOT_SUPERFORM_ROUTER","type":"error"},{"inputs":[],"name":"SRC_TX_TYPE_MISMATCH","type":"error"},{"inputs":[],"name":"SUPERFORM_ID_NONEXISTENT","type":"error"},{"inputs":[],"name":"TRANSFER_TO_ADDRESS_ZERO","type":"error"},{"inputs":[],"name":"TX_HISTORY_NOT_FOUND","type":"error"},{"inputs":[],"name":"ZERO_ADDRESS","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"tokenAddress","type":"address"}],"name":"AERC20TokenRegistered","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":false,"internalType":"bool","name":"approved","type":"bool"}],"name":"ApprovalForAll","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"ApprovalForOne","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"txId","type":"uint256"}],"name":"Completed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"string","name":"oldURI","type":"string"},{"indexed":true,"internalType":"string","name":"newURI","type":"string"},{"indexed":true,"internalType":"bool","name":"frozen","type":"bool"}],"name":"DynamicURIUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"values","type":"uint256[]"}],"name":"TransferBatch","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"operator","type":"address"},{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"TransferSingle","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"}],"name":"TransmutedBatchToERC1155A","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"indexed":false,"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"}],"name":"TransmutedBatchToERC20","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"}],"name":"TransmutedToERC1155A","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"user","type":"address"},{"indexed":false,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"},{"indexed":true,"internalType":"address","name":"receiver","type":"address"}],"name":"TransmutedToERC20","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"payloadId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"txInfo","type":"uint256"},{"indexed":true,"internalType":"address","name":"receiverAddress","type":"address"}],"name":"TxHistorySet","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"string","name":"value","type":"string"},{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"}],"name":"URI","type":"event"},{"inputs":[],"name":"CHAIN_ID","outputs":[{"internalType":"uint64","name":"","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"aERC20Exists","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"aErc20TokenId","outputs":[{"internalType":"address","name":"aErc20Token","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"uint256","name":"","type":"uint256"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address[]","name":"owners","type":"address[]"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"}],"name":"balanceOfBatch","outputs":[{"internalType":"uint256[]","name":"balances","type":"uint256[]"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"srcSender_","type":"address"},{"internalType":"uint256[]","name":"ids_","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts_","type":"uint256[]"}],"name":"burnBatch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"srcSender_","type":"address"},{"internalType":"uint256","name":"id_","type":"uint256"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"burnSingle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"subtractedValues","type":"uint256[]"}],"name":"decreaseAllowanceForMany","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"dynamicURI","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dynamicURIFrozen","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"exists","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"getERC20TokenAddress","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"addedValues","type":"uint256[]"}],"name":"increaseAllowanceForMany","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"},{"internalType":"address","name":"","type":"address"}],"name":"isApprovedForAll","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"receiverAddressSP_","type":"address"},{"internalType":"uint256[]","name":"ids_","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts_","type":"uint256[]"}],"name":"mintBatch","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"receiverAddressSP_","type":"address"},{"internalType":"uint256","name":"id_","type":"uint256"},{"internalType":"uint256","name":"amount_","type":"uint256"}],"name":"mintSingle","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"registerAERC20","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeBatchTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"safeTransferFrom","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"bool","name":"approved","type":"bool"}],"name":"setApprovalForAll","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"}],"name":"setApprovalForMany","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"operator","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"setApprovalForOne","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"dynamicURI_","type":"string"},{"internalType":"bool","name":"freeze_","type":"bool"}],"name":"setDynamicURI","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"txInfo","type":"uint256"},{"internalType":"bytes","name":"params","type":"bytes"}],"internalType":"struct AMBMessage","name":"data_","type":"tuple"}],"name":"stateMultiSync","outputs":[{"internalType":"uint64","name":"srcChainId_","type":"uint64"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint256","name":"txInfo","type":"uint256"},{"internalType":"bytes","name":"params","type":"bytes"}],"internalType":"struct AMBMessage","name":"data_","type":"tuple"}],"name":"stateSync","outputs":[{"internalType":"uint64","name":"srcChainId_","type":"uint64"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes","name":"data_","type":"bytes"}],"name":"stateSyncBroadcast","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"superRegistry","outputs":[{"internalType":"contract ISuperRegistry","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bytes4","name":"interfaceId_","type":"bytes4"}],"name":"supportsInterface","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"address","name":"receiver","type":"address"}],"name":"transmuteBatchToERC1155A","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256[]","name":"ids","type":"uint256[]"},{"internalType":"uint256[]","name":"amounts","type":"uint256[]"},{"internalType":"address","name":"receiver","type":"address"}],"name":"transmuteBatchToERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"transmuteToERC1155A","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"uint256","name":"id","type":"uint256"},{"internalType":"uint256","name":"amount","type":"uint256"},{"internalType":"address","name":"receiver","type":"address"}],"name":"transmuteToERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"transactionId","type":"uint256"}],"name":"txHistory","outputs":[{"internalType":"uint256","name":"txInfo","type":"uint256"},{"internalType":"address","name":"receiverAddressSP","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"payloadId_","type":"uint256"},{"internalType":"uint256","name":"txInfo_","type":"uint256"},{"internalType":"address","name":"receiverAddressSP_","type":"address"}],"name":"updateTxHistory","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"id","type":"uint256"}],"name":"uri","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"xChainPayloadCounter","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"}]