Mure: Smart Contract Suite
Welcome to Mure, a comprehensive suite of smart contracts designed for easy transactions regarding fundraising, distribution, and payments. Our project is built with security, efficiency, and scalability in mind, leveraging the robust capabilities of the Ethereum blockchain.
About
Mure aims to make safe, scalable and trustless transactions available for anyone, even if they don’t have blockchain experience. Developed using Solidity, our contracts are meticulously designed to ensure secure, gas-efficient, and self-custodial management of funds and payments.
Powered by Foundry
Our development process is empowered by Foundry, a blazing-fast, portable, and modular toolkit for Ethereum application development. Foundry allows us to:
- Test: Conduct comprehensive tests with flexibility and high performance.
- Build: Compile Solidity code swiftly, ensuring rapid development cycles.
- Deploy: Streamline smart contract deployment with precise control over network interactions.
Features
- Fundraising: Collect funds from various sources and get automatic, on-chain bookkeeping for easy dispersement of on-chain assets.
- Distribution: Distribute funds through airdrops or claims, leveraging the data stored from the deposits made by the customer.
- Payments: Leverage the blockchain for the on-chain security and use it as a payments confirmation layer to hook into your off-chain store or service business.
API Documentation
Our APIs are used to interface with your smart contract and help with off-chain needs like KYC, AML, allowlisting, and so on.
For detailed information about our API documentation and how to interact with them, please refer to the API Documentation.
License
Mure is released under the BUSL-1.1. See the LICENSE file for more details.
Contact
For any inquiries or to discuss collaboration, please reach out to hello@mure.app.
Contents
- Chargeable
- Claimable
- Config
- PoolConfig
- DelegateErrorReason
- Delegatable
- DepositArgs
- DepositRecord
- FeeConfig
- DepositPermit
- Depositable
- Distributable
- IERC165
- IERC721Metadata
- IERC20Burnable
- PoolApp
- PoolState
- PoolMetadata
- PoolParameters
- PoolMetrics
- PoolParameter
- PoolErrorReason
- Poolable
- Refundable
Chargeable
Author: Mure
Interface for the fees related functionalities for ClaimPlugin
Functions
calculateFee
function calculateFee(address poolContract, string calldata poolName, address depositor)
external
view
returns (uint256);
Claimable
Inherits: IERC165
Author: Mure
Interface for claim functionality of pools with support for ERC-165 detection.
Functions
claim
function claim(ClaimRecord calldata claim) external returns (uint256 depositDelta, uint256 claimDelta);
deltas
function deltas(ClaimRecord calldata claimRecord)
external
pure
returns (uint256 depositDelta, uint256 claimDelta, uint256 fee);
Events
Claim
event Claim(address indexed depositor, uint256 indexed amount);
Errors
BalanceMismatch
error BalanceMismatch(uint256 collectedFunds, uint256 reserves);
Structs
ClaimRecord
struct ClaimRecord {
address claimCurrency;
address depositor;
uint256 share;
uint256 supply;
uint256 claimReserves;
uint256 depositReserves;
uint256 deposit;
uint256 totalCollected;
string poolName;
address custodian;
uint16 feePercentage;
}
Config
Inherits: IERC165
Author: Mure
Interface for MureConfig core with support for ERC-165 detection.
Functions
getAppDelegate
Must not revert, should return address(0) incase delegate does not exist
function getAppDelegate(address poolApp) external returns (address);
setAppDelegate
function setAppDelegate(address poolApp, address delegate) external;
verifyMureSignature
function verifyMureSignature(bytes32 structHash, bytes memory signature) external;
toggleWhitelistedSigner
function toggleWhitelistedSigner(address mureSigner_) external;
PoolConfig
struct PoolConfig {
uint256 claimReserves;
uint256 depositReserves;
uint256 supply;
uint16 plugins;
uint16 feePercentage; // 0 to 10000
address claimCurrency;
}
DelegateErrorReason
enum DelegateErrorReason {
TRANSFER_FAILURE,
INVALID_PERCENTAGE,
ALREADY_DEPOSITED_FUNDS
}
Delegatable
Inherits: IERC165, PoolMetadata
Author: Mure
Interface for Delegate core with support for ERC-165 detection.
Functions
beforeDeposit
function beforeDeposit(string calldata poolName, uint256 amount, address depositor, bytes memory sig) external;
afterDeposit
function afterDeposit(string calldata poolName, uint256 amount, address depositor, bytes memory sig) external;
beforeRefund
function beforeRefund(string calldata poolName, address depositor) external;
afterRefund
function afterRefund(string calldata poolName, address depositor, uint256 amount) external;
withdrawPoolFunds
function withdrawPoolFunds(string calldata poolName) external;
depositPoolFunds
function depositPoolFunds(string calldata poolName, uint256 refundFunds, uint256 claimFunds) external;
deposit
function deposit(string calldata poolName, DepositArgs calldata depositArgs) external;
refund
function refund(string calldata poolName) external;
refund
function refund(string calldata poolName, address depositor, uint256 amount) external;
claim
function claim(string calldata poolName) external;
sendFunds
function sendFunds(address to, uint256 amount, address currency) external;
poolConfig
function poolConfig(string calldata poolName) external view returns (PoolConfig memory);
poolAddress
function poolAddress() external view returns (address);
deposited
function deposited(string calldata poolName, address depositor) external view returns (uint256);
getClaimCurrency
function getClaimCurrency(string calldata poolName) external view returns (address);
Events
PoolFundsDeposit
event PoolFundsDeposit(string poolName, uint256 indexed refundFunds, uint256 indexed claimFunds);
FundTransfer
event FundTransfer(address indexed to, uint256 indexed amount, address indexed currency);
ConfigUpdate
event ConfigUpdate(string poolName);
PoolContractUpdate
event PoolContractUpdate(address indexed poolContract);
Errors
PluginDisabled
error PluginDisabled(uint16 plugin);
PluginEnabled
error PluginEnabled(uint16 plugin);
InvalidAmount
error InvalidAmount();
DelegateError
error DelegateError(DelegateErrorReason reason);
DepositArgs
Structure of deposit arguments
struct DepositArgs {
address depositor;
address payer; // @dev Deprecated, to be removed. The caller is now always the payer
uint256 amount;
bytes data;
FeeConfig feeConfig;
bytes depositSig;
bytes permitSig;
}
DepositRecord
Structure of a deposit
struct DepositRecord {
uint112 amount;
uint8 nonce;
}
FeeConfig
Structure of fee configuration
struct FeeConfig {
uint112 amount;
address recipient;
}
DepositPermit
Structure of a deposit permit
Deprecated, to be removed. The caller is now always the payer. With tightened constraints permit is not necessary
struct DepositPermit {
address depositor;
address caller;
uint256 amount;
string poolName;
}
Depositable
Author: Mure
Interface for deposit functionality of pools.
Functions
deposit
function deposit(string calldata poolName, DepositArgs calldata depositDetails) external;
deposited
function deposited(string calldata poolName, address depositor) external view returns (uint256);
Events
Deposit
event Deposit(string poolName, uint256 indexed amount, address indexed from, uint8 indexed nonce, bytes data);
Distributable
Functions
distribute
function distribute(DistributionRecord calldata distribution, bytes calldata signature) external;
distribute
function distribute(DistributionRecord calldata distribution, address to, bytes calldata signature) external;
moveDistribution
function moveDistribution(address source, string calldata poolName, address from, address to) external;
distribution
function distribution(address source, string calldata poolName, address depositor)
external
view
returns (DistributionHistory memory);
nonce
function nonce(address depositor) external view returns (uint24);
Events
Move
event Move(address indexed source, address indexed from, address indexed to, string poolName);
Distribution
event Distribution(
address indexed token,
address indexed source,
address indexed depositor,
address repository,
string poolName,
uint256 amount
);
Errors
UnsupportedSource
error UnsupportedSource();
UnsupportedToken
error UnsupportedToken();
Undistributed
error Undistributed();
Structs
DistributionRecord
struct DistributionRecord {
address token;
address source;
address repository;
address depositor;
string poolName;
uint256 amount;
uint256 deadline;
}
DistributionHistory
struct DistributionHistory {
uint256 distributed;
}
IERC165
Interface of the ERC165 standard, as defined in the https://eips.ethereum.org/EIPS/eip-165[EIP]. Implementers can declare support of contract interfaces, which can then be queried by others ({ERC165Checker}). For an implementation, see {ERC165}.
Functions
supportsInterface
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[EIP 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);
IERC721Metadata
Functions
name
function name() external view returns (string memory);
symbol
function symbol() external view returns (string memory);
tokenURI
function tokenURI(uint256 tokenId) external view returns (string memory);
IERC20Burnable
Inherits: IERC20
Author: Mure
Interface for IERC20Burnable token extension by Openzeppelin.
Functions
burn
Destroys a value amount of tokens from the caller.
See ERC20-_burn.
function burn(uint256 value) external;
burnFrom
Destroys a value amount of tokens from account, deducting from
the caller’s allowance.
See ERC20-_burn and ERC20-allowance.
Requirements:
- the caller must have allowance for
accounts’s tokens of at leastvalue.
function burnFrom(address account, uint256 value) external;
PoolApp
Inherits: IERC165, Poolable, Depositable, Refundable, PoolMetadata
Author: Mure
Interface for MurePool core with support for ERC-165 detection.
Functions
withdrawPoolFunds
function withdrawPoolFunds(string calldata poolName) external;
refundTo
function refundTo(string calldata poolName, address depositor, uint256 amount) external;
nonce
function nonce(string calldata poolName, address depositor) external view returns (uint8);
updatePoolPaused
function updatePoolPaused(string calldata poolName, bool pause) external;
updatePoolRefundable
function updatePoolRefundable(string calldata poolName, bool refundable) external;
depositPoolFunds
function depositPoolFunds(string calldata poolName, address depositor, uint256 amount) external;
Structs
Transaction
struct Transaction {
address depositor;
uint112 amount;
Operation operation;
}
TransactionWithMetadata
struct TransactionWithMetadata {
address depositor;
uint112 amount;
Operation operation;
bytes data;
}
Enums
Operation
enum Operation {
Deposit,
Withdrawal
}
PoolState
Structure of a pool
struct PoolState {
uint112 totalCollected;
uint112 poolSize;
uint16 flags;
uint16 depositors;
uint32 endTime; // uint32 => year 2106
address currency;
address custodian;
address signer;
}
PoolMetadata
Author: Mure
Interface for pool information like its state and existence
Functions
isPoolActive
function isPoolActive(string calldata poolName) external view returns (bool);
poolExists
function poolExists(string calldata pool) external view returns (bool);
poolState
function poolState(string calldata poolName) external view returns (PoolState memory);
withdrawableAmount
function withdrawableAmount(string calldata poolName) external view returns (uint112);
PoolParameters
Structure of parameters of a pool
struct PoolParameters {
uint112 poolSize;
uint32 endTime; // uint32 => year 2106
uint16 flags;
address currency;
address custodian;
address signer;
}
PoolMetrics
Structure for pool metrics. Could be updated in future
struct PoolMetrics {
uint112 totalWithdrawn;
}
PoolParameter
enum PoolParameter {
POOL_SIZE,
END_TIME, // UINT32 => YEAR 2106
FLAGS,
DEPOSITORS,
CURRENCY,
CUSTODIAN,
SIGNER
}
PoolErrorReason
enum PoolErrorReason {
POOL_SIZE_TOO_SMALL,
TRANSFER_FAILURE,
ARITHMETIC_OUT_OF_BOUNDS,
ALREADY_INVESTED_POOL,
INVALID_POOL_TYPE,
POOL_EMPTY
}
Poolable
Author: Mure
Interface for pool administration functionality and pool errors.
Functions
createPool
function createPool(string calldata poolName, PoolParameters calldata params, bytes calldata sig) external;
updatePool
function updatePool(string calldata poolName, PoolParameters calldata params) external;
poolMetrics
function poolMetrics(string calldata poolName) external view returns (PoolMetrics memory);
Events
PoolCreation
event PoolCreation(string poolName);
PoolUpdate
event PoolUpdate(string poolName);
Withdrawal
event Withdrawal(string poolName, uint256 indexed amount, address indexed to, uint8 indexed nonce, bytes data);
ConsumeDepositorNonce
event ConsumeDepositorNonce(string poolName, address indexed depositor, uint8 nonce);
FundWithdrawal
event FundWithdrawal(string poolName, uint256 indexed amount, address indexed to, bytes data);
Errors
PoolClosed
error PoolClosed();
PoolOpen
error PoolOpen();
PoolError
error PoolError(PoolErrorReason reason);
IllegalPoolState
error IllegalPoolState(PoolParameter param);
IllegalPoolOperation
error IllegalPoolOperation(PoolErrorReason reason);
PoolInitialized
error PoolInitialized();
PoolFull
error PoolFull();
PoolPaused
error PoolPaused();
PoolNotEmpty
error PoolNotEmpty();
Refundable
Author: Mure
Interface for refund fuctionality for pools with support for ERC-165 detection.
Functions
refund
function refund(string calldata poolName) external;
updatePoolRefundable
function updatePoolRefundable(string calldata poolName, bool refundable) external;
Events
Refund
event Refund(string poolName, uint256 indexed amount, address indexed depositor, bytes data);
Errors
DepositNotFound
error DepositNotFound();
Contents
MureErrors
Author: Mure
Library with global errors for Mure
Errors
InvalidAddress
thrown when address is invalid, eg: zero address
error InvalidAddress(address addr);
SignatureExpired
thrown when a signature has expired before verification
error SignatureExpired();
Unauthorized
thrown when any restricted operation is performed by an unauthorized entity
error Unauthorized();
InvalidDelegate
thrown when address is not a valid delegate
error InvalidDelegate();
PoolNotFound
thrown when pool with given parameters is not found
error PoolNotFound();
InvalidFee
thrown when fee is invalid
error InvalidFee();
NoAdmin
thrown when no member has a DEFAULT_ADMIN_ROLE role
error NoAdmin();
Contents
- mayan
- AxlOwnable
- Upgradable
- MockAxelarGasService
- MockAxelarGateway
- ERC20BurnableMock
- ERC20Mock
- ETHReceiverMock
- MockRelayerV2
- MockERC20
Contents
- interfaces
- libraries
- utils
- FastMCTP
- MayanCircle
- MockFeeManager
- MockMessageTransmitter
- MockTokenMessenger
- MockTokenMessengerV2
- MockTokenMinter
- MockWormhole
- SwiftDest
Contents
IFeeManager
Functions
feeCollector
function feeCollector() external view returns (address);
depositFee
function depositFee(address relayer, address token, uint256 amount) external;
calcProtocolBps
function calcProtocolBps(uint64 amount, address tokenIn, bytes32 tokenOut, uint16 destChain, uint8 referrerBps)
external
view
returns (uint8);
IMessageTransmitter
Functions
receiveMessage
function receiveMessage(bytes memory message, bytes calldata attestation) external returns (bool success);
localDomain
function localDomain() external view returns (uint32);
ITokenMinter
Functions
getLocalToken
function getLocalToken(uint32 remoteDomain, bytes32 remoteToken) external view returns (address localToken);
ITokenMessenger
Functions
localMessageTransmitter
function localMessageTransmitter() external view returns (IMessageTransmitter);
localMinter
function localMinter() external view returns (ITokenMinter);
depositForBurn
function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken)
external
returns (uint64 nonce);
depositForBurnWithCaller
function depositForBurnWithCaller(
uint256 amount,
uint32 destinationDomain,
bytes32 mintRecipient,
address burnToken,
bytes32 destinationCaller
) external returns (uint64 nonce);
ITokenMessengerV2
Functions
localMessageTransmitter
function localMessageTransmitter() external view returns (IMessageTransmitter);
localMinter
function localMinter() external view returns (ITokenMinter);
depositForBurnWithHook
function depositForBurnWithHook(
uint256 amount,
uint32 destinationDomain,
bytes32 mintRecipient,
address burnToken,
bytes32 destinationCaller,
uint256 maxFee,
uint32 minFinalityThreshold,
bytes memory hookData
) external returns (uint64 nonce);
IWormhole
Functions
chainId
function chainId() external view returns (uint16);
messageFee
function messageFee() external view returns (uint256);
parseAndVerifyVM
function parseAndVerifyVM(bytes calldata encodedVM)
external
view
returns (VM memory vm, bool valid, string memory reason);
publishMessage
function publishMessage(uint32 nonce, bytes memory payload, uint8 consistencyLevel)
external
payable
returns (uint64 sequence);
Structs
VM
struct VM {
uint8 version;
uint32 timestamp;
uint32 nonce;
uint16 emitterChainId;
bytes32 emitterAddress;
uint64 sequence;
uint8 consistencyLevel;
bytes payload;
bytes32 txHash;
uint32 guardianSetIndex;
bytes signatures;
bytes32 hash;
}
Contents
BytesLib
Functions
toUint8
function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8);
toUint16
function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16);
toUint32
function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32);
toUint64
function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64);
toUint256
function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256);
toBytes32
function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32);
concat
function concat(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory);
Contents
- InvalidEmitterChain
- InvalidEmitterAddress
- InvalidOrderHash
- Unauthorized
- DeadlineViolation
- InvalidOrderStatus
- InsufficientAmount
- InvalidAmount
- InvalidWormholeFee
- InvalidGasDrop
- InvalidAction
- InvalidEvmAddr
- OrderNotExists
- InvalidAuctionConfig
- EmitterAddressExists
- SequenceAlreadyUsed
- InvalidSrcChain
- InvalidAuctionMode
- Status
- Action
- AuctionMode
- Order
- OrderParams
- ExtraParams
- Key
- UnlockMsg
- RefundMsg
- RescueMsg
- FulfillMsg
- PaymentParams
- PermitParams
- UnlockParams
- SwiftStructs constants
InvalidEmitterChain
error InvalidEmitterChain();
InvalidEmitterAddress
error InvalidEmitterAddress();
InvalidOrderHash
error InvalidOrderHash();
Unauthorized
error Unauthorized();
DeadlineViolation
error DeadlineViolation();
InvalidOrderStatus
error InvalidOrderStatus();
InsufficientAmount
error InsufficientAmount();
InvalidAmount
error InvalidAmount();
InvalidWormholeFee
error InvalidWormholeFee();
InvalidGasDrop
error InvalidGasDrop();
InvalidAction
error InvalidAction();
InvalidEvmAddr
error InvalidEvmAddr();
OrderNotExists
error OrderNotExists(bytes32 orderHash);
InvalidAuctionConfig
error InvalidAuctionConfig();
EmitterAddressExists
error EmitterAddressExists();
SequenceAlreadyUsed
error SequenceAlreadyUsed();
InvalidSrcChain
error InvalidSrcChain();
InvalidAuctionMode
error InvalidAuctionMode();
Status
enum Status {
NONE,
CREATED,
FULFILLED,
SETTLED,
CANCELED,
REFUNDED
}
Action
enum Action {
NONE,
SWAP,
FULFILL,
UNLOCK,
COMPRESSED_UNLOCK,
REFUND,
RESCUE
}
AuctionMode
enum AuctionMode {
NONE,
LIMIT_ORDER,
DUTCH_AUCTION
}
Order
struct Order {
Status status;
uint256 fulfilledAmount;
uint256 createdAt;
}
OrderParams
struct OrderParams {
uint8 payloadType;
bytes32 trader;
uint16 destChainId;
bytes32 destAddr;
bytes32 tokenOut;
uint64 minAmountOut;
uint64 gasDrop;
uint64 cancelFee;
uint64 refundFee;
uint64 deadline;
bytes32 referrerAddr;
uint8 referrerBps;
uint8 auctionMode;
bytes32 random;
}
ExtraParams
struct ExtraParams {
uint16 srcChainId;
bytes32 tokenIn;
uint8 protocolBps;
bytes32 customPayloadHash;
}
Key
struct Key {
uint8 payloadType;
bytes32 trader;
uint16 srcChainId;
bytes32 tokenIn;
bytes32 destAddr;
uint16 destChainId;
bytes32 tokenOut;
uint64 minAmountOut;
uint64 gasDrop;
uint64 cancelFee;
uint64 refundFee;
uint64 deadline;
bytes32 referrerAddr;
uint8 referrerBps;
uint8 protocolBps;
uint8 auctionMode;
bytes32 random;
bytes32 customPayloadHash;
}
UnlockMsg
struct UnlockMsg {
uint8 action;
bytes32 orderHash;
uint16 srcChainId;
bytes32 tokenIn;
bytes32 referrerAddr;
uint8 referrerBps;
uint8 protocolBps;
bytes32 unlockReceiver;
bytes32 driver;
uint64 fulfillTime;
}
RefundMsg
struct RefundMsg {
uint8 action;
bytes32 orderHash;
uint16 srcChainId;
bytes32 tokenIn;
bytes32 trader;
bytes32 canceler;
uint64 cancelFee;
uint64 refundFee;
}
RescueMsg
struct RescueMsg {
uint8 action;
bytes32 orderHash;
uint8 orderStatus;
address token;
uint64 amount;
uint16 chainId;
}
FulfillMsg
struct FulfillMsg {
uint8 action;
bytes32 orderHash;
uint64 promisedAmount;
bytes32 driver;
uint16 penaltyPeriod;
}
PaymentParams
struct PaymentParams {
uint8 payloadType;
bytes32 orderHash;
uint64 promisedAmount;
uint64 minAmountOut;
address destAddr;
address tokenOut;
uint64 gasDrop;
bool batch;
}
PermitParams
struct PermitParams {
uint256 value;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
UnlockParams
struct UnlockParams {
bytes32 recipient;
bytes32 driver;
bool batch;
}
Constants
UNLOCK_MSG_SIZE
uint256 constant UNLOCK_MSG_SIZE = 161
FastMCTP
Inherits: ReentrancyGuard
Constants
ETH_DECIMALS
uint8 internal constant ETH_DECIMALS = 18
CCTPV2_SOURCE_DOMAIN_INDEX
uint256 internal constant CCTPV2_SOURCE_DOMAIN_INDEX = 4
CCTPV2_DESTINATION_DOMAIN_INDEX
uint256 internal constant CCTPV2_DESTINATION_DOMAIN_INDEX = 8
CCTPV2_NONCE_INDEX
uint256 internal constant CCTPV2_NONCE_INDEX = 12
CCTPV2_DETINATION_CALLER_INDEX
uint256 internal constant CCTPV2_DETINATION_CALLER_INDEX = 108
CCTPV2_MESSAGE_BODY_INDEX
uint256 internal constant CCTPV2_MESSAGE_BODY_INDEX = 148
CCTPV2_SOURCE_TOKEN_INDEX
uint256 internal constant CCTPV2_SOURCE_TOKEN_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 4
CCTPV2_MINT_RECIPIENT_INDEX
uint256 internal constant CCTPV2_MINT_RECIPIENT_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 36
HOOK_DATA_INDEX
uint256 internal constant HOOK_DATA_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 228
GAS_LIMIT_FEE_MANAGER
uint256 internal constant GAS_LIMIT_FEE_MANAGER = 1000000
State Variables
cctpTokenMessengerV2
ITokenMessengerV2 public cctpTokenMessengerV2
feeManager
address public feeManager
guardian
address public guardian
paused
bool public paused
whitelistedSwapProtocols
mapping(address => bool) public whitelistedSwapProtocols
whitelistedMsgSenders
mapping(address => bool) public whitelistedMsgSenders
Functions
checkRecipient
modifier checkRecipient(bytes memory cctpMsg) ;
whenNotPaused
modifier whenNotPaused() ;
constructor
constructor(address _cctpTokenMessengerV2, address _feeManager) ;
setCctpTokenMessengerV2
function setCctpTokenMessengerV2(address _cctpTokenMessengerV2) external;
setFeeManager
function setFeeManager(address _feeManager) external;
bridge
function bridge(
address tokenIn,
uint256 amountIn,
uint64 redeemFee,
uint256 circleMaxFee,
uint64 gasDrop,
bytes32 destAddr,
uint32 destDomain,
bytes32 referrerAddress,
uint8 referrerBps,
uint8 payloadType,
uint32 minFinalityThreshold,
bytes memory customPayload
) external nonReentrant whenNotPaused;
createOrder
function createOrder(
address tokenIn,
uint256 amountIn,
uint256 circleMaxFee,
uint32 destDomain,
uint32 minFinalityThreshold,
OrderPayload memory orderPayload
) external nonReentrant whenNotPaused;
fulfillOrder
function fulfillOrder(bytes memory cctpMsg, bytes memory cctpSigs, address swapProtocol, bytes memory swapData)
external
payable
nonReentrant
checkRecipient(cctpMsg);
refund
function refund(bytes memory cctpMsg, bytes memory cctpSigs) external payable nonReentrant checkRecipient(cctpMsg);
setMintRecipient
function setMintRecipient(uint32 destDomain, address tokenIn, bytes32 mintRecipient) public;
setDomainCallers
function setDomainCallers(uint32 domain, bytes32 caller) public;
setWhitelistedSwapProtocols
function setWhitelistedSwapProtocols(address protocol, bool isWhitelisted) public;
setWhitelistedMsgSenders
function setWhitelistedMsgSenders(address sender, bool isWhitelisted) public;
setPause
function setPause(bool _pause) public;
changeGuardian
function changeGuardian(address newGuardian) public;
claimGuardian
function claimGuardian() public;
rescueToken
function rescueToken(address token, uint256 amount, address to) public;
rescueEth
function rescueEth(uint256 amount, address payable to) public;
rescueRedeem
function rescueRedeem(bytes memory cctpMsg, bytes memory cctpSigs) public;
redeem
function redeem(bytes memory cctpMsg, bytes memory cctpSigs) external payable nonReentrant checkRecipient(cctpMsg);
receiveCctp
function receiveCctp(bytes memory cctpMsg, bytes memory cctpSigs) internal returns (address, uint256);
recreateBridgePayload
function recreateBridgePayload(bytes memory cctpMsg) internal pure returns (BridgePayload memory);
safeCalcFastMCTPProtocolBps
function safeCalcFastMCTPProtocolBps(
uint8 payloadType,
address localToken,
uint256 cctpAmount,
address tokenOut,
address referrerAddr,
uint8 referrerBps
) internal returns (uint8);
safeGetFeeCollector
function safeGetFeeCollector() internal view returns (address);
depositRelayerFee
function depositRelayerFee(address relayer, address token, uint256 amount) internal;
deNormalizeAmount
function deNormalizeAmount(uint256 amount, uint8 decimals) internal pure returns (uint256);
payEth
function payEth(address to, uint256 amount, bool revertOnFailure) internal;
truncateAddress
function truncateAddress(bytes32 b) internal pure returns (address);
receive
receive() external payable;
Events
OrderFulfilled
event OrderFulfilled(uint32 sourceDomain, bytes32 sourceNonce, uint256 amount);
OrderRefunded
event OrderRefunded(uint32 sourceDomain, bytes32 sourceNonce, uint256 amount);
Errors
Paused
error Paused();
Unauthorized
error Unauthorized();
CctpReceiveFailed
error CctpReceiveFailed();
InvalidGasDrop
error InvalidGasDrop();
InvalidMintRecipient
error InvalidMintRecipient();
InvalidRedeemFee
error InvalidRedeemFee();
InvalidPayload
error InvalidPayload();
DeadlineViolation
error DeadlineViolation();
InvalidAddress
error InvalidAddress();
InvalidPayloadType
error InvalidPayloadType();
EthTransferFailed
error EthTransferFailed();
InvalidAmountOut
error InvalidAmountOut();
MintRecipientNotSet
error MintRecipientNotSet();
CallerNotSet
error CallerNotSet();
InvalidRefundFee
error InvalidRefundFee();
AlreadySet
error AlreadySet();
UnauthorizedSwapProtocol
error UnauthorizedSwapProtocol();
UnauthorizedMsgSender
error UnauthorizedMsgSender();
Structs
BridgePayload
struct BridgePayload {
uint8 payloadType;
bytes32 destAddr;
uint64 gasDrop;
uint64 redeemFee;
bytes32 referrerAddr;
uint8 referrerBps;
bytes32 customPayload;
}
OrderPayload
struct OrderPayload {
uint8 payloadType;
bytes32 destAddr;
bytes32 tokenOut;
uint64 amountOutMin;
uint64 gasDrop;
uint64 redeemFee;
uint64 refundFee;
uint64 deadline;
bytes32 referrerAddr;
uint8 referrerBps;
}
MayanCircle
Inherits: ReentrancyGuard
Constants
ETH_DECIMALS
uint8 constant ETH_DECIMALS = 18
CCTP_DOMAIN_INDEX
uint256 constant CCTP_DOMAIN_INDEX = 4
CCTP_NONCE_INDEX
uint256 constant CCTP_NONCE_INDEX = 12
CCTP_TOKEN_INDEX
uint256 constant CCTP_TOKEN_INDEX = 120
CCTP_RECIPIENT_INDEX
uint256 constant CCTP_RECIPIENT_INDEX = 152
CCTP_AMOUNT_INDEX
uint256 constant CCTP_AMOUNT_INDEX = 208
State Variables
wormhole
IWormhole public wormhole
cctpTokenMessenger
ITokenMessenger public cctpTokenMessenger
feeManager
IFeeManager public feeManager
localDomain
uint32 public localDomain
auctionChainId
uint16 public auctionChainId
auctionAddr
bytes32 public auctionAddr
consistencyLevel
uint8 public consistencyLevel
guardian
address public guardian
paused
bool public paused
chainIdToEmitter
mapping(uint16 => bytes32) public chainIdToEmitter
Functions
constructor
constructor(
address _cctpTokenMessenger,
address _wormhole,
address _feeManager,
uint16 _auctionChainId,
bytes32 _auctionAddr,
uint8 _consistencyLevel
) ;
setWormhole
function setWormhole(address _wormhole) external;
setCctpTokenMessenger
function setCctpTokenMessenger(address _cctpTokenMessenger) external;
setFeeManager
function setFeeManager(address _feeManager) external;
bridgeWithFee
function bridgeWithFee(
address tokenIn,
uint256 amountIn,
uint64 redeemFee,
uint64 gasDrop,
bytes32 destAddr,
uint32 destDomain,
uint8 payloadType,
bytes memory customPayload
) external payable nonReentrant returns (uint64 sequence);
bridgeWithLockedFee
function bridgeWithLockedFee(
address tokenIn,
uint256 amountIn,
uint64 gasDrop,
uint256 redeemFee,
uint32 destDomain,
bytes32 destAddr
) external nonReentrant returns (uint64 cctpNonce);
createOrder
function createOrder(OrderParams memory params) external payable nonReentrant returns (uint64 sequence);
redeemWithLockedFee
function redeemWithLockedFee(bytes memory cctpMsg, bytes memory cctpSigs, bytes32 unlockerAddr)
external
payable
nonReentrant
returns (uint64 sequence);
refineFee
function refineFee(uint32 cctpNonce, uint32 cctpDomain, bytes32 destAddr, bytes32 unlockerAddr)
external
payable
nonReentrant
returns (uint64 sequence);
unlockFee
function unlockFee(bytes memory encodedVm, UnlockFeeMsg memory unlockMsg) external nonReentrant;
unlockFeeRefined
function unlockFeeRefined(
bytes memory encodedVm1,
bytes memory encodedVm2,
UnlockFeeMsg memory unlockMsg,
UnlockRefinedFeeMsg memory refinedMsg
) external nonReentrant;
fulfillOrder
function fulfillOrder(
bytes memory cctpMsg,
bytes memory cctpSigs,
bytes memory encodedVm,
FulfillParams memory params,
address swapProtocol,
bytes memory swapData
) external payable nonReentrant;
refund
function refund(
bytes memory encodedVm,
bytes memory cctpMsg,
bytes memory cctpSigs,
OrderParams memory orderParams,
ExtraParams memory extraParams
) external payable nonReentrant;
setMintRecipient
function setMintRecipient(uint32 destDomain, address tokenIn, bytes32 mintRecipient) public;
setDomainCallers
function setDomainCallers(uint32 domain, bytes32 caller) public;
setEmitter
function setEmitter(uint16 chainId, bytes32 emitter) public;
setDomains
function setDomains(uint16[] memory chainIds, uint32[] memory domains) public;
setConsistencyLevel
function setConsistencyLevel(uint8 _consistencyLevel) public;
setPause
function setPause(bool _pause) public;
rescueToken
function rescueToken(address token, uint256 amount, address to) public;
rescueEth
function rescueEth(uint256 amount, address payable to) public;
changeGuardian
function changeGuardian(address newGuardian) public;
claimGuardian
function claimGuardian() public;
calculatePayloadHashForTest
Debug function to calculate payload hash for testing
This allows tests to compare their hash calculation with the contract’s
function calculatePayloadHashForTest(bytes memory cctpMsg, BridgeWithFeeParams memory bridgeParams)
public
pure
returns (bytes32);
recreateBridgeWithFeeForTest
Debug function to recreate bridge message for testing
function recreateBridgeWithFeeForTest(BridgeWithFeeParams memory bridgeParams, bytes memory cctpMsg)
public
pure
returns (BridgeWithFeeMsg memory);
encodeBridgeWithFeeForTest
Debug function to encode bridge message for testing
function encodeBridgeWithFeeForTest(BridgeWithFeeMsg memory bridgeMsg) public pure returns (bytes memory);
redeemWithFee
function redeemWithFee(
bytes memory cctpMsg,
bytes memory cctpSigs,
bytes memory encodedVm,
BridgeWithFeeParams memory bridgeParams
) external payable nonReentrant;
receiveCctp
function receiveCctp(bytes memory cctpMsg, bytes memory cctpSigs) internal returns (address, uint256);
validateEmitter
function validateEmitter(bytes32 emitter, uint16 chainId) internal view;
recreateBridgeWithFee
function recreateBridgeWithFee(BridgeWithFeeParams memory bridgeParams, bytes memory cctpMsg)
internal
pure
returns (BridgeWithFeeMsg memory);
encodeBridgeWithFee
function encodeBridgeWithFee(BridgeWithFeeMsg memory bridgeMsg) internal pure returns (bytes memory);
depositRelayerFee
function depositRelayerFee(address relayer, address token, uint256 amount) internal;
deNormalizeAmount
function deNormalizeAmount(uint256 amount, uint8 decimals) internal pure returns (uint256);
payEth
function payEth(address to, uint256 amount, bool revertOnFailure) internal;
truncateAddress
function truncateAddress(bytes32 b) internal pure returns (address);
receive
receive() external payable;
Events
OrderFulfilled
event OrderFulfilled(uint32 sourceDomain, uint64 sourceNonce, uint256 amount);
OrderRefunded
event OrderRefunded(uint32 sourceDomain, uint64 sourceNonce, uint256 amount);
Errors
Paused
error Paused();
Unauthorized
error Unauthorized();
InvalidDomain
error InvalidDomain();
InvalidNonce
error InvalidNonce();
InvalidOrder
error InvalidOrder();
CctpReceiveFailed
error CctpReceiveFailed();
InvalidGasDrop
error InvalidGasDrop();
InvalidAction
error InvalidAction();
InvalidEmitter
error InvalidEmitter();
EmitterAlreadySet
error EmitterAlreadySet();
InvalidDestAddr
error InvalidDestAddr();
InvalidMintRecipient
error InvalidMintRecipient();
InvalidRedeemFee
error InvalidRedeemFee();
InvalidPayload
error InvalidPayload();
CallerNotSet
error CallerNotSet();
MintRecipientNotSet
error MintRecipientNotSet();
InvalidCaller
error InvalidCaller();
DeadlineViolation
error DeadlineViolation();
InvalidAddress
error InvalidAddress();
InvalidReferrerFee
error InvalidReferrerFee();
InvalidProtocolFee
error InvalidProtocolFee();
EthTransferFailed
error EthTransferFailed();
InvalidAmountOut
error InvalidAmountOut();
DomainNotSet
error DomainNotSet();
AlreadySet
error AlreadySet();
Structs
BridgeWithFeeParams
struct BridgeWithFeeParams {
uint8 payloadType;
bytes32 destAddr;
uint64 gasDrop;
uint64 redeemFee;
uint64 burnAmount;
bytes32 burnToken;
bytes32 customPayload;
}
BridgeWithFeeMsg
struct BridgeWithFeeMsg {
uint8 action;
uint8 payloadType;
uint64 cctpNonce;
uint32 cctpDomain;
bytes32 destAddr;
uint64 gasDrop;
uint64 redeemFee;
uint64 burnAmount;
bytes32 burnToken;
bytes32 customPayload;
}
OrderParams
struct OrderParams {
address tokenIn;
uint256 amountIn;
uint64 gasDrop;
bytes32 destAddr;
uint16 destChain;
bytes32 tokenOut;
uint64 minAmountOut;
uint64 deadline;
uint64 redeemFee;
bytes32 referrerAddr;
uint8 referrerBps;
}
ExtraParams
struct ExtraParams {
bytes32 trader;
uint16 sourceChainId;
uint8 protocolBps;
}
UnlockFeeMsg
struct UnlockFeeMsg {
uint8 action;
uint8 payloadType;
uint64 cctpNonce;
uint32 cctpDomain;
bytes32 unlockerAddr;
uint64 gasDrop;
}
UnlockRefinedFeeMsg
struct UnlockRefinedFeeMsg {
uint8 action;
uint8 payloadType;
uint64 cctpNonce;
uint32 cctpDomain;
bytes32 unlockerAddr;
uint64 gasDrop;
bytes32 destAddr;
}
FulfillParams
struct FulfillParams {
bytes32 destAddr;
uint16 destChainId;
bytes32 tokenOut;
uint64 promisedAmount;
uint64 gasDrop;
uint64 redeemFee;
uint64 deadline;
bytes32 referrerAddr;
uint8 referrerBps;
uint8 protocolBps;
bytes32 driver;
}
Enums
Action
enum Action {
NONE,
SWAP,
FULFILL,
BRIDGE_WITH_FEE,
UNLOCK_FEE,
UNLOCK_FEE_REFINE
}
MockFeeManager
Inherits: IFeeManager
Title: MockFeeManager
Mock implementation of IFeeManager for testing Mayan contracts
Handles fee calculations and deposits with configurable values
State Variables
_feeCollector
address public _feeCollector
_defaultProtocolBps
uint8 public _defaultProtocolBps
protocolBps
mapping(address => mapping(bytes32 => mapping(uint16 => uint8))) public protocolBps
Functions
constructor
constructor(address feeCollector_, uint8 defaultProtocolBps_) ;
feeCollector
Get the fee collector address
function feeCollector() external view returns (address);
depositFee
Deposit fee for a relayer
function depositFee(address relayer, address token, uint256 amount) external;
Parameters
| Name | Type | Description |
|---|---|---|
relayer | address | The relayer address |
token | address | The token address |
amount | uint256 | The fee amount |
calcProtocolBps
Calculate protocol basis points for MayanCircle
function calcProtocolBps(uint64 amount, address tokenIn, bytes32 tokenOut, uint16 destChain, uint8 referrerBps)
external
view
returns (uint8);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint64 | The transaction amount |
tokenIn | address | The input token |
tokenOut | bytes32 | The output token (bytes32) |
destChain | uint16 | The destination chain |
referrerBps | uint8 | The referrer basis points |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | The protocol basis points |
calcFastMCTPProtocolBps
Calculate protocol basis points for FastMCTP
function calcFastMCTPProtocolBps(
uint8 payloadType,
address localToken,
uint256 cctpAmount,
address tokenOut,
address referrerAddr,
uint8 referrerBps
) external view returns (uint8);
Parameters
| Name | Type | Description |
|---|---|---|
payloadType | uint8 | The payload type |
localToken | address | The local token |
cctpAmount | uint256 | The CCTP amount |
tokenOut | address | The output token |
referrerAddr | address | The referrer address |
referrerBps | uint8 | The referrer basis points |
Returns
| Name | Type | Description |
|---|---|---|
<none> | uint8 | The protocol basis points |
setProtocolBps
Set protocol basis points for a specific configuration (testing only)
function setProtocolBps(address tokenIn, bytes32 tokenOut, uint16 destChain, uint8 bps) external;
setFeeCollector
Set the fee collector (testing only)
function setFeeCollector(address newFeeCollector) external;
setDefaultProtocolBps
Set the default protocol basis points (testing only)
function setDefaultProtocolBps(uint8 newBps) external;
rescueTokens
Rescue tokens from this contract (testing only)
function rescueTokens(address token, address to, uint256 amount) external;
MockMessageTransmitter
Inherits: IMessageTransmitter
Title: MockMessageTransmitter
Mock implementation of IMessageTransmitter for testing CCTP
Receives CCTP messages and mints tokens to the recipient
Constants
CCTP_DOMAIN_INDEX
uint256 constant CCTP_DOMAIN_INDEX = 4
CCTP_NONCE_INDEX
uint256 constant CCTP_NONCE_INDEX = 12
CCTP_TOKEN_INDEX
uint256 constant CCTP_TOKEN_INDEX = 120
CCTP_RECIPIENT_INDEX
uint256 constant CCTP_RECIPIENT_INDEX = 152
CCTP_AMOUNT_INDEX
uint256 constant CCTP_AMOUNT_INDEX = 208
CCTPV2_MESSAGE_BODY_INDEX
uint256 constant CCTPV2_MESSAGE_BODY_INDEX = 148
CCTPV2_SOURCE_TOKEN_INDEX
uint256 constant CCTPV2_SOURCE_TOKEN_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 4
CCTPV2_MINT_RECIPIENT_INDEX
uint256 constant CCTPV2_MINT_RECIPIENT_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 36
CCTPV2_AMOUNT_INDEX
uint256 constant CCTPV2_AMOUNT_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 68
HOOK_DATA_INDEX
uint256 constant HOOK_DATA_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 228
State Variables
_localDomain
uint32 public _localDomain
tokenMinter
address public tokenMinter
Functions
constructor
constructor(uint32 localDomain_, address tokenMinter_) ;
receiveMessage
Receive and process a CCTP message
function receiveMessage(bytes memory message, bytes calldata attestation) external returns (bool success);
Parameters
| Name | Type | Description |
|---|---|---|
message | bytes | The CCTP message bytes |
attestation | bytes | The attestation signatures (ignored in mock) |
Returns
| Name | Type | Description |
|---|---|---|
success | bool | Always returns true for valid messages |
localDomain
Get the local domain
function localDomain() external view returns (uint32);
setLocalDomain
Set the local domain (testing only)
function setLocalDomain(uint32 newDomain) external;
setTokenMinter
Set the token minter address (testing only)
function setTokenMinter(address newTokenMinter) external;
mintTokens
Direct mint function for testing
function mintTokens(address token, address recipient, uint256 amount) external;
MockTokenMessenger
Inherits: ITokenMessenger
Title: MockTokenMessenger
Mock implementation of ITokenMessenger for testing MayanCircle
Returns references to MockMessageTransmitter and MockTokenMinter
State Variables
_localMessageTransmitter
IMessageTransmitter public _localMessageTransmitter
_localMinter
ITokenMinter public _localMinter
Functions
constructor
constructor(address messageTransmitter, address tokenMinter) ;
localMessageTransmitter
Get the local message transmitter
function localMessageTransmitter() external view returns (IMessageTransmitter);
localMinter
Get the local token minter
function localMinter() external view returns (ITokenMinter);
depositForBurn
Deposit tokens for burn (stub)
function depositForBurn(uint256 amount, uint32 destinationDomain, bytes32 mintRecipient, address burnToken)
external
returns (uint64 nonce);
depositForBurnWithCaller
Deposit tokens for burn with caller (stub)
function depositForBurnWithCaller(
uint256 amount,
uint32 destinationDomain,
bytes32 mintRecipient,
address burnToken,
bytes32 destinationCaller
) external returns (uint64 nonce);
setLocalMessageTransmitter
Set the message transmitter (testing only)
function setLocalMessageTransmitter(address newTransmitter) external;
setLocalMinter
Set the token minter (testing only)
function setLocalMinter(address newMinter) external;
MockTokenMessengerV2
Inherits: ITokenMessengerV2
Title: MockTokenMessengerV2
Mock implementation of ITokenMessengerV2 for testing FastMCTP
Returns references to MockMessageTransmitter and MockTokenMinter
State Variables
_localMessageTransmitter
IMessageTransmitter public _localMessageTransmitter
_localMinter
ITokenMinter public _localMinter
Functions
constructor
constructor(address messageTransmitter, address tokenMinter) ;
localMessageTransmitter
Get the local message transmitter
function localMessageTransmitter() external view returns (IMessageTransmitter);
localMinter
Get the local token minter
function localMinter() external view returns (ITokenMinter);
depositForBurnWithHook
Deposit tokens for burn with hook (stub)
function depositForBurnWithHook(
uint256 amount,
uint32 destinationDomain,
bytes32 mintRecipient,
address burnToken,
bytes32 destinationCaller,
uint256 maxFee,
uint32 minFinalityThreshold,
bytes memory hookData
) external returns (uint64 nonce);
setLocalMessageTransmitter
Set the message transmitter (testing only)
function setLocalMessageTransmitter(address newTransmitter) external;
setLocalMinter
Set the token minter (testing only)
function setLocalMinter(address newMinter) external;
MockTokenMinter
Inherits: ITokenMinter
Title: MockTokenMinter
Mock implementation of ITokenMinter for testing
Manages mappings between remote and local tokens
State Variables
tokenMappings
mapping(uint32 => mapping(bytes32 => address)) public tokenMappings
Functions
getLocalToken
Get the local token address for a remote token
function getLocalToken(uint32 remoteDomain, bytes32 remoteToken) external view returns (address localToken);
Parameters
| Name | Type | Description |
|---|---|---|
remoteDomain | uint32 | The domain of the remote chain |
remoteToken | bytes32 | The token address on the remote chain |
Returns
| Name | Type | Description |
|---|---|---|
localToken | address | The corresponding token address on this chain |
setLocalToken
Set the local token for a remote token (testing only)
function setLocalToken(uint32 remoteDomain, bytes32 remoteToken, address localToken) external;
Parameters
| Name | Type | Description |
|---|---|---|
remoteDomain | uint32 | The domain of the remote chain |
remoteToken | bytes32 | The token address on the remote chain |
localToken | address | The token address on this chain |
MockWormhole
Inherits: IWormhole
Title: MockWormhole
Mock implementation of IWormhole for testing Mayan contracts
Always returns valid=true for parseAndVerifyVM to pass Wormhole validation
State Variables
_chainId
uint16 public _chainId
_messageFee
uint256 public _messageFee
encodedVMToVM
mapping(bytes => VM) public encodedVMToVM
vmValidity
mapping(bytes => bool) public vmValidity
vmReason
mapping(bytes => string) public vmReason
Functions
constructor
constructor(uint16 chainId_, uint256 messageFee_) ;
parseAndVerifyVM
Parse and verify a Wormhole VM - always returns valid for testing
function parseAndVerifyVM(bytes calldata encodedVM)
external
view
returns (VM memory vm, bool valid, string memory reason);
Parameters
| Name | Type | Description |
|---|---|---|
encodedVM | bytes | The encoded VM bytes |
Returns
| Name | Type | Description |
|---|---|---|
vm | VM | The parsed VM struct |
valid | bool | Always returns true for testing |
reason | string | Empty string when valid |
publishMessage
Publish a message (stub implementation)
function publishMessage(uint32 nonce, bytes memory payload, uint8 consistencyLevel)
external
payable
returns (uint64 sequence);
chainId
Get the chain ID
function chainId() external view returns (uint16);
messageFee
Get the message fee
function messageFee() external view returns (uint256);
setChainId
Set the chain ID (for testing)
function setChainId(uint16 newChainId) external;
setMessageFee
Set the message fee (for testing)
function setMessageFee(uint256 newMessageFee) external;
setVMForEncoded
Configure a specific VM result for encoded bytes
function setVMForEncoded(bytes calldata encodedVM, VM calldata vmData, bool valid, string calldata reason)
external;
decodeVM
Decode a VM from encoded bytes
Simple decoding - assumes abi.encoded VM structure
function decodeVM(bytes calldata encodedVM) internal view returns (VM memory);
SwiftDest
Inherits: ReentrancyGuard
State Variables
wormhole
IWormhole public wormhole
guardian
address public guardian
orders
mapping(bytes32 => Order) public orders
pendingAmounts
mapping(bytes32 => uint256) public pendingAmounts
Functions
constructor
constructor(address _wormhole) ;
setWormhole
function setWormhole(address _wormhole) external;
fulfillOrder
function fulfillOrder(
uint256 fulfillAmount,
bytes memory encodedVm,
OrderParams memory params,
ExtraParams memory extraParams,
UnlockParams calldata unlockParams,
PermitParams calldata permit
) public payable nonReentrant returns (bytes memory);
fulfillSimple
function fulfillSimple(
uint256 fulfillAmount,
bytes32 orderHash,
OrderParams memory params,
ExtraParams memory extraParams,
UnlockParams memory unlockParams,
PermitParams calldata permit
) public payable nonReentrant;
cancelOrder
function cancelOrder(bytes32 orderHash, OrderParams memory params, ExtraParams memory extraParams, bytes32 canceler)
public
payable
nonReentrant
returns (uint64 sequence);
postBatch
function postBatch(bytes32[] memory orderHashes) public payable returns (uint64 sequence);
rescue
function rescue(bytes memory encodedVm) public;
setPause
function setPause(bool _pause) public;
setAuctionConfig
function setAuctionConfig(address _auctionVerifier, uint16 _auctionChainId, bytes32 _auctionAddr) public;
setConsistencyLevel
function setConsistencyLevel(uint8 _consistencyLevel) public;
setEmitters
function setEmitters(uint16[] memory chainIds, bytes32[] memory addresses) public;
changeGuardian
function changeGuardian(address newGuardian) public;
claimGuardian
function claimGuardian() public;
getOrders
function getOrders(bytes32[] memory orderHashes) public view returns (Order[] memory);
settleWithPayload
function settleWithPayload(OrderParams memory params, ExtraParams memory extraParams)
public
nonReentrant
returns (uint256 netAmount);
buildKey
function buildKey(OrderParams memory params, ExtraParams memory extraParams)
internal
pure
returns (Key memory key);
encodeKey
function encodeKey(Key memory key) internal pure returns (bytes memory encoded);
truncateAddress
function truncateAddress(bytes32 b) internal pure returns (address);
payEth
function payEth(address to, uint256 amount, bool revertOnFailure) internal;
receive
receive() external payable;
Events
OrderSettled
event OrderSettled(bytes32 key, uint256 netAmount);
AxlOwnable
Inherits: IOwnable
Title: AxlOwnable
A contract module which provides a basic access control mechanism, where there is an account (an owner) that can be granted exclusive access to specific functions. The owner account is set through ownership transfer. This module makes it possible to transfer the ownership of the contract to a new account in one step, as well as to an interim pending owner. In the second flow the ownership does not change until the pending owner accepts the ownership transfer.
Constants
_OWNER_SLOT
bytes32 internal constant _OWNER_SLOT = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0
_OWNERSHIP_TRANSFER_SLOT
bytes32 internal constant _OWNERSHIP_TRANSFER_SLOT =
0x9855384122b55936fbfb8ca5120e63c6537a1ac40caf6ae33502b3c5da8c87d1
Functions
constructor
Initializes the contract by transferring ownership to the owner parameter.
constructor(address _owner) ;
Parameters
| Name | Type | Description |
|---|---|---|
_owner | address | Address to set as the initial owner of the contract |
onlyOwner
Modifier that throws an error if called by any account other than the owner.
modifier onlyOwner() ;
owner
Returns the current owner of the contract.
function owner() public view returns (address owner_);
Returns
| Name | Type | Description |
|---|---|---|
owner_ | address | The current owner of the contract |
pendingOwner
Returns the pending owner of the contract.
function pendingOwner() public view returns (address owner_);
Returns
| Name | Type | Description |
|---|---|---|
owner_ | address | The pending owner of the contract |
transferOwnership
Transfers ownership of the contract to a new account newOwner.
Can only be called by the current owner.
function transferOwnership(address newOwner) external virtual onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
newOwner | address | The address to transfer ownership to |
proposeOwnership
Propose to transfer ownership of the contract to a new account newOwner.
Can only be called by the current owner. The ownership does not change until the new owner accepts the ownership transfer.
function proposeOwnership(address newOwner) external virtual onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
newOwner | address | The address to transfer ownership to |
acceptOwnership
Accepts ownership of the contract.
Can only be called by the pending owner
function acceptOwnership() external virtual;
_transferOwnership
Internal function to transfer ownership of the contract to a new account newOwner.
Called in the constructor to set the initial owner.
function _transferOwnership(address newOwner) internal virtual;
Parameters
| Name | Type | Description |
|---|---|---|
newOwner | address | The address to transfer ownership to |
Upgradable
Inherits: AxlOwnable, Implementation, IUpgradable
Title: Upgradable Contract
This contract provides an interface for upgradable smart contracts and includes the functionality to perform upgrades.
Constants
_IMPLEMENTATION_SLOT
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
Functions
constructor
Constructor sets the implementation address to the address of the contract itself
This is used in the onlyProxy modifier to prevent certain functions from being called directly on the implementation contract itself.
The owner is initially set as address(1) because the actual owner is set within the proxy. It is not set as the zero address because Ownable is designed to throw an error for ownership transfers to the zero address.
constructor() AxlOwnable(address(1));
implementation
Returns the address of the current implementation
function implementation() public view returns (address implementation_);
Returns
| Name | Type | Description |
|---|---|---|
implementation_ | address | Address of the current implementation |
upgrade
Upgrades the contract to a new implementation
This function is only callable by the owner.
function upgrade(address newImplementation, bytes32 newImplementationCodeHash, bytes calldata params)
external
override
onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
newImplementation | address | The address of the new implementation contract |
newImplementationCodeHash | bytes32 | The codehash of the new implementation contract |
params | bytes | Optional setup parameters for the new implementation contract |
setup
Sets up the contract with initial data
This function is only callable by the proxy contract.
function setup(bytes calldata data) external override (IImplementation, Implementation) onlyProxy;
Parameters
| Name | Type | Description |
|---|---|---|
data | bytes | Initialization data for the contract |
_setup
Internal function to set up the contract with initial data
This function should be implemented in derived contracts.
function _setup(bytes calldata data) internal virtual;
Parameters
| Name | Type | Description |
|---|---|---|
data | bytes | Initialization data for the contract |
MockAxelarGasService
Inherits: InterchainGasEstimation, Upgradable, IAxelarGasService
Title: AxelarGasService
This contract manages gas payments and refunds for cross-chain communication on the Axelar network.
The owner address of this contract should be the microservice that pays for gas.
Users pay gas for cross-chain calls, and the gasCollector can collect accumulated fees and/or refund users if needed.
Constants
gasCollector
address public immutable gasCollector
Functions
constructor
Constructs the AxelarGasService contract.
constructor(address gasCollector_) ;
Parameters
| Name | Type | Description |
|---|---|---|
gasCollector_ | address | The address of the gas collector |
_setup
function _setup(bytes calldata data) internal override;
onlyCollector
Modifier that ensures the caller is the designated gas collector.
modifier onlyCollector() ;
payGas
Pay for gas for any type of contract execution on a destination chain.
This function is called on the source chain before calling the gateway to execute a remote contract.
If estimateOnChain is true, the function will estimate the gas cost and revert if the payment is insufficient.
function payGas(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
uint256 executionGasLimit,
bool estimateOnChain,
address refundAddress,
bytes calldata params
) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call |
executionGasLimit | uint256 | The gas limit for the contract call |
estimateOnChain | bool | Flag to enable on-chain gas estimation |
refundAddress | address | The address where refunds, if any, should be sent |
params | bytes | Additional parameters for gas payment |
payGasForContractCall
Pay for gas using ERC20 tokens for a contract call on a destination chain.
This function is called on the source chain before calling the gateway to execute a remote contract.
function payGasForContractCall(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
address gasToken,
uint256 gasFeeAmount,
address refundAddress
) external override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call |
gasToken | address | The address of the ERC20 token used to pay for gas |
gasFeeAmount | uint256 | The amount of tokens to pay for gas |
refundAddress | address | The address where refunds, if any, should be sent |
payGasForContractCallWithToken
Pay for gas using ERC20 tokens for a contract call with tokens on a destination chain.
This function is called on the source chain before calling the gateway to execute a remote contract.
function payGasForContractCallWithToken(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
string memory symbol,
uint256 amount,
address gasToken,
uint256 gasFeeAmount,
address refundAddress
) external override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call with tokens will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call with tokens |
symbol | string | The symbol of the token to be sent with the call |
amount | uint256 | The amount of tokens to be sent with the call |
gasToken | address | The address of the ERC20 token used to pay for gas |
gasFeeAmount | uint256 | The amount of tokens to pay for gas |
refundAddress | address | The address where refunds, if any, should be sent |
payNativeGasForContractCall
Pay for gas using native currency for a contract call on a destination chain.
This function is called on the source chain before calling the gateway to execute a remote contract.
function payNativeGasForContractCall(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
address refundAddress
) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call |
refundAddress | address | The address where refunds, if any, should be sent |
payNativeGasForContractCallWithToken
Pay for gas using native currency for a contract call with tokens on a destination chain.
This function is called on the source chain before calling the gateway to execute a remote contract.
function payNativeGasForContractCallWithToken(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
string calldata symbol,
uint256 amount,
address refundAddress
) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call with tokens will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call with tokens |
symbol | string | The symbol of the token to be sent with the call |
amount | uint256 | The amount of tokens to be sent with the call |
refundAddress | address | The address where refunds, if any, should be sent |
payGasForExpressCall
Pay for gas using ERC20 tokens for an express contract call on a destination chain.
This function is called on the source chain before calling the gateway to express execute a remote contract.
function payGasForExpressCall(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
address gasToken,
uint256 gasFeeAmount,
address refundAddress
) external override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call |
gasToken | address | The address of the ERC20 token used to pay for gas |
gasFeeAmount | uint256 | The amount of tokens to pay for gas |
refundAddress | address | The address where refunds, if any, should be sent |
payGasForExpressCallWithToken
Pay for gas using ERC20 tokens for an express contract call with tokens on a destination chain.
This function is called on the source chain before calling the gateway to express execute a remote contract.
function payGasForExpressCallWithToken(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
string memory symbol,
uint256 amount,
address gasToken,
uint256 gasFeeAmount,
address refundAddress
) external override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call with tokens will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call with tokens |
symbol | string | The symbol of the token to be sent with the call |
amount | uint256 | The amount of tokens to be sent with the call |
gasToken | address | The address of the ERC20 token used to pay for gas |
gasFeeAmount | uint256 | The amount of tokens to pay for gas |
refundAddress | address | The address where refunds, if any, should be sent |
payNativeGasForExpressCall
Pay for gas using native currency for an express contract call on a destination chain.
This function is called on the source chain before calling the gateway to execute a remote contract.
function payNativeGasForExpressCall(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
address refundAddress
) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call |
refundAddress | address | The address where refunds, if any, should be sent |
payNativeGasForExpressCallWithToken
Pay for gas using native currency for an express contract call with tokens on a destination chain.
This function is called on the source chain before calling the gateway to execute a remote contract.
function payNativeGasForExpressCallWithToken(
address sender,
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
string calldata symbol,
uint256 amount,
address refundAddress
) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
sender | address | The address making the payment |
destinationChain | string | The target chain where the contract call with tokens will be made |
destinationAddress | string | The target address on the destination chain |
payload | bytes | Data payload for the contract call with tokens |
symbol | string | The symbol of the token to be sent with the call |
amount | uint256 | The amount of tokens to be sent with the call |
refundAddress | address | The address where refunds, if any, should be sent |
addGas
Add additional gas payment using ERC20 tokens after initiating a cross-chain call.
This function can be called on the source chain after calling the gateway to execute a remote contract.
function addGas(bytes32 txHash, uint256 logIndex, address gasToken, uint256 gasFeeAmount, address refundAddress)
external
override;
Parameters
| Name | Type | Description |
|---|---|---|
txHash | bytes32 | The transaction hash of the cross-chain call |
logIndex | uint256 | The log index for the cross-chain call |
gasToken | address | The ERC20 token address used to add gas |
gasFeeAmount | uint256 | The amount of tokens to add as gas |
refundAddress | address | The address where refunds, if any, should be sent |
addNativeGas
Add additional gas payment using native currency after initiating a cross-chain call.
This function can be called on the source chain after calling the gateway to execute a remote contract.
function addNativeGas(bytes32 txHash, uint256 logIndex, address refundAddress) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
txHash | bytes32 | The transaction hash of the cross-chain call |
logIndex | uint256 | The log index for the cross-chain call |
refundAddress | address | The address where refunds, if any, should be sent |
addExpressGas
Add additional gas payment using ERC20 tokens after initiating an express cross-chain call.
This function can be called on the source chain after calling the gateway to express execute a remote contract.
function addExpressGas(
bytes32 txHash,
uint256 logIndex,
address gasToken,
uint256 gasFeeAmount,
address refundAddress
) external override;
Parameters
| Name | Type | Description |
|---|---|---|
txHash | bytes32 | The transaction hash of the cross-chain call |
logIndex | uint256 | The log index for the cross-chain call |
gasToken | address | The ERC20 token address used to add gas |
gasFeeAmount | uint256 | The amount of tokens to add as gas |
refundAddress | address | The address where refunds, if any, should be sent |
addNativeExpressGas
Add additional gas payment using native currency after initiating an express cross-chain call.
This function can be called on the source chain after calling the gateway to express execute a remote contract.
function addNativeExpressGas(bytes32 txHash, uint256 logIndex, address refundAddress) external payable override;
Parameters
| Name | Type | Description |
|---|---|---|
txHash | bytes32 | The transaction hash of the cross-chain call |
logIndex | uint256 | The log index for the cross-chain call |
refundAddress | address | The address where refunds, if any, should be sent |
updateGasInfo
Updates the gas price for a specific chain.
This function is called by the gas oracle to update the gas prices for a specific chains.
function updateGasInfo(string[] calldata chains, GasInfo[] calldata gasUpdates) external onlyCollector;
Parameters
| Name | Type | Description |
|---|---|---|
chains | string[] | Array of chain names |
gasUpdates | GasInfo[] | Array of gas updates |
collectFees
Allows the gasCollector to collect accumulated fees from the contract.
Use address(0) as the token address for native currency.
function collectFees(address payable receiver, address[] calldata tokens, uint256[] calldata amounts)
external
onlyCollector;
Parameters
| Name | Type | Description |
|---|---|---|
receiver | address payable | The address to receive the collected fees |
tokens | address[] | Array of token addresses to be collected |
amounts | uint256[] | Array of amounts to be collected for each respective token address |
refund
Deprecated refund function, kept for backward compatibility.
function refund(address payable receiver, address token, uint256 amount) external onlyCollector;
refund
Refunds gas payment to the receiver in relation to a specific cross-chain transaction.
Only callable by the gasCollector.
Use address(0) as the token address to refund native currency.
function refund(bytes32 txHash, uint256 logIndex, address payable receiver, address token, uint256 amount)
external
onlyCollector;
Parameters
| Name | Type | Description |
|---|---|---|
txHash | bytes32 | The transaction hash of the cross-chain call |
logIndex | uint256 | The log index for the cross-chain call |
receiver | address payable | The address to receive the refund |
token | address | The token address to be refunded |
amount | uint256 | The amount to refund |
_refund
Internal function to implement gas refund logic.
function _refund(bytes32 txHash, uint256 logIndex, address payable receiver, address token, uint256 amount)
private;
contractId
Returns a unique identifier for the contract.
function contractId() external pure returns (bytes32);
Returns
| Name | Type | Description |
|---|---|---|
<none> | bytes32 | bytes32 Hash of the contract identifier |
MockAxelarGateway
Inherits: IAxelarGatewayWithToken
Title: AxelarGateway Contract
This contract serves as the gateway for cross-chain contract calls, and token transfers within the Axelar network. It includes functions for sending tokens, calling contracts, and validating contract calls. The contract is managed via the decentralized governance mechanism on the Axelar network.
EternalStorage is used to simplify storage for upgradability, and InterchainGovernance module is used for governance.
State Variables
tokenMapping
mapping(string => address) tokenMapping
Functions
constructor
constructor() ;
sendToken
Sends tokens to another chain.
Initiates a cross-chain token transfer through the gateway to the specified destination chain and recipient.
function sendToken(
string calldata destinationChain,
string calldata destinationAddress,
string calldata symbol,
uint256 amount
) external;
Parameters
| Name | Type | Description |
|---|---|---|
destinationChain | string | The name of the destination chain. |
destinationAddress | string | The address of the recipient on the destination chain. |
symbol | string | The symbol of the token being transferred. |
amount | uint256 | The amount of the tokens being transferred. |
callContractWithToken
Makes a contract call on another chain with an associated token transfer.
Initiates a cross-chain contract call through the gateway that includes a token transfer to the specified contract on the destination chain.
function callContractWithToken(
string calldata destinationChain,
string calldata contractAddress,
bytes calldata payload,
string calldata symbol,
uint256 amount
) external;
Parameters
| Name | Type | Description |
|---|---|---|
destinationChain | string | The name of the destination chain. |
contractAddress | string | The address of the contract on the destination chain. |
payload | bytes | The payload data to be used in the contract call. |
symbol | string | The symbol of the token being transferred. |
amount | uint256 | The amount of the tokens being transferred. |
isContractCallAndMintApproved
Checks if a contract call with token minting is approved.
Determines whether a given contract call, identified by the commandId and payloadHash, involving token minting is approved.
function isContractCallAndMintApproved(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
address contractAddress,
bytes32 payloadHash,
string calldata symbol,
uint256 amount
) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
commandId | bytes32 | The identifier of the command to check. |
sourceChain | string | The name of the source chain. |
sourceAddress | string | The address of the sender on the source chain. |
contractAddress | address | The address of the contract where the call will be executed. |
payloadHash | bytes32 | The keccak256 hash of the payload data. |
symbol | string | The symbol of the token associated with the minting. |
amount | uint256 | The amount of the tokens to be minted. |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the contract call with token minting is approved, false otherwise. |
validateContractCallAndMint
Validates and approves a contract call with token minting.
Validates the given contract call information and marks it as approved if valid. It also involves the minting of tokens.
function validateContractCallAndMint(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes32 payloadHash,
string calldata symbol,
uint256 amount
) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
commandId | bytes32 | The identifier of the command to validate. |
sourceChain | string | The name of the source chain. |
sourceAddress | string | The address of the sender on the source chain. |
payloadHash | bytes32 | The keccak256 hash of the payload data. |
symbol | string | The symbol of the token associated with the minting. |
amount | uint256 | The amount of the tokens to be minted. |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the contract call with token minting is validated and approved, false otherwise. |
tokenAddresses
Retrieves the address of a token given its symbol.
Gets the contract address of the token registered with the given symbol.
function tokenAddresses(string memory symbol) external view returns (address);
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | The symbol of the token to retrieve the address for. |
Returns
| Name | Type | Description |
|---|---|---|
<none> | address | The contract address of the token corresponding to the given symbol. |
setTokenAddress
Sets the address of a token given its symbol.
Sets the contract address of the token registered with the given symbol.
function setTokenAddress(string memory symbol, address tokenAddress) external;
Parameters
| Name | Type | Description |
|---|---|---|
symbol | string | The symbol of the token. |
tokenAddress | address | The address of the token. |
callContract
Sends a contract call to another chain.
Initiates a cross-chain contract call through the gateway to the specified destination chain and contract.
function callContract(string calldata destinationChain, string calldata contractAddress, bytes calldata payload)
external;
Parameters
| Name | Type | Description |
|---|---|---|
destinationChain | string | The name of the destination chain. |
contractAddress | string | The address of the contract on the destination chain. |
payload | bytes | The payload data to be used in the contract call. |
isContractCallApproved
Checks if a contract call is approved.
Determines whether a given contract call, identified by the commandId and payloadHash, is approved.
function isContractCallApproved(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
address contractAddress,
bytes32 payloadHash
) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
commandId | bytes32 | The identifier of the command to check. |
sourceChain | string | The name of the source chain. |
sourceAddress | string | The address of the sender on the source chain. |
contractAddress | address | The address of the contract where the call will be executed. |
payloadHash | bytes32 | The keccak256 hash of the payload data. |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the contract call is approved, false otherwise. |
validateContractCall
Validates and approves a contract call.
Validates the given contract call information and marks it as approved if valid.
function validateContractCall(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes32 payloadHash
) external returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
commandId | bytes32 | The identifier of the command to validate. |
sourceChain | string | The name of the source chain. |
sourceAddress | string | The address of the sender on the source chain. |
payloadHash | bytes32 | The keccak256 hash of the payload data. |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the contract call is validated and approved, false otherwise. |
isCommandExecuted
Checks if a command has been executed.
Determines whether a command, identified by the commandId, has been executed.
function isCommandExecuted(bytes32 commandId) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
commandId | bytes32 | The identifier of the command to check. |
Returns
| Name | Type | Description |
|---|---|---|
<none> | bool | True if the command has been executed, false otherwise. |
ERC20BurnableMock
Inherits: ERC20Burnable
Functions
constructor
constructor(string memory name, string memory symbol) ERC20(name, symbol);
mint
function mint(address to, uint256 amount) public;
ERC20Mock
Inherits: ERC20
Functions
constructor
constructor() ERC20("ERC20Mock", "E20M");
mint
function mint(address account, uint256 amount) external;
burn
function burn(address account, uint256 amount) external;
ETHReceiverMock
Title: ETHReceiverMock
Simple mock contract that can receive ETH transfers
Used for testing excess ETH refund scenarios
Functions
receive
Fallback function to receive ETH
receive() external payable;
Events
ETHReceived
Emitted when ETH is received
event ETHReceived(address indexed sender, uint256 amount);
MockRelayerV2
Inherits: BaseAdapter
Title: MockRelayerV2
Lightweight mock relayer for testing atomic token transfers and fulfillments
Simulates real-world relayer behavior by atomically transferring funds to receiver and calling fulfill(). Used in MetaIntentV2 tests to replace non-atomic test patterns. Demonstrates proper BaseAdapter extension pattern.
Functions
constructor
constructor(address payable _receiver) BaseAdapter(_receiver);
Parameters
| Name | Type | Description |
|---|---|---|
_receiver | address payable | The address of the MetaIntentReceiver contract |
relayAndFulfill
Atomically transfer funds to receiver and call fulfill
The relayer must already hold the tokens being transferred. Uses BaseAdapter._fulfillToReceiver() for the actual transfer and fulfill call.
function relayAndFulfill(RelayedOrderOutput calldata output) public payable returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The relayed order output to fulfill |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | The payload hash returned by the receiver |
relayAndFulfillERC20
Convenience function for tests: fund relayer with ERC20, then relay and fulfill
Pulls ERC20 from caller, transfers to receiver, and fulfills
function relayAndFulfillERC20(RelayedOrderOutput calldata output) external returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The relayed order output to fulfill |
relayAndFulfillNative
Convenience function for tests: fund relayer with native token, then relay and fulfill
Must be called with sufficient msg.value
function relayAndFulfillNative(RelayedOrderOutput calldata output) external payable returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The relayed order output to fulfill |
_decodeMessage
Decode a message into RelayedOrderOutput (mock implementation)
For the mock relayer, this simply returns the passed output directly. Real protocol adapters would decode their specific message format here.
function _decodeMessage(
bytes calldata /*message*/
)
internal
pure
override
returns (RelayedOrderOutput memory output);
Returns
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | Empty output for mock - real implementations override properly |
Events
RelayAndFulfillCompleted
Emitted when a relay and fulfillment is completed
event RelayAndFulfillCompleted(bytes32 indexed orderId, bytes32 indexed outputHash, address token, uint256 amount);
Errors
InsufficientNativeToken
Revert when insufficient native token provided
error InsufficientNativeToken(uint256 provided, uint256 required);
MockERC20
Inherits: ERC20
Functions
constructor
constructor(string memory name, string memory symbol) ERC20(name, symbol);
mint
function mint(address to, uint256 amount) public;
Contents
ClaimPlugin
Inherits: UUPSUpgradeable, OwnableUpgradeable, ERC165Upgradeable, Claimable
Author: Mure Implements UUPSUpgradeable for upgradeability, OwnableUpgradeable for access control, ERC165Upgradeable for interface support, and Claimable interface for compatibility checks. Facilitates the calculation and execution of reward claims, allowing depositors to receive their entitled rewards along with their shares from the total collected pool funds.
Contract managing reward distribution to users of an application.
Functions
initialize
function initialize(address owner) external initializer;
claim
Sends reward funds from the delegate to depositor.
function claim(ClaimRecord calldata claimRecord) external returns (uint256 depositDelta, uint256 claimDelta);
Parameters
| Name | Type | Description |
|---|---|---|
claimRecord | ClaimRecord | struct containing all information needed to compute and execute a claimRecord. See Claimable.ClaimRecord for more information |
deltas
Returns the refund amount, claim amount and fee.
function deltas(ClaimRecord calldata claimRecord)
public
pure
returns (uint256 depositDelta, uint256 claimDelta, uint256 fee);
Parameters
| Name | Type | Description |
|---|---|---|
claimRecord | ClaimRecord | struct containing all information needed to compute and execute a claimRecord. See Claimable.ClaimRecord for more information |
Returns
| Name | Type | Description |
|---|---|---|
depositDelta | uint256 | amount from the original deposit to be refunded |
claimDelta | uint256 | amount from the claim reserves to be claimed |
fee | uint256 | fee to be charged from claimDelta |
_calculateShare
Calculates the user share amount.
function _calculateShare(uint256 share, uint256 supply, uint256 reserve) private pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
share | uint256 | share of the user |
supply | uint256 | total supply |
reserve | uint256 | current reserve |
calculateFee
Calculates the fee to be charged.
function calculateFee(uint256 amount, uint256 feePercentage) private pure returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | total amount |
feePercentage | uint256 | fee percentage in basis points |
supportsInterface
See IERC165-supportsInterface.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override (ERC165Upgradeable, IERC165)
returns (bool);
_authorizeUpgrade
required by the OZ UUPS module
function _authorizeUpgrade(address) internal override onlyOwner;
Contents
Constants
POOL_OPERATOR_ROLE
Role allows user to create and update pools along with pool administration
bytes32 constant POOL_OPERATOR_ROLE = keccak256("POOL_OPERATOR")
DEFAULT_ADMIN_ROLE
Default RBAC admin role
bytes32 constant DEFAULT_ADMIN_ROLE = 0x00
Role
Enum for pool member roles
enum Role {
DEFAULT_ADMIN,
POOL_OPERATOR
}
AppMember
Struct for a pool member
struct AppMember {
address member;
Role role;
}
Constants
APP_MEMBER_HASH
Struct hash for validating app deployments
keccak256("AppMember(address member,uint8 role)")
bytes32 constant APP_MEMBER_HASH = 0xe3128a5e7b51cb6b5d75b976cb4b51c8420a8c2a5c60709fd3af893c19fc754a
FEE_CONFIG_HASH
Struct hash for validating deposit fee config
keccak256("FeeConfig(uint112 amount,address recipient)")
bytes32 constant FEE_CONFIG_HASH = 0xfec57672da62b01f006c6c3af74423cc502012ed8246681ae395eb5dbaa8e825
Contents
- interfaces
- libraries
- types
- utils
- AcrossAdapter
- BaseAdapter
- MayanAdapter
- MetaIntentReceiver
- MetaIntentTransmitter
Contents
Adapter
Title: Adapter
Interface for adapters that connect underlying protocols to the MetaIntentReceiver
Defines the contract that all adapters must implement to ensure type consistency
Functions
receiver
Returns the MetaIntentReceiver address this adapter forwards to
function receiver() external view returns (address receiverAddr);
Returns
| Name | Type | Description |
|---|---|---|
receiverAddr | address | The address of the MetaIntentReceiver contract |
Receiver
Title: Receiver
Interface for the MetaIntentReceiver contract
Defines the external API for fulfilling order outputs on destination chain
Functions
fulfill
Fulfill an order output by transferring tokens to the recipient
function fulfill(RelayedOrderOutput calldata output) external returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The output to fulfill |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | Hash of the fulfillment payload for verification |
Transmitter
Title: Transmitter
Interface for the MetaIntentTransmitter contract
Defines the external API for executing meta-intent orders
Functions
execute
Execute a meta-intent order by pulling inputs and executing protocol calls
function execute(Order calldata order) external payable returns (bytes32 orderId);
Parameters
| Name | Type | Description |
|---|---|---|
order | Order | The order to execute |
Returns
| Name | Type | Description |
|---|---|---|
orderId | bytes32 | Unique identifier for the executed order |
Contents
ErrorLib
Author: Mure
Library with errors for Mure v2 contracts
Errors
NotAuthorizedProtocol
error NotAuthorizedProtocol();
OrderExpired
error OrderExpired();
NoInputsProvided
error NoInputsProvided();
NoCallsProvided
error NoCallsProvided();
ZeroInputAmount
error ZeroInputAmount();
OrderIdMismatch
error OrderIdMismatch();
NonceAlreadyUsed
error NonceAlreadyUsed();
OrderAlreadyExecuted
error OrderAlreadyExecuted();
OutputAlreadyFulfilled
error OutputAlreadyFulfilled();
CallFailed
error CallFailed(uint256 callIndex, bytes returnData);
InsufficientNativeToken
Revert when insufficient native token provided
error InsufficientNativeToken(uint256 provided, uint256 required);
NativeAmountMismatch
error NativeAmountMismatch();
TransferFailed
error TransferFailed();
InvalidCallTarget
error InvalidCallTarget();
IllegalAmountTransferred
error IllegalAmountTransferred();
InsufficientAllowance
error InsufficientAllowance();
InsufficientTokenBalance
error InsufficientTokenBalance(address token, uint256 expected, uint256 actual);
NativeBalanceNotZero
error NativeBalanceNotZero();
TokenBalanceNotZero
error TokenBalanceNotZero(address token);
InvalidCallSignature
error InvalidCallSignature();
LibAddress
Title: LibAddress
Library for address-related utility functions
Provides functions for converting addresses to cross-chain identifiers
Functions
toIdentifier
Converts an Ethereum address to a bytes32 identifier that can be used across chains.
Uses the address’s numeric value as a bytes32 identifier by casting type in-place.
function toIdentifier(address addr) internal pure returns (bytes32 identifier);
Parameters
| Name | Type | Description |
|---|---|---|
addr | address | The address to convert |
Returns
| Name | Type | Description |
|---|---|---|
identifier | bytes32 | The bytes32 identifier representation of the address |
fromIdentifier
Converts a bytes32 identifier back to an Ethereum address.
Reverses the toIdentifier operation by cleaning the top 96 bits and then returning the address remaining from the last 160 bits.
function fromIdentifier(bytes32 identifier) internal pure returns (address addr);
Parameters
| Name | Type | Description |
|---|---|---|
identifier | bytes32 | The bytes32 identifier to convert |
Returns
| Name | Type | Description |
|---|---|---|
addr | address | The address representation of the identifier |
fromIdentifier
Converts a uint256 identifier back to an Ethereum address.
Reverses the toIdentifier operation by cleaning the top 96 bits and then returning the address remaining from the last 160 bits.
function fromIdentifier(uint256 identifier) internal pure returns (address addr);
Parameters
| Name | Type | Description |
|---|---|---|
identifier | uint256 | The uint256 identifier to convert |
Returns
| Name | Type | Description |
|---|---|---|
addr | address | The address representation of the identifier |
safeFromIdentifier
Converts a uint256 identifier to an Ethereum address while requiring that the leftmost 12 bytes are empty.
Reverts if any bit is set in the leftmost 12 bytes. Then typecasts transparently.
function safeFromIdentifier(uint256 identifier) internal pure returns (address addr);
Parameters
| Name | Type | Description |
|---|---|---|
identifier | uint256 | The uint256 identifier to check and convert |
Returns
| Name | Type | Description |
|---|---|---|
addr | address | Validates and casted Ethereum address. |
Errors
InvalidAddress
The input isn’t safely coerced to an address
error InvalidAddress();
LibToken
Constants
NATIVE_TOKEN
ERC7528 Address Convention
address public constant NATIVE_TOKEN = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE)
Functions
isNativeToken
function isNativeToken(address token) internal pure returns (bool result);
Contents
Call
Arbitrary protocol call
struct Call {
address target; // Protocol contract
uint256 value; // Native value to forward
bytes data; // Encoded function call
}
LibCall
Constants
CALL_TYPE
bytes constant CALL_TYPE = abi.encodePacked("Call(address target,uint256 value,bytes data)")
CALL_TYPE_HASH
bytes32 constant CALL_TYPE_HASH = keccak256(CALL_TYPE)
Functions
callContract
function callContract(Call calldata call) internal returns (bytes memory result);
tryCall
function tryCall(Call calldata call) internal returns (bool success, bool exceededMaxCopy, bytes memory result);
hash
Raw hash of Call data WITHOUT type hash — utility function
For EIP712-compliant hashing, use hashType() instead
function hash(Call calldata call) public pure returns (bytes32 callHash);
hashType
EIP712 hashStruct for Call — includes CALL_TYPE_HASH
Matches: hashStruct(Call) = keccak256(CALL_TYPE_HASH ‖ encodeData(Call))
function hashType(Call calldata call) public pure returns (bytes32 callHash);
hash
Generates a deterministic hash for a Call[]
function hash(Call[] calldata calls) public pure returns (bytes32 callsHash);
Parameters
| Name | Type | Description |
|---|---|---|
calls | Call[] | The Call[] to hash |
Returns
| Name | Type | Description |
|---|---|---|
callsHash | bytes32 | The unique hash for this Call[] |
hashType
EIP712 hashStruct for Call[]
function hashType(Call[] calldata calls) public pure returns (bytes32 callsHash);
Parameters
| Name | Type | Description |
|---|---|---|
calls | Call[] | The Call[] to hash |
Returns
| Name | Type | Description |
|---|---|---|
callsHash | bytes32 | The unique hash for this Call[] |
Order
Minimal order focused on inputs and execution
struct Order {
// Identity (deterministic from inputs, not calls)
address user; // Who provides inputs
uint256 nonce; // Replay protection
uint256 deadline; // Latest timestamp for valid execution
// Assets to consume
OrderInput[] inputs; // Assets sponsor provides
OrderOutput[] outputs; // Expected outputs to be processed
// Protocol execution (black box)
Call[] calls; // Ordered protocol calls to execute
bytes callSig; // Authorizing signature of calls
bytes metadata; // Optional: tags, offchain references, referrals, etc.
}
OrderInput
Input asset specification
struct OrderInput {
address token; // ERC7528 followed for native (see {LibToken})
uint256 amount; // Exact amount to pull
}
OrderOutput
Output asset specification
struct OrderOutput {
bytes32 recipient; // Cross-chain friendly address
bytes32 token; // Output token
uint256 amount; // Amount received
bytes callData; // Calldata to forward to `recipient`, can be empty
// TODO: Should context be here for order types? Or defer to separate contract?
}
RelayedOrderOutput
Output tracking (used by Receiver)
struct RelayedOrderOutput {
bytes32 orderId; // Links back to source order
bytes32 recipient; // Cross-chain friendly address
bytes32 token; // Output token
uint256 amount; // Amount received
bytes callData; // Calldata to forward to `recipient`, can be empty
// TODO: Should context be here for order types? Or defer to separate contract?
}
LibOrder
Constants
ORDER_ROUTE_TYPE
bytes constant ORDER_ROUTE_TYPE =
abi.encodePacked("OrderRoute(bytes32 orderId,uint256 deadline,Call[] calls)", LibCall.CALL_TYPE)
ORDER_ROUTE_TYPE_HASH
bytes32 constant ORDER_ROUTE_TYPE_HASH = keccak256(ORDER_ROUTE_TYPE)
ORDER_INPUT_TYPE
bytes constant ORDER_INPUT_TYPE = abi.encodePacked("OrderInput(address token,uint256 amount)")
ORDER_INPUT_TYPE_HASH
bytes32 constant ORDER_INPUT_TYPE_HASH = keccak256(ORDER_INPUT_TYPE)
ORDER_OUTPUT_TYPE
bytes constant ORDER_OUTPUT_TYPE =
abi.encodePacked("OrderOutput(bytes32 orderId,bytes32 recipient,bytes32 token,uint256 amount,bytes callData)")
ORDER_OUTPUT_TYPE_HASH
bytes32 constant ORDER_OUTPUT_TYPE_HASH = keccak256(ORDER_OUTPUT_TYPE)
Functions
orderId
function orderId(Order calldata order) public view returns (bytes32 id);
hash
Raw hash of Order calls — utility, NOT EIP712-compliant
For EIP712-compliant hashing, use hashType() instead
function hash(Order calldata order) public view returns (bytes32 routeHash);
hashType
EIP712 hashStruct for OrderRoute — includes ORDER_ROUTE_TYPE_HASH
Matches: hashStruct(OrderRoute) = keccak256(ORDER_ROUTE_TYPE_HASH ‖ orderId ‖ encodeData(Call[])) where encodeData(Call[]) = keccak256(hashType(calls[0]) ‖ hashType(calls[1]) ‖ …)
function hashType(Order calldata order) public view returns (bytes32 routeHash);
hash
Generates a deterministic hash for an OrderInput WITHOUT type hash signature
function hash(OrderInput calldata input) public pure returns (bytes32 inputHash);
Parameters
| Name | Type | Description |
|---|---|---|
input | OrderInput | The OrderInput to hash |
Returns
| Name | Type | Description |
|---|---|---|
inputHash | bytes32 | The unique hash for this input |
hashType
Generates a deterministic hash for an OrderInput
function hashType(OrderInput calldata input) public pure returns (bytes32 inputHash);
Parameters
| Name | Type | Description |
|---|---|---|
input | OrderInput | The OrderInput to hash |
Returns
| Name | Type | Description |
|---|---|---|
inputHash | bytes32 | The unique hash for this input |
hash
Generates a deterministic hash for an OrderInput[]
function hash(OrderInput[] calldata inputs) public pure returns (bytes32 inputsHash);
Parameters
| Name | Type | Description |
|---|---|---|
inputs | OrderInput[] | The OrderInput[] to hash |
Returns
| Name | Type | Description |
|---|---|---|
inputsHash | bytes32 | The unique hash for the inputs |
hash
Generates a deterministic hash for an OrderOutput WITHOUT type hash signature
function hash(OrderOutput calldata output) public pure returns (bytes32 outputHash);
Parameters
| Name | Type | Description |
|---|---|---|
output | OrderOutput | The OrderOutput to hash |
Returns
| Name | Type | Description |
|---|---|---|
outputHash | bytes32 | The unique hash for this output |
hashType
Generates a deterministic hash for a RelayedOrderOutput
function hashType(RelayedOrderOutput calldata output) public pure returns (bytes32 outputHash);
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The RelayedOrderOutput to hash |
Returns
| Name | Type | Description |
|---|---|---|
outputHash | bytes32 | The unique hash for this output |
Contents
VaultFallback
Constants
_FALLBACK_TRANSFERRED_EVENT_SIGNATURE
keccak256(bytes("FallbackTransferred(address,address)")).
uint256 private constant _FALLBACK_TRANSFERRED_EVENT_SIGNATURE =
0x76b6ff30b9c54394454c961c5c1860e047b141beb52f06e45509097109524797
_VAULT_SLOT
The fallback vault slot is given by:
bytes32(~uint256(uint32(bytes4(keccak256("_VAULT_SLOT_NOT"))))).
It is intentionally chosen to be a high value
to avoid collision with lower slots.
The choice of manual storage layout is to enable compatibility
with both regular and upgradeable contracts.
bytes32 internal constant _VAULT_SLOT = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffbaf973c6
Functions
_initializeVault
function _initializeVault(address newVault) internal virtual;
_setVault
function _setVault(address newVault) internal virtual;
_sendToVault
Send ALL remaining funds to treasury
function _sendToVault(address token) internal;
Parameters
| Name | Type | Description |
|---|---|---|
token | address | The token address (follows ERC7528 for native) |
vault
function vault() public view virtual returns (address result);
Events
FallbackTransferred
The vault fallback is transferred from oldVault to newVault.
event FallbackTransferred(address indexed oldVault, address indexed newVault);
Errors
VaultIsZeroAddress
The vault to be set cannot be the zero address
error VaultIsZeroAddress();
AcrossAdapter
Inherits: BaseAdapter
Title: AcrossAdapter
Adapter for settling Across bridge claims and forwarding to MetaIntentReceiver
Receives bridged tokens directly from Across and forwards actual received amounts
Functions
constructor
constructor(address receiver) BaseAdapter(receiver);
settle
Settle bridged tokens and forward actual received amount to MetaIntentReceiver
function settle(RelayedOrderOutput calldata expectedOutput) external payable returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
expectedOutput | RelayedOrderOutput | The expected output details (amount is minimum required) |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | The payload hash returned by the receiver |
_fulfillToReceiverWithAmount
Internal helper to fulfill to receiver with a specific amount
This allows us to use the expectedOutput structure but with the actual received amount
function _fulfillToReceiverWithAmount(RelayedOrderOutput calldata baseOutput, uint256 actualAmount)
internal
returns (bytes32 payloadHash);
_decodeMessage
Override _decodeMessage for BaseAdapter compliance
function _decodeMessage(bytes calldata message) internal pure override returns (RelayedOrderOutput memory output);
Parameters
| Name | Type | Description |
|---|---|---|
message | bytes | The encoded message bytes |
Returns
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The decoded RelayedOrderOutput |
receive
receive() external payable override;
Errors
InsufficientSettlementAmount
error InsufficientSettlementAmount(uint256 received, uint256 expected);
BaseAdapter
Inherits: Adapter
Title: BaseAdapter
Base contract for adapters that connect underlying protocols to the MetaIntentReceiver.
Provides reusable functions for connecting with the MetaIntentReceiver,
including token transfer helpers and message decoding patterns.
Protocol-specific adapters should inherit from this contract and override
the virtual functions to implement their specific requirements.
Constants
RECEIVER
The MetaIntentReceiver that this adapter forwards fulfillments to
Receiver public immutable RECEIVER
Functions
constructor
constructor(address receiverAddr) ;
Parameters
| Name | Type | Description |
|---|---|---|
receiverAddr | address | The address of the MetaIntentReceiver contract |
onlyProtocol
modifier onlyProtocol() ;
receiver
Returns the MetaIntentReceiver address this adapter forwards to
function receiver() external view returns (address receiverAddr);
Returns
| Name | Type | Description |
|---|---|---|
receiverAddr | address | The address of the MetaIntentReceiver contract |
_decodeMessage
Decode a protocol-specific message into RelayedOrderOutput
Virtual function that must be overridden by protocol-specific adapters. This internal version allows adapters to use the decoding logic internally.
function _decodeMessage(bytes calldata message) internal virtual returns (RelayedOrderOutput memory output);
Parameters
| Name | Type | Description |
|---|---|---|
message | bytes | The protocol-specific encoded message |
Returns
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The decoded RelayedOrderOutput struct |
_onlyProtocol
Modifier pattern for protocol-specific access control
Override this function to add authorization checks. For example, override to only allow specific protocol bridge contracts to call. Empty by default - implementations should override for production use.
function _onlyProtocol() internal virtual;
_fulfillToReceiver
Transfer tokens to receiver and call fulfill
Handles both native and ERC20 token transfers to the receiver, then calls fulfill() on the MetaIntentReceiver. Follows CEI pattern: checks (balance validation) happen in receiver.
function _fulfillToReceiver(RelayedOrderOutput calldata output) internal returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The relayed order output to fulfill |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | The payload hash returned by the receiver |
receive
receive() external payable virtual;
Errors
NativeTransferFailed
Revert when native token transfer to receiver fails
error NativeTransferFailed();
ReceiverIsZeroAddress
Revert when receiver address is zero
error ReceiverIsZeroAddress();
MayanAdapter
Inherits: BaseAdapter
Title: MayanAdapter
Adapter for settling Mayan protocol claims and forwarding to MetaIntentReceiver
Uses pull configuration - any third-party settler can trigger settlements
Constants
MAYAN_CIRCLE
MayanCircle public immutable MAYAN_CIRCLE
FAST_MCTP
FastMCTP public immutable FAST_MCTP
SWIFT_DEST
SwiftDest public immutable SWIFT_DEST
CCTP_TOKEN_INDEX
uint256 internal constant CCTP_TOKEN_INDEX = 120
CCTP_RECIPIENT_INDEX
uint256 internal constant CCTP_RECIPIENT_INDEX = 152
CCTPV2_MESSAGE_BODY_INDEX
uint256 internal constant CCTPV2_MESSAGE_BODY_INDEX = 148
CCTPV2_SOURCE_TOKEN_INDEX
uint256 internal constant CCTPV2_SOURCE_TOKEN_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 4
HOOK_DATA_INDEX
uint256 internal constant HOOK_DATA_INDEX = CCTPV2_MESSAGE_BODY_INDEX + 228
Functions
constructor
Constructor sets immutable references to Mayan contracts and receiver
constructor(address receiver, address payable mayanCircle, address payable fastMctp, address payable swiftDest)
BaseAdapter(receiver);
Parameters
| Name | Type | Description |
|---|---|---|
receiver | address | Address of the MetaIntentReceiver contract |
mayanCircle | address payable | Address of the MayanCircle contract |
fastMctp | address payable | Address of the FastMCTP contract |
swiftDest | address payable | Address of the SwiftDest contract |
settleMayanCircle
Settle tokens from MayanCircle and forward to MetaIntentReceiver
function settleMayanCircle(
bytes calldata cctpMsg,
bytes calldata cctpSigs,
bytes calldata encodedVm,
MayanCircle.BridgeWithFeeParams calldata bridgeParams,
RelayedOrderOutput calldata expectedOutput
) external payable returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
cctpMsg | bytes | The CCTP message bytes |
cctpSigs | bytes | The CCTP attestation signatures |
encodedVm | bytes | The encoded Wormhole VM |
bridgeParams | MayanCircle.BridgeWithFeeParams | The bridge parameters containing custom payload |
expectedOutput | RelayedOrderOutput | The expected output details (amount is minimum required) |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | The payload hash returned by the receiver |
settleFastMCTP
Settle tokens from FastMCTP and forward to MetaIntentReceiver
function settleFastMCTP(bytes calldata cctpMsg, bytes calldata cctpSigs, RelayedOrderOutput calldata expectedOutput)
external
payable
returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
cctpMsg | bytes | The CCTP V2 message bytes |
cctpSigs | bytes | The CCTP V2 attestation signatures |
expectedOutput | RelayedOrderOutput | The expected output details (amount is minimum required) |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | The payload hash returned by the receiver |
settleSwiftDest
Settle tokens from SwiftDest and forward to MetaIntentReceiver
function settleSwiftDest(
OrderParams calldata params,
ExtraParams calldata extraParams,
RelayedOrderOutput calldata expectedOutput
) external returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
params | OrderParams | The order parameters |
extraParams | ExtraParams | The extra parameters containing custom payload hash |
expectedOutput | RelayedOrderOutput | The expected output details (amount is minimum required) |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | The payload hash returned by the receiver |
_extractTokenFromCctpV1Msg
Extract token address from CCTP V1 message (MayanCircle)
function _extractTokenFromCctpV1Msg(bytes calldata cctpMsg) internal pure returns (address token);
Parameters
| Name | Type | Description |
|---|---|---|
cctpMsg | bytes | The CCTP V1 message bytes |
Returns
| Name | Type | Description |
|---|---|---|
token | address | The token address extracted from the message |
_extractTokenFromCctpV2Msg
Extract token address from CCTP V2 message (FastMCTP)
function _extractTokenFromCctpV2Msg(bytes calldata cctpMsg) internal pure returns (address token);
Parameters
| Name | Type | Description |
|---|---|---|
cctpMsg | bytes | The CCTP V2 message bytes |
Returns
| Name | Type | Description |
|---|---|---|
token | address | The token address extracted from the message |
_extractOrderIdFromCctpV2Msg
Extract orderId from CCTP V2 message hook data (FastMCTP)
Hook data format: payloadType(1) + destAddr(32) + gasDrop(8) + redeemFee(8) + referrerAddr(32) + referrerBps(1) + customPayload(32) Total: 84 bytes before customPayload, customPayload at index HOOK_DATA_INDEX + 82
function _extractOrderIdFromCctpV2Msg(bytes calldata cctpMsg) internal pure returns (bytes32 orderId);
Parameters
| Name | Type | Description |
|---|---|---|
cctpMsg | bytes | The CCTP V2 message bytes |
Returns
| Name | Type | Description |
|---|---|---|
orderId | bytes32 | The orderId extracted from the custom payload field |
_fulfillToReceiverWithAmount
Internal helper to fulfill to receiver with a specific amount
This allows us to use the expectedOutput structure but with the actual received amount
function _fulfillToReceiverWithAmount(RelayedOrderOutput calldata baseOutput, uint256 actualAmount)
internal
returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
baseOutput | RelayedOrderOutput | The base output structure (orderId, recipient, token, callData) |
actualAmount | uint256 | The actual amount received from Mayan |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | The payload hash returned by the receiver |
_decodeMessage
Override _decodeMessage for BaseAdapter compliance
function _decodeMessage(bytes calldata message) internal pure override returns (RelayedOrderOutput memory output);
Parameters
| Name | Type | Description |
|---|---|---|
message | bytes | The encoded message bytes |
Returns
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The decoded RelayedOrderOutput |
receive
receive() external payable override;
Errors
InvalidMayanContract
error InvalidMayanContract();
SettlementFailed
error SettlementFailed();
InsufficientSettlementAmount
error InsufficientSettlementAmount(uint256 received, uint256 expected);
InvalidCctpMessage
error InvalidCctpMessage();
OrderIdMismatch
error OrderIdMismatch(bytes32 expected, bytes32 actual);
TokenMismatch
error TokenMismatch(bytes32 expected, bytes32 actual);
MetaIntentReceiver
Inherits: Receiver, ReentrancyGuard, OwnableRoles, Pausable, VaultFallback
Title: MetaIntentReceiver
Tracks order fulfillment on destination chain and handles token transfers to recipients
Called by underlying protocols (Across, UniswapX, etc.) to mark completion and transfer tokens
Constants
ADMIN_ROLE
Administrator role identifier
uint256 public constant ADMIN_ROLE = _ROLE_0
OPERATOR_ROLE
Operator role identifier
uint256 public constant OPERATOR_ROLE = _ROLE_1
State Variables
_fulfillments
Track which outputs have been fulfilled with their payload hashes
mapping(bytes32 orderId => mapping(bytes32 outputHash => bytes32 payloadHash)) _fulfillments
Functions
constructor
constructor(address owner, address operator, address vault) ;
fulfill
Fulfill an order output by transferring tokens to the recipient
function fulfill(RelayedOrderOutput calldata output)
external
// onlyAuthorized
whenNotPaused
nonReentrant
returns (bytes32 payloadHash);
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The output to fulfill |
Returns
| Name | Type | Description |
|---|---|---|
payloadHash | bytes32 | Hash of the fulfillment payload for verification |
setVault
function setVault(address newVault) external onlyRoles(ADMIN_ROLE);
pause
Pause the contract, preventing state change calls
Can only be called by an administrator
function pause() external onlyRoles(OPERATOR_ROLE);
unpause
Unpause the contract, allowing state change calls
Can only be called by an administrator
function unpause() external onlyRoles(OPERATOR_ROLE);
outputFulfilled
Check if a specific output hash exists for an order
function outputFulfilled(bytes32 orderId, bytes32 outputHash) external view returns (bool exists);
Parameters
| Name | Type | Description |
|---|---|---|
orderId | bytes32 | The order ID |
outputHash | bytes32 | The output hash to check |
Returns
| Name | Type | Description |
|---|---|---|
exists | bool | True if the output exists |
outputPayloadHash
Get the payload hash for a fulfilled output
function outputPayloadHash(bytes32 orderId, bytes32 outputHash) external view returns (bytes32 result);
Parameters
| Name | Type | Description |
|---|---|---|
orderId | bytes32 | The order ID |
outputHash | bytes32 | The output hash |
Returns
| Name | Type | Description |
|---|---|---|
result | bytes32 | The payload hash if output exists, bytes32(0) otherwise |
_payloadHash
Calculate payload hash for an output
function _payloadHash(bytes32 protocolId, uint32 timestamp) internal pure returns (bytes32 hash);
Parameters
| Name | Type | Description |
|---|---|---|
protocolId | bytes32 | The protocol ID |
timestamp | uint32 | The timestamp |
Returns
| Name | Type | Description |
|---|---|---|
hash | bytes32 | The payload hash |
_processCall
Process call and handle fallback on failure
function _processCall(RelayedOrderOutput calldata output) private;
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The output to process |
_relayToRecipient
Send funds and relay optional calldata to recipient
Calldata can only be relayed iff recipient is a contract
function _relayToRecipient(RelayedOrderOutput calldata output) internal;
Parameters
| Name | Type | Description |
|---|---|---|
output | RelayedOrderOutput | The output containing fallbackReceiver info |
receive
receive() external payable;
Events
OutputFulfilled
Emitted when a single output is fulfilled
event OutputFulfilled(
bytes32 indexed orderId,
bytes32 indexed outputHash,
bytes32 indexed payloadHash,
bytes32 recipient,
bytes32 token,
uint256 amount,
address filler
);
MetaIntentTransmitter
Inherits: Transmitter, ReentrancyGuard, OwnableRoles, Pausable, EIP712
Title: MetaIntentTransmitter
One-way order issuer that:
- Pulls inputs from user
- Executes protocol calls in order
- Emits event and exits
Constants
OPERATOR_ROLE
Operator role identifier
uint256 public constant OPERATOR_ROLE = _ROLE_0
AUTHORITY_ROLE
Authority role identifier
uint256 public constant AUTHORITY_ROLE = _ROLE_1
TOKEN_STACK_SLOT
Note: storage-location: erc7201:metaintenttransmitter.tokens
bytes32 constant TOKEN_STACK_SLOT = 0x1b08c89f51b1decc132fa8988a44ec87df810cdce8fa337e2d1606c8b95fe100
State Variables
_nonces
Prevent nonce reuse per user
mapping(address user => mapping(uint256 nonce => bytes32 orderId)) _nonces
_executedOrders
Track order execution for analytics
mapping(bytes32 orderId => uint256 nonce) _executedOrders
routeAuthority
Address for authorizing routes
address public routeAuthority
Functions
constructor
constructor(address owner, address operator, address authorizer, address initialRouteAuthority) EIP712();
execute
Execute a meta-intent order by pulling inputs and executing protocol calls
function execute(Order calldata order) external payable whenNotPaused nonReentrant returns (bytes32 orderId);
Parameters
| Name | Type | Description |
|---|---|---|
order | Order | The order to execute |
Returns
| Name | Type | Description |
|---|---|---|
orderId | bytes32 | Unique identifier for the executed order |
pause
Pause the contract, preventing state change calls
Can only be called by an administrator
function pause() external onlyRoles(OPERATOR_ROLE);
unpause
Unpause the contract, allowing state change calls
Can only be called by an administrator
function unpause() external onlyRoles(OPERATOR_ROLE);
setRouteAuthority
Update the route authority address
Can only be called by an administrator
function setRouteAuthority(address newRouteAuthority) external onlyRoles(AUTHORITY_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
newRouteAuthority | address | The new Mure signer address |
previewOrderId
Compute orderId without executing (for front-end)
function previewOrderId(Order calldata order) external view returns (bytes32);
orderConsumed
Check if an order has been consumed
function orderConsumed(bytes32 orderId) public view returns (bool);
nonceConsumed
Check if nonce has been used
function nonceConsumed(address user, uint256 nonce) public view returns (bool);
_consumeNonce
Consume a nonce for user and associate it with orderId
function _consumeNonce(address user, uint256 nonce, bytes32 orderId) internal;
_refundExcess
If return any current balance to msg.sender
function _refundExcess(address to) internal;
_verifyCallSignature
Verifies that the call signature is valid for the given order
Uses EIP712 domain hashing and SignatureCheckerLib for verification
function _verifyCallSignature(Order calldata order) internal view;
Parameters
| Name | Type | Description |
|---|---|---|
order | Order | The order to verify signature for |
_domainNameAndVersion
function _domainNameAndVersion() internal pure override returns (string memory name, string memory version);
_tokens
function _tokens() internal pure returns (LibTransient.TStack storage ptr);
_pushAddr
function _pushAddr(LibTransient.TStack storage tokens, address addr) internal;
_popAddr
function _popAddr(LibTransient.TStack storage tokens) internal returns (address addr);
_setRouteAuthority
function _setRouteAuthority(address newRouteAuthority) internal;
Events
OrderInitiated
Emitted when order is successfully initialized
Off-chain systems index this to track order lifecycle
event OrderInitiated(bytes32 indexed orderId, address indexed user, uint256 timestamp);
RouteAuthorityUpdated
Emitted when the route authority address is rotated
Off-chain systems index this to track signer changes
event RouteAuthorityUpdated(address indexed oldAuthority, address indexed newAuthority);
Delegate
Inherits: ERC165Upgradeable, ReentrancyGuardUpgradeable, AccessControlUpgradeable, Delegatable
Author: Mure Implements AccessControlUpgradeable for access control, UUPSUpgradeable for efficient upgrades, ERC165Upgradeable for interface support, and Delegatable for plugin compatibility. Manages storage for delegated functions, including user share per pool, pool configurations, pool contract,and plugins. Also provides hooks for custom functionality in pool-related operations. Delegate handles the various plugins that might be required by a particular application, for example, for reward claims and for fees deduction. Each application can subscribe to one or more plugins which will then link to the delegate for that application and be available to use. NOTE: A single instance of a delegate shall be bound to a single instance of the pool contract.
Abstract contract governing delegated functionality for the applications in Mure protocol.
Constants
DelegateStorageLocation
Struct hash for storage location
keccak256(abi.encode(uint256(keccak256("mure.Delegate")) - 1)) & ~bytes32(uint256(0xff))
bytes32 internal constant DelegateStorageLocation =
0xc4200f32c1c30cddd40d021baa377d96970df44812e3c252691c8e5d8633a500
CLAIM
Defines if the claim plugin is enabled
uint16 constant CLAIM = 0x01
DELEGATE_OPERATOR_ROLE
Role allows user to create and update pools along with pool administration
bytes32 public constant DELEGATE_OPERATOR_ROLE = keccak256("DELEGATE_OPERATOR")
Functions
onlyPool
modifier onlyPool() ;
validPool
modifier validPool(string calldata poolName) ;
onlyPlugin
modifier onlyPlugin() ;
pluginEnabled
modifier pluginEnabled(string calldata poolName, uint16 plugin) ;
pluginDisabled
modifier pluginDisabled(string calldata poolName, uint16 plugin) ;
onlyCustodianOrOwner
modifier onlyCustodianOrOwner(string calldata poolName) ;
__Delegate_init
Initializes the contract setting owner, poolContract, and claimPlugin.
function __Delegate_init(address owner, address poolContract_, address claimPlugin_) internal onlyInitializing;
withdrawPoolFunds
Places a delegated call to withdraw pool funds.
pauses the pool and locks refunds
function withdrawPoolFunds(string calldata poolName) external onlyCustodianOrOwner(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositPoolFunds
Deposits the withdrawn pool funds back. This operation assumes that the contract is an approved spender of the depositor.
Transfers the original collected funds back to the pool app. Additional funds stay on the delegate
Unpauses the pool and unlocks refunds
function depositPoolFunds(string calldata poolName, uint256 depositFunds, uint256 claimFunds)
external
onlyCustodianOrOwner(poolName)
nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositFunds | uint256 | the amount to be deposited back to the pool |
claimFunds | uint256 | funds for claims |
share
Returns the user depositor value.
function share(string calldata poolName, address depositor) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositor | address | address of the depositor |
state
Returns the pool config state.
function state(string calldata poolName) external view returns (PoolConfig memory);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
claim
Processes user claims.
function claim(string calldata poolName) external pluginEnabled(poolName, CLAIM) validPool(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
activateClaimPlugin
Activates the claim plugin.
function activateClaimPlugin(string calldata poolName, address claimCurrency)
external
onlyRole(DELEGATE_OPERATOR_ROLE)
validPool(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool to activate the plugin on |
claimCurrency | address |
deactivateClaimPlugin
Deactivates the claim plugin.
function deactivateClaimPlugin(string calldata poolName)
external
onlyRole(DELEGATE_OPERATOR_ROLE)
validPool(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool to deactivate the plugin on |
setPoolClaimCurrency
Sets the pool claim currency.
function setPoolClaimCurrency(string calldata poolName, address currency)
external
onlyRole(DELEGATE_OPERATOR_ROLE)
validPool(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
currency | address | the claim currency to be set |
setPoolFeePercentage
Sets the pools fee percentage.
Can only be called if the fee plugin is enabled.
Fee percentage is in basis points (1 = 0.01%).
function setPoolFeePercentage(string calldata poolName, uint16 feePercentage)
external
onlyRole(DELEGATE_OPERATOR_ROLE)
validPool(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
feePercentage | uint16 | the fee percentage to be set |
setPoolContract
Sets the pool app address.
Set as address(0) to deprecate delegate.
function setPoolContract(address poolContract) external onlyRole(DELEGATE_OPERATOR_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
poolContract | address | address of the pool app |
setClaimPlugin
Sets the claim plugin address.
function setClaimPlugin(address pluginAddress) external onlyRole(DELEGATE_OPERATOR_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
pluginAddress | address | address of the claim plugin |
deposit
Places a delegated call to deposit on the pool app. This operation assumes that the pool app is an approved spender of the depositor.
function deposit(string calldata poolName, DepositArgs calldata depositArgs) external nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositArgs | DepositArgs | deposit args as the DepositArgs struct |
refund
Places a delegated call for refund on the pool app.
function refund(string calldata poolName) external nonReentrant pluginDisabled(poolName, CLAIM);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
refund
Places a delegated call for refund on the pool app.
function refund(string calldata poolName, address depositor, uint256 amount) external nonReentrant onlyPlugin;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositor | address | |
amount | uint256 | amount to refund |
sendFunds
Transfers funds to a specific address.
Can only be called by a verified plugin.
function sendFunds(address to, uint256 amount, address currency) external onlyPlugin nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
to | address | address to be transferred to |
amount | uint256 | the amount to be transferred |
currency | address | the currency to be transferred |
previewClaim
Returns the refund amount, claim amount and fee.
function previewClaim(string calldata poolName, address depositor)
external
view
returns (uint256 depositDelta, uint256 claimDelta, uint256 fee);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositor | address | address of the depositor |
Returns
| Name | Type | Description |
|---|---|---|
depositDelta | uint256 | amount from the original deposit to be refunded |
claimDelta | uint256 | amount from the claim reserves to be claimed |
fee | uint256 | fee to be charged from claimDelta |
beforeDeposit
Hook to be called by the pool app before a deposit.
function beforeDeposit(string calldata poolName, uint256 amount, address depositor, bytes memory sig)
external
virtual
onlyPool;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
amount | uint256 | the amount to be deposited |
depositor | address | address of the depositor |
sig | bytes | the signature used for deposit |
afterDeposit
Hook to be called by the pool app after a deposit.
function afterDeposit(string calldata poolName, uint256 amount, address depositor, bytes memory sig)
external
virtual
onlyPool;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
amount | uint256 | the amount to be deposited |
depositor | address | address of the depositor |
sig | bytes | the signature used for deposit |
beforeRefund
Hook to be called by the pool app before a refund.
function beforeRefund(string calldata poolName, address depositor) external virtual onlyPool;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositor | address | address of the depositor |
afterRefund
Hook to be called by the pool app after a refund.
function afterRefund(string calldata poolName, address depositor, uint256 amount) external virtual onlyPool;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositor | address | address of the depositor |
amount | uint256 | refunded amount |
withdrawCurrency
Withdraw any token from the contract. This should only be used in emergencies
as this can withdraw capital from any pool, be it active or not. Always prefer using withdraw
over this function, unless you need clean up the contract by, e.g., burning garbage tokens.
function withdrawCurrency(address receiver, address currency) external onlyRole(DELEGATE_OPERATOR_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
receiver | address | the address to which the token will be transferred |
currency | address | the address of the token contract |
poolConfig
Retrieves the config of the specified pool.
function poolConfig(string calldata poolName) external view returns (PoolConfig memory);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to retrieve the config of |
poolAddress
Retrieves the pool app address.
function poolAddress() external view returns (address);
claimPluginAddress
Retrieves the claim plugin address.
function claimPluginAddress() external view returns (address);
isPoolActive
Checks if the specified pool is active.
function isPoolActive(string calldata poolName) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to check if it is active |
withdrawableAmount
Checks if the specified pool is active.
function withdrawableAmount(string calldata poolName) external view returns (uint112);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to check if it is active |
poolState
Retrieves the state of the specified pool.
Requires the pool to exist.
function poolState(string calldata poolName) external view returns (PoolState memory);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to retrieve the state of |
deposited
Retrieves the amount deposited by the specified depositor in the specified pool.
Requires the pool to exist.
function deposited(string calldata poolName, address depositor) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to retrieve the deposit from |
depositor | address | the address of the depositor |
poolExists
Checks if the specified pool exists.
function poolExists(string calldata poolName) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to check for existence |
getClaimCurrency
Returns the address of the claim currency for a pool.
function getClaimCurrency(string calldata poolName) external view returns (address);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to check for claim currency |
supportsInterface
See IERC165-supportsInterface.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override (ERC165Upgradeable, IERC165, AccessControlUpgradeable)
returns (bool);
_transferCurrency
Transfers currency between two addresses with a specified amount of a given currency.
function _transferCurrency(address from, address to, uint256 amount, address currency) internal;
Parameters
| Name | Type | Description |
|---|---|---|
from | address | the address from which the transfer is initiated |
to | address | the address to which the transfer is made |
amount | uint256 | the amount of the currency being transferred |
currency | address | the address of the currency being transferred |
_refund
function _refund(address poolContract, string calldata poolName, address depositor, uint256 amount) internal;
_addSupply
function _addSupply(string calldata poolName, address depositor, uint256 supply) internal;
_deductSupply
function _deductSupply(string calldata poolName, address depositor, uint256 supply) internal;
_claim
function _claim(string calldata poolName, uint256 totalCollected, address custodian, uint256 userDeposit) internal;
_pluginEnabled
Checks whether a specific plugin is enabled.
function _pluginEnabled(uint16 plugins, uint16 plugin) internal pure returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
plugins | uint16 | the set of plugins being checked |
plugin | uint16 | the plugin being checked for activation |
_activatePlugin
Activates the specified plugin.
function _activatePlugin(uint16 plugins, uint16 plugin) internal pure returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
plugins | uint16 | the set of plugins being modified |
plugin | uint16 | the plugin being activated |
_deactivatePlugin
Deactivates the specified plugin.
function _deactivatePlugin(uint16 plugins, uint16 plugin) internal pure returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
plugins | uint16 | the set of plugins being modified |
plugin | uint16 | the plugin being activated |
_getStorage
Retrieves the storage for the Delegate contract.
function _getStorage() internal pure returns (DelegateStorage storage $);
_isPlugin
Checks if the provided address is a plugin.
function _isPlugin(address address_) internal view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
address_ | address | the address to check |
Events
PluginActivated
event PluginActivated(string poolName, uint16 indexed plugin);
PluginDeactivated
event PluginDeactivated(string poolName, uint16 indexed plugin);
PluginUpdate
event PluginUpdate(address indexed pluginAddress, uint16 indexed plugin);
Structs
DelegateStorage
Note: storage-location: erc7201:mure.Delegate
struct DelegateStorage {
mapping(string => mapping(address => uint256)) shares;
mapping(string => PoolConfig) poolConfigs;
address poolContract;
address claimPlugin;
}
MureAxlTransceiver
Inherits: AxelarExecutableWithToken, Context
Constants
gasService
IAxelarGasService public immutable gasService
Functions
constructor
constructor(address gateway_, address gasService_) AxelarExecutableWithToken(gateway_);
Parameters
| Name | Type | Description |
|---|---|---|
gateway_ | address | address of axl gateway on deployed chain |
gasService_ | address | address of axl gas service on deployed chain |
transmitMessageWithToken
function transmitMessageWithToken(
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload,
string calldata symbol,
uint256 amount
) external payable;
_execute
function _execute(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload
) internal override;
_executeWithToken
logic to be executed on dest chain
this is triggered automatically by relayer
function _executeWithToken(
bytes32 commandId,
string calldata sourceChain,
string calldata sourceAddress,
bytes calldata payload,
string calldata tokenSymbol,
uint256 amount
) internal override;
Parameters
| Name | Type | Description |
|---|---|---|
commandId | bytes32 | |
sourceChain | string | |
sourceAddress | string | |
payload | bytes | encoded gmp message sent from src chain |
tokenSymbol | string | symbol of token sent from src chain |
amount | uint256 | amount of tokens sent from src chain |
Events
Executed
event Executed(bytes32 commandId, string sourceChain, string sourceAddress, bytes payload);
ExecutedWithToken
event ExecutedWithToken(
bytes32 commandId, string sourceChain, string sourceAddress, bytes payload, string tokenSymbol, uint256 amount
);
Errors
CallFailed
error CallFailed();
InsufficientGas
error InsufficientGas();
MureConfig
Inherits: EIP712Upgradeable, OwnableUpgradeable, UUPSUpgradeable, ERC165Upgradeable, Config
Title: MureConfig
Author: Mure
Upgradeable configuration contract governing Mure protocol settings, signers, and app delegates.
Implements Ownable for access control, UUPSUpgradeable for efficient upgrades, ERC165Upgradeable for
interface support, and Config interface for compatibility checks.
Manages whitelisted signers for secure operations, like verifying any EIP-712 signature used within the
Mure protocol is signed by one of the whitelisted signers. Supports toggling the whitelisting of signers.
Manages app delegates for flexible app functionality. Ensures that delegate contracts being set for an
application conform to the Delegatable interface, maintaining consistency and compatibility.
Constants
MureConfigStorageLocation
Struct hash for storage location
keccak256(abi.encode(uint256(keccak256("mure.MureConfig")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant MureConfigStorageLocation =
0x449166636934a062783bf0dfc33be04087c7302a55ece21ecb76ecfd3ffd2100
Functions
initialize
function initialize(string calldata name, string calldata version, address owner, address[] calldata signers)
external
initializer;
toggleWhitelistedSigner
Toggles the whitelisting of the specified address.
function toggleWhitelistedSigner(address signer_) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
signer_ | address | The address whose whitelisting is to be toggled. |
setAppDelegate
Sets the app delegate.
Set to address(0) to disable delegate
function setAppDelegate(address app, address delegate) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
app | address | address of the app |
delegate | address | address of the delegate |
getAppDelegate
Retrieves the app delegate.
function getAppDelegate(address app) external view returns (address);
Parameters
| Name | Type | Description |
|---|---|---|
app | address | address of the app |
verifyMureSignature
Validates if the provided signature has been created by one of the whitelisted signers.
function verifyMureSignature(bytes32 structHash, bytes memory signature) external view;
Parameters
| Name | Type | Description |
|---|---|---|
structHash | bytes32 | The hashed message that was signed. |
signature | bytes | The signature to be validated. |
isWhitelistedSigner
Checks whether the specified address is whitelisted.
function isWhitelistedSigner(address address_) public view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
address_ | address | The address to check. |
_toggleWhitelistedSigner
Toggles the whitelisting of the specified address.
function _toggleWhitelistedSigner(address signer_) private;
Parameters
| Name | Type | Description |
|---|---|---|
signer_ | address | The address whose whitelisting is to be toggled. |
_getStorage
Retrieves the storage for the MureConfig contract.
function _getStorage() private pure returns (MureConfigStorage storage $);
_supportsDelegateInterface
Checks if delegate supports delegate interface.
function _supportsDelegateInterface(address delegate) private view returns (bool);
supportsInterface
See IERC165-supportsInterface.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override (ERC165Upgradeable, IERC165)
returns (bool);
_authorizeUpgrade
required by the OZ UUPS module
function _authorizeUpgrade(address) internal override onlyOwner;
Events
AppDelegated
event AppDelegated(address indexed app, address indexed delegate);
Structs
MureConfigStorage
Note: storage-location: erc7201:mure.MureConfig
struct MureConfigStorage {
mapping(address => uint8) signers; // 1 - allowlisted
mapping(address => address) delegate;
}
MureDelegate
Inherits: Delegate
Functions
initialize
function initialize(address owner, address poolContract_, address claimPlugin_) external initializer;
MureDistribution
Inherits: EIP712Upgradeable, ERC165Upgradeable, AccessControlUpgradeable, ReentrancyGuardUpgradeable, UUPSUpgradeable, Distributable
Title: MureDistribution
Author: Mure
Distribution contract for distributing assets described by PoolMetadata contracts.
Recommended use is with a MurePool contract, where off-chain signatures are provided for
permits and saving gas by depending on off-chain compute power for complex computations based on
on-chain state.
Constants
DISTRIBUTION_ADMIN_ROLE
Role allows user to create and update pools along with pool administration
bytes32 public constant DISTRIBUTION_ADMIN_ROLE = keccak256("DISTRIBUTION_ADMIN")
MureDistributionStorageLocation
Hash for storage location
keccak256(abi.encode(uint256(keccak256("mure.MureDistribution")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant MureDistributionStorageLocation =
0xcb2c43c8a077042ee388281b9a5a398915ca6047194d75b071075a7b241a5800
DISTRIBUTION_HASH
Struct hash for validating deposits
keccak256("Distribution(address token,address source,string pool,address repository,address depositor,address claimer,uint256 amount,uint256 deadline,uint24 nonce)")
bytes32 private constant DISTRIBUTION_HASH = 0xc947aa90aaf074203df95a7de07adb71025f14e165fb180a3c83663110a02ce1
Functions
distributable
modifier distributable(DistributionRecord calldata distribution) ;
validManager
modifier validManager(address source) ;
initialize
function initialize(string calldata name, string calldata version, address owner) external initializer;
reinitialize
function reinitialize(address signer) external reinitializer(2);
supportsInterface
See IERC165-supportsInterface.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override (ERC165Upgradeable, AccessControlUpgradeable)
returns (bool);
distribute
function distribute(DistributionRecord calldata distribution, bytes calldata signature) external;
distribute
function distribute(DistributionRecord calldata distribution, address to, bytes calldata signature) external;
moveDistribution
Moves a distribution record from one depositor to another.
Only used for moving complete distributions in cases such as from being a compromised wallet.
function moveDistribution(address source, string calldata poolName, address from, address to)
external
validManager(source);
Parameters
| Name | Type | Description |
|---|---|---|
source | address | the address to the application contract where the deposit information exists |
poolName | string | the name of the pool where the deposit was conducted |
from | address | the address of the original depositor |
to | address | the address of the new depositor |
distribution
Read distribution history of depositor in the designated source and poolName
function distribution(address source, string calldata poolName, address depositor)
external
view
returns (DistributionHistory memory);
Parameters
| Name | Type | Description |
|---|---|---|
source | address | the address of the pooling contract |
poolName | string | the name pf the pool |
depositor | address | the address of the depositor |
nonce
Read nonce of depositor
function nonce(address depositor) external view returns (uint24);
Parameters
| Name | Type | Description |
|---|---|---|
depositor | address | the address of the depositor |
_distribute
Assumes that the token address is a valid ERC20 token as the standard doesn’t
depend on ERC165. Make sure that the token is valid to avoid reverts without error codes
function _distribute(DistributionRecord calldata distribution, address to, bytes calldata signature)
internal
distributable(distribution)
nonReentrant;
_hashDistribution
Generates a struct hash for a distribution.
function _hashDistribution(DistributionRecord calldata distribution, address to) private view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
distribution | DistributionRecord | the distribution information |
to | address |
_transferAssets
function _transferAssets(DistributionRecord calldata distribution, address to) internal;
_encodeDistributionKey
function _encodeDistributionKey(address source, string calldata poolName, address depositor)
internal
pure
returns (bytes32);
_verifySignature
function _verifySignature(DistributionRecord calldata distribution, address signer, address to, bytes calldata sig)
private
view;
_getDistributionStorage
Retrieves the storage for the pool metrics.
function _getDistributionStorage() private pure returns (MureDistributionStorage storage $);
_authorizeUpgrade
function _authorizeUpgrade(address) internal override onlyRole(DISTRIBUTION_ADMIN_ROLE);
Structs
MureDistributionStorage
Note: storage-location: erc7201:mure.MureDistribution
struct MureDistributionStorage {
mapping(bytes32 => DistributionHistory) distributions;
mapping(address => uint24) nonces;
address signer; // added with patch
}
MurePool
Inherits: EIP712Upgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable, ERC165Upgradeable, AccessControlUpgradeable, PoolApp
Title: MurePool
Author: Mure
Facilitates secure and configurable pool management, supporting operations such as pool creation, deposits, withdrawals, and refunds.
Core implementation contract for pooled investments in the Mure protocol. Utilizes the beacon proxy pattern to deploy multiple proxies, each representing a distinct application within the protocol. The MureFactory contract handles these deployments. Implements the EIP-712 standard for signature validation, preventing unauthorized access. Relies on the MureConfig contract to verify EIP-712 signatures and manage the pool creation process. Interaction with the MureConfig contract allows dynamic configuration and signature validation. Security measures include the OpenZeppelin PausableUpgradeable pattern for emergency pausing, ReentrancyGuardUpgradeable to prevent reentrancy attacks, and role based access control through AccessControlUpgradeable. Flag-based functionality enables features like refundability, passthrough of funds, and more. Provides hooks for custom functionality in pool-related operations Depending on the kind of application, the MurePool proxy instance could be linked to a MureDelegate proxy instance for interacting with various plugins that the protocol provides.
Constants
MurePoolStorageLocation
Hash for storage location
keccak256(abi.encode(uint256(keccak256("mure.MurePool")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant MurePoolStorageLocation =
0x79bd164051f83036bb52eee1d9b6be5ba887eaf3a9d8907adbaadfa56c970700
PoolMetricsStorageLocation
Hash for storage location
keccak256(abi.encode(uint256(keccak256("mure.PoolMetrics")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PoolMetricsStorageLocation =
0x1ca3e723ed845754b3d7cf12c13e1b284ab752e694e983a627f991c98b3a0700
DEPOSIT_HASH
Struct hash for validating deposits
keccak256("Deposit(uint256 amount,string pool,address depositor,uint8 nonce,address caller,FeeConfig feeConfig,bytes permitSig)FeeConfig(uint112 amount,address recipient)")
bytes32 private constant DEPOSIT_HASH = 0xc89d53aaf3bcb1537286e629ce2d0d2490185593558793ccb9d770ed5a9b85ba
DEPOSIT_PERMIT_HASH
Struct hash for validating deposit permits
keccak256("DepositPermit(uint256 amount,string pool,address caller,uint256 depositorNonce)")
bytes32 private constant DEPOSIT_PERMIT_HASH = 0xc366e7e07f30c8c114e87a55f528d0226c44edffd2f25b0230dd00e3263a349c
CREATE_POOL_HASH
Struct hash for validating pool creation
keccak256("CreatePool(string pool,uint32 endTime,uint24 nonce)")
bytes32 private constant CREATE_POOL_HASH = 0x38c6f9238aff6821963f06d84f958ebb018ff9e4343c962882ef7b3308ff1b4d
MURE_CONFIG
Address for the MureConfig contract
Update config address
address constant MURE_CONFIG = 0x2b727332eF478bAe460ecF0CAb7C1487a87D68B8
INITIALIZED
Defines if the pool is initialized
uint16 constant INITIALIZED = 0x01
PAUSED
Defines if the pool is paused from any interaction
uint16 constant PAUSED = 0x02
PASSTHROUGH_FUNDS
PASSTHROUGH_FUNDS and REFUNDABLE cannot be set at the same time
Defines if deposits should pass straight to associtated raising wallet upon deposit
uint16 constant PASSTHROUGH_FUNDS = 0x04
REFUNDABLE
PASSTHROUGH_FUNDS and REFUNDABLE cannot be set at the same time
Defines if the pool is open for claiming refunds
uint16 constant REFUNDABLE = 0x08
TIERED
Defines if the pool is having tiers and gating
uint16 constant TIERED = 0x10
CROSS_CHAIN
Defines if the pool is cross-chain enabled, pooling funds across different networks
uint16 constant CROSS_CHAIN = 0x20
DELEGATED
Defines if the pool allows for use of delegated wallets for security
uint16 constant DELEGATED = 0x40
Functions
poolValid
modifier poolValid(string calldata poolName) ;
poolActive
modifier poolActive(string calldata poolName) ;
poolNotPaused
modifier poolNotPaused(string calldata poolName) ;
valid
modifier valid(PoolParameters calldata params) ;
onlyDelegateOrOperator
modifier onlyDelegateOrOperator() ;
onlyDelegate
modifier onlyDelegate() ;
notDelegated
modifier notDelegated() ;
initialize
function initialize(string calldata name, string calldata version, AppMember[] calldata members)
external
initializer;
createPool
Creates a new pool with the specified parameters.
Requires the pool to not already exist. Can only be called by a pool operator.
function createPool(string calldata poolName, PoolParameters calldata params, bytes memory sig)
external
onlyRole(POOL_OPERATOR_ROLE)
valid(params);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to create |
params | PoolParameters | the parameters for the new pool |
sig | bytes | the signature generated for pool creation for client |
updatePool
Updates the specified pool with the provided parameters.
Requires the pool to exist. Can only be called by a pool operator.
Requires the updated pool size to be greater than or equal to the total amount collected.
function updatePool(string calldata poolName, PoolParameters calldata params)
external
onlyRole(POOL_OPERATOR_ROLE)
valid(params)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to update |
params | PoolParameters | the updated parameters for the pool |
updatePoolSize
Updates the size of the specified pool.
Requires the pool to exist. Can only be called by a pool operator.
Requires the new pool size to be greater than or equal to the total amount collected.
function updatePoolSize(string calldata poolName, uint256 poolSize)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to update |
poolSize | uint256 | the updated size of the pool |
updatePoolEndTime
Updates the end time of the specified pool.
Requires the pool to exist. Can only be called by a pool operator.
function updatePoolEndTime(string calldata poolName, uint256 endTime)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to update |
endTime | uint256 | the updated end time for the pool |
updatePoolSigner
Updates the signer of the specified pool.
Requires the pool to exist. Can only be called by a pool operator.
function updatePoolSigner(string calldata poolName, address _signer)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to update |
_signer | address | the updated signer for the pool |
updatePoolPaused
Pauses or unpauses the specified pool.
Requires the pool to exist. Can only be called by a pool operator or delegate.
function updatePoolPaused(string calldata poolName, bool pause)
external
onlyDelegateOrOperator
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to pause or unpause |
pause | bool | a boolean representing whether to pause or unpause the pool |
updatePoolRefundable
Updates whether the specified pool allows refunds or not.
Requires the pool to exist. Can only be called by a pool operator.
Requires that the pool does not have the PASSTHROUGH_FUNDS flag set if enabling refunds.
function updatePoolRefundable(string calldata poolName, bool refundable)
external
onlyDelegateOrOperator
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to update |
refundable | bool | a boolean representing whether refunds should be enabled or not |
updatePoolPassthroughFunds
Updates whether the specified pool passes funds through to the custodian directly or not.
Requires the pool to exist. Can only be called by a pool operator.
Requires that the pool does not have the REFUNDABLE flag set if enabling passthrough funds.
function updatePoolPassthroughFunds(string calldata poolName, bool passthroughFunds)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to update |
passthroughFunds | bool | a boolean representing whether to enable passthrough funds or not |
withdrawPoolFunds
Withdraws the total collected amount from the specified pool.
Requires the pool to exist. Can only be called by a pool operator or the delegate if it is set.
function withdrawPoolFunds(string calldata poolName) external onlyDelegateOrOperator poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to withdraw from |
withdrawCurrency
Withdraw any token from the contract. This should only be used in emergencies
as this can withdraw capital from any pool, be it active or not. Always prefer using withdrawPoolFunds
over this function, unless you need clean up the contract by, e.g., burning garbage tokens.
function withdrawCurrency(address receiver, address currency) external onlyRole(DEFAULT_ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
receiver | address | the address to which the token will be transferred |
currency | address | the address of the token contract |
addDeposit
Adds a deposit of the specified amount to the pool for the designated depositor.
Requires the pool to exist. Can only be called by a pool operator.
function addDeposit(string calldata poolName, address depositor, uint256 amount)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to add the deposit to |
depositor | address | the address of the depositor |
amount | uint256 | the amount of the deposit |
deductDeposit
Deducts the specified amount from the deposit of the designated depositor in the pool.
Requires the pool to exist. Can only be called by a pool operator.
function deductDeposit(string calldata poolName, address depositor, uint256 amount)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to deduct the deposit from |
depositor | address | the address of the depositor |
amount | uint256 | the amount to deduct |
moveDeposit
Moves the specified amount from one depositor’s deposit to another in the pool.
Requires the pool to exist. Can only be called by a pool operator.
function moveDeposit(string calldata poolName, address from, address to, uint256 amount)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to move the deposit in |
from | address | the address of the depositor to deduct the deposit from |
to | address | the address of the depositor to add the deposit to |
amount | uint256 | the amount to move |
batchDeposit
Adds or deducts balances on a per-depositor basis in batches.
Requires the pool to exist. Can only be called by the contract owner.
function batchDeposit(string calldata poolName, Transaction[] calldata transactions)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to move the deposit in |
transactions | Transaction[] | the set of Transactions to execute on the provided poolName |
batchDeposit
Adds or deducts balances on a per-depositor basis in batches.
Requires the pool to exist. Can only be called by the contract owner.
function batchDeposit(string calldata poolName, TransactionWithMetadata[] calldata transactions)
external
onlyRole(POOL_OPERATOR_ROLE)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to move the deposit in |
transactions | TransactionWithMetadata[] | the set of TransactionWithMetadatas to execute on the provided poolName |
deposit
Deposits amount of the relevant currency for the pool poolName.
This operation assumes that the contract is an approved spender of the depositor.
This operation is disabled for delegated pools, use depositFor instead
function deposit(string calldata poolName, DepositArgs calldata depositDetails) external notDelegated;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | bytes32 representation of the pool name |
depositDetails | DepositArgs | details of the deposit per the DepositArgs struct |
refund
Allows a user to refund their deposited amount from the specified pool. This operation is disabled for delegated pools, use refundTo instead.
Requires the pool to exist.
Requires the pool to be not paused and must have the REFUNDABLE flag set.
function refund(string calldata poolName) external notDelegated;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool from which to refund |
refund
Allows a user to refund their deposited amount from the specified pool. This operation is disabled for delegated pools, use refundTo instead.
Requires the pool to exist.
Requires the pool to be not paused and must have the REFUNDABLE flag set.
function refund(string calldata poolName, bytes calldata data) external notDelegated;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool from which to refund |
data | bytes | additional data as contextual data for off-chain validation |
refundTo
Allows a refund of the deposited amount from the specified pool.
Requires the pool to exist.
Requires the pool to be not paused and must have the REFUNDABLE flag set.
function refundTo(string calldata poolName, address depositor, uint256 amount) external onlyDelegate;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool from which to refund |
depositor | address | address of the depositor |
amount | uint256 |
depositPoolFunds
Deposits the withdrawn pool funds back. This operation assumes that the contract is an approved spender of the depositor.
Transfers the original collected funds back to the pool app
function depositPoolFunds(string calldata poolName, address depositor, uint256 amount) external onlyDelegate;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositor | address | the address of the depositor |
amount | uint256 | the amount to be deposited back to the pool |
poolState
Retrieves the state of the specified pool.
Requires the pool to exist.
function poolState(string calldata poolName) external view poolValid(poolName) returns (PoolState memory);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to retrieve the state of |
poolMetrics
Retrieves the metrics of the specified pool.
Requires the pool to exist.
function poolMetrics(string calldata poolName) external view poolValid(poolName) returns (PoolMetrics memory);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to retrieve the metrics of |
deposited
Retrieves the amount deposited by the specified depositor in the specified pool.
Requires the pool to exist.
function deposited(string calldata poolName, address depositor)
external
view
poolValid(poolName)
returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to retrieve the deposit from |
depositor | address | the address of the depositor |
nonce
Retrieves the nonce of the specified depositor in the specified pool.
Requires the pool to exist.
function nonce(string calldata poolName, address depositor) external view poolValid(poolName) returns (uint8);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to retrieve the nonce from |
depositor | address | the address of the depositor |
nonce
Retrieves the nonce for create pool signature generation.
function nonce() external view returns (uint24);
poolExists
Checks if the specified pool exists.
function poolExists(string calldata pool) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
pool | string | the name of the pool to check for existence |
isPoolActive
Checks if the specified pool is active.
function isPoolActive(string calldata poolName) external view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to check if it is active |
withdrawableAmount
Checks if the specified pool is active.
function withdrawableAmount(string calldata poolName) external view returns (uint112);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to check if it is active |
supportsInterface
See IERC165-supportsInterface.
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override (ERC165Upgradeable, IERC165, AccessControlUpgradeable)
returns (bool);
_grantRolesToMembers
Grants roles to the members based on their specified roles in the struct.
function _grantRolesToMembers(AppMember[] calldata members) private;
Parameters
| Name | Type | Description |
|---|---|---|
members | AppMember[] | An array of AppMember structs containing the member’s address and their role to be granted. |
_deposit
Deposits amount of the relevant currency for the pool poolName.
This operation assumes that the contract is an approved spender of the depositor.
function _deposit(string calldata poolName, DepositArgs calldata depositDetails)
private
whenNotPaused
nonReentrant
poolValid(poolName)
poolActive(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | bytes32 representation of the pool name |
depositDetails | DepositArgs | the amount, depositor, payer, permitSig and additional data for the deposit |
_refund
Allows a user to refund their deposited amount from the specified pool.
Requires the pool to exist.
Requires the pool to be not paused and must have the REFUNDABLE flag set.
function _refund(string calldata poolName, address depositor, uint256 amount, bytes memory data)
private
nonReentrant
whenNotPaused
poolNotPaused(poolName)
poolValid(poolName);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool from which to refund |
depositor | address | address of the depositor to refund from |
amount | uint256 | the amount to refund |
data | bytes | additional data as contextual data for off-chain validation |
_depositPoolFunds
Deposits the withdrawn pool funds back.
Transfers the original collected funds back to the pool app
function _depositPoolFunds(string calldata poolName, address depositor, uint256 amount) private nonReentrant;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
depositor | address | the address of the depositor |
amount | uint256 | the amount to be deposited back to the pool |
_addDeposit
Adds deposit amount to designated poolName under depositor.
As totalCollected is bound by poolSize, overflow is not possible unless poolSize
is in a disallowed state to begin with.
function _addDeposit(string calldata poolName, address depositor, uint256 amount, bytes memory data) private;
_unsafeAddDeposit
Adds deposit amount to designated poolName under depositor.
Skips pool size check. To be used for manual overrides like moveDeposit and batchDeposit
function _unsafeAddDeposit(string calldata poolName, address depositor, uint256 amount, bytes memory data) private;
_deductDeposit
Deducts deposit amount from designated poolName under depositor.
As totalCollected is the cumulative sum of all depositors under poolName,
underflow is not possible unless totalCollected is in a disallowed state to begin with.
function _deductDeposit(string calldata poolName, address depositor, uint256 amount, bytes memory data) private;
_transferUpdate
Updates the transfer between two addresses with a specified amount of a given currency.
function _transferUpdate(address from, address to, uint256 amount, address currency) private;
Parameters
| Name | Type | Description |
|---|---|---|
from | address | the address from which the transfer is initiated |
to | address | the address to which the transfer is made |
amount | uint256 | the amount of the currency being transferred |
currency | address | the address of the currency being transferred |
_poolExists
Checks whether a pool with the specified name exists.
function _poolExists(string calldata pool) private view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
pool | string | the name of the pool being checked |
_verifyParams
Verifies the validity of the specified pool parameters.
function _verifyParams(PoolParameters calldata config) private pure;
Parameters
| Name | Type | Description |
|---|---|---|
config | PoolParameters | the parameters of the pool being verified |
_poolComplete
Checks whether the specified pool has been completed.
function _poolComplete(string calldata poolName) private view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool being checked |
_hashDeposit
Generates a hashed representation of the specified amount and pool name, along with the sender’s nonce.
function _hashDeposit(
uint256 amount,
string calldata poolName,
address depositor,
address caller,
FeeConfig memory feeConfig,
bytes memory permitSig
) internal view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | the amount of the deposit |
poolName | string | the name of the pool |
depositor | address | address of the depositor |
caller | address | |
feeConfig | FeeConfig | |
permitSig | bytes | signature to permit deposit on behalf of user |
_hashCreatePool
Generates a struct hash of the specified pool name and end time, along with the nonce.
function _hashCreatePool(string calldata poolName, uint32 endTime) private view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool |
endTime | uint32 | the endtime block timestamp for the pool |
_verifyPoolSize
Verifies the validity of the pool size for an existing pool.
function _verifyPoolSize(uint112 totalCollected, uint112 newPoolSize) private pure;
Parameters
| Name | Type | Description |
|---|---|---|
totalCollected | uint112 | total collected amount for the pool being updated |
newPoolSize | uint112 | new pool size for the pool being updated |
_hasFlag
Checks whether a specific flag is activated within a set of flags.
function _hasFlag(uint16 flags, uint16 flag) private pure returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
flags | uint16 | the set of flags being checked |
flag | uint16 | the flag being checked for activation |
_activateFlag
Activates the specified flag within a set of flags.
function _activateFlag(uint16 flags, uint16 flag) private pure returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
flags | uint16 | the set of flags being modified |
flag | uint16 | the flag being activated |
_deactivateFlag
Deactivates the specified flag within a set of flags.
function _deactivateFlag(uint16 flags, uint16 flag) private pure returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
flags | uint16 | the set of flags being modified |
flag | uint16 | the flag being deactivated |
_getDelegateAddress
Retrieves the delegate address from config.
function _getDelegateAddress() private returns (address delegate);
_beforeDeposit
Performs delegate operations before deposit operation.
function _beforeDeposit(
address delegateAddress,
string calldata poolName,
uint256 amount,
address depositor,
bytes calldata sig
) private;
Parameters
| Name | Type | Description |
|---|---|---|
delegateAddress | address | address of the delegate contract |
poolName | string | name of the pool |
amount | uint256 | deposit amount |
depositor | address | |
sig | bytes | deposit signature |
_afterDeposit
Performs delegate operations after deposit operation.
function _afterDeposit(
address delegateAddress,
string calldata poolName,
uint256 amount,
address depositor,
bytes calldata sig
) private;
Parameters
| Name | Type | Description |
|---|---|---|
delegateAddress | address | address of the delegate contract |
poolName | string | name of the pool |
amount | uint256 | deposit amount |
depositor | address | |
sig | bytes | deposit signature |
_beforeRefund
Performs delegate operations before refund operation.
function _beforeRefund(address delegateAddress, string calldata poolName, address depositor) private;
Parameters
| Name | Type | Description |
|---|---|---|
delegateAddress | address | address of the delegate contract |
poolName | string | name of the pool |
depositor | address | address of the depositor |
_afterRefund
Performs delegate operations after refund operation.
function _afterRefund(address delegateAddress, string calldata poolName, address depositor, uint256 amount)
private;
Parameters
| Name | Type | Description |
|---|---|---|
delegateAddress | address | address of the delegate contract |
poolName | string | name of the pool |
depositor | address | address of the depositor |
amount | uint256 | the refund amount |
_consumeDepositorNonce
Increments depositor’s nonce for the pool.
function _consumeDepositorNonce(string calldata poolName, address depositor, DepositRecord storage deposit_)
private;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | |
depositor | address | |
deposit_ | DepositRecord | reference to the deposit record |
_getStorage
Retrieves the storage for the MurePool contract.
function _getStorage() private pure returns (MurePoolStorage storage $);
_getPoolMetricsStorage
Retrieves the storage for the pool metrics.
function _getPoolMetricsStorage() private pure returns (PoolMetricsStorage storage $);
_verifySignature
function _verifySignature(
DepositArgs memory depositDetails,
string calldata poolName,
address signer,
bytes calldata depositSig
) private view;
_hashDepositPermit
function _hashDepositPermit(DepositPermit memory permit) internal view returns (bytes32);
_verifyDepositPermit
function _verifyDepositPermit(DepositPermit memory permit, bytes memory permitSig) internal view;
Structs
MurePoolStorage
Note: storage-location: erc7201:mure.MurePool
struct MurePoolStorage {
mapping(string => PoolState) pools;
mapping(string => mapping(address => DepositRecord)) deposits;
uint24 nonce;
}
PoolMetricsStorage
Note: storage-location: erc7201:mure.PoolMetrics
struct PoolMetricsStorage {
mapping(string => PoolMetrics) poolMetrics;
}
MurePoolFactory
Inherits: Ownable, EIP712
Title: MurePoolFactory
Author: Mure
Factory contract for deploying applications as instances of the BeaconProxy contract
within the Mure protocol.
Facilitates the secure and efficient deployment of upgradeable app contracts using the beacon proxy pattern. Implements the EIP-712 standard for signature validation and Ownable for access control. The factory contract relies on the MureConfig contract to verify EIP-712 signatures and manage the deployment process. Signatures are added with an expiry to enhance the security of the deployment process by ensuring that the provided signature is only valid within a certain time frame.
Constants
DEPLOY_APP_HASH
Struct hash for validating app deployments
keccak256("Deployment(string appName,string version,AppMember[] appMembers,uint256 nonce,uint256 deadline,address caller,string data)AppMember(address member,uint8 role)")
bytes32 private constant DEPLOY_APP_HASH = 0xe78e92e91ab6665af572917421100be08c66583917c23ae7a02b72bed7edc218
State Variables
beaconAddress
address public beaconAddress
config
MureConfig public config
nonces
Nonce mapping for signatures to prevent replay
mapping(address => uint256) public nonces
Functions
constructor
constructor(address beaconAddress_, address config_, string memory name_, string memory version_)
Ownable(msg.sender)
EIP712(name_, version_);
deployAppProxy
Deploys an instance of the beacon proxy.
Requires signature for authorization.
function deployAppProxy(
string calldata appName,
string calldata version,
AppMember[] calldata appMembers,
uint256 deadline,
string calldata data,
bytes calldata sig
) external returns (address proxy);
Parameters
| Name | Type | Description |
|---|---|---|
appName | string | name of the app contract instance |
version | string | of the app contract instance |
appMembers | AppMember[] | array of app members and their roles for the app contract instance |
deadline | uint256 | expiration time of the signature |
data | string | data to be emitted on creation |
sig | bytes | signature generated for the user |
setBeaconAddress
Sets the beacon address for future proxy creation.
Can only be called by the contract owner.
function setBeaconAddress(address beaconAddress_) external onlyOwner;
Parameters
| Name | Type | Description |
|---|---|---|
beaconAddress_ | address | new beacon address to be set |
_hash
Generates a hashed representation of the app name, version, members, deadline, along with the sender’s nonce.
function _hash(
string calldata appName,
string calldata version,
AppMember[] calldata appMembers,
uint256 deadline,
string calldata data
) private view returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
appName | string | name of the app contract |
version | string | version of the app contract |
appMembers | AppMember[] | array of admin addresses and their corresponding roles for the app contract |
deadline | uint256 | expiry of the signature |
data | string | data to be emitted on creation |
_hashAppMembers
Computes the keccak256 hash of an array of AppMember structs.
function _hashAppMembers(AppMember[] calldata appMembers) private pure returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
appMembers | AppMember[] | The array of AppMember structs to be hashed. |
_extractAppRoles
Extracts and categorizes members into admins and operators based on their roles.
function _extractAppRoles(AppMember[] calldata appMembers)
private
pure
returns (address[] memory, address[] memory);
Parameters
| Name | Type | Description |
|---|---|---|
appMembers | AppMember[] | An array of AppMember structs containing the member address and role. |
_validateAdminRoleExists
Validates that there is at least one member with the DEFAULT_ADMIN role in the provided appMembers array.
function _validateAdminRoleExists(AppMember[] calldata appMembers) private pure returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
appMembers | AppMember[] | An array of AppMember structs containing the member address and role. |
Events
Deployment
event Deployment(
string indexed appName, address[] appAdmins, address[] appOperators, address indexed appAddress, string data
);
BeaconUpdate
event BeaconUpdate(address indexed beaconAddress);
TestUsdc
Inherits: ERC20
Functions
constructor
constructor() ERC20("TestUsdc", "USDC");
mint
function mint(address account, uint256 amount) external;
burn
function burn(address account, uint256 amount) external;
Ticket
Inherits: AccessControl, ERC20, ERC20Permit
Title: Ticket
Author: Mure
ERC-20 token contract for a ticketing system. This token contract is meant to facilitate ticket system. A user can deposit a configurable currency in exchange for this token. A burn mechanism is provided to be used to indicate ticket consumption.
Constants
FEE_MANAGER
Role allows user to update fee configuration
bytes32 public constant FEE_MANAGER = keccak256("FEE_MANAGER")
TICKET_OPERATOR
Role allows user to operate the ticket contract
bytes32 public constant TICKET_OPERATOR = keccak256("TICKET_OPERATOR")
TRANSFER_ROLE
Role allows user to transfer the token
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE")
State Variables
CURRENCY
The address of the exchange currency token contract.
address public CURRENCY
exchangePrice
Exchange rate of a ticket with the configured currency.
uint256 public exchangePrice
feeConfig
Fee configuration for the received funds. Fee splits are in basis points.
FeeConfig private feeConfig
discountConfig
Discount rates based on purchase quantity sorted based on quantity. Percentages are in basis points.
DiscountRate[] private discountConfig
Functions
constructor
Construct a new instance of this TICKET contract configured with the given immutable contract addresses.
constructor(
address currencyAddress_,
uint256 exchangePrice_,
DiscountRate[] memory discountConfig_,
FeeConfig memory feeConfig_,
address operator_,
address feeManager_,
string memory name_,
string memory symbol_
) ERC20(name_, symbol_) ERC20Permit(name_);
Parameters
| Name | Type | Description |
|---|---|---|
currencyAddress_ | address | the address of the ERC-20 currency token contract. |
exchangePrice_ | uint256 | the initial currency exchange price. |
discountConfig_ | DiscountRate[] | the initial discount rates. |
feeConfig_ | FeeConfig | the initial fee recipient configuration. |
operator_ | address | |
feeManager_ | address | |
name_ | string | name of the token contract. |
symbol_ | string | symbol of the token contract. |
purchaseTicket
Exchange currency for $TICKET.
Transfers deposited currency to FEE_RECIPIENTS and mints $TICKET based on price.
function purchaseTicket(uint256 quantity) external;
Parameters
| Name | Type | Description |
|---|---|---|
quantity | uint256 | the amount of $TICKET to purchase. |
purchaseTicket
Exchange currency for $TICKET.
Transfers deposited currency to FEE_RECIPIENTS and mints $TICKET based on price.
function purchaseTicket(uint256 quantity, address to) external;
Parameters
| Name | Type | Description |
|---|---|---|
quantity | uint256 | the amount of $TICKET to purchase. |
to | address | address to send the $TICKET to. |
sendTickets
send $TICKET to an address.
Mints $TICKET to the specified address.
function sendTickets(uint256 quantity, address to) external onlyRole(TICKET_OPERATOR);
Parameters
| Name | Type | Description |
|---|---|---|
quantity | uint256 | the amount of $TICKET to send. |
to | address | address to send the $TICKET to. |
sendTickets
send $TICKET to multiple address.
Mints $TICKET to the specified addresses.
function sendTickets(TicketRecipient[] calldata recipients) external onlyRole(TICKET_OPERATOR);
Parameters
| Name | Type | Description |
|---|---|---|
recipients | TicketRecipient[] | array of ticket recipients. |
updateExchangePrice
Allow a permitted caller to update the base exchange price.
function updateExchangePrice(uint256 exchangePrice_) external onlyRole(TICKET_OPERATOR);
Parameters
| Name | Type | Description |
|---|---|---|
exchangePrice_ | uint256 | updated base price. |
updateCurrencyAddress
Allow a permitted caller to update the exchange currency address.
function updateCurrencyAddress(address currencyAddress_) external onlyRole(TICKET_OPERATOR);
Parameters
| Name | Type | Description |
|---|---|---|
currencyAddress_ | address | updated currency address. |
getPrice
Returns the price in currency to charge for given $TICKET amount.
function getPrice(uint256 purchaseQuantity) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
purchaseQuantity | uint256 | the amount of $TICKET to purchase |
getDiscountRate
Returns the discount rate for given $TICKET amount.
function getDiscountRate(uint256 purchaseQuantity) external view returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
purchaseQuantity | uint256 | the amount of $TICKET to purchase |
getDiscountConfig
function getDiscountConfig() external view returns (DiscountRate[] memory);
getFeeConfig
function getFeeConfig() external view returns (FeeRecipient[] memory, uint16);
decimals
function decimals() public view virtual override returns (uint8);
setDiscountConfig
Sets discount rates for purchase quantities.
makes sure that the array is sorted based on quantity and the percentages being set are valid.
function setDiscountConfig(DiscountRate[] calldata discountConfig_) public onlyRole(TICKET_OPERATOR);
Parameters
| Name | Type | Description |
|---|---|---|
discountConfig_ | DiscountRate[] | discount config with percentages in basis points |
setFeeConfig
Sets the fee configuration.
function setFeeConfig(FeeConfig calldata feeConfig_) public onlyRole(FEE_MANAGER);
Parameters
| Name | Type | Description |
|---|---|---|
feeConfig_ | FeeConfig | fee configuration with percentages in basis points |
burn
Permit callers to burn their $TICKET.
function burn(uint256 quantity) public;
Parameters
| Name | Type | Description |
|---|---|---|
quantity | uint256 | The quantity of tickets to burn. |
withdrawCurrency
Withdraw any token from the contract. This should only be used in emergencies
function withdrawCurrency(address receiver, address currency) external onlyRole(FEE_MANAGER);
Parameters
| Name | Type | Description |
|---|---|---|
receiver | address | the address to which the token will be transferred |
currency | address | the address of the token contract |
_mintTicket
Mints $TICKET to specified address.
function _mintTicket(TicketRecipient memory ticketRecipient) private;
Parameters
| Name | Type | Description |
|---|---|---|
ticketRecipient | TicketRecipient | ticket quantity and recipient configuration |
_transferFee
Transfers the fee for $TICKET purchase.
function _transferFee(uint256 amount) private;
Parameters
| Name | Type | Description |
|---|---|---|
amount | uint256 | the amount of price being charged |
_transferCurrency
Transfers currency from the given address to the given address.
function _transferCurrency(address from, address to, uint256 amount) private;
Parameters
| Name | Type | Description |
|---|---|---|
from | address | the address from which the transfer is initiated |
to | address | the address to which the currency will be transferred |
amount | uint256 | the amount of currency to be transferred |
_calculatePrice
Determines the price in currency to charge for given $TICKET amount.
Deducts the discount from base price.
function _calculatePrice(uint256 purchaseQuantity) private view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
purchaseQuantity | uint256 | the amount of $TICKET to purchase |
_calculateDiscountRate
Determines the discount rate based on quantity being purchased.
function _calculateDiscountRate(uint256 purchaseQuantity) private view returns (uint16);
Parameters
| Name | Type | Description |
|---|---|---|
purchaseQuantity | uint256 | the amount of $TICKET to purchase |
_setFeeConfig
Sets the fee configuration.
function _setFeeConfig(FeeConfig memory feeConfig_) private;
Parameters
| Name | Type | Description |
|---|---|---|
feeConfig_ | FeeConfig | fee configuration with percentages in basis points |
_setDiscountConfig
Sets discount rates for purchase quantities.
makes sure that the array is sorted based on quantity and the percentages being set are valid.
function _setDiscountConfig(DiscountRate[] memory discountConfig_) private;
Parameters
| Name | Type | Description |
|---|---|---|
discountConfig_ | DiscountRate[] | discount config with percentages in basis points |
_update
Override ERC20._update to restrict transfers to whitelisted addresses
function _update(address from, address to, uint256 value) internal virtual override;
Events
DiscountUpdated
event DiscountUpdated(DiscountRate[] indexed discountConfig);
TicketsMinted
event TicketsMinted(address indexed to, uint256 indexed quantity);
TicketsBurned
event TicketsBurned(address indexed from, uint256 indexed quantity);
CurrencyUpdated
event CurrencyUpdated(address indexed currencyAddress);
FeeConfigUpdated
event FeeConfigUpdated(FeeConfig indexed feeConfig);
ExchangePriceUpdated
event ExchangePriceUpdated(uint256 indexed exchangePrice);
Errors
TransferFailure
This error is thrown when transfer of currency fails.
error TransferFailure();
InvalidDiscountRate
This error is thrown when the discount rate being set is invalid.
error InvalidDiscountRate();
InvalidFeeConfig
This error is thrown when the fee configuration being set is invalid.
error InvalidFeeConfig();
UnauthorizedTransfer
This error is thrown when the transfer isn’t made from or to a whitelisted address.
error UnauthorizedTransfer();
Structs
DiscountRate
Struct for discount rate configuration
struct DiscountRate {
uint256 quantity;
uint16 discount;
}
FeeRecipient
Struct for fee recipient configuration
struct FeeRecipient {
address recipient;
uint16 split;
}
TicketRecipient
Struct for ticket recipients
struct TicketRecipient {
address recipient;
uint256 quantity;
}
FeeConfig
Struct for fee configuration
struct FeeConfig {
FeeRecipient[] feeRecipients;
uint16 burnSplit;
}
TicketConsumer
Inherits: EIP712Upgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable, AccessControlUpgradeable
Title: TicketConsumer
Author: Mure
Contract to record commitments and consume Tickets associated with the Ticket and Pool contract
Utilizes the beacon proxy pattern to deploy multiple proxies, each representing a distinct application within the protocol. Implements the EIP-712 standard for signature validation, preventing unauthorized access. Security measures include the OpenZeppelin PausableUpgradeable pattern for emergency pausing, ReentrancyGuardUpgradeable to prevent reentrancy attacks, and role based access control through AccessControlUpgradeable.
Constants
ADMIN_ROLE
Role allows user to update contract configurations
bytes32 public constant ADMIN_ROLE = keccak256("TICKET_CONSUMER_ADMIN")
TicketConsumerStorageLocation
Hash for storage location
keccak256(abi.encode(uint256(keccak256("mure.TicketConsumer")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant TicketConsumerStorageLocation =
0xa517efc6fde9e1a3d05cb7ac467254548b2bee1ce4290b0a81a21700967a6300
COMMIT_TICKET_HASH
Struct hash for validating ticket commitment
keccak256("CommitTickets(uint256 quantity,address committer,string pool,uint256 amount)")
bytes32 private constant COMMIT_TICKET_HASH = 0x94ff97a6bb66dc5d656631dfe6b320f3b5cd4350fb456819848e7526cd060f8a
Functions
constructor
constructor() ;
initialize
function initialize(
ContractConfiguration calldata contractConfig,
address admin_,
string calldata name_,
string calldata version_
) external initializer;
commitTicket
Deposit a ticket to commit to a round.
Burns the deposited ticket and registers commitment.
function commitTicket(string calldata poolName, uint256 quantity, bytes calldata sig) external;
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
quantity | uint256 | the amount of $TICKET to burn. |
sig | bytes | the signature to authorize commitment. |
commitTicketAndDeposit
Deposit a ticket to commit to a round and deposits the committed amount to the pool.
Burns the deposited ticket and registers commitment. Deposits amount to the configured pool.
function commitTicketAndDeposit(
uint256 quantity,
string calldata poolName,
bytes calldata sig,
DepositArgs calldata depositArgs
) external;
Parameters
| Name | Type | Description |
|---|---|---|
quantity | uint256 | the amount of $TICKET to burn. |
poolName | string | the name of the pool. |
sig | bytes | the signature to authorize commitment. |
depositArgs | DepositArgs | parameters of the deposit as DepositArgs struct. |
getPoolConfig
Returns the pool deposit range and total allotment.
function getPoolConfig(string calldata poolName) external view returns (uint256, uint256, uint256, uint256);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
getContractConfig
Returns the ticket address set on the contract.
function getContractConfig() external view returns (ContractConfiguration memory);
getTicketAddress
Returns the ticket address set on the contract.
function getTicketAddress() external view returns (address);
getCommittedTickets
Returns the signer address set on the contract.
function getCommittedTickets(string calldata poolName, address committer) external view returns (uint256);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
committer | address | address of the committer |
setPoolConfiguration
Updates the pool configuration for deposits.
function setPoolConfiguration(
string calldata poolName,
uint256 minimumDepositAmount,
uint256 maximumDepositAmount,
uint256 commitmentStartTime,
uint256 commitmentEndTime
) external onlyRole(ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | name of the pool |
minimumDepositAmount | uint256 | minimum base deposit amount for pool per ticket |
maximumDepositAmount | uint256 | maximum deposit amount for pool per ticket |
commitmentStartTime | uint256 | epoch timestamp for when commitments should start |
commitmentEndTime | uint256 | epoch timestamp for when commitments should end |
setContractConfiguration
Updates the pool configuration for deposits.
function setContractConfiguration(ContractConfiguration calldata contractConfig) external onlyRole(ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
contractConfig | ContractConfiguration | base contract configuration |
setCommitmentsPaused
Updates the pool configuration for deposits.
function setCommitmentsPaused(bool paused) external onlyRole(ADMIN_ROLE);
Parameters
| Name | Type | Description |
|---|---|---|
paused | bool | boolean to define if commitments are paused |
_depositFunds
Deposits committed amount into the pool.
function _depositFunds(string calldata poolName, DepositArgs calldata depositParams) private nonReentrant;
_consumeTicket
Consumes tickets.
Burns the deposited tickets and registers commitment.
function _consumeTicket(address from, uint256 quantity, string calldata poolName, uint256 depositedAmount) private;
isPoolCommitmentActive
Checks if commitments for the specified pool are active.
function isPoolCommitmentActive(string calldata poolName) private view returns (bool);
Parameters
| Name | Type | Description |
|---|---|---|
poolName | string | the name of the pool to check if it is active |
_getStorage
Retrieves the storage for the TicketConsumer contract.
function _getStorage() private pure returns (TicketConsumerStorage storage $);
_hashCommit
Generates a hashed representation of the specified quantity and committer address.
function _hashCommit(uint256 quantity, address committer, string calldata poolName, uint256 depositAmount)
private
view
returns (bytes32);
Parameters
| Name | Type | Description |
|---|---|---|
quantity | uint256 | the quantity to commit |
committer | address | address of the committer |
poolName | string | name of the pool |
depositAmount | uint256 | amount being deposited with the commitment |
_verifySignature
Verifies the signature for commitment authorization.
function _verifySignature(
uint256 quantity,
address committer,
address signer,
uint256 depositAmount,
string calldata poolName,
bytes calldata sig
) private view;
Parameters
| Name | Type | Description |
|---|---|---|
quantity | uint256 | the quantity to commit |
committer | address | address of the committer |
signer | address | address of the signer |
depositAmount | uint256 | amount being deposited with the commitment |
poolName | string | name of the pool |
sig | bytes | signature to verify |
Events
TicketsConsumed
event TicketsConsumed(
address indexed from, string poolName, uint256 ticketQuantity, uint256 indexed depositedAmount
);
Errors
Unauthorized
error Unauthorized();
InvalidDepositAmount
error InvalidDepositAmount();
CommitmentsInactive
error CommitmentsInactive();
Structs
ContractConfiguration
Struct for pool configuration
struct ContractConfiguration {
address ticketContract;
address poolContract;
address signer;
bool paused;
}
PoolConfiguration
Struct for pool configuration
struct PoolConfiguration {
uint256 maximumDepositAmount;
uint256 minimumDepositAmount;
uint32 commitmentStartTime;
uint32 commitmentEndTime;
mapping(address committer => uint256 ticketCount) committedTickets;
}
TicketConsumerStorage
Note: storage-location: erc7201:mure.TicketConsumer
struct TicketConsumerStorage {
address TICKET;
address SIGNER;
address POOL_CONTRACT;
bool paused;
mapping(string poolName => PoolConfiguration) poolConfig;
}