Overview
Max Total Supply
203.39796805 LBTC
Holders
112 (0.00%)
Market
Price
$0.00 @ 0.000000 ETH
Onchain Market Cap
$0.00
Circulating Supply Market Cap
-
Other Info
Token Contract (WITH 8 Decimals)
Balance
0.000002 LBTCValue
$0.00Loading...
Loading
Loading...
Loading
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
TransparentUpgradeableProxy
Compiler Version
v0.8.24+commit.e11b9ed9
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/TransparentUpgradeableProxy.sol) pragma solidity ^0.8.20; import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol"; import {ERC1967Proxy} from "../ERC1967/ERC1967Proxy.sol"; import {IERC1967} from "../../interfaces/IERC1967.sol"; import {ProxyAdmin} from "./ProxyAdmin.sol"; /** * @dev Interface for {TransparentUpgradeableProxy}. In order to implement transparency, {TransparentUpgradeableProxy} * does not implement this interface directly, and its upgradeability mechanism is implemented by an internal dispatch * mechanism. The compiler is unaware that these functions are implemented by {TransparentUpgradeableProxy} and will not * include them in the ABI so this interface must be used to interact with it. */ interface ITransparentUpgradeableProxy is IERC1967 { function upgradeToAndCall(address, bytes calldata) external payable; } /** * @dev This contract implements a proxy that is upgradeable through an associated {ProxyAdmin} instance. * * To avoid https://medium.com/nomic-labs-blog/malicious-backdoors-in-ethereum-proxies-62629adf3357[proxy selector * clashing], which can potentially be used in an attack, this contract uses the * https://blog.openzeppelin.com/the-transparent-proxy-pattern/[transparent proxy pattern]. This pattern implies two * things that go hand in hand: * * 1. If any account other than the admin calls the proxy, the call will be forwarded to the implementation, even if * that call matches the {ITransparentUpgradeableProxy-upgradeToAndCall} function exposed by the proxy itself. * 2. If the admin calls the proxy, it can call the `upgradeToAndCall` function but any other call won't be forwarded to * the implementation. If the admin tries to call a function on the implementation it will fail with an error indicating * the proxy admin cannot fallback to the target implementation. * * These properties mean that the admin account can only be used for upgrading the proxy, so it's best if it's a * dedicated account that is not used for anything else. This will avoid headaches due to sudden errors when trying to * call a function from the proxy implementation. For this reason, the proxy deploys an instance of {ProxyAdmin} and * allows upgrades only if they come through it. You should think of the `ProxyAdmin` instance as the administrative * interface of the proxy, including the ability to change who can trigger upgrades by transferring ownership. * * NOTE: The real interface of this proxy is that defined in `ITransparentUpgradeableProxy`. This contract does not * inherit from that interface, and instead `upgradeToAndCall` is implicitly implemented using a custom dispatch * mechanism in `_fallback`. Consequently, the compiler will not produce an ABI for this contract. This is necessary to * fully implement transparency without decoding reverts caused by selector clashes between the proxy and the * implementation. * * NOTE: This proxy does not inherit from {Context} deliberately. The {ProxyAdmin} of this contract won't send a * meta-transaction in any way, and any other meta-transaction setup should be made in the implementation contract. * * IMPORTANT: This contract avoids unnecessary storage reads by setting the admin only during construction as an * immutable variable, preventing any changes thereafter. However, the admin slot defined in ERC-1967 can still be * overwritten by the implementation logic pointed to by this proxy. In such cases, the contract may end up in an * undesirable state where the admin slot is different from the actual admin. * * WARNING: It is not recommended to extend this contract to add additional external functions. If you do so, the * compiler will not check that there are no selector conflicts, due to the note above. A selector clash between any new * function and the functions declared in {ITransparentUpgradeableProxy} will be resolved in favor of the new one. This * could render the `upgradeToAndCall` function inaccessible, preventing upgradeability and compromising transparency. */ contract TransparentUpgradeableProxy is ERC1967Proxy { // An immutable address for the admin to avoid unnecessary SLOADs before each call // at the expense of removing the ability to change the admin once it's set. // This is acceptable if the admin is always a ProxyAdmin instance or similar contract // with its own ability to transfer the permissions to another account. address private immutable _admin; /** * @dev The proxy caller is the current admin, and can't fallback to the proxy target. */ error ProxyDeniedAdminAccess(); /** * @dev Initializes an upgradeable proxy managed by an instance of a {ProxyAdmin} with an `initialOwner`, * backed by the implementation at `_logic`, and optionally initialized with `_data` as explained in * {ERC1967Proxy-constructor}. */ constructor(address _logic, address initialOwner, bytes memory _data) payable ERC1967Proxy(_logic, _data) { _admin = address(new ProxyAdmin(initialOwner)); // Set the storage value and emit an event for ERC-1967 compatibility ERC1967Utils.changeAdmin(_proxyAdmin()); } /** * @dev Returns the admin of this proxy. */ function _proxyAdmin() internal virtual returns (address) { return _admin; } /** * @dev If caller is the admin process the call internally, otherwise transparently fallback to the proxy behavior. */ function _fallback() internal virtual override { if (msg.sender == _proxyAdmin()) { if (msg.sig != ITransparentUpgradeableProxy.upgradeToAndCall.selector) { revert ProxyDeniedAdminAccess(); } else { _dispatchUpgradeToAndCall(); } } else { super._fallback(); } } /** * @dev Upgrade the implementation of the proxy. See {ERC1967Utils-upgradeToAndCall}. * * Requirements: * * - If `data` is empty, `msg.value` must be zero. */ function _dispatchUpgradeToAndCall() private { (address newImplementation, bytes memory data) = abi.decode(msg.data[4:], (address, bytes)); ERC1967Utils.upgradeToAndCall(newImplementation, data); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Client} from "../libraries/Client.sol"; /// @notice Application contracts that intend to receive messages from /// the router should implement this interface. interface IAny2EVMMessageReceiver { /// @notice Called by the Router to deliver a message. /// If this reverts, any token transfers also revert. The message /// will move to a FAILED state and become available for manual execution. /// @param message CCIP Message /// @dev Note ensure you check the msg.sender is the OffRampRouter function ccipReceive(Client.Any2EVMMessage calldata message) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Pool} from "../libraries/Pool.sol"; import {IERC165} from "../../vendor/openzeppelin-solidity/v5.0.2/contracts/utils/introspection/IERC165.sol"; /// @notice Shared public interface for multiple V1 pool types. /// Each pool type handles a different child token model (lock/unlock, mint/burn.) interface IPoolV1 is IERC165 { /// @notice Lock tokens into the pool or burn the tokens. /// @param lockOrBurnIn Encoded data fields for the processing of tokens on the source chain. /// @return lockOrBurnOut Encoded data fields for the processing of tokens on the destination chain. function lockOrBurn( Pool.LockOrBurnInV1 calldata lockOrBurnIn ) external returns (Pool.LockOrBurnOutV1 memory lockOrBurnOut); /// @notice Releases or mints tokens to the receiver address. /// @param releaseOrMintIn All data required to release or mint tokens. /// @return releaseOrMintOut The amount of tokens released or minted on the local chain, denominated /// in the local token's decimals. /// @dev The offramp asserts that the balanceOf of the receiver has been incremented by exactly the number /// of tokens that is returned in ReleaseOrMintOutV1.destinationAmount. If the amounts do not match, the tx reverts. function releaseOrMint( Pool.ReleaseOrMintInV1 calldata releaseOrMintIn ) external returns (Pool.ReleaseOrMintOutV1 memory); /// @notice Checks whether a remote chain is supported in the token pool. /// @param remoteChainSelector The selector of the remote chain. /// @return true if the given chain is a permissioned remote chain. function isSupportedChain(uint64 remoteChainSelector) external view returns (bool); /// @notice Returns if the token pool supports the given token. /// @param token The address of the token. /// @return true if the token is supported by the pool. function isSupportedToken(address token) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice This interface contains the only RMN-related functions that might be used on-chain by other CCIP contracts. interface IRMN { /// @notice A Merkle root tagged with the address of the commit store contract it is destined for. struct TaggedRoot { address commitStore; bytes32 root; } /// @notice Callers MUST NOT cache the return value as a blessed tagged root could become unblessed. function isBlessed(TaggedRoot calldata taggedRoot) external view returns (bool); /// @notice Iff there is an active global or legacy curse, this function returns true. function isCursed() external view returns (bool); /// @notice Iff there is an active global curse, or an active curse for `subject`, this function returns true. /// @param subject To check whether a particular chain is cursed, set to bytes16(uint128(chainSelector)). function isCursed(bytes16 subject) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {Client} from "../libraries/Client.sol"; interface IRouter { error OnlyOffRamp(); /// @notice Route the message to its intended receiver contract. /// @param message Client.Any2EVMMessage struct. /// @param gasForCallExactCheck of params for exec /// @param gasLimit set of params for exec /// @param receiver set of params for exec /// @dev if the receiver is a contracts that signals support for CCIP execution through EIP-165. /// the contract is called. If not, only tokens are transferred. /// @return success A boolean value indicating whether the ccip message was received without errors. /// @return retBytes A bytes array containing return data form CCIP receiver. /// @return gasUsed the gas used by the external customer call. Does not include any overhead. function routeMessage( Client.Any2EVMMessage calldata message, uint16 gasForCallExactCheck, uint256 gasLimit, address receiver ) external returns (bool success, bytes memory retBytes, uint256 gasUsed); /// @notice Returns the configured onramp for a specific destination chain. /// @param destChainSelector The destination chain Id to get the onRamp for. /// @return onRampAddress The address of the onRamp. function getOnRamp(uint64 destChainSelector) external view returns (address onRampAddress); /// @notice Return true if the given offRamp is a configured offRamp for the given source chain. /// @param sourceChainSelector The source chain selector to check. /// @param offRamp The address of the offRamp to check. function isOffRamp(uint64 sourceChainSelector, address offRamp) external view returns (bool isOffRamp); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import {Client} from "../libraries/Client.sol"; interface IRouterClient { error UnsupportedDestinationChain(uint64 destChainSelector); error InsufficientFeeTokenAmount(); error InvalidMsgValue(); /// @notice Checks if the given chain ID is supported for sending/receiving. /// @param destChainSelector The chain to check. /// @return supported is true if it is supported, false if not. function isChainSupported(uint64 destChainSelector) external view returns (bool supported); /// @param destinationChainSelector The destination chainSelector /// @param message The cross-chain CCIP message including data and/or tokens /// @return fee returns execution fee for the message /// delivery to destination chain, denominated in the feeToken specified in the message. /// @dev Reverts with appropriate reason upon invalid message. function getFee( uint64 destinationChainSelector, Client.EVM2AnyMessage memory message ) external view returns (uint256 fee); /// @notice Request a message to be sent to the destination chain /// @param destinationChainSelector The destination chain ID /// @param message The cross-chain CCIP message including data and/or tokens /// @return messageId The message ID /// @dev Note if msg.value is larger than the required fee (from getFee) we accept /// the overpayment with no refund. /// @dev Reverts with appropriate reason upon invalid message. function ccipSend( uint64 destinationChainSelector, Client.EVM2AnyMessage calldata message ) external payable returns (bytes32); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // End consumer library. library Client { /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers. struct EVMTokenAmount { address token; // token address on the local chain. uint256 amount; // Amount of tokens. } struct Any2EVMMessage { bytes32 messageId; // MessageId corresponding to ccipSend on source. uint64 sourceChainSelector; // Source chain selector. bytes sender; // abi.decode(sender) if coming from an EVM chain. bytes data; // payload sent in original message. EVMTokenAmount[] destTokenAmounts; // Tokens and their amounts in their destination chain representation. } // If extraArgs is empty bytes, the default is 200k gas limit. struct EVM2AnyMessage { bytes receiver; // abi.encode(receiver address) for dest EVM chains bytes data; // Data payload EVMTokenAmount[] tokenAmounts; // Token transfers address feeToken; // Address of feeToken. address(0) means you will send msg.value. bytes extraArgs; // Populate this with _argsToBytes(EVMExtraArgsV2) } // bytes4(keccak256("CCIP EVMExtraArgsV1")); bytes4 public constant EVM_EXTRA_ARGS_V1_TAG = 0x97a657c9; struct EVMExtraArgsV1 { uint256 gasLimit; } function _argsToBytes(EVMExtraArgsV1 memory extraArgs) internal pure returns (bytes memory bts) { return abi.encodeWithSelector(EVM_EXTRA_ARGS_V1_TAG, extraArgs); } // bytes4(keccak256("CCIP EVMExtraArgsV2")); bytes4 public constant EVM_EXTRA_ARGS_V2_TAG = 0x181dcf10; /// @param gasLimit: gas limit for the callback on the destination chain. /// @param allowOutOfOrderExecution: if true, it indicates that the message can be executed in any order relative to other messages from the same sender. /// This value's default varies by chain. On some chains, a particular value is enforced, meaning if the expected value /// is not set, the message request will revert. struct EVMExtraArgsV2 { uint256 gasLimit; bool allowOutOfOrderExecution; } function _argsToBytes(EVMExtraArgsV2 memory extraArgs) internal pure returns (bytes memory bts) { return abi.encodeWithSelector(EVM_EXTRA_ARGS_V2_TAG, extraArgs); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import {MerkleMultiProof} from "../libraries/MerkleMultiProof.sol"; import {Client} from "./Client.sol"; // Library for CCIP internal definitions common to multiple contracts. library Internal { error InvalidEVMAddress(bytes encodedAddress); /// @dev The minimum amount of gas to perform the call with exact gas. /// We include this in the offramp so that we can redeploy to adjust it /// should a hardfork change the gas costs of relevant opcodes in callWithExactGas. uint16 internal constant GAS_FOR_CALL_EXACT_CHECK = 5_000; // @dev We limit return data to a selector plus 4 words. This is to avoid // malicious contracts from returning large amounts of data and causing // repeated out-of-gas scenarios. uint16 internal constant MAX_RET_BYTES = 4 + 4 * 32; /// @dev The expected number of bytes returned by the balanceOf function. uint256 internal constant MAX_BALANCE_OF_RET_BYTES = 32; /// @notice A collection of token price and gas price updates. /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers. struct PriceUpdates { TokenPriceUpdate[] tokenPriceUpdates; GasPriceUpdate[] gasPriceUpdates; } /// @notice Token price in USD. /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers. struct TokenPriceUpdate { address sourceToken; // Source token uint224 usdPerToken; // 1e18 USD per 1e18 of the smallest token denomination. } /// @notice Gas price for a given chain in USD, its value may contain tightly packed fields. /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers. struct GasPriceUpdate { uint64 destChainSelector; // Destination chain selector uint224 usdPerUnitGas; // 1e18 USD per smallest unit (e.g. wei) of destination chain gas } /// @notice A timestamped uint224 value that can contain several tightly packed fields. struct TimestampedPackedUint224 { uint224 value; // ───────╮ Value in uint224, packed. uint32 timestamp; // ────╯ Timestamp of the most recent price update. } /// @dev Gas price is stored in 112-bit unsigned int. uint224 can pack 2 prices. /// When packing L1 and L2 gas prices, L1 gas price is left-shifted to the higher-order bits. /// Using uint8 type, which cannot be higher than other bit shift operands, to avoid shift operand type warning. uint8 public constant GAS_PRICE_BITS = 112; struct PoolUpdate { address token; // The IERC20 token address address pool; // The token pool address } struct SourceTokenData { // The source pool address, abi encoded. This value is trusted as it was obtained through the onRamp. It can be // relied upon by the destination pool to validate the source pool. bytes sourcePoolAddress; // The address of the destination token, abi encoded in the case of EVM chains // This value is UNTRUSTED as any pool owner can return whatever value they want. bytes destTokenAddress; // Optional pool data to be transferred to the destination chain. Be default this is capped at // CCIP_LOCK_OR_BURN_V1_RET_BYTES bytes. If more data is required, the TokenTransferFeeConfig.destBytesOverhead // has to be set for the specific token. bytes extraData; uint32 destGasAmount; // The amount of gas available for the releaseOrMint and balanceOf calls on the offRamp } /// @notice Report that is submitted by the execution DON at the execution phase. (including chain selector data) /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers. struct ExecutionReportSingleChain { uint64 sourceChainSelector; // Source chain selector for which the report is submitted Any2EVMRampMessage[] messages; // Contains a bytes array for each message, each inner bytes array contains bytes per transferred token bytes[][] offchainTokenData; bytes32[] proofs; uint256 proofFlagBits; } /// @notice Report that is submitted by the execution DON at the execution phase. /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers. struct ExecutionReport { EVM2EVMMessage[] messages; // Contains a bytes array for each message, each inner bytes array contains bytes per transferred token bytes[][] offchainTokenData; bytes32[] proofs; uint256 proofFlagBits; } /// @notice The cross chain message that gets committed to EVM chains. /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers. struct EVM2EVMMessage { uint64 sourceChainSelector; // ────────╮ the chain selector of the source chain, note: not chainId address sender; // ────────────────────╯ sender address on the source chain address receiver; // ──────────────────╮ receiver address on the destination chain uint64 sequenceNumber; // ─────────────╯ sequence number, not unique across lanes uint256 gasLimit; // user supplied maximum gas amount available for dest chain execution bool strict; // ───────────────────────╮ DEPRECATED uint64 nonce; // │ nonce for this lane for this sender, not unique across senders/lanes address feeToken; // ──────────────────╯ fee token uint256 feeTokenAmount; // fee token amount bytes data; // arbitrary data payload supplied by the message sender Client.EVMTokenAmount[] tokenAmounts; // array of tokens and amounts to transfer bytes[] sourceTokenData; // array of token data, one per token bytes32 messageId; // a hash of the message data } /// @dev EVM2EVMMessage struct has 13 fields, including 3 variable arrays. /// Each variable array takes 1 more slot to store its length. /// When abi encoded, excluding array contents, /// EVM2EVMMessage takes up a fixed number of 16 lots, 32 bytes each. /// For structs that contain arrays, 1 more slot is added to the front, reaching a total of 17. uint256 public constant MESSAGE_FIXED_BYTES = 32 * 17; /// @dev Each token transfer adds 1 EVMTokenAmount and 3 bytes at 3 slots each and one slot for the destGasAmount. /// When abi encoded, each EVMTokenAmount takes 2 slots, each bytes takes 1 slot for length, one slot of data and one /// slot for the offset. This results in effectively 3*3 slots per SourceTokenData. /// 0x20 /// destGasAmount /// sourcePoolAddress_offset /// destTokenAddress_offset /// extraData_offset /// sourcePoolAddress_length /// sourcePoolAddress_content // assume 1 slot /// destTokenAddress_length /// destTokenAddress_content // assume 1 slot /// extraData_length // contents billed separately uint256 public constant MESSAGE_FIXED_BYTES_PER_TOKEN = 32 * ((1 + 3 * 3) + 2); /// @dev Any2EVMRampMessage struct has 10 fields, including 3 variable unnested arrays (data, receiver and tokenAmounts). /// Each variable array takes 1 more slot to store its length. /// When abi encoded, excluding array contents, /// Any2EVMMessage takes up a fixed number of 13 slots, 32 bytes each. /// For structs that contain arrays, 1 more slot is added to the front, reaching a total of 14. /// The fixed bytes does not cover struct data (this is represented by ANY_2_EVM_MESSAGE_FIXED_BYTES_PER_TOKEN) uint256 public constant ANY_2_EVM_MESSAGE_FIXED_BYTES = 32 * 14; /// @dev Each token transfer adds 1 RampTokenAmount /// RampTokenAmount has 5 fields, 2 of which are bytes type, 1 Address, 1 uint256 and 1 uint32. /// Each bytes type takes 1 slot for length, 1 slot for data and 1 slot for the offset. /// address /// uint256 amount takes 1 slot. /// uint32 destGasAmount takes 1 slot. uint256 public constant ANY_2_EVM_MESSAGE_FIXED_BYTES_PER_TOKEN = 32 * ((2 * 3) + 3); bytes32 internal constant EVM_2_EVM_MESSAGE_HASH = keccak256("EVM2EVMMessageHashV2"); /// @dev Used to hash messages for single-lane ramps. /// OnRamp hash(EVM2EVMMessage) = OffRamp hash(EVM2EVMMessage) /// The EVM2EVMMessage's messageId is expected to be the output of this hash function /// @param original Message to hash /// @param metadataHash Immutable metadata hash representing a lane with a fixed OnRamp /// @return hashedMessage hashed message as a keccak256 function _hash(EVM2EVMMessage memory original, bytes32 metadataHash) internal pure returns (bytes32) { // Fixed-size message fields are included in nested hash to reduce stack pressure. // This hashing scheme is also used by RMN. If changing it, please notify the RMN maintainers. return keccak256( abi.encode( MerkleMultiProof.LEAF_DOMAIN_SEPARATOR, metadataHash, keccak256( abi.encode( original.sender, original.receiver, original.sequenceNumber, original.gasLimit, original.strict, original.nonce, original.feeToken, original.feeTokenAmount ) ), keccak256(original.data), keccak256(abi.encode(original.tokenAmounts)), keccak256(abi.encode(original.sourceTokenData)) ) ); } bytes32 internal constant ANY_2_EVM_MESSAGE_HASH = keccak256("Any2EVMMessageHashV1"); bytes32 internal constant EVM_2_ANY_MESSAGE_HASH = keccak256("EVM2AnyMessageHashV1"); /// @dev Used to hash messages for multi-lane family-agnostic OffRamps. /// OnRamp hash(EVM2AnyMessage) != Any2EVMRampMessage.messageId /// OnRamp hash(EVM2AnyMessage) != OffRamp hash(Any2EVMRampMessage) /// @param original OffRamp message to hash /// @param metadataHash Hash preimage to ensure global uniqueness /// @return hashedMessage hashed message as a keccak256 function _hash(Any2EVMRampMessage memory original, bytes32 metadataHash) internal pure returns (bytes32) { // Fixed-size message fields are included in nested hash to reduce stack pressure. // This hashing scheme is also used by RMN. If changing it, please notify the RMN maintainers. return keccak256( abi.encode( MerkleMultiProof.LEAF_DOMAIN_SEPARATOR, metadataHash, keccak256( abi.encode( original.header.messageId, original.receiver, original.header.sequenceNumber, original.gasLimit, original.header.nonce ) ), keccak256(original.sender), keccak256(original.data), keccak256(abi.encode(original.tokenAmounts)) ) ); } function _hash(EVM2AnyRampMessage memory original, bytes32 metadataHash) internal pure returns (bytes32) { // Fixed-size message fields are included in nested hash to reduce stack pressure. // This hashing scheme is also used by RMN. If changing it, please notify the RMN maintainers. return keccak256( abi.encode( MerkleMultiProof.LEAF_DOMAIN_SEPARATOR, metadataHash, keccak256( abi.encode( original.sender, original.header.sequenceNumber, original.header.nonce, original.feeToken, original.feeTokenAmount ) ), keccak256(original.receiver), keccak256(original.data), keccak256(abi.encode(original.tokenAmounts)), keccak256(original.extraArgs) ) ); } /// @dev We disallow the first 1024 addresses to avoid calling into a range known for hosting precompiles. Calling /// into precompiles probably won't cause any issues, but to be safe we can disallow this range. It is extremely /// unlikely that anyone would ever be able to generate an address in this range. There is no official range of /// precompiles, but EIP-7587 proposes to reserve the range 0x100 to 0x1ff. Our range is more conservative, even /// though it might not be exhaustive for all chains, which is OK. We also disallow the zero address, which is a /// common practice. uint256 public constant PRECOMPILE_SPACE = 1024; /// @notice This methods provides validation for parsing abi encoded addresses by ensuring the /// address is within the EVM address space. If it isn't it will revert with an InvalidEVMAddress error, which /// we can catch and handle more gracefully than a revert from abi.decode. /// @return The address if it is valid, the function will revert otherwise. function _validateEVMAddress(bytes memory encodedAddress) internal pure returns (address) { if (encodedAddress.length != 32) revert InvalidEVMAddress(encodedAddress); uint256 encodedAddressUint = abi.decode(encodedAddress, (uint256)); if (encodedAddressUint > type(uint160).max || encodedAddressUint < PRECOMPILE_SPACE) { revert InvalidEVMAddress(encodedAddress); } return address(uint160(encodedAddressUint)); } /// @notice Enum listing the possible message execution states within /// the offRamp contract. /// UNTOUCHED never executed /// IN_PROGRESS currently being executed, used a replay protection /// SUCCESS successfully executed. End state /// FAILURE unsuccessfully executed, manual execution is now enabled. /// @dev RMN depends on this enum, if changing, please notify the RMN maintainers. enum MessageExecutionState { UNTOUCHED, IN_PROGRESS, SUCCESS, FAILURE } /// @notice CCIP OCR plugin type, used to separate execution & commit transmissions and configs enum OCRPluginType { Commit, Execution } /// @notice Family-agnostic header for OnRamp & OffRamp messages. /// The messageId is not expected to match hash(message), since it may originate from another ramp family struct RampMessageHeader { bytes32 messageId; // Unique identifier for the message, generated with the source chain's encoding scheme (i.e. not necessarily abi.encoded) uint64 sourceChainSelector; // ──╮ the chain selector of the source chain, note: not chainId uint64 destChainSelector; // | the chain selector of the destination chain, note: not chainId uint64 sequenceNumber; // │ sequence number, not unique across lanes uint64 nonce; // ────────────────╯ nonce for this lane for this sender, not unique across senders/lanes } struct EVM2AnyTokenTransfer { // The source pool EVM address. This value is trusted as it was obtained through the onRamp. It can be // relied upon by the destination pool to validate the source pool. address sourcePoolAddress; // The EVM address of the destination token // This value is UNTRUSTED as any pool owner can return whatever value they want. bytes destTokenAddress; // Optional pool data to be transferred to the destination chain. Be default this is capped at // CCIP_LOCK_OR_BURN_V1_RET_BYTES bytes. If more data is required, the TokenTransferFeeConfig.destBytesOverhead // has to be set for the specific token. bytes extraData; uint256 amount; // Amount of tokens. // Destination chain specific execution data encoded in bytes // for an EVM destination, it consists of the amount of gas available for the releaseOrMint // and transfer calls made by the offRamp bytes destExecData; } struct Any2EVMTokenTransfer { // The source pool EVM address encoded to bytes. This value is trusted as it is obtained through the onRamp. It can be // relied upon by the destination pool to validate the source pool. bytes sourcePoolAddress; address destTokenAddress; // ───╮ Address of destination token uint32 destGasAmount; //────────╯ The amount of gas available for the releaseOrMint and transfer calls on the offRamp. // Optional pool data to be transferred to the destination chain. Be default this is capped at // CCIP_LOCK_OR_BURN_V1_RET_BYTES bytes. If more data is required, the TokenTransferFeeConfig.destBytesOverhead // has to be set for the specific token. bytes extraData; uint256 amount; // Amount of tokens. } /// @notice Family-agnostic message routed to an OffRamp /// Note: hash(Any2EVMRampMessage) != hash(EVM2AnyRampMessage), hash(Any2EVMRampMessage) != messageId /// due to encoding & parameter differences struct Any2EVMRampMessage { RampMessageHeader header; // Message header bytes sender; // sender address on the source chain bytes data; // arbitrary data payload supplied by the message sender address receiver; // receiver address on the destination chain uint256 gasLimit; // user supplied maximum gas amount available for dest chain execution Any2EVMTokenTransfer[] tokenAmounts; // array of tokens and amounts to transfer } /// @notice Family-agnostic message emitted from the OnRamp /// Note: hash(Any2EVMRampMessage) != hash(EVM2AnyRampMessage) due to encoding & parameter differences /// messageId = hash(EVM2AnyRampMessage) using the source EVM chain's encoding format struct EVM2AnyRampMessage { RampMessageHeader header; // Message header address sender; // sender address on the source chain bytes data; // arbitrary data payload supplied by the message sender bytes receiver; // receiver address on the destination chain bytes extraArgs; // destination-chain specific extra args, such as the gasLimit for EVM chains address feeToken; // fee token uint256 feeTokenAmount; // fee token amount uint256 feeValueJuels; // fee amount in Juels EVM2AnyTokenTransfer[] tokenAmounts; // array of tokens and amounts to transfer } // bytes4(keccak256("CCIP ChainFamilySelector EVM")) bytes4 public constant CHAIN_FAMILY_SELECTOR_EVM = 0x2812d52c; /// @dev Struct to hold a merkle root and an interval for a source chain so that an array of these can be passed in the CommitReport. /// @dev RMN depends on this struct, if changing, please notify the RMN maintainers. /// @dev ineffiecient struct packing intentionally chosen to maintain order of specificity. Not a storage struct so impact is minimal. // solhint-disable-next-line gas-struct-packing struct MerkleRoot { uint64 sourceChainSelector; // Remote source chain selector that the Merkle Root is scoped to bytes onRampAddress; // Generic onramp address, to support arbitrary sources; for EVM, use abi.encode uint64 minSeqNr; // ─────────────╮ Minimum sequence number, inclusive uint64 maxSeqNr; // ─────────────╯ Maximum sequence number, inclusive bytes32 merkleRoot; // Merkle root covering the interval & source chain messages } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.4; library MerkleMultiProof { /// @notice Leaf domain separator, should be used as the first 32 bytes of a leaf's preimage. bytes32 internal constant LEAF_DOMAIN_SEPARATOR = 0x0000000000000000000000000000000000000000000000000000000000000000; /// @notice Internal domain separator, should be used as the first 32 bytes of an internal node's preiimage. bytes32 internal constant INTERNAL_DOMAIN_SEPARATOR = 0x0000000000000000000000000000000000000000000000000000000000000001; uint256 internal constant MAX_NUM_HASHES = 256; error InvalidProof(); error LeavesCannotBeEmpty(); /// @notice Computes the root based on provided pre-hashed leaf nodes in /// leaves, internal nodes in proofs, and using proofFlagBits' i-th bit to /// determine if an element of proofs or one of the previously computed leafs /// or internal nodes will be used for the i-th hash. /// @param leaves Should be pre-hashed and the first 32 bytes of a leaf's /// preimage should match LEAF_DOMAIN_SEPARATOR. /// @param proofs The hashes to be used instead of a leaf hash when the proofFlagBits /// indicates a proof should be used. /// @param proofFlagBits A single uint256 of which each bit indicates whether a leaf or /// a proof needs to be used in a hash operation. /// @dev the maximum number of hash operations it set to 256. Any input that would require /// more than 256 hashes to get to a root will revert. /// @dev For given input `leaves` = [a,b,c] `proofs` = [D] and `proofFlagBits` = 5 /// totalHashes = 3 + 1 - 1 = 3 /// ** round 1 ** /// proofFlagBits = (5 >> 0) & 1 = true /// hashes[0] = hashPair(a, b) /// (leafPos, hashPos, proofPos) = (2, 0, 0); /// /// ** round 2 ** /// proofFlagBits = (5 >> 1) & 1 = false /// hashes[1] = hashPair(D, c) /// (leafPos, hashPos, proofPos) = (3, 0, 1); /// /// ** round 3 ** /// proofFlagBits = (5 >> 2) & 1 = true /// hashes[2] = hashPair(hashes[0], hashes[1]) /// (leafPos, hashPos, proofPos) = (3, 2, 1); /// /// i = 3 and no longer < totalHashes. The algorithm is done /// return hashes[totalHashes - 1] = hashes[2]; the last hash we computed. // We mark this function as internal to force it to be inlined in contracts // that use it, but semantically it is public. // solhint-disable-next-line chainlink-solidity/prefix-internal-functions-with-underscore function merkleRoot( bytes32[] memory leaves, bytes32[] memory proofs, uint256 proofFlagBits ) internal pure returns (bytes32) { unchecked { uint256 leavesLen = leaves.length; uint256 proofsLen = proofs.length; if (leavesLen == 0) revert LeavesCannotBeEmpty(); if (!(leavesLen <= MAX_NUM_HASHES + 1 && proofsLen <= MAX_NUM_HASHES + 1)) revert InvalidProof(); uint256 totalHashes = leavesLen + proofsLen - 1; if (!(totalHashes <= MAX_NUM_HASHES)) revert InvalidProof(); if (totalHashes == 0) { return leaves[0]; } bytes32[] memory hashes = new bytes32[](totalHashes); (uint256 leafPos, uint256 hashPos, uint256 proofPos) = (0, 0, 0); for (uint256 i = 0; i < totalHashes; ++i) { // Checks if the bit flag signals the use of a supplied proof or a leaf/previous hash. bytes32 a; if (proofFlagBits & (1 << i) == (1 << i)) { // Use a leaf or a previously computed hash. if (leafPos < leavesLen) { a = leaves[leafPos++]; } else { a = hashes[hashPos++]; } } else { // Use a supplied proof. a = proofs[proofPos++]; } // The second part of the hashed pair is never a proof as hashing two proofs would result in a // hash that can already be computed offchain. bytes32 b; if (leafPos < leavesLen) { b = leaves[leafPos++]; } else { b = hashes[hashPos++]; } if (!(hashPos <= i)) revert InvalidProof(); hashes[i] = _hashPair(a, b); } if (!(hashPos == totalHashes - 1 && leafPos == leavesLen && proofPos == proofsLen)) revert InvalidProof(); // Return the last hash. return hashes[totalHashes - 1]; } } /// @notice Hashes two bytes32 objects in their given order, prepended by the /// INTERNAL_DOMAIN_SEPARATOR. function _hashInternalNode(bytes32 left, bytes32 right) private pure returns (bytes32 hash) { return keccak256(abi.encode(INTERNAL_DOMAIN_SEPARATOR, left, right)); } /// @notice Hashes two bytes32 objects. The order is taken into account, /// using the lower value first. function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _hashInternalNode(a, b) : _hashInternalNode(b, a); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice This library contains various token pool functions to aid constructing the return data. library Pool { // The tag used to signal support for the pool v1 standard // bytes4(keccak256("CCIP_POOL_V1")) bytes4 public constant CCIP_POOL_V1 = 0xaff2afbf; // The number of bytes in the return data for a pool v1 releaseOrMint call. // This should match the size of the ReleaseOrMintOutV1 struct. uint16 public constant CCIP_POOL_V1_RET_BYTES = 32; // The default max number of bytes in the return data for a pool v1 lockOrBurn call. // This data can be used to send information to the destination chain token pool. Can be overwritten // in the TokenTransferFeeConfig.destBytesOverhead if more data is required. uint32 public constant CCIP_LOCK_OR_BURN_V1_RET_BYTES = 32; struct LockOrBurnInV1 { bytes receiver; // The recipient of the tokens on the destination chain, abi encoded uint64 remoteChainSelector; // ─╮ The chain ID of the destination chain address originalSender; // ─────╯ The original sender of the tx on the source chain uint256 amount; // The amount of tokens to lock or burn, denominated in the source token's decimals address localToken; // The address on this chain of the token to lock or burn } struct LockOrBurnOutV1 { // The address of the destination token, abi encoded in the case of EVM chains // This value is UNTRUSTED as any pool owner can return whatever value they want. bytes destTokenAddress; // Optional pool data to be transferred to the destination chain. Be default this is capped at // CCIP_LOCK_OR_BURN_V1_RET_BYTES bytes. If more data is required, the TokenTransferFeeConfig.destBytesOverhead // has to be set for the specific token. bytes destPoolData; } struct ReleaseOrMintInV1 { bytes originalSender; // The original sender of the tx on the source chain uint64 remoteChainSelector; // ─╮ The chain ID of the source chain address receiver; // ───────────╯ The recipient of the tokens on the destination chain. uint256 amount; // The amount of tokens to release or mint, denominated in the source token's decimals address localToken; // The address on this chain of the token to release or mint /// @dev WARNING: sourcePoolAddress should be checked prior to any processing of funds. Make sure it matches the /// expected pool address for the given remoteChainSelector. bytes sourcePoolAddress; // The address of the source pool, abi encoded in the case of EVM chains bytes sourcePoolData; // The data received from the source pool to process the release or mint /// @dev WARNING: offchainTokenData is untrusted data. bytes offchainTokenData; // The offchain data to process the release or mint } struct ReleaseOrMintOutV1 { // The number of tokens released or minted on the destination chain, denominated in the local token's decimals. // This value is expected to be equal to the ReleaseOrMintInV1.amount in the case where the source and destination // chain have the same number of decimals. uint256 destinationAmount; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.4; /// @notice Implements Token Bucket rate limiting. /// @dev uint128 is safe for rate limiter state. /// For USD value rate limiting, it can adequately store USD value in 18 decimals. /// For ERC20 token amount rate limiting, all tokens that will be listed will have at most /// a supply of uint128.max tokens, and it will therefore not overflow the bucket. /// In exceptional scenarios where tokens consumed may be larger than uint128, /// e.g. compromised issuer, an enabled RateLimiter will check and revert. library RateLimiter { error BucketOverfilled(); error OnlyCallableByAdminOrOwner(); error TokenMaxCapacityExceeded(uint256 capacity, uint256 requested, address tokenAddress); error TokenRateLimitReached(uint256 minWaitInSeconds, uint256 available, address tokenAddress); error AggregateValueMaxCapacityExceeded(uint256 capacity, uint256 requested); error AggregateValueRateLimitReached(uint256 minWaitInSeconds, uint256 available); error InvalidRateLimitRate(Config rateLimiterConfig); error DisabledNonZeroRateLimit(Config config); error RateLimitMustBeDisabled(); event TokensConsumed(uint256 tokens); event ConfigChanged(Config config); struct TokenBucket { uint128 tokens; // ──────╮ Current number of tokens that are in the bucket. uint32 lastUpdated; // │ Timestamp in seconds of the last token refill, good for 100+ years. bool isEnabled; // ──────╯ Indication whether the rate limiting is enabled or not uint128 capacity; // ────╮ Maximum number of tokens that can be in the bucket. uint128 rate; // ────────╯ Number of tokens per second that the bucket is refilled. } struct Config { bool isEnabled; // Indication whether the rate limiting should be enabled uint128 capacity; // ────╮ Specifies the capacity of the rate limiter uint128 rate; // ───────╯ Specifies the rate of the rate limiter } /// @notice _consume removes the given tokens from the pool, lowering the /// rate tokens allowed to be consumed for subsequent calls. /// @param requestTokens The total tokens to be consumed from the bucket. /// @param tokenAddress The token to consume capacity for, use 0x0 to indicate aggregate value capacity. /// @dev Reverts when requestTokens exceeds bucket capacity or available tokens in the bucket /// @dev emits removal of requestTokens if requestTokens is > 0 function _consume(TokenBucket storage s_bucket, uint256 requestTokens, address tokenAddress) internal { // If there is no value to remove or rate limiting is turned off, skip this step to reduce gas usage if (!s_bucket.isEnabled || requestTokens == 0) { return; } uint256 tokens = s_bucket.tokens; uint256 capacity = s_bucket.capacity; uint256 timeDiff = block.timestamp - s_bucket.lastUpdated; if (timeDiff != 0) { if (tokens > capacity) revert BucketOverfilled(); // Refill tokens when arriving at a new block time tokens = _calculateRefill(capacity, tokens, timeDiff, s_bucket.rate); s_bucket.lastUpdated = uint32(block.timestamp); } if (capacity < requestTokens) { // Token address 0 indicates consuming aggregate value rate limit capacity. if (tokenAddress == address(0)) revert AggregateValueMaxCapacityExceeded(capacity, requestTokens); revert TokenMaxCapacityExceeded(capacity, requestTokens, tokenAddress); } if (tokens < requestTokens) { uint256 rate = s_bucket.rate; // Wait required until the bucket is refilled enough to accept this value, round up to next higher second // Consume is not guaranteed to succeed after wait time passes if there is competing traffic. // This acts as a lower bound of wait time. uint256 minWaitInSeconds = ((requestTokens - tokens) + (rate - 1)) / rate; if (tokenAddress == address(0)) revert AggregateValueRateLimitReached(minWaitInSeconds, tokens); revert TokenRateLimitReached(minWaitInSeconds, tokens, tokenAddress); } tokens -= requestTokens; // Downcast is safe here, as tokens is not larger than capacity s_bucket.tokens = uint128(tokens); emit TokensConsumed(requestTokens); } /// @notice Gets the token bucket with its values for the block it was requested at. /// @return The token bucket. function _currentTokenBucketState(TokenBucket memory bucket) internal view returns (TokenBucket memory) { // We update the bucket to reflect the status at the exact time of the // call. This means we might need to refill a part of the bucket based // on the time that has passed since the last update. bucket.tokens = uint128(_calculateRefill(bucket.capacity, bucket.tokens, block.timestamp - bucket.lastUpdated, bucket.rate)); bucket.lastUpdated = uint32(block.timestamp); return bucket; } /// @notice Sets the rate limited config. /// @param s_bucket The token bucket /// @param config The new config function _setTokenBucketConfig(TokenBucket storage s_bucket, Config memory config) internal { // First update the bucket to make sure the proper rate is used for all the time // up until the config change. uint256 timeDiff = block.timestamp - s_bucket.lastUpdated; if (timeDiff != 0) { s_bucket.tokens = uint128(_calculateRefill(s_bucket.capacity, s_bucket.tokens, timeDiff, s_bucket.rate)); s_bucket.lastUpdated = uint32(block.timestamp); } s_bucket.tokens = uint128(_min(config.capacity, s_bucket.tokens)); s_bucket.isEnabled = config.isEnabled; s_bucket.capacity = config.capacity; s_bucket.rate = config.rate; emit ConfigChanged(config); } /// @notice Validates the token bucket config function _validateTokenBucketConfig(Config memory config, bool mustBeDisabled) internal pure { if (config.isEnabled) { if (config.rate >= config.capacity || config.rate == 0) { revert InvalidRateLimitRate(config); } if (mustBeDisabled) { revert RateLimitMustBeDisabled(); } } else { if (config.rate != 0 || config.capacity != 0) { revert DisabledNonZeroRateLimit(config); } } } /// @notice Calculate refilled tokens /// @param capacity bucket capacity /// @param tokens current bucket tokens /// @param timeDiff block time difference since last refill /// @param rate bucket refill rate /// @return the value of tokens after refill function _calculateRefill( uint256 capacity, uint256 tokens, uint256 timeDiff, uint256 rate ) private pure returns (uint256) { return _min(capacity, tokens + timeDiff * rate); } /// @notice Return the smallest of two integers /// @param a first int /// @param b second int /// @return smallest function _min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.24; import {IPoolV1} from "../interfaces/IPool.sol"; import {IRMN} from "../interfaces/IRMN.sol"; import {IRouter} from "../interfaces/IRouter.sol"; import {OwnerIsCreator} from "../../shared/access/OwnerIsCreator.sol"; import {Pool} from "../libraries/Pool.sol"; import {RateLimiter} from "../libraries/RateLimiter.sol"; import {IERC20} from "../../vendor/openzeppelin-solidity/v4.8.3/contracts/token/ERC20/IERC20.sol"; import {IERC165} from "../../vendor/openzeppelin-solidity/v5.0.2/contracts/utils/introspection/IERC165.sol"; import {EnumerableSet} from "../../vendor/openzeppelin-solidity/v5.0.2/contracts/utils/structs/EnumerableSet.sol"; /// @notice Base abstract class with common functions for all token pools. /// A token pool serves as isolated place for holding tokens and token specific logic /// that may execute as tokens move across the bridge. abstract contract TokenPool is IPoolV1, OwnerIsCreator { using EnumerableSet for EnumerableSet.AddressSet; using EnumerableSet for EnumerableSet.UintSet; using RateLimiter for RateLimiter.TokenBucket; error CallerIsNotARampOnRouter(address caller); error ZeroAddressNotAllowed(); error SenderNotAllowed(address sender); error AllowListNotEnabled(); error NonExistentChain(uint64 remoteChainSelector); error ChainNotAllowed(uint64 remoteChainSelector); error CursedByRMN(); error ChainAlreadyExists(uint64 chainSelector); error InvalidSourcePoolAddress(bytes sourcePoolAddress); error InvalidToken(address token); error Unauthorized(address caller); event Locked(address indexed sender, uint256 amount); event Burned(address indexed sender, uint256 amount); event Released(address indexed sender, address indexed recipient, uint256 amount); event Minted(address indexed sender, address indexed recipient, uint256 amount); event ChainAdded( uint64 remoteChainSelector, bytes remoteToken, RateLimiter.Config outboundRateLimiterConfig, RateLimiter.Config inboundRateLimiterConfig ); event ChainConfigured( uint64 remoteChainSelector, RateLimiter.Config outboundRateLimiterConfig, RateLimiter.Config inboundRateLimiterConfig ); event ChainRemoved(uint64 remoteChainSelector); event RemotePoolSet(uint64 indexed remoteChainSelector, bytes previousPoolAddress, bytes remotePoolAddress); event AllowListAdd(address sender); event AllowListRemove(address sender); event RouterUpdated(address oldRouter, address newRouter); struct ChainUpdate { uint64 remoteChainSelector; // ──╮ Remote chain selector bool allowed; // ────────────────╯ Whether the chain should be enabled bytes remotePoolAddress; // Address of the remote pool, ABI encoded in the case of a remote EVM chain. bytes remoteTokenAddress; // Address of the remote token, ABI encoded in the case of a remote EVM chain. RateLimiter.Config outboundRateLimiterConfig; // Outbound rate limited config, meaning the rate limits for all of the onRamps for the given chain RateLimiter.Config inboundRateLimiterConfig; // Inbound rate limited config, meaning the rate limits for all of the offRamps for the given chain } struct RemoteChainConfig { RateLimiter.TokenBucket outboundRateLimiterConfig; // Outbound rate limited config, meaning the rate limits for all of the onRamps for the given chain RateLimiter.TokenBucket inboundRateLimiterConfig; // Inbound rate limited config, meaning the rate limits for all of the offRamps for the given chain bytes remotePoolAddress; // Address of the remote pool, ABI encoded in the case of a remote EVM chain. bytes remoteTokenAddress; // Address of the remote token, ABI encoded in the case of a remote EVM chain. } /// @dev The bridgeable token that is managed by this pool. IERC20 internal immutable i_token; /// @dev The address of the RMN proxy address internal immutable i_rmnProxy; /// @dev The immutable flag that indicates if the pool is access-controlled. bool internal immutable i_allowlistEnabled; /// @dev A set of addresses allowed to trigger lockOrBurn as original senders. /// Only takes effect if i_allowlistEnabled is true. /// This can be used to ensure only token-issuer specified addresses can /// move tokens. EnumerableSet.AddressSet internal s_allowList; /// @dev The address of the router IRouter internal s_router; /// @dev A set of allowed chain selectors. We want the allowlist to be enumerable to /// be able to quickly determine (without parsing logs) who can access the pool. /// @dev The chain selectors are in uint256 format because of the EnumerableSet implementation. EnumerableSet.UintSet internal s_remoteChainSelectors; mapping(uint64 remoteChainSelector => RemoteChainConfig) internal s_remoteChainConfigs; /// @notice The address of the rate limiter admin. /// @dev Can be address(0) if none is configured. address internal s_rateLimitAdmin; constructor(IERC20 token, address[] memory allowlist, address rmnProxy, address router) { if (address(token) == address(0) || router == address(0) || rmnProxy == address(0)) revert ZeroAddressNotAllowed(); i_token = token; i_rmnProxy = rmnProxy; s_router = IRouter(router); // Pool can be set as permissioned or permissionless at deployment time only to save hot-path gas. i_allowlistEnabled = allowlist.length > 0; if (i_allowlistEnabled) { _applyAllowListUpdates(new address[](0), allowlist); } } /// @notice Get RMN proxy address /// @return rmnProxy Address of RMN proxy function getRmnProxy() public view returns (address rmnProxy) { return i_rmnProxy; } /// @inheritdoc IPoolV1 function isSupportedToken(address token) public view virtual returns (bool) { return token == address(i_token); } /// @notice Gets the IERC20 token that this pool can lock or burn. /// @return token The IERC20 token representation. function getToken() public view returns (IERC20 token) { return i_token; } /// @notice Gets the pool's Router /// @return router The pool's Router function getRouter() public view returns (address router) { return address(s_router); } /// @notice Sets the pool's Router /// @param newRouter The new Router function setRouter(address newRouter) public onlyOwner { if (newRouter == address(0)) revert ZeroAddressNotAllowed(); address oldRouter = address(s_router); s_router = IRouter(newRouter); emit RouterUpdated(oldRouter, newRouter); } /// @notice Signals which version of the pool interface is supported function supportsInterface(bytes4 interfaceId) public pure virtual override returns (bool) { return interfaceId == Pool.CCIP_POOL_V1 || interfaceId == type(IPoolV1).interfaceId || interfaceId == type(IERC165).interfaceId; } // ================================================================ // │ Validation │ // ================================================================ /// @notice Validates the lock or burn input for correctness on /// - token to be locked or burned /// - RMN curse status /// - allowlist status /// - if the sender is a valid onRamp /// - rate limit status /// @param lockOrBurnIn The input to validate. /// @dev This function should always be called before executing a lock or burn. Not doing so would allow /// for various exploits. function _validateLockOrBurn(Pool.LockOrBurnInV1 memory lockOrBurnIn) internal { if (!isSupportedToken(lockOrBurnIn.localToken)) revert InvalidToken(lockOrBurnIn.localToken); if (IRMN(i_rmnProxy).isCursed(bytes16(uint128(lockOrBurnIn.remoteChainSelector)))) revert CursedByRMN(); _checkAllowList(lockOrBurnIn.originalSender); _onlyOnRamp(lockOrBurnIn.remoteChainSelector); _consumeOutboundRateLimit(lockOrBurnIn.remoteChainSelector, lockOrBurnIn.amount); } /// @notice Validates the release or mint input for correctness on /// - token to be released or minted /// - RMN curse status /// - if the sender is a valid offRamp /// - if the source pool is valid /// - rate limit status /// @param releaseOrMintIn The input to validate. /// @dev This function should always be called before executing a release or mint. Not doing so would allow /// for various exploits. function _validateReleaseOrMint(Pool.ReleaseOrMintInV1 memory releaseOrMintIn) internal { if (!isSupportedToken(releaseOrMintIn.localToken)) revert InvalidToken(releaseOrMintIn.localToken); if (IRMN(i_rmnProxy).isCursed(bytes16(uint128(releaseOrMintIn.remoteChainSelector)))) revert CursedByRMN(); _onlyOffRamp(releaseOrMintIn.remoteChainSelector); // Validates that the source pool address is configured on this pool. bytes memory configuredRemotePool = getRemotePool(releaseOrMintIn.remoteChainSelector); if ( configuredRemotePool.length == 0 || keccak256(releaseOrMintIn.sourcePoolAddress) != keccak256(configuredRemotePool) ) { revert InvalidSourcePoolAddress(releaseOrMintIn.sourcePoolAddress); } _consumeInboundRateLimit(releaseOrMintIn.remoteChainSelector, releaseOrMintIn.amount); } // ================================================================ // │ Chain permissions │ // ================================================================ /// @notice Gets the pool address on the remote chain. /// @param remoteChainSelector Remote chain selector. /// @dev To support non-evm chains, this value is encoded into bytes function getRemotePool(uint64 remoteChainSelector) public view returns (bytes memory) { return s_remoteChainConfigs[remoteChainSelector].remotePoolAddress; } /// @notice Gets the token address on the remote chain. /// @param remoteChainSelector Remote chain selector. /// @dev To support non-evm chains, this value is encoded into bytes function getRemoteToken(uint64 remoteChainSelector) public view returns (bytes memory) { return s_remoteChainConfigs[remoteChainSelector].remoteTokenAddress; } /// @notice Sets the remote pool address for a given chain selector. /// @param remoteChainSelector The remote chain selector for which the remote pool address is being set. /// @param remotePoolAddress The address of the remote pool. function setRemotePool(uint64 remoteChainSelector, bytes calldata remotePoolAddress) external onlyOwner { if (!isSupportedChain(remoteChainSelector)) revert NonExistentChain(remoteChainSelector); bytes memory prevAddress = s_remoteChainConfigs[remoteChainSelector].remotePoolAddress; s_remoteChainConfigs[remoteChainSelector].remotePoolAddress = remotePoolAddress; emit RemotePoolSet(remoteChainSelector, prevAddress, remotePoolAddress); } /// @inheritdoc IPoolV1 function isSupportedChain(uint64 remoteChainSelector) public view returns (bool) { return s_remoteChainSelectors.contains(remoteChainSelector); } /// @notice Get list of allowed chains /// @return list of chains. function getSupportedChains() public view returns (uint64[] memory) { uint256[] memory uint256ChainSelectors = s_remoteChainSelectors.values(); uint64[] memory chainSelectors = new uint64[](uint256ChainSelectors.length); for (uint256 i = 0; i < uint256ChainSelectors.length; ++i) { chainSelectors[i] = uint64(uint256ChainSelectors[i]); } return chainSelectors; } /// @notice Sets the permissions for a list of chains selectors. Actual senders for these chains /// need to be allowed on the Router to interact with this pool. /// @dev Only callable by the owner /// @param chains A list of chains and their new permission status & rate limits. Rate limits /// are only used when the chain is being added through `allowed` being true. function applyChainUpdates(ChainUpdate[] calldata chains) external virtual onlyOwner { for (uint256 i = 0; i < chains.length; ++i) { ChainUpdate memory update = chains[i]; RateLimiter._validateTokenBucketConfig(update.outboundRateLimiterConfig, !update.allowed); RateLimiter._validateTokenBucketConfig(update.inboundRateLimiterConfig, !update.allowed); if (update.allowed) { // If the chain already exists, revert if (!s_remoteChainSelectors.add(update.remoteChainSelector)) { revert ChainAlreadyExists(update.remoteChainSelector); } if (update.remotePoolAddress.length == 0 || update.remoteTokenAddress.length == 0) { revert ZeroAddressNotAllowed(); } s_remoteChainConfigs[update.remoteChainSelector] = RemoteChainConfig({ outboundRateLimiterConfig: RateLimiter.TokenBucket({ rate: update.outboundRateLimiterConfig.rate, capacity: update.outboundRateLimiterConfig.capacity, tokens: update.outboundRateLimiterConfig.capacity, lastUpdated: uint32(block.timestamp), isEnabled: update.outboundRateLimiterConfig.isEnabled }), inboundRateLimiterConfig: RateLimiter.TokenBucket({ rate: update.inboundRateLimiterConfig.rate, capacity: update.inboundRateLimiterConfig.capacity, tokens: update.inboundRateLimiterConfig.capacity, lastUpdated: uint32(block.timestamp), isEnabled: update.inboundRateLimiterConfig.isEnabled }), remotePoolAddress: update.remotePoolAddress, remoteTokenAddress: update.remoteTokenAddress }); emit ChainAdded( update.remoteChainSelector, update.remoteTokenAddress, update.outboundRateLimiterConfig, update.inboundRateLimiterConfig ); } else { // If the chain doesn't exist, revert if (!s_remoteChainSelectors.remove(update.remoteChainSelector)) { revert NonExistentChain(update.remoteChainSelector); } delete s_remoteChainConfigs[update.remoteChainSelector]; emit ChainRemoved(update.remoteChainSelector); } } } // ================================================================ // │ Rate limiting │ // ================================================================ /// @notice Sets the rate limiter admin address. /// @dev Only callable by the owner. /// @param rateLimitAdmin The new rate limiter admin address. function setRateLimitAdmin(address rateLimitAdmin) external onlyOwner { s_rateLimitAdmin = rateLimitAdmin; } /// @notice Gets the rate limiter admin address. function getRateLimitAdmin() external view returns (address) { return s_rateLimitAdmin; } /// @notice Consumes outbound rate limiting capacity in this pool function _consumeOutboundRateLimit(uint64 remoteChainSelector, uint256 amount) internal { s_remoteChainConfigs[remoteChainSelector].outboundRateLimiterConfig._consume(amount, address(i_token)); } /// @notice Consumes inbound rate limiting capacity in this pool function _consumeInboundRateLimit(uint64 remoteChainSelector, uint256 amount) internal { s_remoteChainConfigs[remoteChainSelector].inboundRateLimiterConfig._consume(amount, address(i_token)); } /// @notice Gets the token bucket with its values for the block it was requested at. /// @return The token bucket. function getCurrentOutboundRateLimiterState( uint64 remoteChainSelector ) external view returns (RateLimiter.TokenBucket memory) { return s_remoteChainConfigs[remoteChainSelector].outboundRateLimiterConfig._currentTokenBucketState(); } /// @notice Gets the token bucket with its values for the block it was requested at. /// @return The token bucket. function getCurrentInboundRateLimiterState( uint64 remoteChainSelector ) external view returns (RateLimiter.TokenBucket memory) { return s_remoteChainConfigs[remoteChainSelector].inboundRateLimiterConfig._currentTokenBucketState(); } /// @notice Sets the chain rate limiter config. /// @param remoteChainSelector The remote chain selector for which the rate limits apply. /// @param outboundConfig The new outbound rate limiter config, meaning the onRamp rate limits for the given chain. /// @param inboundConfig The new inbound rate limiter config, meaning the offRamp rate limits for the given chain. function setChainRateLimiterConfig( uint64 remoteChainSelector, RateLimiter.Config memory outboundConfig, RateLimiter.Config memory inboundConfig ) external { if (msg.sender != s_rateLimitAdmin && msg.sender != owner()) revert Unauthorized(msg.sender); _setRateLimitConfig(remoteChainSelector, outboundConfig, inboundConfig); } function _setRateLimitConfig( uint64 remoteChainSelector, RateLimiter.Config memory outboundConfig, RateLimiter.Config memory inboundConfig ) internal { if (!isSupportedChain(remoteChainSelector)) revert NonExistentChain(remoteChainSelector); RateLimiter._validateTokenBucketConfig(outboundConfig, false); s_remoteChainConfigs[remoteChainSelector].outboundRateLimiterConfig._setTokenBucketConfig(outboundConfig); RateLimiter._validateTokenBucketConfig(inboundConfig, false); s_remoteChainConfigs[remoteChainSelector].inboundRateLimiterConfig._setTokenBucketConfig(inboundConfig); emit ChainConfigured(remoteChainSelector, outboundConfig, inboundConfig); } // ================================================================ // │ Access │ // ================================================================ /// @notice Checks whether remote chain selector is configured on this contract, and if the msg.sender /// is a permissioned onRamp for the given chain on the Router. function _onlyOnRamp(uint64 remoteChainSelector) internal view { if (!isSupportedChain(remoteChainSelector)) revert ChainNotAllowed(remoteChainSelector); if (!(msg.sender == s_router.getOnRamp(remoteChainSelector))) revert CallerIsNotARampOnRouter(msg.sender); } /// @notice Checks whether remote chain selector is configured on this contract, and if the msg.sender /// is a permissioned offRamp for the given chain on the Router. function _onlyOffRamp(uint64 remoteChainSelector) internal view { if (!isSupportedChain(remoteChainSelector)) revert ChainNotAllowed(remoteChainSelector); if (!s_router.isOffRamp(remoteChainSelector, msg.sender)) revert CallerIsNotARampOnRouter(msg.sender); } // ================================================================ // │ Allowlist │ // ================================================================ function _checkAllowList(address sender) internal view { if (i_allowlistEnabled) { if (!s_allowList.contains(sender)) { revert SenderNotAllowed(sender); } } } /// @notice Gets whether the allowList functionality is enabled. /// @return true is enabled, false if not. function getAllowListEnabled() external view returns (bool) { return i_allowlistEnabled; } /// @notice Gets the allowed addresses. /// @return The allowed addresses. function getAllowList() external view returns (address[] memory) { return s_allowList.values(); } /// @notice Apply updates to the allow list. /// @param removes The addresses to be removed. /// @param adds The addresses to be added. function applyAllowListUpdates(address[] calldata removes, address[] calldata adds) external onlyOwner { _applyAllowListUpdates(removes, adds); } /// @notice Internal version of applyAllowListUpdates to allow for reuse in the constructor. function _applyAllowListUpdates(address[] memory removes, address[] memory adds) internal { if (!i_allowlistEnabled) revert AllowListNotEnabled(); for (uint256 i = 0; i < removes.length; ++i) { address toRemove = removes[i]; if (s_allowList.remove(toRemove)) { emit AllowListRemove(toRemove); } } for (uint256 i = 0; i < adds.length; ++i) { address toAdd = adds[i]; if (toAdd == address(0)) { continue; } if (s_allowList.add(toAdd)) { emit AllowListAdd(toAdd); } } } }
// SPDX-License-Identifier: BUSL-1.1 pragma solidity 0.8.24; import {IRMN} from "../../interfaces/IRMN.sol"; /// @notice WARNING: This contract is to be only used for testing, all methods are unprotected. contract MockRMN is IRMN { error CustomError(bytes err); bytes private s_isCursedRevert; bool private s_globalCursed; mapping(bytes16 subject => bool cursed) private s_cursedBySubject; mapping(address commitStore => mapping(bytes32 root => bool blessed)) private s_blessedByRoot; function setTaggedRootBlessed(IRMN.TaggedRoot calldata taggedRoot, bool blessed) external { s_blessedByRoot[taggedRoot.commitStore][taggedRoot.root] = blessed; } function setGlobalCursed(bool cursed) external { s_globalCursed = cursed; } function setChainCursed(uint64 chainSelector, bool cursed) external { s_cursedBySubject[bytes16(uint128(chainSelector))] = cursed; } /// @notice Setting a revert error with length of 0 will disable reverts /// @dev Useful to test revert handling of ARMProxy function setIsCursedRevert(bytes calldata revertErr) external { s_isCursedRevert = revertErr; } // IRMN implementation follows function isCursed() external view returns (bool) { if (s_isCursedRevert.length > 0) { revert CustomError(s_isCursedRevert); } return s_globalCursed; } function isCursed(bytes16 subject) external view returns (bool) { if (s_isCursedRevert.length > 0) { revert CustomError(s_isCursedRevert); } return s_globalCursed || s_cursedBySubject[subject]; } function isBlessed(IRMN.TaggedRoot calldata taggedRoot) external view returns (bool) { return s_blessedByRoot[taggedRoot.commitStore][taggedRoot.root]; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ConfirmedOwnerWithProposal} from "./ConfirmedOwnerWithProposal.sol"; /// @title The ConfirmedOwner contract /// @notice A contract with helpers for basic contract ownership. contract ConfirmedOwner is ConfirmedOwnerWithProposal { constructor(address newOwner) ConfirmedOwnerWithProposal(newOwner, address(0)) {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {IOwnable} from "../interfaces/IOwnable.sol"; /// @title The ConfirmedOwner contract /// @notice A contract with helpers for basic contract ownership. contract ConfirmedOwnerWithProposal is IOwnable { address private s_owner; address private s_pendingOwner; event OwnershipTransferRequested(address indexed from, address indexed to); event OwnershipTransferred(address indexed from, address indexed to); constructor(address newOwner, address pendingOwner) { // solhint-disable-next-line gas-custom-errors require(newOwner != address(0), "Cannot set owner to zero"); s_owner = newOwner; if (pendingOwner != address(0)) { _transferOwnership(pendingOwner); } } /// @notice Allows an owner to begin transferring ownership to a new address. function transferOwnership(address to) public override onlyOwner { _transferOwnership(to); } /// @notice Allows an ownership transfer to be completed by the recipient. function acceptOwnership() external override { // solhint-disable-next-line gas-custom-errors require(msg.sender == s_pendingOwner, "Must be proposed owner"); address oldOwner = s_owner; s_owner = msg.sender; s_pendingOwner = address(0); emit OwnershipTransferred(oldOwner, msg.sender); } /// @notice Get the current owner function owner() public view override returns (address) { return s_owner; } /// @notice validate, transfer ownership, and emit relevant events function _transferOwnership(address to) private { // solhint-disable-next-line gas-custom-errors require(to != msg.sender, "Cannot transfer to self"); s_pendingOwner = to; emit OwnershipTransferRequested(s_owner, to); } /// @notice validate access function _validateOwnership() internal view { // solhint-disable-next-line gas-custom-errors require(msg.sender == s_owner, "Only callable by owner"); } /// @notice Reverts if called by anyone other than the contract owner. modifier onlyOwner() { _validateOwnership(); _; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import {ConfirmedOwner} from "./ConfirmedOwner.sol"; /// @title The OwnerIsCreator contract /// @notice A contract with helpers for basic contract ownership. contract OwnerIsCreator is ConfirmedOwner { constructor() ConfirmedOwner(msg.sender) {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @notice This library contains various callWithExactGas functions. All of them are /// safe from gas bomb attacks. /// @dev There is code duplication in this library. This is done to not leave the assembly /// the blocks. library CallWithExactGas { error NoContract(); error NoGasForCallExactCheck(); error NotEnoughGasForCall(); bytes4 internal constant NO_CONTRACT_SIG = 0x0c3b563c; bytes4 internal constant NO_GAS_FOR_CALL_EXACT_CHECK_SIG = 0xafa32a2c; bytes4 internal constant NOT_ENOUGH_GAS_FOR_CALL_SIG = 0x37c3be29; /// @notice calls target address with exactly gasAmount gas and payload as calldata. /// Accounts for gasForCallExactCheck gas that will be used by this function. Will revert /// if the target is not a contact. Will revert when there is not enough gas to call the /// target with gasAmount gas. /// @dev Ignores the return data, which makes it immune to gas bomb attacks. /// @return success whether the call succeeded function _callWithExactGas( bytes memory payload, address target, uint256 gasLimit, uint16 gasForCallExactCheck ) internal returns (bool success) { assembly { // solidity calls check that a contract actually exists at the destination, so we do the same // Note we do this check prior to measuring gas so gasForCallExactCheck (our "cushion") // doesn't need to account for it. if iszero(extcodesize(target)) { mstore(0x0, NO_CONTRACT_SIG) revert(0x0, 0x4) } let g := gas() // Compute g -= gasForCallExactCheck and check for underflow // The gas actually passed to the callee is _min(gasAmount, 63//64*gas available). // We want to ensure that we revert if gasAmount > 63//64*gas available // as we do not want to provide them with less, however that check itself costs // gas. gasForCallExactCheck ensures we have at least enough gas to be able // to revert if gasAmount > 63//64*gas available. if lt(g, gasForCallExactCheck) { mstore(0x0, NO_GAS_FOR_CALL_EXACT_CHECK_SIG) revert(0x0, 0x4) } g := sub(g, gasForCallExactCheck) // if g - g//64 <= gasAmount, revert. We subtract g//64 because of EIP-150 if iszero(gt(sub(g, div(g, 64)), gasLimit)) { mstore(0x0, NOT_ENOUGH_GAS_FOR_CALL_SIG) revert(0x0, 0x4) } // call and return whether we succeeded. ignore return data // call(gas,addr,value,argsOffset,argsLength,retOffset,retLength) success := call(gasLimit, target, 0, add(payload, 0x20), mload(payload), 0x0, 0x0) } return success; } /// @notice calls target address with exactly gasAmount gas and payload as calldata. /// Account for gasForCallExactCheck gas that will be used by this function. Will revert /// if the target is not a contact. Will revert when there is not enough gas to call the /// target with gasAmount gas. /// @dev Caps the return data length, which makes it immune to gas bomb attacks. /// @dev Return data cap logic borrowed from /// https://github.com/nomad-xyz/ExcessivelySafeCall/blob/main/src/ExcessivelySafeCall.sol. /// @return success whether the call succeeded /// @return retData the return data from the call, capped at maxReturnBytes bytes /// @return gasUsed the gas used by the external call. Does not include the overhead of this function. function _callWithExactGasSafeReturnData( bytes memory payload, address target, uint256 gasLimit, uint16 gasForCallExactCheck, uint16 maxReturnBytes ) internal returns (bool success, bytes memory retData, uint256 gasUsed) { // allocate retData memory ahead of time retData = new bytes(maxReturnBytes); assembly { // solidity calls check that a contract actually exists at the destination, so we do the same // Note we do this check prior to measuring gas so gasForCallExactCheck (our "cushion") // doesn't need to account for it. if iszero(extcodesize(target)) { mstore(0x0, NO_CONTRACT_SIG) revert(0x0, 0x4) } let g := gas() // Compute g -= gasForCallExactCheck and check for underflow // The gas actually passed to the callee is _min(gasAmount, 63//64*gas available). // We want to ensure that we revert if gasAmount > 63//64*gas available // as we do not want to provide them with less, however that check itself costs // gas. gasForCallExactCheck ensures we have at least enough gas to be able // to revert if gasAmount > 63//64*gas available. if lt(g, gasForCallExactCheck) { mstore(0x0, NO_GAS_FOR_CALL_EXACT_CHECK_SIG) revert(0x0, 0x4) } g := sub(g, gasForCallExactCheck) // if g - g//64 <= gasAmount, revert. We subtract g//64 because of EIP-150 if iszero(gt(sub(g, div(g, 64)), gasLimit)) { mstore(0x0, NOT_ENOUGH_GAS_FOR_CALL_SIG) revert(0x0, 0x4) } // We save the gas before the call so we can calculate how much gas the call used let gasBeforeCall := gas() // call and return whether we succeeded. ignore return data // call(gas,addr,value,argsOffset,argsLength,retOffset,retLength) success := call(gasLimit, target, 0, add(payload, 0x20), mload(payload), 0x0, 0x0) gasUsed := sub(gasBeforeCall, gas()) // limit our copy to maxReturnBytes bytes let toCopy := returndatasize() if gt(toCopy, maxReturnBytes) { toCopy := maxReturnBytes } // Store the length of the copied bytes mstore(retData, toCopy) // copy the bytes from retData[0:_toCopy] returndatacopy(add(retData, 0x20), 0x0, toCopy) } return (success, retData, gasUsed); } /// @notice Calls target address with exactly gasAmount gas and payload as calldata /// or reverts if at least gasLimit gas is not available. /// @dev Does not check if target is a contract. If it is not a contract, the low-level /// call will still be made and it will succeed. /// @dev Ignores the return data, which makes it immune to gas bomb attacks. /// @return success whether the call succeeded /// @return sufficientGas Whether there was enough gas to make the call function _callWithExactGasEvenIfTargetIsNoContract( bytes memory payload, address target, uint256 gasLimit, uint16 gasForCallExactCheck ) internal returns (bool success, bool sufficientGas) { assembly { let g := gas() // Compute g -= CALL_WITH_EXACT_GAS_CUSHION and check for underflow. We // need the cushion since the logic following the above call to gas also // costs gas which we cannot account for exactly. So cushion is a // conservative upper bound for the cost of this logic. if iszero(lt(g, gasForCallExactCheck)) { g := sub(g, gasForCallExactCheck) // If g - g//64 <= gasAmount, we don't have enough gas. We subtract g//64 because of EIP-150. if gt(sub(g, div(g, 64)), gasLimit) { // Call and ignore success/return data. Note that we did not check // whether a contract actually exists at the target address. success := call(gasLimit, target, 0, add(payload, 0x20), mload(payload), 0x0, 0x0) sufficientGas := true } } } return (success, sufficientGas); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IOwnable { function owner() external returns (address); function transferOwnership(address recipient) external; function acceptOwnership() external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/draft-IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.20; import {IERC165} from "./IERC165.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165Checker { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface. */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return supportsERC165InterfaceUnchecked(account, type(IERC165).interfaceId) && !supportsERC165InterfaceUnchecked(account, INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && supportsERC165InterfaceUnchecked(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. */ function getSupportedInterfaces( address account, bytes4[] memory interfaceIds ) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = supportsERC165InterfaceUnchecked(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!supportsERC165InterfaceUnchecked(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * * Some precompiled contracts will falsely indicate support for a given interface, so caution * should be exercised when using this function. * * Interface identification is specified in ERC-165. */ function supportsERC165InterfaceUnchecked(address account, bytes4 interfaceId) internal view returns (bool) { // prepare call bytes memory encodedParams = abi.encodeCall(IERC165.supportsInterface, (interfaceId)); // perform static call bool success; uint256 returnSize; uint256 returnValue; assembly { success := staticcall(30000, account, add(encodedParams, 0x20), mload(encodedParams), 0x00, 0x20) returnSize := returndatasize() returnValue := mload(0x00) } return success && returnSize >= 0x20 && returnValue > 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev 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}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[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); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/EnumerableSet.sol) // This file was procedurally generated from scripts/generate/templates/EnumerableSet.js. pragma solidity ^0.8.20; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ```solidity * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure * unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an * array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position is the index of the value in the `values` array plus 1. // Position 0 is used to mean a value is not in the set. mapping(bytes32 value => uint256) _positions; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._positions[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We cache the value's position to prevent multiple reads from the same storage slot uint256 position = set._positions[value]; if (position != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 valueIndex = position - 1; uint256 lastIndex = set._values.length - 1; if (valueIndex != lastIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the lastValue to the index where the value to delete is set._values[valueIndex] = lastValue; // Update the tracked position of the lastValue (that was just moved) set._positions[lastValue] = position; } // Delete the slot where the moved value was stored set._values.pop(); // Delete the tracked position for the deleted slot delete set._positions[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._positions[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { bytes32[] memory store = _values(set._inner); bytes32[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values in the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol"; import { IWorker } from "./IWorker.sol"; import { ILayerZeroExecutor } from "./ILayerZeroExecutor.sol"; import { ILayerZeroReadExecutor } from "./ILayerZeroReadExecutor.sol"; interface IExecutor is IWorker, ILayerZeroExecutor, ILayerZeroReadExecutor { struct DstConfigParam { uint32 dstEid; uint64 lzReceiveBaseGas; uint64 lzComposeBaseGas; uint16 multiplierBps; uint128 floorMarginUSD; uint128 nativeCap; } struct DstConfig { uint64 lzReceiveBaseGas; uint16 multiplierBps; uint128 floorMarginUSD; // uses priceFeed PRICE_RATIO_DENOMINATOR uint128 nativeCap; uint64 lzComposeBaseGas; } struct ExecutionParams { address receiver; Origin origin; bytes32 guid; bytes message; bytes extraData; uint256 gasLimit; } struct NativeDropParams { address receiver; uint256 amount; } event DstConfigSet(DstConfigParam[] params); event NativeDropApplied(Origin origin, uint32 dstEid, address oapp, NativeDropParams[] params, bool[] success); function dstConfig(uint32 _dstEid) external view returns (uint64, uint16, uint128, uint128, uint64); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { IExecutor } from "./IExecutor.sol"; interface IExecutorFeeLib { struct FeeParams { address priceFeed; uint32 dstEid; address sender; uint256 calldataSize; uint16 defaultMultiplierBps; } struct FeeParamsForRead { address priceFeed; address sender; uint16 defaultMultiplierBps; } error Executor_NoOptions(); error Executor_NativeAmountExceedsCap(uint256 amount, uint256 cap); error Executor_UnsupportedOptionType(uint8 optionType); error Executor_InvalidExecutorOptions(uint256 cursor); error Executor_ZeroLzReceiveGasProvided(); error Executor_ZeroLzComposeGasProvided(); error Executor_ZeroCalldataSizeProvided(); error Executor_EidNotSupported(uint32 eid); function getFeeOnSend( FeeParams calldata _params, IExecutor.DstConfig calldata _dstConfig, bytes calldata _options ) external returns (uint256 fee); function getFee( FeeParams calldata _params, IExecutor.DstConfig calldata _dstConfig, bytes calldata _options ) external view returns (uint256 fee); function getFeeOnSend( FeeParamsForRead calldata _params, IExecutor.DstConfig calldata _dstConfig, bytes calldata _options ) external returns (uint256 fee); function getFee( FeeParamsForRead calldata _params, IExecutor.DstConfig calldata _dstConfig, bytes calldata _options ) external view returns (uint256 fee); function version() external view returns (uint64 major, uint8 minor); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface ILayerZeroExecutor { // @notice query price and assign jobs at the same time // @param _dstEid - the destination endpoint identifier // @param _sender - the source sending contract address. executors may apply price discrimination to senders // @param _calldataSize - dynamic data size of message + caller params // @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain function assignJob( uint32 _dstEid, address _sender, uint256 _calldataSize, bytes calldata _options ) external returns (uint256 price); // @notice query the executor price for relaying the payload and its proof to the destination chain // @param _dstEid - the destination endpoint identifier // @param _sender - the source sending contract address. executors may apply price discrimination to senders // @param _calldataSize - dynamic data size of message + caller params // @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain function getFee( uint32 _dstEid, address _sender, uint256 _calldataSize, bytes calldata _options ) external view returns (uint256 price); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface ILayerZeroReadExecutor { // @notice query price and assign jobs at the same time // @param _sender - the source sending contract address. executors may apply price discrimination to senders // @param _options - optional parameters for extra service plugins, e.g. sending dust tokens at the destination chain function assignJob(address _sender, bytes calldata _options) external returns (uint256 fee); // @notice query the executor price for executing the payload on this chain // @param _sender - the source sending contract address. executors may apply price discrimination to senders // @param _options - optional parameters for extra service plugins, e.g. sending dust tokens function getFee(address _sender, bytes calldata _options) external view returns (uint256 fee); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface ILayerZeroTreasury { function getFee( address _sender, uint32 _dstEid, uint256 _totalNativeFee, bool _payInLzToken ) external view returns (uint256 fee); function payFee( address _sender, uint32 _dstEid, uint256 _totalNativeFee, bool _payInLzToken ) external payable returns (uint256 fee); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IWorker { event SetWorkerLib(address workerLib); event SetPriceFeed(address priceFeed); event SetDefaultMultiplierBps(uint16 multiplierBps); event SetSupportedOptionTypes(uint32 dstEid, uint8[] optionTypes); event Withdraw(address lib, address to, uint256 amount); error Worker_NotAllowed(); error Worker_OnlyMessageLib(); error Worker_RoleRenouncingDisabled(); function setPriceFeed(address _priceFeed) external; function priceFeed() external view returns (address); function setDefaultMultiplierBps(uint16 _multiplierBps) external; function defaultMultiplierBps() external view returns (uint16); function withdrawFee(address _lib, address _to, uint256 _amount) external; function setSupportedOptionTypes(uint32 _eid, uint8[] calldata _optionTypes) external; function getSupportedOptionTypes(uint32 _eid) external view returns (uint8[] memory); }
// SPDX-License-Identifier: MIT OR Apache-2.0 pragma solidity ^0.8.20; /// @dev copied from https://github.com/nomad-xyz/ExcessivelySafeCall/blob/main/src/ExcessivelySafeCall.sol. library SafeCall { /// @notice calls a contract with a specified gas limit and value and captures the return data /// @param _target The address to call /// @param _gas The amount of gas to forward to the remote contract /// @param _value The value in wei to send to the remote contract /// to memory. /// @param _maxCopy The maximum number of bytes of returndata to copy /// to memory. /// @param _calldata The data to send to the remote contract /// @return success and returndata, as `.call()`. Returndata is capped to /// `_maxCopy` bytes. function safeCall( address _target, uint256 _gas, uint256 _value, uint16 _maxCopy, bytes memory _calldata ) internal returns (bool, bytes memory) { // check that target has code uint size; assembly { size := extcodesize(_target) } if (size == 0) { return (false, new bytes(0)); } // set up for assembly call uint256 _toCopy; bool _success; bytes memory _returnData = new bytes(_maxCopy); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := call( _gas, // gas _target, // recipient _value, // ether value add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 100 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } return (_success, _returnData); } /// @notice Use when you _really_ really _really_ don't trust the called /// contract. This prevents the called contract from causing reversion of /// the caller in as many ways as we can. /// @dev The main difference between this and a solidity low-level call is /// that we limit the number of bytes that the callee can cause to be /// copied to caller memory. This prevents stupid things like malicious /// contracts returning 10,000,000 bytes causing a local OOG when copying /// to memory. /// @param _target The address to call /// @param _gas The amount of gas to forward to the remote contract /// @param _maxCopy The maximum number of bytes of returndata to copy /// to memory. /// @param _calldata The data to send to the remote contract /// @return success and returndata, as `.call()`. Returndata is capped to /// `_maxCopy` bytes. function safeStaticCall( address _target, uint256 _gas, uint16 _maxCopy, bytes memory _calldata ) internal view returns (bool, bytes memory) { // check that target has code uint size; assembly { size := extcodesize(_target) } if (size == 0) { return (false, new bytes(0)); } // set up for assembly call uint256 _toCopy; bool _success; bytes memory _returnData = new bytes(_maxCopy); // dispatch message to recipient // by assembly calling "handle" function // we call via assembly to avoid memcopying a very large returndata // returned by a malicious contract assembly { _success := staticcall( _gas, // gas _target, // recipient add(_calldata, 0x20), // inloc mload(_calldata), // inlen 0, // outloc 0 // outlen ) // limit our copy to 256 bytes _toCopy := returndatasize() if gt(_toCopy, _maxCopy) { _toCopy := _maxCopy } // Store the length of the copied bytes mstore(_returnData, _toCopy) // copy the bytes from returndata[0:_toCopy] returndatacopy(add(_returnData, 0x20), 0, _toCopy) } return (_success, _returnData); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; /// @dev simply a container of endpoint address and local eid abstract contract MessageLibBase { address internal immutable endpoint; uint32 internal immutable localEid; error LZ_MessageLib_OnlyEndpoint(); modifier onlyEndpoint() { if (endpoint != msg.sender) revert LZ_MessageLib_OnlyEndpoint(); _; } constructor(address _endpoint, uint32 _localEid) { endpoint = _endpoint; localEid = _localEid; } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { Transfer } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/Transfer.sol"; import { ILayerZeroExecutor } from "./interfaces/ILayerZeroExecutor.sol"; import { ILayerZeroTreasury } from "./interfaces/ILayerZeroTreasury.sol"; import { SafeCall } from "./libs/SafeCall.sol"; import { MessageLibBase } from "./MessageLibBase.sol"; struct WorkerOptions { uint8 workerId; bytes options; } struct SetDefaultExecutorConfigParam { uint32 eid; ExecutorConfig config; } struct ExecutorConfig { uint32 maxMessageSize; address executor; } /// @dev base contract for both SendLibBaseE1 and SendLibBaseE2 abstract contract SendLibBase is MessageLibBase, Ownable { using SafeCall for address; address private constant DEFAULT_CONFIG = address(0); uint16 internal constant TREASURY_MAX_COPY = 32; uint256 internal immutable treasuryGasLimit; uint256 internal treasuryNativeFeeCap; // config address public treasury; mapping(address oapp => mapping(uint32 eid => ExecutorConfig)) public executorConfigs; // accumulated fees for workers and treasury mapping(address worker => uint256) public fees; event ExecutorFeePaid(address executor, uint256 fee); event TreasurySet(address treasury); event DefaultExecutorConfigsSet(SetDefaultExecutorConfigParam[] params); event ExecutorConfigSet(address oapp, uint32 eid, ExecutorConfig config); event TreasuryNativeFeeCapSet(uint256 newTreasuryNativeFeeCap); error LZ_MessageLib_InvalidMessageSize(uint256 actual, uint256 max); error LZ_MessageLib_InvalidAmount(uint256 requested, uint256 available); error LZ_MessageLib_TransferFailed(); error LZ_MessageLib_InvalidExecutor(); error LZ_MessageLib_ZeroMessageSize(); constructor( address _endpoint, uint32 _localEid, uint256 _treasuryGasLimit, uint256 _treasuryNativeFeeCap ) MessageLibBase(_endpoint, _localEid) { treasuryGasLimit = _treasuryGasLimit; treasuryNativeFeeCap = _treasuryNativeFeeCap; } function setDefaultExecutorConfigs(SetDefaultExecutorConfigParam[] calldata _params) external onlyOwner { for (uint256 i = 0; i < _params.length; ++i) { SetDefaultExecutorConfigParam calldata param = _params[i]; if (param.config.executor == address(0x0)) revert LZ_MessageLib_InvalidExecutor(); if (param.config.maxMessageSize == 0) revert LZ_MessageLib_ZeroMessageSize(); executorConfigs[DEFAULT_CONFIG][param.eid] = param.config; } emit DefaultExecutorConfigsSet(_params); } /// @dev the new value can not be greater than the old value, i.e. down only function setTreasuryNativeFeeCap(uint256 _newTreasuryNativeFeeCap) external onlyOwner { // assert the new value is no greater than the old value if (_newTreasuryNativeFeeCap > treasuryNativeFeeCap) revert LZ_MessageLib_InvalidAmount(_newTreasuryNativeFeeCap, treasuryNativeFeeCap); treasuryNativeFeeCap = _newTreasuryNativeFeeCap; emit TreasuryNativeFeeCapSet(_newTreasuryNativeFeeCap); } // ============================ View =================================== // @dev get the executor config and if not set, return the default config function getExecutorConfig(address _oapp, uint32 _remoteEid) public view returns (ExecutorConfig memory rtnConfig) { ExecutorConfig storage defaultConfig = executorConfigs[DEFAULT_CONFIG][_remoteEid]; ExecutorConfig storage customConfig = executorConfigs[_oapp][_remoteEid]; uint32 maxMessageSize = customConfig.maxMessageSize; rtnConfig.maxMessageSize = maxMessageSize != 0 ? maxMessageSize : defaultConfig.maxMessageSize; address executor = customConfig.executor; rtnConfig.executor = executor != address(0x0) ? executor : defaultConfig.executor; } // ======================= Internal ======================= function _assertMessageSize(uint256 _actual, uint256 _max) internal pure { if (_actual > _max) revert LZ_MessageLib_InvalidMessageSize(_actual, _max); } function _payExecutor( address _executor, uint32 _dstEid, address _sender, uint256 _msgSize, bytes memory _executorOptions ) internal returns (uint256 executorFee) { executorFee = ILayerZeroExecutor(_executor).assignJob(_dstEid, _sender, _msgSize, _executorOptions); if (executorFee > 0) { fees[_executor] += executorFee; } emit ExecutorFeePaid(_executor, executorFee); } function _payTreasury( address _sender, uint32 _dstEid, uint256 _totalNativeFee, bool _payInLzToken ) internal returns (uint256 treasuryNativeFee, uint256 lzTokenFee) { if (treasury != address(0x0)) { bytes memory callData = abi.encodeCall( ILayerZeroTreasury.payFee, (_sender, _dstEid, _totalNativeFee, _payInLzToken) ); (bool success, bytes memory result) = treasury.safeCall(treasuryGasLimit, 0, TREASURY_MAX_COPY, callData); (treasuryNativeFee, lzTokenFee) = _parseTreasuryResult(_totalNativeFee, _payInLzToken, success, result); // fee should be in lzTokenFee if payInLzToken, otherwise in native if (treasuryNativeFee > 0) { fees[treasury] += treasuryNativeFee; } } } /// @dev the abstract process for quote() is: /// 0/ split out the executor options and options of other workers /// 1/ quote workers /// 2/ quote executor /// 3/ quote treasury /// @return nativeFee, lzTokenFee function _quote( address _sender, uint32 _dstEid, uint256 _msgSize, bool _payInLzToken, bytes calldata _options ) internal view returns (uint256, uint256) { (bytes memory executorOptions, WorkerOptions[] memory validationOptions) = _splitOptions(_options); // quote the verifier used in the library. for ULN, it is a list of DVNs uint256 nativeFee = _quoteVerifier(_sender, _dstEid, validationOptions); // quote executor ExecutorConfig memory config = getExecutorConfig(_sender, _dstEid); // assert msg size _assertMessageSize(_msgSize, config.maxMessageSize); nativeFee += ILayerZeroExecutor(config.executor).getFee(_dstEid, _sender, _msgSize, executorOptions); // quote treasury (uint256 treasuryNativeFee, uint256 lzTokenFee) = _quoteTreasury(_sender, _dstEid, nativeFee, _payInLzToken); nativeFee += treasuryNativeFee; return (nativeFee, lzTokenFee); } /// @dev this interface should be DoS-free if the user is paying with native. properties /// 1/ treasury can return an overly high lzToken fee /// 2/ if treasury returns an overly high native fee, it will be capped by maxNativeFee, /// which can be reasoned with the configurations /// 3/ the owner can not configure the treasury in a way that force this function to revert function _quoteTreasury( address _sender, uint32 _dstEid, uint256 _totalNativeFee, bool _payInLzToken ) internal view returns (uint256 nativeFee, uint256 lzTokenFee) { // treasury must be set, and it has to be a contract if (treasury != address(0x0)) { bytes memory callData = abi.encodeCall( ILayerZeroTreasury.getFee, (_sender, _dstEid, _totalNativeFee, _payInLzToken) ); (bool success, bytes memory result) = treasury.safeStaticCall( treasuryGasLimit, TREASURY_MAX_COPY, callData ); return _parseTreasuryResult(_totalNativeFee, _payInLzToken, success, result); } } function _parseTreasuryResult( uint256 _totalNativeFee, bool _payInLzToken, bool _success, bytes memory _result ) internal view returns (uint256 nativeFee, uint256 lzTokenFee) { // failure, charges nothing if (!_success || _result.length < TREASURY_MAX_COPY) return (0, 0); // parse the result uint256 treasureFeeQuote = abi.decode(_result, (uint256)); if (_payInLzToken) { lzTokenFee = treasureFeeQuote; } else { // pay in native // we must prevent high-treasuryFee Dos attack // nativeFee = min(treasureFeeQuote, maxNativeFee) // opportunistically raise the maxNativeFee to be the same as _totalNativeFee // can't use the _totalNativeFee alone because the oapp can use custom workers to force the fee to 0. // maxNativeFee = max (_totalNativeFee, treasuryNativeFeeCap) uint256 maxNativeFee = _totalNativeFee > treasuryNativeFeeCap ? _totalNativeFee : treasuryNativeFeeCap; // min (treasureFeeQuote, nativeFeeCap) nativeFee = treasureFeeQuote > maxNativeFee ? maxNativeFee : treasureFeeQuote; } } /// @dev authenticated by msg.sender only function _debitFee(uint256 _amount) internal { uint256 fee = fees[msg.sender]; if (_amount > fee) revert LZ_MessageLib_InvalidAmount(_amount, fee); unchecked { fees[msg.sender] = fee - _amount; } } function _setTreasury(address _treasury) internal { treasury = _treasury; emit TreasurySet(_treasury); } function _setExecutorConfig(uint32 _remoteEid, address _oapp, ExecutorConfig memory _config) internal { executorConfigs[_oapp][_remoteEid] = _config; emit ExecutorConfigSet(_oapp, _remoteEid, _config); } // ======================= Virtual ======================= /// @dev these two functions will be overridden with specific logics of the library function function _quoteVerifier( address _oapp, uint32 _eid, WorkerOptions[] memory _options ) internal view virtual returns (uint256 nativeFee); /// @dev this function will split the options into executorOptions and validationOptions function _splitOptions( bytes calldata _options ) internal view virtual returns (bytes memory executorOptions, WorkerOptions[] memory validationOptions); }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { BytesLib } from "solidity-bytes-utils/contracts/BytesLib.sol"; import { BitMap256 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol"; import { CalldataBytesLib } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol"; library DVNOptions { using CalldataBytesLib for bytes; using BytesLib for bytes; uint8 internal constant WORKER_ID = 2; uint8 internal constant OPTION_TYPE_PRECRIME = 1; error DVN_InvalidDVNIdx(); error DVN_InvalidDVNOptions(uint256 cursor); /// @dev group dvn options by its idx /// @param _options [dvn_id][dvn_option][dvn_id][dvn_option]... /// dvn_option = [option_size][dvn_idx][option_type][option] /// option_size = len(dvn_idx) + len(option_type) + len(option) /// dvn_id: uint8, dvn_idx: uint8, option_size: uint16, option_type: uint8, option: bytes /// @return dvnOptions the grouped options, still share the same format of _options /// @return dvnIndices the dvn indices function groupDVNOptionsByIdx( bytes memory _options ) internal pure returns (bytes[] memory dvnOptions, uint8[] memory dvnIndices) { if (_options.length == 0) return (dvnOptions, dvnIndices); uint8 numDVNs = getNumDVNs(_options); // if there is only 1 dvn, we can just return the whole options if (numDVNs == 1) { dvnOptions = new bytes[](1); dvnOptions[0] = _options; dvnIndices = new uint8[](1); dvnIndices[0] = _options.toUint8(3); // dvn idx return (dvnOptions, dvnIndices); } // otherwise, we need to group the options by dvn_idx dvnIndices = new uint8[](numDVNs); dvnOptions = new bytes[](numDVNs); unchecked { uint256 cursor = 0; uint256 start = 0; uint8 lastDVNIdx = 255; // 255 is an invalid dvn_idx while (cursor < _options.length) { ++cursor; // skip worker_id // optionLength asserted in getNumDVNs (skip check) uint16 optionLength = _options.toUint16(cursor); cursor += 2; // dvnIdx asserted in getNumDVNs (skip check) uint8 dvnIdx = _options.toUint8(cursor); // dvnIdx must equal to the lastDVNIdx for the first option // so it is always skipped in the first option // this operation slices out options whenever the scan finds a different lastDVNIdx if (lastDVNIdx == 255) { lastDVNIdx = dvnIdx; } else if (dvnIdx != lastDVNIdx) { uint256 len = cursor - start - 3; // 3 is for worker_id and option_length bytes memory opt = _options.slice(start, len); _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, opt); // reset the start and lastDVNIdx start += len; lastDVNIdx = dvnIdx; } cursor += optionLength; } // skip check the cursor here because the cursor is asserted in getNumDVNs // if we have reached the end of the options, we need to process the last dvn uint256 size = cursor - start; bytes memory op = _options.slice(start, size); _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, op); // revert dvnIndices to start from 0 for (uint8 i = 0; i < numDVNs; ++i) { --dvnIndices[i]; } } } function _insertDVNOptions( bytes[] memory _dvnOptions, uint8[] memory _dvnIndices, uint8 _dvnIdx, bytes memory _newOptions ) internal pure { // dvnIdx starts from 0 but default value of dvnIndices is 0, // so we tell if the slot is empty by adding 1 to dvnIdx if (_dvnIdx == 255) revert DVN_InvalidDVNIdx(); uint8 dvnIdxAdj = _dvnIdx + 1; for (uint256 j = 0; j < _dvnIndices.length; ++j) { uint8 index = _dvnIndices[j]; if (dvnIdxAdj == index) { _dvnOptions[j] = abi.encodePacked(_dvnOptions[j], _newOptions); break; } else if (index == 0) { // empty slot, that means it is the first time we see this dvn _dvnIndices[j] = dvnIdxAdj; _dvnOptions[j] = _newOptions; break; } } } /// @dev get the number of unique dvns /// @param _options the format is the same as groupDVNOptionsByIdx function getNumDVNs(bytes memory _options) internal pure returns (uint8 numDVNs) { uint256 cursor = 0; BitMap256 bitmap; // find number of unique dvn_idx unchecked { while (cursor < _options.length) { ++cursor; // skip worker_id uint16 optionLength = _options.toUint16(cursor); cursor += 2; if (optionLength < 2) revert DVN_InvalidDVNOptions(cursor); // at least 1 byte for dvn_idx and 1 byte for option_type uint8 dvnIdx = _options.toUint8(cursor); // if dvnIdx is not set, increment numDVNs // max num of dvns is 255, 255 is an invalid dvn_idx // The order of the dvnIdx is not required to be sequential, as enforcing the order may weaken // the composability of the options. e.g. if we refrain from enforcing the order, an OApp that has // already enforced certain options can append additional options to the end of the enforced // ones without restrictions. if (dvnIdx == 255) revert DVN_InvalidDVNIdx(); if (!bitmap.get(dvnIdx)) { ++numDVNs; bitmap = bitmap.set(dvnIdx); } cursor += optionLength; } } if (cursor != _options.length) revert DVN_InvalidDVNOptions(cursor); } /// @dev decode the next dvn option from _options starting from the specified cursor /// @param _options the format is the same as groupDVNOptionsByIdx /// @param _cursor the cursor to start decoding /// @return optionType the type of the option /// @return option the option /// @return cursor the cursor to start decoding the next option function nextDVNOption( bytes calldata _options, uint256 _cursor ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) { unchecked { // skip worker id cursor = _cursor + 1; // read option size uint16 size = _options.toU16(cursor); cursor += 2; // read option type optionType = _options.toU8(cursor + 1); // skip dvn_idx // startCursor and endCursor are used to slice the option from _options uint256 startCursor = cursor + 2; // skip option type and dvn_idx uint256 endCursor = cursor + size; option = _options[startCursor:endCursor]; cursor += size; } } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { ExecutorOptions } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/ExecutorOptions.sol"; import { DVNOptions } from "./DVNOptions.sol"; library UlnOptions { using SafeCast for uint256; uint16 internal constant TYPE_1 = 1; // legacy options type 1 uint16 internal constant TYPE_2 = 2; // legacy options type 2 uint16 internal constant TYPE_3 = 3; error LZ_ULN_InvalidWorkerOptions(uint256 cursor); error LZ_ULN_InvalidWorkerId(uint8 workerId); error LZ_ULN_InvalidLegacyType1Option(); error LZ_ULN_InvalidLegacyType2Option(); error LZ_ULN_UnsupportedOptionType(uint16 optionType); /// @dev decode the options into executorOptions and dvnOptions /// @param _options the options can be either legacy options (type 1 or 2) or type 3 options /// @return executorOptions the executor options, share the same format of type 3 options /// @return dvnOptions the dvn options, share the same format of type 3 options function decode( bytes calldata _options ) internal pure returns (bytes memory executorOptions, bytes memory dvnOptions) { // at least 2 bytes for the option type, but can have no options if (_options.length < 2) revert LZ_ULN_InvalidWorkerOptions(0); uint16 optionsType = uint16(bytes2(_options[0:2])); uint256 cursor = 2; // type3 options: [worker_option][worker_option]... // worker_option: [worker_id][option_size][option] // worker_id: uint8, option_size: uint16, option: bytes if (optionsType == TYPE_3) { unchecked { uint256 start = cursor; uint8 lastWorkerId; // worker_id starts from 1, so 0 is an invalid worker_id // heuristic: we assume that the options are mostly EXECUTOR options only // checking the workerID can reduce gas usage for most cases while (cursor < _options.length) { uint8 workerId = uint8(bytes1(_options[cursor:cursor + 1])); if (workerId == 0) revert LZ_ULN_InvalidWorkerId(0); // workerId must equal to the lastWorkerId for the first option // so it is always skipped in the first option // this operation slices out options whenever the the scan finds a different workerId if (lastWorkerId == 0) { lastWorkerId = workerId; } else if (workerId != lastWorkerId) { bytes calldata op = _options[start:cursor]; // slice out the last worker's options (executorOptions, dvnOptions) = _insertWorkerOptions( executorOptions, dvnOptions, lastWorkerId, op ); // reset the start cursor and lastWorkerId start = cursor; lastWorkerId = workerId; } ++cursor; // for workerId uint16 size = uint16(bytes2(_options[cursor:cursor + 2])); if (size == 0) revert LZ_ULN_InvalidWorkerOptions(cursor); cursor += size + 2; } // the options length must be the same as the cursor at the end if (cursor != _options.length) revert LZ_ULN_InvalidWorkerOptions(cursor); // if we have reached the end of the options and the options are not empty // we need to process the last worker's options if (_options.length > 2) { bytes calldata op = _options[start:cursor]; (executorOptions, dvnOptions) = _insertWorkerOptions(executorOptions, dvnOptions, lastWorkerId, op); } } } else { executorOptions = decodeLegacyOptions(optionsType, _options); } } function _insertWorkerOptions( bytes memory _executorOptions, bytes memory _dvnOptions, uint8 _workerId, bytes calldata _newOptions ) private pure returns (bytes memory, bytes memory) { if (_workerId == ExecutorOptions.WORKER_ID) { _executorOptions = _executorOptions.length == 0 ? _newOptions : abi.encodePacked(_executorOptions, _newOptions); } else if (_workerId == DVNOptions.WORKER_ID) { _dvnOptions = _dvnOptions.length == 0 ? _newOptions : abi.encodePacked(_dvnOptions, _newOptions); } else { revert LZ_ULN_InvalidWorkerId(_workerId); } return (_executorOptions, _dvnOptions); } /// @dev decode the legacy options (type 1 or 2) into executorOptions /// @param _optionType the legacy option type /// @param _options the legacy options, which still has the option type in the first 2 bytes /// @return executorOptions the executor options, share the same format of type 3 options /// Data format: /// legacy type 1: [extraGas] /// legacy type 2: [extraGas][dstNativeAmt][dstNativeAddress] /// extraGas: uint256, dstNativeAmt: uint256, dstNativeAddress: bytes function decodeLegacyOptions( uint16 _optionType, bytes calldata _options ) internal pure returns (bytes memory executorOptions) { if (_optionType == TYPE_1) { if (_options.length != 34) revert LZ_ULN_InvalidLegacyType1Option(); // execution gas uint128 executionGas = uint256(bytes32(_options[2:2 + 32])).toUint128(); // dont use the encode function in the ExecutorOptions lib for saving gas by calling abi.encodePacked once // the result is a lzReceive option: [executor_id][option_size][option_type][execution_gas] // option_type: uint8, execution_gas: uint128 // option_size = len(option_type) + len(execution_gas) = 1 + 16 = 17 executorOptions = abi.encodePacked( ExecutorOptions.WORKER_ID, uint16(17), // 16 + 1, 16 for option_length, + 1 for option_type ExecutorOptions.OPTION_TYPE_LZRECEIVE, executionGas ); } else if (_optionType == TYPE_2) { // receiver size <= 32 if (_options.length <= 66 || _options.length > 98) revert LZ_ULN_InvalidLegacyType2Option(); // execution gas uint128 executionGas = uint256(bytes32(_options[2:2 + 32])).toUint128(); // nativeDrop (amount + receiver) uint128 amount = uint256(bytes32(_options[34:34 + 32])).toUint128(); // offset 2 + 32 bytes32 receiver; unchecked { uint256 receiverLen = _options.length - 66; // offset 2 + 32 + 32 receiver = bytes32(_options[66:]); receiver = receiver >> (8 * (32 - receiverLen)); // padding 0 to the left } // dont use the encode function in the ExecutorOptions lib for saving gas by calling abi.encodePacked once // the result has one lzReceive option and one nativeDrop option: // [executor_id][lzReceive_option_size][option_type][execution_gas] + // [executor_id][nativeDrop_option_size][option_type][nativeDrop_amount][receiver] // option_type: uint8, execution_gas: uint128, nativeDrop_amount: uint128, receiver: bytes32 // lzReceive_option_size = len(option_type) + len(execution_gas) = 1 + 16 = 17 // nativeDrop_option_size = len(option_type) + len(nativeDrop_amount) + len(receiver) = 1 + 16 + 32 = 49 executorOptions = abi.encodePacked( ExecutorOptions.WORKER_ID, uint16(17), // 16 + 1, 16 for option_length, + 1 for option_type ExecutorOptions.OPTION_TYPE_LZRECEIVE, executionGas, ExecutorOptions.WORKER_ID, uint16(49), // 48 + 1, 32 + 16 for option_length, + 1 for option_type ExecutorOptions.OPTION_TYPE_NATIVE_DROP, amount, receiver ); } else { revert LZ_ULN_UnsupportedOptionType(_optionType); } } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "./interfaces/ILayerZeroEndpointV2.sol"; enum ExecutionState { NotExecutable, // executor: waits for PayloadVerified event and starts polling for executable VerifiedButNotExecutable, // executor: starts active polling for executable Executable, Executed } contract EndpointV2ViewUpgradeable is Initializable { bytes32 public constant EMPTY_PAYLOAD_HASH = bytes32(0); bytes32 public constant NIL_PAYLOAD_HASH = bytes32(type(uint256).max); ILayerZeroEndpointV2 public endpoint; function __EndpointV2View_init(address _endpoint) internal onlyInitializing { __EndpointV2View_init_unchained(_endpoint); } function __EndpointV2View_init_unchained(address _endpoint) internal onlyInitializing { endpoint = ILayerZeroEndpointV2(_endpoint); } function initializable(Origin memory _origin, address _receiver) public view returns (bool) { try endpoint.initializable(_origin, _receiver) returns (bool _initializable) { return _initializable; } catch { return false; } } /// @dev check if a message is verifiable. function verifiable( Origin memory _origin, address _receiver, address _receiveLib, bytes32 _payloadHash ) public view returns (bool) { if (!endpoint.isValidReceiveLibrary(_receiver, _origin.srcEid, _receiveLib)) return false; if (!endpoint.verifiable(_origin, _receiver)) return false; // checked in _inbound for verify if (_payloadHash == EMPTY_PAYLOAD_HASH) return false; return true; } /// @dev check if a message is executable. /// @return ExecutionState of Executed, Executable, or NotExecutable function executable(Origin memory _origin, address _receiver) public view returns (ExecutionState) { bytes32 payloadHash = endpoint.inboundPayloadHash(_receiver, _origin.srcEid, _origin.sender, _origin.nonce); // executed if the payload hash has been cleared and the nonce is less than or equal to lazyInboundNonce if ( payloadHash == EMPTY_PAYLOAD_HASH && _origin.nonce <= endpoint.lazyInboundNonce(_receiver, _origin.srcEid, _origin.sender) ) { return ExecutionState.Executed; } // executable if nonce has not been executed and has not been nilified and nonce is less than or equal to inboundNonce if ( payloadHash != NIL_PAYLOAD_HASH && _origin.nonce <= endpoint.inboundNonce(_receiver, _origin.srcEid, _origin.sender) ) { return ExecutionState.Executable; } // only start active executable polling if payload hash is not empty nor nil if (payloadHash != EMPTY_PAYLOAD_HASH && payloadHash != NIL_PAYLOAD_HASH) { return ExecutionState.VerifiedButNotExecutable; } // return NotExecutable as a catch-all return ExecutionState.NotExecutable; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { IMessageLibManager } from "./IMessageLibManager.sol"; import { IMessagingComposer } from "./IMessagingComposer.sol"; import { IMessagingChannel } from "./IMessagingChannel.sol"; import { IMessagingContext } from "./IMessagingContext.sol"; struct MessagingParams { uint32 dstEid; bytes32 receiver; bytes message; bytes options; bool payInLzToken; } struct MessagingReceipt { bytes32 guid; uint64 nonce; MessagingFee fee; } struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; } struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; } interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext { event PacketSent(bytes encodedPayload, bytes options, address sendLibrary); event PacketVerified(Origin origin, address receiver, bytes32 payloadHash); event PacketDelivered(Origin origin, address receiver); event LzReceiveAlert( address indexed receiver, address indexed executor, Origin origin, bytes32 guid, uint256 gas, uint256 value, bytes message, bytes extraData, bytes reason ); event LzTokenSet(address token); event DelegateSet(address sender, address delegate); function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory); function send( MessagingParams calldata _params, address _refundAddress ) external payable returns (MessagingReceipt memory); function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external; function verifiable(Origin calldata _origin, address _receiver) external view returns (bool); function initializable(Origin calldata _origin, address _receiver) external view returns (bool); function lzReceive( Origin calldata _origin, address _receiver, bytes32 _guid, bytes calldata _message, bytes calldata _extraData ) external payable; // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external; function setLzToken(address _lzToken) external; function lzToken() external view returns (address); function nativeToken() external view returns (address); function setDelegate(address _delegate) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { Origin } from "./ILayerZeroEndpointV2.sol"; interface ILayerZeroReceiver { function allowInitializePath(Origin calldata _origin) external view returns (bool); function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64); function lzReceive( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { IERC165 } from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import { SetConfigParam } from "./IMessageLibManager.sol"; enum MessageLibType { Send, Receive, SendAndReceive } interface IMessageLib is IERC165 { function setConfig(address _oapp, SetConfigParam[] calldata _config) external; function getConfig(uint32 _eid, address _oapp, uint32 _configType) external view returns (bytes memory config); function isSupportedEid(uint32 _eid) external view returns (bool); // message libs of same major version are compatible function version() external view returns (uint64 major, uint8 minor, uint8 endpointVersion); function messageLibType() external view returns (MessageLibType); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; struct SetConfigParam { uint32 eid; uint32 configType; bytes config; } interface IMessageLibManager { struct Timeout { address lib; uint256 expiry; } event LibraryRegistered(address newLib); event DefaultSendLibrarySet(uint32 eid, address newLib); event DefaultReceiveLibrarySet(uint32 eid, address newLib); event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry); event SendLibrarySet(address sender, uint32 eid, address newLib); event ReceiveLibrarySet(address receiver, uint32 eid, address newLib); event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout); function registerLibrary(address _lib) external; function isRegisteredLibrary(address _lib) external view returns (bool); function getRegisteredLibraries() external view returns (address[] memory); function setDefaultSendLibrary(uint32 _eid, address _newLib) external; function defaultSendLibrary(uint32 _eid) external view returns (address); function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external; function defaultReceiveLibrary(uint32 _eid) external view returns (address); function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external; function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry); function isSupportedEid(uint32 _eid) external view returns (bool); function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool); /// ------------------- OApp interfaces ------------------- function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external; function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib); function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool); function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external; function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault); function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external; function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry); function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external; function getConfig( address _oapp, address _lib, uint32 _eid, uint32 _configType ) external view returns (bytes memory config); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IMessagingChannel { event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce); event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash); event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash); function eid() external view returns (uint32); // this is an emergency function if a message cannot be verified for some reasons // required to provide _nextNonce to avoid race condition function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external; function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external; function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external; function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32); function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64); function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64); function inboundPayloadHash( address _receiver, uint32 _srcEid, bytes32 _sender, uint64 _nonce ) external view returns (bytes32); function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IMessagingComposer { event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message); event ComposeDelivered(address from, address to, bytes32 guid, uint16 index); event LzComposeAlert( address indexed from, address indexed to, address indexed executor, bytes32 guid, uint16 index, uint256 gas, uint256 value, bytes message, bytes extraData, bytes reason ); function composeQueue( address _from, address _to, bytes32 _guid, uint16 _index ) external view returns (bytes32 messageHash); function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external; function lzCompose( address _from, address _to, bytes32 _guid, uint16 _index, bytes calldata _message, bytes calldata _extraData ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IMessagingContext { function isSendingMessage() external view returns (bool); function getSendContext() external view returns (uint32 dstEid, address sender); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { MessagingFee } from "./ILayerZeroEndpointV2.sol"; import { IMessageLib } from "./IMessageLib.sol"; struct Packet { uint64 nonce; uint32 srcEid; address sender; uint32 dstEid; bytes32 receiver; bytes32 guid; bytes message; } interface ISendLib is IMessageLib { function send( Packet calldata _packet, bytes calldata _options, bool _payInLzToken ) external returns (MessagingFee memory, bytes memory encodedPacket); function quote( Packet calldata _packet, bytes calldata _options, bool _payInLzToken ) external view returns (MessagingFee memory); function setTreasury(address _treasury) external; function withdrawFee(address _to, uint256 _amount) external; function withdrawLzTokenFee(address _lzToken, address _to, uint256 _amount) external; }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; library AddressCast { error AddressCast_InvalidSizeForAddress(); error AddressCast_InvalidAddress(); function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) { if (_addressBytes.length > 32) revert AddressCast_InvalidAddress(); result = bytes32(_addressBytes); unchecked { uint256 offset = 32 - _addressBytes.length; result = result >> (offset * 8); } } function toBytes32(address _address) internal pure returns (bytes32 result) { result = bytes32(uint256(uint160(_address))); } function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) { if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress(); result = new bytes(_size); unchecked { uint256 offset = 256 - _size * 8; assembly { mstore(add(result, 32), shl(offset, _addressBytes32)) } } } function toAddress(bytes32 _addressBytes32) internal pure returns (address result) { result = address(uint160(uint256(_addressBytes32))); } function toAddress(bytes calldata _addressBytes) internal pure returns (address result) { if (_addressBytes.length != 20) revert AddressCast_InvalidAddress(); result = address(bytes20(_addressBytes)); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; library CalldataBytesLib { function toU8(bytes calldata _bytes, uint256 _start) internal pure returns (uint8) { return uint8(_bytes[_start]); } function toU16(bytes calldata _bytes, uint256 _start) internal pure returns (uint16) { unchecked { uint256 end = _start + 2; return uint16(bytes2(_bytes[_start:end])); } } function toU32(bytes calldata _bytes, uint256 _start) internal pure returns (uint32) { unchecked { uint256 end = _start + 4; return uint32(bytes4(_bytes[_start:end])); } } function toU64(bytes calldata _bytes, uint256 _start) internal pure returns (uint64) { unchecked { uint256 end = _start + 8; return uint64(bytes8(_bytes[_start:end])); } } function toU128(bytes calldata _bytes, uint256 _start) internal pure returns (uint128) { unchecked { uint256 end = _start + 16; return uint128(bytes16(_bytes[_start:end])); } } function toU256(bytes calldata _bytes, uint256 _start) internal pure returns (uint256) { unchecked { uint256 end = _start + 32; return uint256(bytes32(_bytes[_start:end])); } } function toAddr(bytes calldata _bytes, uint256 _start) internal pure returns (address) { unchecked { uint256 end = _start + 20; return address(bytes20(_bytes[_start:end])); } } function toB32(bytes calldata _bytes, uint256 _start) internal pure returns (bytes32) { unchecked { uint256 end = _start + 32; return bytes32(_bytes[_start:end]); } } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; library Errors { error LZ_LzTokenUnavailable(); error LZ_InvalidReceiveLibrary(); error LZ_InvalidNonce(uint64 nonce); error LZ_InvalidArgument(); error LZ_InvalidExpiry(); error LZ_InvalidAmount(uint256 required, uint256 supplied); error LZ_OnlyRegisteredOrDefaultLib(); error LZ_OnlyRegisteredLib(); error LZ_OnlyNonDefaultLib(); error LZ_Unauthorized(); error LZ_DefaultSendLibUnavailable(); error LZ_DefaultReceiveLibUnavailable(); error LZ_PathNotInitializable(); error LZ_PathNotVerifiable(); error LZ_OnlySendLib(); error LZ_OnlyReceiveLib(); error LZ_UnsupportedEid(); error LZ_UnsupportedInterface(); error LZ_AlreadyRegistered(); error LZ_SameValue(); error LZ_InvalidPayloadHash(); error LZ_PayloadHashNotFound(bytes32 expected, bytes32 actual); error LZ_ComposeNotFound(bytes32 expected, bytes32 actual); error LZ_ComposeExists(); error LZ_SendReentrancy(); error LZ_NotImplemented(); error LZ_InsufficientFee( uint256 requiredNative, uint256 suppliedNative, uint256 requiredLzToken, uint256 suppliedLzToken ); error LZ_ZeroLzTokenFee(); }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { AddressCast } from "./AddressCast.sol"; library GUID { using AddressCast for address; function generate( uint64 _nonce, uint32 _srcEid, address _sender, uint32 _dstEid, bytes32 _receiver ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_nonce, _srcEid, _sender.toBytes32(), _dstEid, _receiver)); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library Transfer { using SafeERC20 for IERC20; address internal constant ADDRESS_ZERO = address(0); error Transfer_NativeFailed(address _to, uint256 _value); error Transfer_ToAddressIsZero(); function native(address _to, uint256 _value) internal { if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero(); (bool success, ) = _to.call{ value: _value }(""); if (!success) revert Transfer_NativeFailed(_to, _value); } function token(address _token, address _to, uint256 _value) internal { if (_to == ADDRESS_ZERO) revert Transfer_ToAddressIsZero(); IERC20(_token).safeTransfer(_to, _value); } function nativeOrToken(address _token, address _to, uint256 _value) internal { if (_token == ADDRESS_ZERO) { native(_to, _value); } else { token(_token, _to, _value); } } }
// SPDX-License-Identifier: MIT // modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/BitMaps.sol pragma solidity ^0.8.20; type BitMap256 is uint256; using BitMaps for BitMap256 global; library BitMaps { /** * @dev Returns whether the bit at `index` is set. */ function get(BitMap256 bitmap, uint8 index) internal pure returns (bool) { uint256 mask = 1 << index; return BitMap256.unwrap(bitmap) & mask != 0; } /** * @dev Sets the bit at `index`. */ function set(BitMap256 bitmap, uint8 index) internal pure returns (BitMap256) { uint256 mask = 1 << index; return BitMap256.wrap(BitMap256.unwrap(bitmap) | mask); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { CalldataBytesLib } from "../../libs/CalldataBytesLib.sol"; library ExecutorOptions { using CalldataBytesLib for bytes; uint8 internal constant WORKER_ID = 1; uint8 internal constant OPTION_TYPE_LZRECEIVE = 1; uint8 internal constant OPTION_TYPE_NATIVE_DROP = 2; uint8 internal constant OPTION_TYPE_LZCOMPOSE = 3; uint8 internal constant OPTION_TYPE_ORDERED_EXECUTION = 4; error Executor_InvalidLzReceiveOption(); error Executor_InvalidNativeDropOption(); error Executor_InvalidLzComposeOption(); /// @dev decode the next executor option from the options starting from the specified cursor /// @param _options [executor_id][executor_option][executor_id][executor_option]... /// executor_option = [option_size][option_type][option] /// option_size = len(option_type) + len(option) /// executor_id: uint8, option_size: uint16, option_type: uint8, option: bytes /// @param _cursor the cursor to start decoding from /// @return optionType the type of the option /// @return option the option of the executor /// @return cursor the cursor to start decoding the next executor option function nextExecutorOption( bytes calldata _options, uint256 _cursor ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) { unchecked { // skip worker id cursor = _cursor + 1; // read option size uint16 size = _options.toU16(cursor); cursor += 2; // read option type optionType = _options.toU8(cursor); // startCursor and endCursor are used to slice the option from _options uint256 startCursor = cursor + 1; // skip option type uint256 endCursor = cursor + size; option = _options[startCursor:endCursor]; cursor += size; } } function decodeLzReceiveOption(bytes calldata _option) internal pure returns (uint128 gas, uint128 value) { if (_option.length != 16 && _option.length != 32) revert Executor_InvalidLzReceiveOption(); gas = _option.toU128(0); value = _option.length == 32 ? _option.toU128(16) : 0; } function decodeNativeDropOption(bytes calldata _option) internal pure returns (uint128 amount, bytes32 receiver) { if (_option.length != 48) revert Executor_InvalidNativeDropOption(); amount = _option.toU128(0); receiver = _option.toB32(16); } function decodeLzComposeOption( bytes calldata _option ) internal pure returns (uint16 index, uint128 gas, uint128 value) { if (_option.length != 18 && _option.length != 34) revert Executor_InvalidLzComposeOption(); index = _option.toU16(0); gas = _option.toU128(2); value = _option.length == 34 ? _option.toU128(18) : 0; } function encodeLzReceiveOption(uint128 _gas, uint128 _value) internal pure returns (bytes memory) { return _value == 0 ? abi.encodePacked(_gas) : abi.encodePacked(_gas, _value); } function encodeNativeDropOption(uint128 _amount, bytes32 _receiver) internal pure returns (bytes memory) { return abi.encodePacked(_amount, _receiver); } function encodeLzComposeOption(uint16 _index, uint128 _gas, uint128 _value) internal pure returns (bytes memory) { return _value == 0 ? abi.encodePacked(_index, _gas) : abi.encodePacked(_index, _gas, _value); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { Packet } from "../../interfaces/ISendLib.sol"; import { AddressCast } from "../../libs/AddressCast.sol"; library PacketV1Codec { using AddressCast for address; using AddressCast for bytes32; uint8 internal constant PACKET_VERSION = 1; // header (version + nonce + path) // version uint256 private constant PACKET_VERSION_OFFSET = 0; // nonce uint256 private constant NONCE_OFFSET = 1; // path uint256 private constant SRC_EID_OFFSET = 9; uint256 private constant SENDER_OFFSET = 13; uint256 private constant DST_EID_OFFSET = 45; uint256 private constant RECEIVER_OFFSET = 49; // payload (guid + message) uint256 private constant GUID_OFFSET = 81; // keccak256(nonce + path) uint256 private constant MESSAGE_OFFSET = 113; function encode(Packet memory _packet) internal pure returns (bytes memory encodedPacket) { encodedPacket = abi.encodePacked( PACKET_VERSION, _packet.nonce, _packet.srcEid, _packet.sender.toBytes32(), _packet.dstEid, _packet.receiver, _packet.guid, _packet.message ); } function encodePacketHeader(Packet memory _packet) internal pure returns (bytes memory) { return abi.encodePacked( PACKET_VERSION, _packet.nonce, _packet.srcEid, _packet.sender.toBytes32(), _packet.dstEid, _packet.receiver ); } function encodePayload(Packet memory _packet) internal pure returns (bytes memory) { return abi.encodePacked(_packet.guid, _packet.message); } function header(bytes calldata _packet) internal pure returns (bytes calldata) { return _packet[0:GUID_OFFSET]; } function version(bytes calldata _packet) internal pure returns (uint8) { return uint8(bytes1(_packet[PACKET_VERSION_OFFSET:NONCE_OFFSET])); } function nonce(bytes calldata _packet) internal pure returns (uint64) { return uint64(bytes8(_packet[NONCE_OFFSET:SRC_EID_OFFSET])); } function srcEid(bytes calldata _packet) internal pure returns (uint32) { return uint32(bytes4(_packet[SRC_EID_OFFSET:SENDER_OFFSET])); } function sender(bytes calldata _packet) internal pure returns (bytes32) { return bytes32(_packet[SENDER_OFFSET:DST_EID_OFFSET]); } function senderAddressB20(bytes calldata _packet) internal pure returns (address) { return sender(_packet).toAddress(); } function dstEid(bytes calldata _packet) internal pure returns (uint32) { return uint32(bytes4(_packet[DST_EID_OFFSET:RECEIVER_OFFSET])); } function receiver(bytes calldata _packet) internal pure returns (bytes32) { return bytes32(_packet[RECEIVER_OFFSET:GUID_OFFSET]); } function receiverB20(bytes calldata _packet) internal pure returns (address) { return receiver(_packet).toAddress(); } function guid(bytes calldata _packet) internal pure returns (bytes32) { return bytes32(_packet[GUID_OFFSET:MESSAGE_OFFSET]); } function message(bytes calldata _packet) internal pure returns (bytes calldata) { return bytes(_packet[MESSAGE_OFFSET:]); } function payload(bytes calldata _packet) internal pure returns (bytes calldata) { return bytes(_packet[GUID_OFFSET:]); } function payloadHash(bytes calldata _packet) internal pure returns (bytes32) { return keccak256(payload(_packet)); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { IMessagingContext } from "./interfaces/IMessagingContext.sol"; import { Errors } from "./libs/Errors.sol"; /// this contract acts as a non-reentrancy guard and a source of messaging context /// the context includes the remote eid and the sender address /// it separates the send and receive context to allow messaging receipts (send back on receive()) abstract contract MessagingContext is IMessagingContext { uint256 private constant NOT_ENTERED = 1; uint256 private _sendContext = NOT_ENTERED; /// @dev the sendContext is set to 8 bytes 0s + 4 bytes eid + 20 bytes sender modifier sendContext(uint32 _dstEid, address _sender) { if (_sendContext != NOT_ENTERED) revert Errors.LZ_SendReentrancy(); _sendContext = (uint256(_dstEid) << 160) | uint160(_sender); _; _sendContext = NOT_ENTERED; } /// @dev returns true if sending message function isSendingMessage() public view returns (bool) { return _sendContext != NOT_ENTERED; } /// @dev returns (eid, sender) if sending message, (0, 0) otherwise function getSendContext() external view returns (uint32, address) { return isSendingMessage() ? _getSendContext(_sendContext) : (0, address(0)); } function _getSendContext(uint256 _context) internal pure returns (uint32, address) { return (uint32(_context >> 160), address(uint160(_context))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { ILayerZeroEndpointV2 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol"; /** * @title IOAppCore */ interface IOAppCore { // Custom error messages error OnlyPeer(uint32 eid, bytes32 sender); error NoPeer(uint32 eid); error InvalidEndpointCall(); error InvalidDelegate(); // Event emitted when a peer (OApp) is set for a corresponding endpoint event PeerSet(uint32 eid, bytes32 peer); /** * @notice Retrieves the OApp version information. * @return senderVersion The version of the OAppSender.sol contract. * @return receiverVersion The version of the OAppReceiver.sol contract. */ function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion); /** * @notice Retrieves the LayerZero endpoint associated with the OApp. * @return iEndpoint The LayerZero endpoint as an interface. */ function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint); /** * @notice Retrieves the peer (OApp) associated with a corresponding endpoint. * @param _eid The endpoint ID. * @return peer The peer address (OApp instance) associated with the corresponding endpoint. */ function peers(uint32 _eid) external view returns (bytes32 peer); /** * @notice Sets the peer address (OApp instance) for a corresponding endpoint. * @param _eid The endpoint ID. * @param _peer The address of the peer to be associated with the corresponding endpoint. */ function setPeer(uint32 _eid, bytes32 _peer) external; /** * @notice Sets the delegate address for the OApp Core. * @param _delegate The address of the delegate to be set. */ function setDelegate(address _delegate) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /** * @title IOAppMsgInspector * @dev Interface for the OApp Message Inspector, allowing examination of message and options contents. */ interface IOAppMsgInspector { // Custom error message for inspection failure error InspectionFailed(bytes message, bytes options); /** * @notice Allows the inspector to examine LayerZero message contents and optionally throw a revert if invalid. * @param _message The message payload to be inspected. * @param _options Additional options or parameters for inspection. * @return valid A boolean indicating whether the inspection passed (true) or failed (false). * * @dev Optionally done as a revert, OR use the boolean provided to handle the failure. */ function inspect(bytes calldata _message, bytes calldata _options) external view returns (bool valid); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /** * @dev Struct representing enforced option parameters. */ struct EnforcedOptionParam { uint32 eid; // Endpoint ID uint16 msgType; // Message Type bytes options; // Additional options } /** * @title IOAppOptionsType3 * @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options. */ interface IOAppOptionsType3 { // Custom error message for invalid options error InvalidOptions(bytes options); // Event emitted when enforced options are set event EnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions); /** * @notice Sets enforced options for specific endpoint and message type combinations. * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options. */ function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external; /** * @notice Combines options for a given endpoint and message type. * @param _eid The endpoint ID. * @param _msgType The OApp message type. * @param _extraOptions Additional options passed by the caller. * @return options The combination of caller specified options AND enforced options. */ function combineOptions( uint32 _eid, uint16 _msgType, bytes calldata _extraOptions ) external view returns (bytes memory options); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { ILayerZeroReceiver, Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol"; interface IOAppReceiver is ILayerZeroReceiver { /** * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint. * @param _origin The origin information containing the source endpoint and sender address. * - srcEid: The source chain endpoint ID. * - sender: The sender address on the src chain. * - nonce: The nonce of the message. * @param _message The lzReceive payload. * @param _sender The sender address. * @return isSender Is a valid sender. * * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer. * @dev The default sender IS the OAppReceiver implementer. */ function isComposeMsgSender( Origin calldata _origin, bytes calldata _message, address _sender ) external view returns (bool isSender); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IOAppOptionsType3, EnforcedOptionParam } from "../interfaces/IOAppOptionsType3.sol"; /** * @title OAppOptionsType3 * @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options. */ abstract contract OAppOptionsType3 is IOAppOptionsType3, Ownable { uint16 internal constant OPTION_TYPE_3 = 3; // @dev The "msgType" should be defined in the child contract. mapping(uint32 eid => mapping(uint16 msgType => bytes enforcedOption)) public enforcedOptions; /** * @dev Sets the enforced options for specific endpoint and message type combinations. * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options. * * @dev Only the owner/admin of the OApp can call this function. * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc. * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType. * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose(). */ function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner { _setEnforcedOptions(_enforcedOptions); } /** * @dev Sets the enforced options for specific endpoint and message type combinations. * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options. * * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc. * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType. * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose(). */ function _setEnforcedOptions(EnforcedOptionParam[] memory _enforcedOptions) internal virtual { for (uint256 i = 0; i < _enforcedOptions.length; i++) { // @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining. _assertOptionsType3(_enforcedOptions[i].options); enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options; } emit EnforcedOptionSet(_enforcedOptions); } /** * @notice Combines options for a given endpoint and message type. * @param _eid The endpoint ID. * @param _msgType The OAPP message type. * @param _extraOptions Additional options passed by the caller. * @return options The combination of caller specified options AND enforced options. * * @dev If there is an enforced lzReceive option: * - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether} * - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function. * @dev This presence of duplicated options is handled off-chain in the verifier/executor. */ function combineOptions( uint32 _eid, uint16 _msgType, bytes calldata _extraOptions ) public view virtual returns (bytes memory) { bytes memory enforced = enforcedOptions[_eid][_msgType]; // No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options. if (enforced.length == 0) return _extraOptions; // No caller options, return enforced if (_extraOptions.length == 0) return enforced; // @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined. if (_extraOptions.length >= 2) { _assertOptionsType3(_extraOptions); // @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced. return bytes.concat(enforced, _extraOptions[2:]); } // No valid set of options was found. revert InvalidOptions(_extraOptions); } /** * @dev Internal function to assert that options are of type 3. * @param _options The options to be checked. */ function _assertOptionsType3(bytes memory _options) internal pure virtual { uint16 optionsType; assembly { optionsType := mload(add(_options, 2)) } if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; // @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers // solhint-disable-next-line no-unused-import import { OAppSender, MessagingFee, MessagingReceipt } from "./OAppSender.sol"; // @dev Import the 'Origin' so it's exposed to OApp implementers // solhint-disable-next-line no-unused-import import { OAppReceiver, Origin } from "./OAppReceiver.sol"; import { OAppCore } from "./OAppCore.sol"; /** * @title OApp * @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality. */ abstract contract OApp is OAppSender, OAppReceiver { /** * @dev Constructor to initialize the OApp with the provided endpoint and owner. * @param _endpoint The address of the LOCAL LayerZero endpoint. * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. */ constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {} /** * @notice Retrieves the OApp version information. * @return senderVersion The version of the OAppSender.sol implementation. * @return receiverVersion The version of the OAppReceiver.sol implementation. */ function oAppVersion() public pure virtual override(OAppSender, OAppReceiver) returns (uint64 senderVersion, uint64 receiverVersion) { return (SENDER_VERSION, RECEIVER_VERSION); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IOAppCore, ILayerZeroEndpointV2 } from "./interfaces/IOAppCore.sol"; /** * @title OAppCore * @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations. */ abstract contract OAppCore is IOAppCore, Ownable { // The LayerZero endpoint associated with the given OApp ILayerZeroEndpointV2 public immutable endpoint; // Mapping to store peers associated with corresponding endpoints mapping(uint32 eid => bytes32 peer) public peers; /** * @dev Constructor to initialize the OAppCore with the provided endpoint and delegate. * @param _endpoint The address of the LOCAL Layer Zero endpoint. * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. * * @dev The delegate typically should be set as the owner of the contract. */ constructor(address _endpoint, address _delegate) { endpoint = ILayerZeroEndpointV2(_endpoint); if (_delegate == address(0)) revert InvalidDelegate(); endpoint.setDelegate(_delegate); } /** * @notice Sets the peer address (OApp instance) for a corresponding endpoint. * @param _eid The endpoint ID. * @param _peer The address of the peer to be associated with the corresponding endpoint. * * @dev Only the owner/admin of the OApp can call this function. * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp. * @dev Set this to bytes32(0) to remove the peer address. * @dev Peer is a bytes32 to accommodate non-evm chains. */ function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner { _setPeer(_eid, _peer); } /** * @notice Sets the peer address (OApp instance) for a corresponding endpoint. * @param _eid The endpoint ID. * @param _peer The address of the peer to be associated with the corresponding endpoint. * * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp. * @dev Set this to bytes32(0) to remove the peer address. * @dev Peer is a bytes32 to accommodate non-evm chains. */ function _setPeer(uint32 _eid, bytes32 _peer) internal virtual { peers[_eid] = _peer; emit PeerSet(_eid, _peer); } /** * @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set. * ie. the peer is set to bytes32(0). * @param _eid The endpoint ID. * @return peer The address of the peer associated with the specified endpoint. */ function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) { bytes32 peer = peers[_eid]; if (peer == bytes32(0)) revert NoPeer(_eid); return peer; } /** * @notice Sets the delegate address for the OApp. * @param _delegate The address of the delegate to be set. * * @dev Only the owner/admin of the OApp can call this function. * @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract. */ function setDelegate(address _delegate) public onlyOwner { endpoint.setDelegate(_delegate); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { IOAppReceiver, Origin } from "./interfaces/IOAppReceiver.sol"; import { OAppCore } from "./OAppCore.sol"; /** * @title OAppReceiver * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers. */ abstract contract OAppReceiver is IOAppReceiver, OAppCore { // Custom error message for when the caller is not the registered endpoint/ error OnlyEndpoint(address addr); // @dev The version of the OAppReceiver implementation. // @dev Version is bumped when changes are made to this contract. uint64 internal constant RECEIVER_VERSION = 2; /** * @notice Retrieves the OApp version information. * @return senderVersion The version of the OAppSender.sol contract. * @return receiverVersion The version of the OAppReceiver.sol contract. * * @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented. * ie. this is a RECEIVE only OApp. * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions. */ function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) { return (0, RECEIVER_VERSION); } /** * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint. * @dev _origin The origin information containing the source endpoint and sender address. * - srcEid: The source chain endpoint ID. * - sender: The sender address on the src chain. * - nonce: The nonce of the message. * @dev _message The lzReceive payload. * @param _sender The sender address. * @return isSender Is a valid sender. * * @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer. * @dev The default sender IS the OAppReceiver implementer. */ function isComposeMsgSender( Origin calldata /*_origin*/, bytes calldata /*_message*/, address _sender ) public view virtual returns (bool) { return _sender == address(this); } /** * @notice Checks if the path initialization is allowed based on the provided origin. * @param origin The origin information containing the source endpoint and sender address. * @return Whether the path has been initialized. * * @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received. * @dev This defaults to assuming if a peer has been set, its initialized. * Can be overridden by the OApp if there is other logic to determine this. */ function allowInitializePath(Origin calldata origin) public view virtual returns (bool) { return peers[origin.srcEid] == origin.sender; } /** * @notice Retrieves the next nonce for a given source endpoint and sender address. * @dev _srcEid The source endpoint ID. * @dev _sender The sender address. * @return nonce The next nonce. * * @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement. * @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered. * @dev This is also enforced by the OApp. * @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0. */ function nextNonce(uint32 /*_srcEid*/, bytes32 /*_sender*/) public view virtual returns (uint64 nonce) { return 0; } /** * @dev Entry point for receiving messages or packets from the endpoint. * @param _origin The origin information containing the source endpoint and sender address. * - srcEid: The source chain endpoint ID. * - sender: The sender address on the src chain. * - nonce: The nonce of the message. * @param _guid The unique identifier for the received LayerZero message. * @param _message The payload of the received message. * @param _executor The address of the executor for the received message. * @param _extraData Additional arbitrary data provided by the corresponding executor. * * @dev Entry point for receiving msg/packet from the LayerZero endpoint. */ function lzReceive( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) public payable virtual { // Ensures that only the endpoint can attempt to lzReceive() messages to this OApp. if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender); // Ensure that the sender matches the expected peer for the source endpoint. if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender); // Call the internal OApp implementation of lzReceive. _lzReceive(_origin, _guid, _message, _executor, _extraData); } /** * @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation. */ function _lzReceive( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) internal virtual; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { MessagingParams, MessagingFee, MessagingReceipt } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol"; import { OAppCore } from "./OAppCore.sol"; /** * @title OAppSender * @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint. */ abstract contract OAppSender is OAppCore { using SafeERC20 for IERC20; // Custom error messages error NotEnoughNative(uint256 msgValue); error LzTokenUnavailable(); // @dev The version of the OAppSender implementation. // @dev Version is bumped when changes are made to this contract. uint64 internal constant SENDER_VERSION = 1; /** * @notice Retrieves the OApp version information. * @return senderVersion The version of the OAppSender.sol contract. * @return receiverVersion The version of the OAppReceiver.sol contract. * * @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented. * ie. this is a SEND only OApp. * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions */ function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) { return (SENDER_VERSION, 0); } /** * @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation. * @param _dstEid The destination endpoint ID. * @param _message The message payload. * @param _options Additional options for the message. * @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens. * @return fee The calculated MessagingFee for the message. * - nativeFee: The native fee for the message. * - lzTokenFee: The LZ token fee for the message. */ function _quote( uint32 _dstEid, bytes memory _message, bytes memory _options, bool _payInLzToken ) internal view virtual returns (MessagingFee memory fee) { return endpoint.quote( MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken), address(this) ); } /** * @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message. * @param _dstEid The destination endpoint ID. * @param _message The message payload. * @param _options Additional options for the message. * @param _fee The calculated LayerZero fee for the message. * - nativeFee: The native fee. * - lzTokenFee: The lzToken fee. * @param _refundAddress The address to receive any excess fee values sent to the endpoint. * @return receipt The receipt for the sent message. * - guid: The unique identifier for the sent message. * - nonce: The nonce of the sent message. * - fee: The LayerZero fee incurred for the message. */ function _lzSend( uint32 _dstEid, bytes memory _message, bytes memory _options, MessagingFee memory _fee, address _refundAddress ) internal virtual returns (MessagingReceipt memory receipt) { // @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint. uint256 messageValue = _payNative(_fee.nativeFee); if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee); return // solhint-disable-next-line check-send-result endpoint.send{ value: messageValue }( MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0), _refundAddress ); } /** * @dev Internal function to pay the native fee associated with the message. * @param _nativeFee The native fee to be paid. * @return nativeFee The amount of native currency paid. * * @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction, * this will need to be overridden because msg.value would contain multiple lzFees. * @dev Should be overridden in the event the LayerZero endpoint requires a different native currency. * @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees. * @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time. */ function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) { if (msg.value != _nativeFee) revert NotEnoughNative(msg.value); return _nativeFee; } /** * @dev Internal function to pay the LZ token fee associated with the message. * @param _lzTokenFee The LZ token fee to be paid. * * @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint. * @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend(). */ function _payLzToken(uint256 _lzTokenFee) internal virtual { // @dev Cannot cache the token because it is not immutable in the endpoint. address lzToken = endpoint.lzToken(); if (lzToken == address(0)) revert LzTokenUnavailable(); // Pay LZ token fee by sending tokens to the endpoint. IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; // @dev Import the Origin so it's exposed to OAppPreCrimeSimulator implementers. // solhint-disable-next-line no-unused-import import { InboundPacket, Origin } from "../libs/Packet.sol"; /** * @title IOAppPreCrimeSimulator Interface * @dev Interface for the preCrime simulation functionality in an OApp. */ interface IOAppPreCrimeSimulator { // @dev simulation result used in PreCrime implementation error SimulationResult(bytes result); error OnlySelf(); /** * @dev Emitted when the preCrime contract address is set. * @param preCrimeAddress The address of the preCrime contract. */ event PreCrimeSet(address preCrimeAddress); /** * @dev Retrieves the address of the preCrime contract implementation. * @return The address of the preCrime contract. */ function preCrime() external view returns (address); /** * @dev Retrieves the address of the OApp contract. * @return The address of the OApp contract. */ function oApp() external view returns (address); /** * @dev Sets the preCrime contract address. * @param _preCrime The address of the preCrime contract. */ function setPreCrime(address _preCrime) external; /** * @dev Mocks receiving a packet, then reverts with a series of data to infer the state/result. * @param _packets An array of LayerZero InboundPacket objects representing received packets. */ function lzReceiveAndRevert(InboundPacket[] calldata _packets) external payable; /** * @dev checks if the specified peer is considered 'trusted' by the OApp. * @param _eid The endpoint Id to check. * @param _peer The peer to check. * @return Whether the peer passed is considered 'trusted' by the OApp. */ function isPeer(uint32 _eid, bytes32 _peer) external view returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; struct PreCrimePeer { uint32 eid; bytes32 preCrime; bytes32 oApp; } // TODO not done yet interface IPreCrime { error OnlyOffChain(); // for simulate() error PacketOversize(uint256 max, uint256 actual); error PacketUnsorted(); error SimulationFailed(bytes reason); // for preCrime() error SimulationResultNotFound(uint32 eid); error InvalidSimulationResult(uint32 eid, bytes reason); error CrimeFound(bytes crime); function getConfig(bytes[] calldata _packets, uint256[] calldata _packetMsgValues) external returns (bytes memory); function simulate( bytes[] calldata _packets, uint256[] calldata _packetMsgValues ) external payable returns (bytes memory); function buildSimulationResult() external view returns (bytes memory); function preCrime( bytes[] calldata _packets, uint256[] calldata _packetMsgValues, bytes[] calldata _simulations ) external; function version() external view returns (uint64 major, uint8 minor); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol"; import { PacketV1Codec } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol"; /** * @title InboundPacket * @dev Structure representing an inbound packet received by the contract. */ struct InboundPacket { Origin origin; // Origin information of the packet. uint32 dstEid; // Destination endpointId of the packet. address receiver; // Receiver address for the packet. bytes32 guid; // Unique identifier of the packet. uint256 value; // msg.value of the packet. address executor; // Executor address for the packet. bytes message; // Message payload of the packet. bytes extraData; // Additional arbitrary data for the packet. } /** * @title PacketDecoder * @dev Library for decoding LayerZero packets. */ library PacketDecoder { using PacketV1Codec for bytes; /** * @dev Decode an inbound packet from the given packet data. * @param _packet The packet data to decode. * @return packet An InboundPacket struct representing the decoded packet. */ function decode(bytes calldata _packet) internal pure returns (InboundPacket memory packet) { packet.origin = Origin(_packet.srcEid(), _packet.sender(), _packet.nonce()); packet.dstEid = _packet.dstEid(); packet.receiver = _packet.receiverB20(); packet.guid = _packet.guid(); packet.message = _packet.message(); } /** * @dev Decode multiple inbound packets from the given packet data and associated message values. * @param _packets An array of packet data to decode. * @param _packetMsgValues An array of associated message values for each packet. * @return packets An array of InboundPacket structs representing the decoded packets. */ function decode( bytes[] calldata _packets, uint256[] memory _packetMsgValues ) internal pure returns (InboundPacket[] memory packets) { packets = new InboundPacket[](_packets.length); for (uint256 i = 0; i < _packets.length; i++) { bytes calldata packet = _packets[i]; packets[i] = PacketDecoder.decode(packet); // @dev Allows the verifier to specify the msg.value that gets passed in lzReceive. packets[i].value = _packetMsgValues[i]; } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IPreCrime } from "./interfaces/IPreCrime.sol"; import { IOAppPreCrimeSimulator, InboundPacket, Origin } from "./interfaces/IOAppPreCrimeSimulator.sol"; /** * @title OAppPreCrimeSimulator * @dev Abstract contract serving as the base for preCrime simulation functionality in an OApp. */ abstract contract OAppPreCrimeSimulator is IOAppPreCrimeSimulator, Ownable { // The address of the preCrime implementation. address public preCrime; /** * @dev Retrieves the address of the OApp contract. * @return The address of the OApp contract. * * @dev The simulator contract is the base contract for the OApp by default. * @dev If the simulator is a separate contract, override this function. */ function oApp() external view virtual returns (address) { return address(this); } /** * @dev Sets the preCrime contract address. * @param _preCrime The address of the preCrime contract. */ function setPreCrime(address _preCrime) public virtual onlyOwner { preCrime = _preCrime; emit PreCrimeSet(_preCrime); } /** * @dev Interface for pre-crime simulations. Always reverts at the end with the simulation results. * @param _packets An array of InboundPacket objects representing received packets to be delivered. * * @dev WARNING: MUST revert at the end with the simulation results. * @dev Gives the preCrime implementation the ability to mock sending packets to the lzReceive function, * WITHOUT actually executing them. */ function lzReceiveAndRevert(InboundPacket[] calldata _packets) public payable virtual { for (uint256 i = 0; i < _packets.length; i++) { InboundPacket calldata packet = _packets[i]; // Ignore packets that are not from trusted peers. if (!isPeer(packet.origin.srcEid, packet.origin.sender)) continue; // @dev Because a verifier is calling this function, it doesnt have access to executor params: // - address _executor // - bytes calldata _extraData // preCrime will NOT work for OApps that rely on these two parameters inside of their _lzReceive(). // They are instead stubbed to default values, address(0) and bytes("") // @dev Calling this.lzReceiveSimulate removes ability for assembly return 0 callstack exit, // which would cause the revert to be ignored. this.lzReceiveSimulate{ value: packet.value }( packet.origin, packet.guid, packet.message, packet.executor, packet.extraData ); } // @dev Revert with the simulation results. msg.sender must implement IPreCrime.buildSimulationResult(). revert SimulationResult(IPreCrime(msg.sender).buildSimulationResult()); } /** * @dev Is effectively an internal function because msg.sender must be address(this). * Allows resetting the call stack for 'internal' calls. * @param _origin The origin information containing the source endpoint and sender address. * - srcEid: The source chain endpoint ID. * - sender: The sender address on the src chain. * - nonce: The nonce of the message. * @param _guid The unique identifier of the packet. * @param _message The message payload of the packet. * @param _executor The executor address for the packet. * @param _extraData Additional data for the packet. */ function lzReceiveSimulate( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) external payable virtual { // @dev Ensure ONLY can be called 'internally'. if (msg.sender != address(this)) revert OnlySelf(); _lzReceiveSimulate(_origin, _guid, _message, _executor, _extraData); } /** * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive. * @param _origin The origin information. * - srcEid: The source chain endpoint ID. * - sender: The sender address from the src chain. * - nonce: The nonce of the LayerZero message. * @param _guid The GUID of the LayerZero message. * @param _message The LayerZero message. * @param _executor The address of the off-chain executor. * @param _extraData Arbitrary data passed by the msg executor. * * @dev Enables the preCrime simulator to mock sending lzReceive() messages, * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver. */ function _lzReceiveSimulate( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) internal virtual; /** * @dev checks if the specified peer is considered 'trusted' by the OApp. * @param _eid The endpoint Id to check. * @param _peer The peer to check. * @return Whether the peer passed is considered 'trusted' by the OApp. */ function isPeer(uint32 _eid, bytes32 _peer) public view virtual returns (bool); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { MessagingReceipt, MessagingFee } from "@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol"; /** * @dev Struct representing token parameters for the OFT send() operation. */ struct SendParam { uint32 dstEid; // Destination endpoint ID. bytes32 to; // Recipient address. uint256 amountLD; // Amount to send in local decimals. uint256 minAmountLD; // Minimum amount to send in local decimals. bytes extraOptions; // Additional options supplied by the caller to be used in the LayerZero message. bytes composeMsg; // The composed message for the send() operation. bytes oftCmd; // The OFT command to be executed, unused in default OFT implementations. } /** * @dev Struct representing OFT limit information. * @dev These amounts can change dynamically and are up the specific oft implementation. */ struct OFTLimit { uint256 minAmountLD; // Minimum amount in local decimals that can be sent to the recipient. uint256 maxAmountLD; // Maximum amount in local decimals that can be sent to the recipient. } /** * @dev Struct representing OFT receipt information. */ struct OFTReceipt { uint256 amountSentLD; // Amount of tokens ACTUALLY debited from the sender in local decimals. // @dev In non-default implementations, the amountReceivedLD COULD differ from this value. uint256 amountReceivedLD; // Amount of tokens to be received on the remote side. } /** * @dev Struct representing OFT fee details. * @dev Future proof mechanism to provide a standardized way to communicate fees to things like a UI. */ struct OFTFeeDetail { int256 feeAmountLD; // Amount of the fee in local decimals. string description; // Description of the fee. } /** * @title IOFT * @dev Interface for the OftChain (OFT) token. * @dev Does not inherit ERC20 to accommodate usage by OFTAdapter as well. * @dev This specific interface ID is '0x02e49c2c'. */ interface IOFT { // Custom error messages error InvalidLocalDecimals(); error SlippageExceeded(uint256 amountLD, uint256 minAmountLD); // Events event OFTSent( bytes32 indexed guid, // GUID of the OFT message. uint32 dstEid, // Destination Endpoint ID. address indexed fromAddress, // Address of the sender on the src chain. uint256 amountSentLD, // Amount of tokens sent in local decimals. uint256 amountReceivedLD // Amount of tokens received in local decimals. ); event OFTReceived( bytes32 indexed guid, // GUID of the OFT message. uint32 srcEid, // Source Endpoint ID. address indexed toAddress, // Address of the recipient on the dst chain. uint256 amountReceivedLD // Amount of tokens received in local decimals. ); /** * @notice Retrieves interfaceID and the version of the OFT. * @return interfaceId The interface ID. * @return version The version. * * @dev interfaceId: This specific interface ID is '0x02e49c2c'. * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs. * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented. * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1) */ function oftVersion() external view returns (bytes4 interfaceId, uint64 version); /** * @notice Retrieves the address of the token associated with the OFT. * @return token The address of the ERC20 token implementation. */ function token() external view returns (address); /** * @notice Indicates whether the OFT contract requires approval of the 'token()' to send. * @return requiresApproval Needs approval of the underlying token implementation. * * @dev Allows things like wallet implementers to determine integration requirements, * without understanding the underlying token implementation. */ function approvalRequired() external view returns (bool); /** * @notice Retrieves the shared decimals of the OFT. * @return sharedDecimals The shared decimals of the OFT. */ function sharedDecimals() external view returns (uint8); /** * @notice Provides a quote for OFT-related operations. * @param _sendParam The parameters for the send operation. * @return limit The OFT limit information. * @return oftFeeDetails The details of OFT fees. * @return receipt The OFT receipt information. */ function quoteOFT( SendParam calldata _sendParam ) external view returns (OFTLimit memory, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory); /** * @notice Provides a quote for the send() operation. * @param _sendParam The parameters for the send() operation. * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token. * @return fee The calculated LayerZero messaging fee from the send() operation. * * @dev MessagingFee: LayerZero msg fee * - nativeFee: The native fee. * - lzTokenFee: The lzToken fee. */ function quoteSend(SendParam calldata _sendParam, bool _payInLzToken) external view returns (MessagingFee memory); /** * @notice Executes the send() operation. * @param _sendParam The parameters for the send operation. * @param _fee The fee information supplied by the caller. * - nativeFee: The native fee. * - lzTokenFee: The lzToken fee. * @param _refundAddress The address to receive any excess funds from fees etc. on the src. * @return receipt The LayerZero messaging receipt from the send() operation. * @return oftReceipt The OFT receipt information. * * @dev MessagingReceipt: LayerZero msg receipt * - guid: The unique identifier for the sent message. * - nonce: The nonce of the sent message. * - fee: The LayerZero fee incurred for the message. */ function send( SendParam calldata _sendParam, MessagingFee calldata _fee, address _refundAddress ) external payable returns (MessagingReceipt memory, OFTReceipt memory); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; library OFTComposeMsgCodec { // Offset constants for decoding composed messages uint8 private constant NONCE_OFFSET = 8; uint8 private constant SRC_EID_OFFSET = 12; uint8 private constant AMOUNT_LD_OFFSET = 44; uint8 private constant COMPOSE_FROM_OFFSET = 76; /** * @dev Encodes a OFT composed message. * @param _nonce The nonce value. * @param _srcEid The source endpoint ID. * @param _amountLD The amount in local decimals. * @param _composeMsg The composed message. * @return _msg The encoded Composed message. */ function encode( uint64 _nonce, uint32 _srcEid, uint256 _amountLD, bytes memory _composeMsg // 0x[composeFrom][composeMsg] ) internal pure returns (bytes memory _msg) { _msg = abi.encodePacked(_nonce, _srcEid, _amountLD, _composeMsg); } /** * @dev Retrieves the nonce for the composed message. * @param _msg The message. * @return The nonce value. */ function nonce(bytes calldata _msg) internal pure returns (uint64) { return uint64(bytes8(_msg[:NONCE_OFFSET])); } /** * @dev Retrieves the source endpoint ID for the composed message. * @param _msg The message. * @return The source endpoint ID. */ function srcEid(bytes calldata _msg) internal pure returns (uint32) { return uint32(bytes4(_msg[NONCE_OFFSET:SRC_EID_OFFSET])); } /** * @dev Retrieves the amount in local decimals from the composed message. * @param _msg The message. * @return The amount in local decimals. */ function amountLD(bytes calldata _msg) internal pure returns (uint256) { return uint256(bytes32(_msg[SRC_EID_OFFSET:AMOUNT_LD_OFFSET])); } /** * @dev Retrieves the composeFrom value from the composed message. * @param _msg The message. * @return The composeFrom value. */ function composeFrom(bytes calldata _msg) internal pure returns (bytes32) { return bytes32(_msg[AMOUNT_LD_OFFSET:COMPOSE_FROM_OFFSET]); } /** * @dev Retrieves the composed message. * @param _msg The message. * @return The composed message. */ function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) { return _msg[COMPOSE_FROM_OFFSET:]; } /** * @dev Converts an address to bytes32. * @param _addr The address to convert. * @return The bytes32 representation of the address. */ function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } /** * @dev Converts bytes32 to an address. * @param _b The bytes32 value to convert. * @return The address representation of bytes32. */ function bytes32ToAddress(bytes32 _b) internal pure returns (address) { return address(uint160(uint256(_b))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; library OFTMsgCodec { // Offset constants for encoding and decoding OFT messages uint8 private constant SEND_TO_OFFSET = 32; uint8 private constant SEND_AMOUNT_SD_OFFSET = 40; /** * @dev Encodes an OFT LayerZero message. * @param _sendTo The recipient address. * @param _amountShared The amount in shared decimals. * @param _composeMsg The composed message. * @return _msg The encoded message. * @return hasCompose A boolean indicating whether the message has a composed payload. */ function encode( bytes32 _sendTo, uint64 _amountShared, bytes memory _composeMsg ) internal view returns (bytes memory _msg, bool hasCompose) { hasCompose = _composeMsg.length > 0; // @dev Remote chains will want to know the composed function caller ie. msg.sender on the src. _msg = hasCompose ? abi.encodePacked(_sendTo, _amountShared, addressToBytes32(msg.sender), _composeMsg) : abi.encodePacked(_sendTo, _amountShared); } /** * @dev Checks if the OFT message is composed. * @param _msg The OFT message. * @return A boolean indicating whether the message is composed. */ function isComposed(bytes calldata _msg) internal pure returns (bool) { return _msg.length > SEND_AMOUNT_SD_OFFSET; } /** * @dev Retrieves the recipient address from the OFT message. * @param _msg The OFT message. * @return The recipient address. */ function sendTo(bytes calldata _msg) internal pure returns (bytes32) { return bytes32(_msg[:SEND_TO_OFFSET]); } /** * @dev Retrieves the amount in shared decimals from the OFT message. * @param _msg The OFT message. * @return The amount in shared decimals. */ function amountSD(bytes calldata _msg) internal pure returns (uint64) { return uint64(bytes8(_msg[SEND_TO_OFFSET:SEND_AMOUNT_SD_OFFSET])); } /** * @dev Retrieves the composed message from the OFT message. * @param _msg The OFT message. * @return The composed message. */ function composeMsg(bytes calldata _msg) internal pure returns (bytes memory) { return _msg[SEND_AMOUNT_SD_OFFSET:]; } /** * @dev Converts an address to bytes32. * @param _addr The address to convert. * @return The bytes32 representation of the address. */ function addressToBytes32(address _addr) internal pure returns (bytes32) { return bytes32(uint256(uint160(_addr))); } /** * @dev Converts bytes32 to an address. * @param _b The bytes32 value to convert. * @return The address representation of bytes32. */ function bytes32ToAddress(bytes32 _b) internal pure returns (address) { return address(uint160(uint256(_b))); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { IERC20Metadata, IERC20 } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IOFT, OFTCore } from "./OFTCore.sol"; /** * @title OFTAdapter Contract * @dev OFTAdapter is a contract that adapts an ERC-20 token to the OFT functionality. * * @dev For existing ERC20 tokens, this can be used to convert the token to crosschain compatibility. * @dev WARNING: ONLY 1 of these should exist for a given global mesh, * unless you make a NON-default implementation of OFT and needs to be done very carefully. * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out. * IF the 'innerToken' applies something like a transfer fee, the default will NOT work... * a pre/post balance check will need to be done to calculate the amountSentLD/amountReceivedLD. */ abstract contract OFTAdapter is OFTCore { using SafeERC20 for IERC20; IERC20 internal immutable innerToken; /** * @dev Constructor for the OFTAdapter contract. * @param _token The address of the ERC-20 token to be adapted. * @param _lzEndpoint The LayerZero endpoint address. * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. */ constructor( address _token, address _lzEndpoint, address _delegate ) OFTCore(IERC20Metadata(_token).decimals(), _lzEndpoint, _delegate) { innerToken = IERC20(_token); } /** * @dev Retrieves the address of the underlying ERC20 implementation. * @return The address of the adapted ERC-20 token. * * @dev In the case of OFTAdapter, address(this) and erc20 are NOT the same contract. */ function token() public view returns (address) { return address(innerToken); } /** * @notice Indicates whether the OFT contract requires approval of the 'token()' to send. * @return requiresApproval Needs approval of the underlying token implementation. * * @dev In the case of default OFTAdapter, approval is required. * @dev In non-default OFTAdapter contracts with something like mint and burn privileges, it would NOT need approval. */ function approvalRequired() external pure virtual returns (bool) { return true; } /** * @dev Locks tokens from the sender's specified balance in this contract. * @param _from The address to debit from. * @param _amountLD The amount of tokens to send in local decimals. * @param _minAmountLD The minimum amount to send in local decimals. * @param _dstEid The destination chain ID. * @return amountSentLD The amount sent in local decimals. * @return amountReceivedLD The amount received in local decimals on the remote. * * @dev msg.sender will need to approve this _amountLD of tokens to be locked inside of the contract. * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out. * IF the 'innerToken' applies something like a transfer fee, the default will NOT work... * a pre/post balance check will need to be done to calculate the amountReceivedLD. */ function _debit( address _from, uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid ) internal virtual override returns (uint256 amountSentLD, uint256 amountReceivedLD) { (amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid); // @dev Lock tokens by moving them into this contract from the caller. innerToken.safeTransferFrom(_from, address(this), amountSentLD); } /** * @dev Credits tokens to the specified address. * @param _to The address to credit the tokens to. * @param _amountLD The amount of tokens to credit in local decimals. * @dev _srcEid The source chain ID. * @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals. * * @dev WARNING: The default OFTAdapter implementation assumes LOSSLESS transfers, ie. 1 token in, 1 token out. * IF the 'innerToken' applies something like a transfer fee, the default will NOT work... * a pre/post balance check will need to be done to calculate the amountReceivedLD. */ function _credit( address _to, uint256 _amountLD, uint32 /*_srcEid*/ ) internal virtual override returns (uint256 amountReceivedLD) { // @dev Unlock the tokens and transfer to the recipient. innerToken.safeTransfer(_to, _amountLD); // @dev In the case of NON-default OFTAdapter, the amountLD MIGHT not be == amountReceivedLD. return _amountLD; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { OApp, Origin } from "@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol"; import { OAppOptionsType3 } from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol"; import { IOAppMsgInspector } from "@layerzerolabs/oapp-evm/contracts/oapp/interfaces/IOAppMsgInspector.sol"; import { OAppPreCrimeSimulator } from "@layerzerolabs/oapp-evm/contracts/precrime/OAppPreCrimeSimulator.sol"; import { IOFT, SendParam, OFTLimit, OFTReceipt, OFTFeeDetail, MessagingReceipt, MessagingFee } from "./interfaces/IOFT.sol"; import { OFTMsgCodec } from "./libs/OFTMsgCodec.sol"; import { OFTComposeMsgCodec } from "./libs/OFTComposeMsgCodec.sol"; /** * @title OFTCore * @dev Abstract contract for the OftChain (OFT) token. */ abstract contract OFTCore is IOFT, OApp, OAppPreCrimeSimulator, OAppOptionsType3 { using OFTMsgCodec for bytes; using OFTMsgCodec for bytes32; // @notice Provides a conversion rate when swapping between denominations of SD and LD // - shareDecimals == SD == shared Decimals // - localDecimals == LD == local decimals // @dev Considers that tokens have different decimal amounts on various chains. // @dev eg. // For a token // - locally with 4 decimals --> 1.2345 => uint(12345) // - remotely with 2 decimals --> 1.23 => uint(123) // - The conversion rate would be 10 ** (4 - 2) = 100 // @dev If you want to send 1.2345 -> (uint 12345), you CANNOT represent that value on the remote, // you can only display 1.23 -> uint(123). // @dev To preserve the dust that would otherwise be lost on that conversion, // we need to unify a denomination that can be represented on ALL chains inside of the OFT mesh uint256 public immutable decimalConversionRate; // @notice Msg types that are used to identify the various OFT operations. // @dev This can be extended in child contracts for non-default oft operations // @dev These values are used in things like combineOptions() in OAppOptionsType3.sol. uint16 public constant SEND = 1; uint16 public constant SEND_AND_CALL = 2; // Address of an optional contract to inspect both 'message' and 'options' address public msgInspector; event MsgInspectorSet(address inspector); /** * @dev Constructor. * @param _localDecimals The decimals of the token on the local chain (this chain). * @param _endpoint The address of the LayerZero endpoint. * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. */ constructor(uint8 _localDecimals, address _endpoint, address _delegate) OApp(_endpoint, _delegate) { if (_localDecimals < sharedDecimals()) revert InvalidLocalDecimals(); decimalConversionRate = 10 ** (_localDecimals - sharedDecimals()); } /** * @notice Retrieves interfaceID and the version of the OFT. * @return interfaceId The interface ID. * @return version The version. * * @dev interfaceId: This specific interface ID is '0x02e49c2c'. * @dev version: Indicates a cross-chain compatible msg encoding with other OFTs. * @dev If a new feature is added to the OFT cross-chain msg encoding, the version will be incremented. * ie. localOFT version(x,1) CAN send messages to remoteOFT version(x,1) */ function oftVersion() external pure virtual returns (bytes4 interfaceId, uint64 version) { return (type(IOFT).interfaceId, 1); } /** * @dev Retrieves the shared decimals of the OFT. * @return The shared decimals of the OFT. * * @dev Sets an implicit cap on the amount of tokens, over uint64.max() will need some sort of outbound cap / totalSupply cap * Lowest common decimal denominator between chains. * Defaults to 6 decimal places to provide up to 18,446,744,073,709.551615 units (max uint64). * For tokens exceeding this totalSupply(), they will need to override the sharedDecimals function with something smaller. * ie. 4 sharedDecimals would be 1,844,674,407,370,955.1615 */ function sharedDecimals() public view virtual returns (uint8) { return 6; } /** * @dev Sets the message inspector address for the OFT. * @param _msgInspector The address of the message inspector. * * @dev This is an optional contract that can be used to inspect both 'message' and 'options'. * @dev Set it to address(0) to disable it, or set it to a contract address to enable it. */ function setMsgInspector(address _msgInspector) public virtual onlyOwner { msgInspector = _msgInspector; emit MsgInspectorSet(_msgInspector); } /** * @notice Provides a quote for OFT-related operations. * @param _sendParam The parameters for the send operation. * @return oftLimit The OFT limit information. * @return oftFeeDetails The details of OFT fees. * @return oftReceipt The OFT receipt information. */ function quoteOFT( SendParam calldata _sendParam ) external view virtual returns (OFTLimit memory oftLimit, OFTFeeDetail[] memory oftFeeDetails, OFTReceipt memory oftReceipt) { uint256 minAmountLD = 0; // Unused in the default implementation. uint256 maxAmountLD = type(uint64).max; // Unused in the default implementation. oftLimit = OFTLimit(minAmountLD, maxAmountLD); // Unused in the default implementation; reserved for future complex fee details. oftFeeDetails = new OFTFeeDetail[](0); // @dev This is the same as the send() operation, but without the actual send. // - amountSentLD is the amount in local decimals that would be sent from the sender. // - amountReceivedLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance. // @dev The amountSentLD MIGHT not equal the amount the user actually receives. HOWEVER, the default does. (uint256 amountSentLD, uint256 amountReceivedLD) = _debitView( _sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid ); oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD); } /** * @notice Provides a quote for the send() operation. * @param _sendParam The parameters for the send() operation. * @param _payInLzToken Flag indicating whether the caller is paying in the LZ token. * @return msgFee The calculated LayerZero messaging fee from the send() operation. * * @dev MessagingFee: LayerZero msg fee * - nativeFee: The native fee. * - lzTokenFee: The lzToken fee. */ function quoteSend( SendParam calldata _sendParam, bool _payInLzToken ) external view virtual returns (MessagingFee memory msgFee) { // @dev mock the amount to receive, this is the same operation used in the send(). // The quote is as similar as possible to the actual send() operation. (, uint256 amountReceivedLD) = _debitView(_sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid); // @dev Builds the options and OFT message to quote in the endpoint. (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD); // @dev Calculates the LayerZero fee for the send() operation. return _quote(_sendParam.dstEid, message, options, _payInLzToken); } /** * @dev Executes the send operation. * @param _sendParam The parameters for the send operation. * @param _fee The calculated fee for the send() operation. * - nativeFee: The native fee. * - lzTokenFee: The lzToken fee. * @param _refundAddress The address to receive any excess funds. * @return msgReceipt The receipt for the send operation. * @return oftReceipt The OFT receipt information. * * @dev MessagingReceipt: LayerZero msg receipt * - guid: The unique identifier for the sent message. * - nonce: The nonce of the sent message. * - fee: The LayerZero fee incurred for the message. */ function send( SendParam calldata _sendParam, MessagingFee calldata _fee, address _refundAddress ) external payable virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) { return _send(_sendParam, _fee, _refundAddress); } /** * @dev Internal function to execute the send operation. * @param _sendParam The parameters for the send operation. * @param _fee The calculated fee for the send() operation. * - nativeFee: The native fee. * - lzTokenFee: The lzToken fee. * @param _refundAddress The address to receive any excess funds. * @return msgReceipt The receipt for the send operation. * @return oftReceipt The OFT receipt information. * * @dev MessagingReceipt: LayerZero msg receipt * - guid: The unique identifier for the sent message. * - nonce: The nonce of the sent message. * - fee: The LayerZero fee incurred for the message. */ function _send( SendParam calldata _sendParam, MessagingFee calldata _fee, address _refundAddress ) internal virtual returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) { // @dev Applies the token transfers regarding this send() operation. // - amountSentLD is the amount in local decimals that was ACTUALLY sent/debited from the sender. // - amountReceivedLD is the amount in local decimals that will be received/credited to the recipient on the remote OFT instance. (uint256 amountSentLD, uint256 amountReceivedLD) = _debit( msg.sender, _sendParam.amountLD, _sendParam.minAmountLD, _sendParam.dstEid ); // @dev Builds the options and OFT message to quote in the endpoint. (bytes memory message, bytes memory options) = _buildMsgAndOptions(_sendParam, amountReceivedLD); // @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt. msgReceipt = _lzSend(_sendParam.dstEid, message, options, _fee, _refundAddress); // @dev Formulate the OFT receipt. oftReceipt = OFTReceipt(amountSentLD, amountReceivedLD); emit OFTSent(msgReceipt.guid, _sendParam.dstEid, msg.sender, amountSentLD, amountReceivedLD); } /** * @dev Internal function to build the message and options. * @param _sendParam The parameters for the send() operation. * @param _amountLD The amount in local decimals. * @return message The encoded message. * @return options The encoded options. */ function _buildMsgAndOptions( SendParam calldata _sendParam, uint256 _amountLD ) internal view virtual returns (bytes memory message, bytes memory options) { bool hasCompose; // @dev This generated message has the msg.sender encoded into the payload so the remote knows who the caller is. (message, hasCompose) = OFTMsgCodec.encode( _sendParam.to, _toSD(_amountLD), // @dev Must be include a non empty bytes if you want to compose, EVEN if you dont need it on the remote. // EVEN if you dont require an arbitrary payload to be sent... eg. '0x01' _sendParam.composeMsg ); // @dev Change the msg type depending if its composed or not. uint16 msgType = hasCompose ? SEND_AND_CALL : SEND; // @dev Combine the callers _extraOptions with the enforced options via the OAppOptionsType3. options = combineOptions(_sendParam.dstEid, msgType, _sendParam.extraOptions); // @dev Optionally inspect the message and options depending if the OApp owner has set a msg inspector. // @dev If it fails inspection, needs to revert in the implementation. ie. does not rely on return boolean address inspector = msgInspector; // caches the msgInspector to avoid potential double storage read if (inspector != address(0)) IOAppMsgInspector(inspector).inspect(message, options); } /** * @dev Internal function to handle the receive on the LayerZero endpoint. * @param _origin The origin information. * - srcEid: The source chain endpoint ID. * - sender: The sender address from the src chain. * - nonce: The nonce of the LayerZero message. * @param _guid The unique identifier for the received LayerZero message. * @param _message The encoded message. * @dev _executor The address of the executor. * @dev _extraData Additional data. */ function _lzReceive( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address /*_executor*/, // @dev unused in the default implementation. bytes calldata /*_extraData*/ // @dev unused in the default implementation. ) internal virtual override { // @dev The src sending chain doesnt know the address length on this chain (potentially non-evm) // Thus everything is bytes32() encoded in flight. address toAddress = _message.sendTo().bytes32ToAddress(); // @dev Credit the amountLD to the recipient and return the ACTUAL amount the recipient received in local decimals uint256 amountReceivedLD = _credit(toAddress, _toLD(_message.amountSD()), _origin.srcEid); if (_message.isComposed()) { // @dev Proprietary composeMsg format for the OFT. bytes memory composeMsg = OFTComposeMsgCodec.encode( _origin.nonce, _origin.srcEid, amountReceivedLD, _message.composeMsg() ); // @dev Stores the lzCompose payload that will be executed in a separate tx. // Standardizes functionality for executing arbitrary contract invocation on some non-evm chains. // @dev The off-chain executor will listen and process the msg based on the src-chain-callers compose options passed. // @dev The index is used when a OApp needs to compose multiple msgs on lzReceive. // For default OFT implementation there is only 1 compose msg per lzReceive, thus its always 0. endpoint.sendCompose(toAddress, _guid, 0 /* the index of the composed message*/, composeMsg); } emit OFTReceived(_guid, _origin.srcEid, toAddress, amountReceivedLD); } /** * @dev Internal function to handle the OAppPreCrimeSimulator simulated receive. * @param _origin The origin information. * - srcEid: The source chain endpoint ID. * - sender: The sender address from the src chain. * - nonce: The nonce of the LayerZero message. * @param _guid The unique identifier for the received LayerZero message. * @param _message The LayerZero message. * @param _executor The address of the off-chain executor. * @param _extraData Arbitrary data passed by the msg executor. * * @dev Enables the preCrime simulator to mock sending lzReceive() messages, * routes the msg down from the OAppPreCrimeSimulator, and back up to the OAppReceiver. */ function _lzReceiveSimulate( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) internal virtual override { _lzReceive(_origin, _guid, _message, _executor, _extraData); } /** * @dev Check if the peer is considered 'trusted' by the OApp. * @param _eid The endpoint ID to check. * @param _peer The peer to check. * @return Whether the peer passed is considered 'trusted' by the OApp. * * @dev Enables OAppPreCrimeSimulator to check whether a potential Inbound Packet is from a trusted source. */ function isPeer(uint32 _eid, bytes32 _peer) public view virtual override returns (bool) { return peers[_eid] == _peer; } /** * @dev Internal function to remove dust from the given local decimal amount. * @param _amountLD The amount in local decimals. * @return amountLD The amount after removing dust. * * @dev Prevents the loss of dust when moving amounts between chains with different decimals. * @dev eg. uint(123) with a conversion rate of 100 becomes uint(100). */ function _removeDust(uint256 _amountLD) internal view virtual returns (uint256 amountLD) { return (_amountLD / decimalConversionRate) * decimalConversionRate; } /** * @dev Internal function to convert an amount from shared decimals into local decimals. * @param _amountSD The amount in shared decimals. * @return amountLD The amount in local decimals. */ function _toLD(uint64 _amountSD) internal view virtual returns (uint256 amountLD) { return _amountSD * decimalConversionRate; } /** * @dev Internal function to convert an amount from local decimals into shared decimals. * @param _amountLD The amount in local decimals. * @return amountSD The amount in shared decimals. */ function _toSD(uint256 _amountLD) internal view virtual returns (uint64 amountSD) { return uint64(_amountLD / decimalConversionRate); } /** * @dev Internal function to mock the amount mutation from a OFT debit() operation. * @param _amountLD The amount to send in local decimals. * @param _minAmountLD The minimum amount to send in local decimals. * @dev _dstEid The destination endpoint ID. * @return amountSentLD The amount sent, in local decimals. * @return amountReceivedLD The amount to be received on the remote chain, in local decimals. * * @dev This is where things like fees would be calculated and deducted from the amount to be received on the remote. */ function _debitView( uint256 _amountLD, uint256 _minAmountLD, uint32 /*_dstEid*/ ) internal view virtual returns (uint256 amountSentLD, uint256 amountReceivedLD) { // @dev Remove the dust so nothing is lost on the conversion between chains with different decimals for the token. amountSentLD = _removeDust(_amountLD); // @dev The amount to send is the same as amount received in the default implementation. amountReceivedLD = amountSentLD; // @dev Check for slippage. if (amountReceivedLD < _minAmountLD) { revert SlippageExceeded(amountReceivedLD, _minAmountLD); } } /** * @dev Internal function to perform a debit operation. * @param _from The address to debit. * @param _amountLD The amount to send in local decimals. * @param _minAmountLD The minimum amount to send in local decimals. * @param _dstEid The destination endpoint ID. * @return amountSentLD The amount sent in local decimals. * @return amountReceivedLD The amount received in local decimals on the remote. * * @dev Defined here but are intended to be overriden depending on the OFT implementation. * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD. */ function _debit( address _from, uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid ) internal virtual returns (uint256 amountSentLD, uint256 amountReceivedLD); /** * @dev Internal function to perform a credit operation. * @param _to The address to credit. * @param _amountLD The amount to credit in local decimals. * @param _srcEid The source endpoint ID. * @return amountReceivedLD The amount ACTUALLY received in local decimals. * * @dev Defined here but are intended to be overriden depending on the OFT implementation. * @dev Depending on OFT implementation the _amountLD could differ from the amountReceivedLD. */ function _credit( address _to, uint256 _amountLD, uint32 _srcEid ) internal virtual returns (uint256 amountReceivedLD); }
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.22; import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { ILayerZeroEndpointV2, MessagingParams, MessagingReceipt, MessagingFee, Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol"; import { ExecutionState } from "@layerzerolabs/lz-evm-protocol-v2/contracts/EndpointV2ViewUpgradeable.sol"; import { ILayerZeroReceiver } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol"; import { SetConfigParam } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/IMessageLibManager.sol"; import { MessagingContext } from "@layerzerolabs/lz-evm-protocol-v2/contracts/MessagingContext.sol"; import { Packet } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ISendLib.sol"; import { OFTMsgCodec } from "@layerzerolabs/oft-evm/contracts/libs/OFTMsgCodec.sol"; import { Origin } from "@layerzerolabs/oapp-evm/contracts/oapp/OAppReceiver.sol"; import { Errors } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/Errors.sol"; import { GUID } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/GUID.sol"; import { ExecutorOptions } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/ExecutorOptions.sol"; import { PacketV1Codec } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/PacketV1Codec.sol"; import { WorkerOptions } from "@layerzerolabs/lz-evm-messagelib-v2/contracts/SendLibBase.sol"; import { IExecutorFeeLib } from "@layerzerolabs/lz-evm-messagelib-v2/contracts/interfaces/IExecutorFeeLib.sol"; import { DVNOptions } from "@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/DVNOptions.sol"; import { UlnOptions } from "@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/UlnOptions.sol"; import { CalldataBytesLib } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol"; contract EndpointV2Mock is ILayerZeroEndpointV2, MessagingContext { using ExecutorOptions for bytes; using OFTMsgCodec for bytes; using OFTMsgCodec for bytes32; using OFTMsgCodec for address; using SafeCast for uint256; using CalldataBytesLib for bytes; bytes32 public constant EMPTY_PAYLOAD_HASH = bytes32(0); uint32 public immutable eid; mapping(address => address) public lzEndpointLookup; mapping(address receiver => mapping(uint32 srcEid => mapping(bytes32 sender => uint64 nonce))) public lazyInboundNonce; mapping(address receiver => mapping(uint32 srcEid => mapping(bytes32 sender => mapping(uint64 inboundNonce => bytes32 payloadHash)))) public inboundPayloadHash; mapping(address sender => mapping(uint32 dstEid => mapping(bytes32 receiver => uint64 nonce))) public outboundNonce; RelayerFeeConfig public relayerFeeConfig; ProtocolFeeConfig protocolFeeConfig; uint256 public verifierFee; struct ProtocolFeeConfig { uint256 zroFee; uint256 nativeBP; } struct RelayerFeeConfig { uint128 dstPriceRatio; // 10^10 uint128 dstGasPriceInWei; uint128 dstNativeAmtCap; uint64 baseGas; uint64 gasPerByte; } uint8 internal constant _NOT_ENTERED = 1; uint8 internal constant _ENTERED = 2; uint8 internal _receive_entered_state = 1; modifier receiveNonReentrant() { require(_receive_entered_state == _NOT_ENTERED, "LayerZeroMock: no receive reentrancy"); _receive_entered_state = _ENTERED; _; _receive_entered_state = _NOT_ENTERED; } event ValueTransferFailed(address indexed to, uint256 indexed quantity); constructor(uint32 _eid) { eid = _eid; // init config relayerFeeConfig = RelayerFeeConfig({ dstPriceRatio: 1e10, // 1:1, same chain, same native coin dstGasPriceInWei: 1e10, dstNativeAmtCap: 1e19, baseGas: 100, gasPerByte: 1 }); protocolFeeConfig = ProtocolFeeConfig({ zroFee: 1e18, nativeBP: 1000 }); // BP 0.1 verifierFee = 1e16; } function send( MessagingParams calldata _params, address _refundAddress ) public payable sendContext(_params.dstEid, msg.sender) returns (MessagingReceipt memory receipt) { if (_params.payInLzToken) revert Errors.LZ_LzTokenUnavailable(); address lzEndpoint = lzEndpointLookup[_params.receiver.bytes32ToAddress()]; require(lzEndpoint != address(0), "LayerZeroMock: destination LayerZero Endpoint not found"); // get the correct outbound nonce uint64 latestNonce = _outbound(msg.sender, _params.dstEid, _params.receiver); Packet memory packet = Packet({ nonce: latestNonce, srcEid: eid, sender: msg.sender, dstEid: _params.dstEid, receiver: _params.receiver, guid: GUID.generate(latestNonce, eid, msg.sender, _params.dstEid, _params.receiver), message: _params.message }); receipt.guid = packet.guid; receipt.nonce = packet.nonce; receipt.fee = _quote(_params, msg.sender); require(msg.value >= receipt.fee.nativeFee, "LayerZeroMock: not enough native for fees"); // refund if they send too much uint256 amount = msg.value - receipt.fee.nativeFee; if (amount > 0) { (bool success, ) = _refundAddress.call{ value: amount }(""); require(success, "LayerZeroMock: failed to refund"); } uint256 totalGas; uint256 dstAmount; (totalGas, dstAmount) = executeNativeAirDropAndReturnLzGas(_params.options); // TODO fix // composed calls with correct gas Origin memory origin = Origin({ srcEid: packet.srcEid, sender: packet.sender.addressToBytes32(), nonce: packet.nonce }); bytes memory payload = PacketV1Codec.encodePayload(packet); bytes32 payloadHash = keccak256(payload); EndpointV2Mock(lzEndpoint).receivePayload{ value: dstAmount }( origin, packet.receiver.bytes32ToAddress(), payloadHash, packet.message, totalGas, dstAmount, packet.guid ); } function receivePayload( Origin calldata _origin, address _receiver, bytes32 _payloadHash, bytes calldata _message, uint256 _gas, uint256 _msgValue, bytes32 _guid ) external payable receiveNonReentrant { inboundPayloadHash[_receiver][_origin.srcEid][_origin.sender][_origin.nonce] = _payloadHash; if (_msgValue > 0) { try ILayerZeroReceiver(_receiver).lzReceive{ value: _msgValue, gas: _gas }( _origin, _guid, _message, address(0), "" ) {} catch (bytes memory /*reason*/) {} } else { try ILayerZeroReceiver(_receiver).lzReceive{ gas: _gas }(_origin, _guid, _message, address(0), "") {} catch (bytes memory /*reason*/) {} } } function getExecutorFee(uint256 _payloadSize, bytes calldata _options) public view returns (uint256) { uint256 nativeFee; // 2) get Executor fee // a) decodeLzReceiveOption // b) decodeNativeDropOption // c) decodeLzComposeOption (uint256 totalDstAmount, uint256 totalGas) = _decodeExecutorOptions(_options); uint256 remoteGasTotal = relayerFeeConfig.dstGasPriceInWei * (relayerFeeConfig.baseGas + totalGas); nativeFee += totalDstAmount + remoteGasTotal; // tokenConversionRate = dstPrice / localPrice // basePrice = totalRemoteToken * tokenConversionRate uint256 basePrice = (nativeFee * relayerFeeConfig.dstPriceRatio) / 10 ** 10; // pricePerByte = (dstGasPriceInWei * gasPerBytes) * tokenConversionRate uint256 pricePerByte = ((relayerFeeConfig.dstGasPriceInWei * relayerFeeConfig.gasPerByte * relayerFeeConfig.dstPriceRatio) / 10 ** 10) * _payloadSize; return basePrice + pricePerByte; } function _quote( MessagingParams calldata _params, address /*_sender*/ ) internal view returns (MessagingFee memory messagingFee) { (bytes memory executorOptions, ) = splitOptions(_params.options); // 2) get Executor fee uint256 executorFee = this.getExecutorFee(_params.message.length, executorOptions); // 1) get Verifier fee // 3) get Treasury fee uint256 treasuryAndVerifierFee = _getTreasuryAndVerifierFees(executorFee, verifierFee); messagingFee.lzTokenFee = 0; messagingFee.nativeFee = executorFee + treasuryAndVerifierFee; } function _getTreasuryAndVerifierFees(uint256 _executorFee, uint256 _verifierFee) internal view returns (uint256) { return ((_executorFee + _verifierFee) * protocolFeeConfig.nativeBP) / 10000; } function _outbound(address _sender, uint32 _dstEid, bytes32 _receiver) internal returns (uint64 nonce) { unchecked { nonce = ++outboundNonce[_sender][_dstEid][_receiver]; } } function setDestLzEndpoint(address destAddr, address lzEndpointAddr) external { lzEndpointLookup[destAddr] = lzEndpointAddr; } function _decodeExecutorOptions( bytes calldata _options ) internal view returns (uint256 dstAmount, uint256 totalGas) { if (_options.length == 0) { revert IExecutorFeeLib.Executor_NoOptions(); } uint256 cursor = 0; totalGas = relayerFeeConfig.baseGas; while (cursor < _options.length) { (uint8 optionType, bytes calldata option, uint256 newCursor) = _options.nextExecutorOption(cursor); cursor = newCursor; if (optionType == ExecutorOptions.OPTION_TYPE_LZRECEIVE) { (uint128 gas, uint128 value) = ExecutorOptions.decodeLzReceiveOption(option); dstAmount += value; totalGas += gas; } else if (optionType == ExecutorOptions.OPTION_TYPE_NATIVE_DROP) { (uint128 nativeDropAmount, ) = ExecutorOptions.decodeNativeDropOption(option); dstAmount += nativeDropAmount; } else if (optionType == ExecutorOptions.OPTION_TYPE_LZCOMPOSE) { (, uint128 gas, uint128 value) = ExecutorOptions.decodeLzComposeOption(option); dstAmount += value; totalGas += gas; } else { revert IExecutorFeeLib.Executor_UnsupportedOptionType(optionType); } } if (cursor != _options.length) revert IExecutorFeeLib.Executor_InvalidExecutorOptions(cursor); if (dstAmount > relayerFeeConfig.dstNativeAmtCap) revert IExecutorFeeLib.Executor_NativeAmountExceedsCap(dstAmount, relayerFeeConfig.dstNativeAmtCap); } function splitOptions(bytes calldata _options) internal pure returns (bytes memory, WorkerOptions[] memory) { (bytes memory executorOpts, bytes memory dvnOpts) = decode(_options); if (dvnOpts.length == 0) { return (executorOpts, new WorkerOptions[](0)); } WorkerOptions[] memory workerOpts = new WorkerOptions[](1); workerOpts[0] = WorkerOptions(DVNOptions.WORKER_ID, dvnOpts); return (executorOpts, workerOpts); } function decode( bytes calldata _options ) internal pure returns (bytes memory executorOptions, bytes memory dvnOptions) { // at least 2 bytes for the option type, but can have no options if (_options.length < 2) revert UlnOptions.LZ_ULN_InvalidWorkerOptions(0); uint16 optionsType = uint16(bytes2(_options[0:2])); uint256 cursor = 2; // type3 options: [worker_option][worker_option]... // worker_option: [worker_id][option_size][option] // worker_id: uint8, option_size: uint16, option: bytes if (optionsType == UlnOptions.TYPE_3) { unchecked { uint256 start = cursor; uint8 lastWorkerId; // worker_id starts from 1, so 0 is an invalid worker_id // heuristic: we assume that the options are mostly EXECUTOR options only // checking the workerID can reduce gas usage for most cases while (cursor < _options.length) { uint8 workerId = uint8(bytes1(_options[cursor:cursor + 1])); if (workerId == 0) revert UlnOptions.LZ_ULN_InvalidWorkerId(0); // workerId must equal to the lastWorkerId for the first option // so it is always skipped in the first option // this operation slices out options whenever the scan finds a different workerId if (lastWorkerId == 0) { lastWorkerId = workerId; } else if (workerId != lastWorkerId) { bytes calldata op = _options[start:cursor]; // slice out the last worker's options (executorOptions, dvnOptions) = _insertWorkerOptions( executorOptions, dvnOptions, lastWorkerId, op ); // reset the start cursor and lastWorkerId start = cursor; lastWorkerId = workerId; } ++cursor; // for workerId uint16 size = uint16(bytes2(_options[cursor:cursor + 2])); if (size == 0) revert UlnOptions.LZ_ULN_InvalidWorkerOptions(cursor); cursor += size + 2; } // the options length must be the same as the cursor at the end if (cursor != _options.length) revert UlnOptions.LZ_ULN_InvalidWorkerOptions(cursor); // if we have reached the end of the options and the options are not empty // we need to process the last worker's options if (_options.length > 2) { bytes calldata op = _options[start:cursor]; (executorOptions, dvnOptions) = _insertWorkerOptions(executorOptions, dvnOptions, lastWorkerId, op); } } } else { executorOptions = decodeLegacyOptions(optionsType, _options); } } function _insertWorkerOptions( bytes memory _executorOptions, bytes memory _dvnOptions, uint8 _workerId, bytes calldata _newOptions ) private pure returns (bytes memory, bytes memory) { if (_workerId == ExecutorOptions.WORKER_ID) { _executorOptions = _executorOptions.length == 0 ? _newOptions : abi.encodePacked(_executorOptions, _newOptions); } else if (_workerId == DVNOptions.WORKER_ID) { _dvnOptions = _dvnOptions.length == 0 ? _newOptions : abi.encodePacked(_dvnOptions, _newOptions); } else { revert UlnOptions.LZ_ULN_InvalidWorkerId(_workerId); } return (_executorOptions, _dvnOptions); } function decodeLegacyOptions( uint16 _optionType, bytes calldata _options ) internal pure returns (bytes memory executorOptions) { if (_optionType == UlnOptions.TYPE_1) { if (_options.length != 34) revert UlnOptions.LZ_ULN_InvalidLegacyType1Option(); // execution gas uint128 executionGas = uint256(bytes32(_options[2:2 + 32])).toUint128(); // dont use the encode function in the ExecutorOptions lib for saving gas by calling abi.encodePacked once // the result is a lzReceive option: [executor_id][option_size][option_type][execution_gas] // option_type: uint8, execution_gas: uint128 // option_size = len(option_type) + len(execution_gas) = 1 + 16 = 17 executorOptions = abi.encodePacked( ExecutorOptions.WORKER_ID, uint16(17), // 16 + 1, 16 for option_length, + 1 for option_type ExecutorOptions.OPTION_TYPE_LZRECEIVE, executionGas ); } else if (_optionType == UlnOptions.TYPE_2) { // receiver size <= 32 if (_options.length <= 66 || _options.length > 98) revert UlnOptions.LZ_ULN_InvalidLegacyType2Option(); // execution gas uint128 executionGas = uint256(bytes32(_options[2:2 + 32])).toUint128(); // nativeDrop (amount + receiver) uint128 amount = uint256(bytes32(_options[34:34 + 32])).toUint128(); // offset 2 + 32 bytes32 receiver; unchecked { uint256 receiverLen = _options.length - 66; // offset 2 + 32 + 32 receiver = bytes32(_options[66:]); receiver = receiver >> (8 * (32 - receiverLen)); // padding 0 to the left } // dont use the encode function in the ExecutorOptions lib for saving gas by calling abi.encodePacked once // the result has one lzReceive option and one nativeDrop option: // [executor_id][lzReceive_option_size][option_type][execution_gas] + // [executor_id][nativeDrop_option_size][option_type][nativeDrop_amount][receiver] // option_type: uint8, execution_gas: uint128, nativeDrop_amount: uint128, receiver: bytes32 // lzReceive_option_size = len(option_type) + len(execution_gas) = 1 + 16 = 17 // nativeDrop_option_size = len(option_type) + len(nativeDrop_amount) + len(receiver) = 1 + 16 + 32 = 49 executorOptions = abi.encodePacked( ExecutorOptions.WORKER_ID, uint16(17), // 16 + 1, 16 for option_length, + 1 for option_type ExecutorOptions.OPTION_TYPE_LZRECEIVE, executionGas, ExecutorOptions.WORKER_ID, uint16(49), // 48 + 1, 32 + 16 for option_length, + 1 for option_type ExecutorOptions.OPTION_TYPE_NATIVE_DROP, amount, receiver ); } else { revert UlnOptions.LZ_ULN_UnsupportedOptionType(_optionType); } } // NOT IMPLEMENTING function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external {} function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external {} mapping(address from => mapping(address to => mapping(bytes32 guid => mapping(uint16 index => bytes32 messageHash)))) public composeQueue; function defaultReceiveLibrary(uint32 /*_eid*/) external pure returns (address) { return address(0); } function defaultReceiveLibraryTimeout(uint32 /*_eid*/) external pure returns (address lib, uint256 expiry) { return (address(0), 0); } function defaultSendLibrary(uint32 /*_eid*/) external pure returns (address) { return address(0); } function executable(Origin calldata /*_origin*/, address /*receiver*/) external pure returns (ExecutionState) { return ExecutionState.NotExecutable; } function getConfig( address /*_oapp*/, address /*_lib*/, uint32 /*_eid*/, uint32 /*_configType*/ ) external pure returns (bytes memory config) { return bytes("0x"); } function getReceiveLibrary( address /*receiver*/, uint32 /*_eid*/ ) external pure returns (address lib, bool isDefault) { return (address(0), false); } function getRegisteredLibraries() external pure returns (address[] memory) { address[] memory addresses = new address[](1); addresses[0] = address(0); return addresses; } function getSendLibrary(address /*_sender*/, uint32 /*_eid*/) external pure returns (address lib) { return address(0); } function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64) { return lazyInboundNonce[_receiver][_srcEid][_sender]; } function isDefaultSendLibrary(address /*_sender*/, uint32 /*_eid*/) external pure returns (bool) { return false; } function isRegisteredLibrary(address /*_lib*/) external pure returns (bool) { return false; } function isSupportedEid(uint32 /*_eid*/) external pure returns (bool) { return false; } function lzCompose( address /*_from,*/, address /*_to,*/, bytes32 /*_guid,*/, uint16 /*_index,*/, bytes calldata /*_message,*/, bytes calldata /*_extraData*/ ) external payable {} function lzReceive( Origin calldata /*_origin,*/, address /*_receiver,*/, bytes32 /*_guid,*/, bytes calldata /*_message,*/, bytes calldata /*_extraData*/ ) external payable {} function lzToken() external pure returns (address) { return address(0); } function nativeToken() external pure returns (address) { return address(0); } function nextGuid( address /*_sender,*/, uint32 /*_dstEid,*/, bytes32 /*_receiver*/ ) external pure returns (bytes32) { return 0; } function nilify( address /*_oapp,*/, uint32 /*_srcEid,*/, bytes32 /*_sender,*/, uint64 /*_nonce,*/, bytes32 /*_payloadHash*/ ) external {} function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory) { return _quote(_params, _sender); } mapping(address receiver => mapping(uint32 srcEid => Timeout)) public receiveLibraryTimeout; function registerLibrary(address /*_lib*/) public {} function sendCompose(address, /*_to*/ bytes32, /*_guid*/ uint16, /*_index*/ bytes calldata /*_message*/) external {} function setConfig(address, /*_oapp*/ address, /*_lib*/ SetConfigParam[] calldata /*_params*/) external {} function setDefaultReceiveLibrary(uint32 /*_eid*/, address /*_newLib*/, uint256 /*_gracePeriod*/) external {} function setDefaultReceiveLibraryTimeout(uint32 /*_eid*/, address /*_lib*/, uint256 /*_expiry*/) external {} function setDefaultSendLibrary(uint32 /*_eid*/, address /*_newLib*/) external {} function setDelegate(address /*_delegate*/) external {} function setLzToken(address /*_lzToken*/) external {} function setReceiveLibrary( address, /*_oapp*/ uint32, /*_eid*/ address, /*_newLib*/ uint256 /*_gracePeriod*/ ) external {} function setReceiveLibraryTimeout( address, /*_oapp*/ uint32, /*_eid*/ address, /*_lib*/ uint256 /*_gracePeriod*/ ) external {} function setSendLibrary(address, /*_oapp*/ uint32, /*_eid*/ address /*_newLib*/) external {} function skip(address, /*_oapp*/ uint32, /*_srcEid*/ bytes32, /*_sender*/ uint64 /*_nonce*/) external {} function verifiable( Origin calldata /*_origin*/, address /*_receiver*/, address /*_receiveLib*/, bytes32 /*_payloadHash*/ ) external pure returns (bool) { return false; } function verify(Origin calldata /*origin*/, address /*_receiver*/, bytes32 /*_payloadHash*/) external {} // Helper Functions function executeNativeAirDropAndReturnLzGas( bytes calldata _options ) public returns (uint256 totalGas, uint256 dstAmount) { (bytes memory executorOpts, ) = decode(_options); return this._executeNativeAirDropAndReturnLzGas(executorOpts); } function _executeNativeAirDropAndReturnLzGas( bytes calldata _options ) public returns (uint256 totalGas, uint256 dstAmount) { if (_options.length == 0) { revert IExecutorFeeLib.Executor_NoOptions(); } uint256 cursor = 0; while (cursor < _options.length) { (uint8 optionType, bytes calldata option, uint256 newCursor) = _options.nextExecutorOption(cursor); cursor = newCursor; if (optionType == ExecutorOptions.OPTION_TYPE_LZRECEIVE) { (uint128 gas, uint128 value) = ExecutorOptions.decodeLzReceiveOption(option); totalGas += gas; dstAmount += value; } else if (optionType == ExecutorOptions.OPTION_TYPE_NATIVE_DROP) { (uint128 nativeDropAmount, bytes32 receiver) = ExecutorOptions.decodeNativeDropOption(option); (bool success, ) = receiver.bytes32ToAddress().call{ value: nativeDropAmount }(""); if (!success) { emit ValueTransferFailed(receiver.bytes32ToAddress(), nativeDropAmount); } } else { revert IExecutorFeeLib.Executor_UnsupportedOptionType(optionType); } } if (cursor != _options.length) revert IExecutorFeeLib.Executor_InvalidExecutorOptions(cursor); } function _initializable( Origin calldata _origin, address _receiver, uint64 _lazyInboundNonce ) internal view returns (bool) { return _lazyInboundNonce > 0 || // allowInitializePath already checked ILayerZeroReceiver(_receiver).allowInitializePath(_origin); } /// @dev bytes(0) payloadHash can never be submitted function _verifiable( Origin calldata _origin, address _receiver, uint64 _lazyInboundNonce ) internal view returns (bool) { return _origin.nonce > _lazyInboundNonce || // either initializing an empty slot or reverifying inboundPayloadHash[_receiver][_origin.srcEid][_origin.sender][_origin.nonce] != EMPTY_PAYLOAD_HASH; // only allow reverifying if it hasn't been executed } // ========================= VIEW FUNCTIONS FOR OFFCHAIN ONLY ========================= // Not involved in any state transition function. // ==================================================================================== function initializable(Origin calldata _origin, address _receiver) external view returns (bool) { return _initializable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]); } function verifiable(Origin calldata _origin, address _receiver) external view returns (bool) { return _verifiable(_origin, _receiver, lazyInboundNonce[_receiver][_origin.srcEid][_origin.sender]); } /// @dev called when the endpoint checks if the msgLib attempting to verify the msg is the configured msgLib of the Oapp /// @dev this check provides the ability for Oapp to lock in a trusted msgLib /// @dev it will fist check if the msgLib is the currently configured one. then check if the msgLib is the one in grace period of msgLib versioning upgrade function isValidReceiveLibrary( address _receiver, uint32 _srcEid, address _actualReceiveLib ) public view returns (bool) { return true; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol) pragma solidity ^0.8.20; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ```solidity * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ```solidity * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules} * to enforce additional security measures for this role. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable { struct RoleData { mapping(address account => bool) hasRole; bytes32 adminRole; } bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /// @custom:storage-location erc7201:openzeppelin.storage.AccessControl struct AccessControlStorage { mapping(bytes32 role => RoleData) _roles; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800; function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) { assembly { $.slot := AccessControlStorageLocation } } /** * @dev Modifier that checks that an account has a specific role. Reverts * with an {AccessControlUnauthorizedAccount} error including the required role. */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); return $._roles[role].hasRole[account]; } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()` * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier. */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account` * is missing `role`. */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert AccessControlUnauthorizedAccount(account, role); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) { AccessControlStorage storage $ = _getAccessControlStorage(); return $._roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address callerConfirmation) public virtual { if (callerConfirmation != _msgSender()) { revert AccessControlBadConfirmation(); } _revokeRole(role, callerConfirmation); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { AccessControlStorage storage $ = _getAccessControlStorage(); bytes32 previousAdminRole = getRoleAdmin(role); $._roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); if (!hasRole(role, account)) { $._roles[role].hasRole[account] = true; emit RoleGranted(role, account, _msgSender()); return true; } else { return false; } } /** * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual returns (bool) { AccessControlStorage storage $ = _getAccessControlStorage(); if (hasRole(role, account)) { $._roles[role].hasRole[account] = false; emit RoleRevoked(role, account, _msgSender()); return true; } else { return false; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlDefaultAdminRules.sol) pragma solidity ^0.8.20; import {IAccessControlDefaultAdminRules} from "@openzeppelin/contracts/access/extensions/IAccessControlDefaultAdminRules.sol"; import {AccessControlUpgradeable} from "../AccessControlUpgradeable.sol"; import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol"; import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {IERC5313} from "@openzeppelin/contracts/interfaces/IERC5313.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Extension of {AccessControl} that allows specifying special rules to manage * the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions * over other roles that may potentially have privileged rights in the system. * * If a specific role doesn't have an admin role assigned, the holder of the * `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it. * * This contract implements the following risk mitigations on top of {AccessControl}: * * * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced. * * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account. * * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted. * * The delay can be changed by scheduling, see {changeDefaultAdminDelay}. * * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`. * * Example usage: * * ```solidity * contract MyToken is AccessControlDefaultAdminRules { * constructor() AccessControlDefaultAdminRules( * 3 days, * msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder * ) {} * } * ``` */ abstract contract AccessControlDefaultAdminRulesUpgradeable is Initializable, IAccessControlDefaultAdminRules, IERC5313, AccessControlUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.AccessControlDefaultAdminRules struct AccessControlDefaultAdminRulesStorage { // pending admin pair read/written together frequently address _pendingDefaultAdmin; uint48 _pendingDefaultAdminSchedule; // 0 == unset uint48 _currentDelay; address _currentDefaultAdmin; // pending delay pair read/written together frequently uint48 _pendingDelay; uint48 _pendingDelaySchedule; // 0 == unset } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControlDefaultAdminRules")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant AccessControlDefaultAdminRulesStorageLocation = 0xeef3dac4538c82c8ace4063ab0acd2d15cdb5883aa1dff7c2673abb3d8698400; function _getAccessControlDefaultAdminRulesStorage() private pure returns (AccessControlDefaultAdminRulesStorage storage $) { assembly { $.slot := AccessControlDefaultAdminRulesStorageLocation } } /** * @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address. */ function __AccessControlDefaultAdminRules_init(uint48 initialDelay, address initialDefaultAdmin) internal onlyInitializing { __AccessControlDefaultAdminRules_init_unchained(initialDelay, initialDefaultAdmin); } function __AccessControlDefaultAdminRules_init_unchained(uint48 initialDelay, address initialDefaultAdmin) internal onlyInitializing { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); if (initialDefaultAdmin == address(0)) { revert AccessControlInvalidDefaultAdmin(address(0)); } $._currentDelay = initialDelay; _grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC5313-owner}. */ function owner() public view virtual returns (address) { return defaultAdmin(); } /// /// Override AccessControl role management /// /** * @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`. */ function grantRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) { if (role == DEFAULT_ADMIN_ROLE) { revert AccessControlEnforcedDefaultAdminRules(); } super.grantRole(role, account); } /** * @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`. */ function revokeRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) { if (role == DEFAULT_ADMIN_ROLE) { revert AccessControlEnforcedDefaultAdminRules(); } super.revokeRole(role, account); } /** * @dev See {AccessControl-renounceRole}. * * For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling * {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule * has also passed when calling this function. * * After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions. * * NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin}, * thereby disabling any functionality that is only available for it, and the possibility of reassigning a * non-administrated role. */ function renounceRole(bytes32 role, address account) public virtual override(AccessControlUpgradeable, IAccessControl) { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { (address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin(); if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) { revert AccessControlEnforcedDefaultAdminDelay(schedule); } delete $._pendingDefaultAdminSchedule; } super.renounceRole(role, account); } /** * @dev See {AccessControl-_grantRole}. * * For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the * role has been previously renounced. * * NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE` * assignable again. Make sure to guarantee this is the expected behavior in your implementation. */ function _grantRole(bytes32 role, address account) internal virtual override returns (bool) { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); if (role == DEFAULT_ADMIN_ROLE) { if (defaultAdmin() != address(0)) { revert AccessControlEnforcedDefaultAdminRules(); } $._currentDefaultAdmin = account; } return super._grantRole(role, account); } /** * @dev See {AccessControl-_revokeRole}. */ function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { delete $._currentDefaultAdmin; } return super._revokeRole(role, account); } /** * @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override { if (role == DEFAULT_ADMIN_ROLE) { revert AccessControlEnforcedDefaultAdminRules(); } super._setRoleAdmin(role, adminRole); } /// /// AccessControlDefaultAdminRules accessors /// /** * @inheritdoc IAccessControlDefaultAdminRules */ function defaultAdmin() public view virtual returns (address) { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); return $._currentDefaultAdmin; } /** * @inheritdoc IAccessControlDefaultAdminRules */ function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); return ($._pendingDefaultAdmin, $._pendingDefaultAdminSchedule); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function defaultAdminDelay() public view virtual returns (uint48) { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); uint48 schedule = $._pendingDelaySchedule; return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? $._pendingDelay : $._currentDelay; } /** * @inheritdoc IAccessControlDefaultAdminRules */ function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); schedule = $._pendingDelaySchedule; return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? ($._pendingDelay, schedule) : (0, 0); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) { return 5 days; } /// /// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin /// /** * @inheritdoc IAccessControlDefaultAdminRules */ function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _beginDefaultAdminTransfer(newAdmin); } /** * @dev See {beginDefaultAdminTransfer}. * * Internal function without access restriction. */ function _beginDefaultAdminTransfer(address newAdmin) internal virtual { uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay(); _setPendingDefaultAdmin(newAdmin, newSchedule); emit DefaultAdminTransferScheduled(newAdmin, newSchedule); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _cancelDefaultAdminTransfer(); } /** * @dev See {cancelDefaultAdminTransfer}. * * Internal function without access restriction. */ function _cancelDefaultAdminTransfer() internal virtual { _setPendingDefaultAdmin(address(0), 0); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function acceptDefaultAdminTransfer() public virtual { (address newDefaultAdmin, ) = pendingDefaultAdmin(); if (_msgSender() != newDefaultAdmin) { // Enforce newDefaultAdmin explicit acceptance. revert AccessControlInvalidDefaultAdmin(_msgSender()); } _acceptDefaultAdminTransfer(); } /** * @dev See {acceptDefaultAdminTransfer}. * * Internal function without access restriction. */ function _acceptDefaultAdminTransfer() internal virtual { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); (address newAdmin, uint48 schedule) = pendingDefaultAdmin(); if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) { revert AccessControlEnforcedDefaultAdminDelay(schedule); } _revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin()); _grantRole(DEFAULT_ADMIN_ROLE, newAdmin); delete $._pendingDefaultAdmin; delete $._pendingDefaultAdminSchedule; } /// /// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay /// /** * @inheritdoc IAccessControlDefaultAdminRules */ function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _changeDefaultAdminDelay(newDelay); } /** * @dev See {changeDefaultAdminDelay}. * * Internal function without access restriction. */ function _changeDefaultAdminDelay(uint48 newDelay) internal virtual { uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay); _setPendingDelay(newDelay, newSchedule); emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _rollbackDefaultAdminDelay(); } /** * @dev See {rollbackDefaultAdminDelay}. * * Internal function without access restriction. */ function _rollbackDefaultAdminDelay() internal virtual { _setPendingDelay(0, 0); } /** * @dev Returns the amount of seconds to wait after the `newDelay` will * become the new {defaultAdminDelay}. * * The value returned guarantees that if the delay is reduced, it will go into effect * after a wait that honors the previously set delay. * * See {defaultAdminDelayIncreaseWait}. */ function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) { uint48 currentDelay = defaultAdminDelay(); // When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up // to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day // to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new // delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like // using milliseconds instead of seconds. // // When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees // that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled. // For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days. return newDelay > currentDelay ? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48 : currentDelay - newDelay; } /// /// Private setters /// /** * @dev Setter of the tuple for pending admin and its schedule. * * May emit a DefaultAdminTransferCanceled event. */ function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); (, uint48 oldSchedule) = pendingDefaultAdmin(); $._pendingDefaultAdmin = newAdmin; $._pendingDefaultAdminSchedule = newSchedule; // An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted. if (_isScheduleSet(oldSchedule)) { // Emit for implicit cancellations when another default admin was scheduled. emit DefaultAdminTransferCanceled(); } } /** * @dev Setter of the tuple for pending delay and its schedule. * * May emit a DefaultAdminDelayChangeCanceled event. */ function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private { AccessControlDefaultAdminRulesStorage storage $ = _getAccessControlDefaultAdminRulesStorage(); uint48 oldSchedule = $._pendingDelaySchedule; if (_isScheduleSet(oldSchedule)) { if (_hasSchedulePassed(oldSchedule)) { // Materialize a virtual delay $._currentDelay = $._pendingDelay; } else { // Emit for implicit cancellations when another delay was scheduled. emit DefaultAdminDelayChangeCanceled(); } } $._pendingDelay = newDelay; $._pendingDelaySchedule = newSchedule; } /// /// Private helpers /// /** * @dev Defines if an `schedule` is considered set. For consistency purposes. */ function _isScheduleSet(uint48 schedule) private pure returns (bool) { return schedule != 0; } /** * @dev Defines if an `schedule` is considered passed. For consistency purposes. */ function _hasSchedulePassed(uint48 schedule) private view returns (bool) { return schedule < block.timestamp; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol) pragma solidity ^0.8.20; import {OwnableUpgradeable} from "./OwnableUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is specified at deployment time in the constructor for `Ownable`. This * can later be changed with {transferOwnership} and {acceptOwnership}. * * This module is used through inheritance. It will make available all functions * from parent (Ownable). */ abstract contract Ownable2StepUpgradeable is Initializable, OwnableUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.Ownable2Step struct Ownable2StepStorage { address _pendingOwner; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable2Step")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant Ownable2StepStorageLocation = 0x237e158222e3e6968b72b9db0d8043aacf074ad9f650f0d1606b4d82ee432c00; function _getOwnable2StepStorage() private pure returns (Ownable2StepStorage storage $) { assembly { $.slot := Ownable2StepStorageLocation } } event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner); function __Ownable2Step_init() internal onlyInitializing { } function __Ownable2Step_init_unchained() internal onlyInitializing { } /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { Ownable2StepStorage storage $ = _getOwnable2StepStorage(); return $._pendingOwner; } /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { Ownable2StepStorage storage $ = _getOwnable2StepStorage(); $._pendingOwner = newOwner; emit OwnershipTransferStarted(owner(), newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner. * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual override { Ownable2StepStorage storage $ = _getOwnable2StepStorage(); delete $._pendingOwner; super._transferOwnership(newOwner); } /** * @dev The new owner accepts the ownership transfer. */ function acceptOwnership() public virtual { address sender = _msgSender(); if (pendingOwner() != sender) { revert OwnableUnauthorizedAccount(sender); } _transferOwnership(sender); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev 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 initial owner is set to the address provided by the deployer. This can * later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.Ownable struct OwnableStorage { address _owner; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Ownable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant OwnableStorageLocation = 0x9016d09d72d40fdae2fd8ceac6b6234c7706214fd39c1cd1e609a0528c199300; function _getOwnableStorage() private pure returns (OwnableStorage storage $) { assembly { $.slot := OwnableStorageLocation } } /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ function __Ownable_init(address initialOwner) internal onlyInitializing { __Ownable_init_unchained(initialOwner); } function __Ownable_init_unchained(address initialOwner) internal onlyInitializing { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { OwnableStorage storage $ = _getOwnableStorage(); return $._owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { OwnableStorage storage $ = _getOwnableStorage(); address oldOwner = $._owner; $._owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.20; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ```solidity * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Storage of the initializable contract. * * It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions * when using with upgradeable contracts. * * @custom:storage-location erc7201:openzeppelin.storage.Initializable */ struct InitializableStorage { /** * @dev Indicates that the contract has been initialized. */ uint64 _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool _initializing; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00; /** * @dev The contract is already initialized. */ error InvalidInitialization(); /** * @dev The contract is not initializing. */ error NotInitializing(); /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint64 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. * * Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any * number of times. This behavior in the constructor can be useful during testing and is not expected to be used in * production. * * Emits an {Initialized} event. */ modifier initializer() { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); // Cache values to avoid duplicated sloads bool isTopLevelCall = !$._initializing; uint64 initialized = $._initialized; // Allowed calls: // - initialSetup: the contract is not in the initializing state and no previous version was // initialized // - construction: the contract is initialized at version 1 (no reininitialization) and the // current contract is just being deployed bool initialSetup = initialized == 0 && isTopLevelCall; bool construction = initialized == 1 && address(this).code.length == 0; if (!initialSetup && !construction) { revert InvalidInitialization(); } $._initialized = 1; if (isTopLevelCall) { $._initializing = true; } _; if (isTopLevelCall) { $._initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * A reinitializer may be used after the original initialization step. This is essential to configure modules that * are added through upgrades and that require initialization. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. * * WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization. * * Emits an {Initialized} event. */ modifier reinitializer(uint64 version) { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing || $._initialized >= version) { revert InvalidInitialization(); } $._initialized = version; $._initializing = true; _; $._initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { _checkInitializing(); _; } /** * @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}. */ function _checkInitializing() internal view virtual { if (!_isInitializing()) { revert NotInitializing(); } } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { // solhint-disable-next-line var-name-mixedcase InitializableStorage storage $ = _getInitializableStorage(); if ($._initializing) { revert InvalidInitialization(); } if ($._initialized != type(uint64).max) { $._initialized = type(uint64).max; emit Initialized(type(uint64).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint64) { return _getInitializableStorage()._initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _getInitializableStorage()._initializing; } /** * @dev Returns a pointer to the storage namespace. */ // solhint-disable-next-line var-name-mixedcase function _getInitializableStorage() private pure returns (InitializableStorage storage $) { assembly { $.slot := INITIALIZABLE_STORAGE } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol"; import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. */ abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors { /// @custom:storage-location erc7201:openzeppelin.storage.ERC20 struct ERC20Storage { mapping(address account => uint256) _balances; mapping(address account => mapping(address spender => uint256)) _allowances; uint256 _totalSupply; string _name; string _symbol; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00; function _getERC20Storage() private pure returns (ERC20Storage storage $) { assembly { $.slot := ERC20StorageLocation } } /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { ERC20Storage storage $ = _getERC20Storage(); $._name = name_; $._symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { ERC20Storage storage $ = _getERC20Storage(); return $._symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { ERC20Storage storage $ = _getERC20Storage(); return $._allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows $._totalSupply += value; } else { uint256 fromBalance = $._balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. $._balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. $._totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. $._balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * ``` * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { ERC20Storage storage $ = _getERC20Storage(); if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } $._allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Pausable.sol) pragma solidity ^0.8.20; import {ERC20Upgradeable} from "../ERC20Upgradeable.sol"; import {PausableUpgradeable} from "../../../utils/PausableUpgradeable.sol"; import {Initializable} from "../../../proxy/utils/Initializable.sol"; /** * @dev ERC20 token with pausable token transfers, minting and burning. * * Useful for scenarios such as preventing trades until the end of an evaluation * period, or having an emergency switch for freezing all token transfers in the * event of a large bug. * * IMPORTANT: This contract does not include public pause and unpause functions. In * addition to inheriting this contract, you must define both functions, invoking the * {Pausable-_pause} and {Pausable-_unpause} internal functions, with appropriate * access control, e.g. using {AccessControl} or {Ownable}. Not doing so will * make the contract pause mechanism of the contract unreachable, and thus unusable. */ abstract contract ERC20PausableUpgradeable is Initializable, ERC20Upgradeable, PausableUpgradeable { function __ERC20Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __ERC20Pausable_init_unchained() internal onlyInitializing { } /** * @dev See {ERC20-_update}. * * Requirements: * * - the contract must not be paused. */ function _update(address from, address to, uint256 value) internal virtual override whenNotPaused { super._update(from, to, value); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol) pragma solidity ^0.8.20; import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol"; import {ERC20Upgradeable} from "../ERC20Upgradeable.sol"; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; import {EIP712Upgradeable} from "../../../utils/cryptography/EIP712Upgradeable.sol"; import {NoncesUpgradeable} from "../../../utils/NoncesUpgradeable.sol"; import {Initializable} from "../../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20Permit, EIP712Upgradeable, NoncesUpgradeable { bytes32 private constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Permit deadline has expired. */ error ERC2612ExpiredSignature(uint256 deadline); /** * @dev Mismatched signature. */ error ERC2612InvalidSigner(address signer, address owner); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ function __ERC20Permit_init(string memory name) internal onlyInitializing { __EIP712_init_unchained(name, "1"); } function __ERC20Permit_init_unchained(string memory) internal onlyInitializing {} /** * @inheritdoc IERC20Permit */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { if (block.timestamp > deadline) { revert ERC2612ExpiredSignature(deadline); } bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); if (signer != owner) { revert ERC2612InvalidSigner(signer, owner); } _approve(owner, spender, value); } /** * @inheritdoc IERC20Permit */ function nonces(address owner) public view virtual override(IERC20Permit, NoncesUpgradeable) returns (uint256) { return super.nonces(owner); } /** * @inheritdoc IERC20Permit */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view virtual returns (bytes32) { return _domainSeparatorV4(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.20; import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol"; import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. */ abstract contract EIP712Upgradeable is Initializable, IERC5267 { bytes32 private constant TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); /// @custom:storage-location erc7201:openzeppelin.storage.EIP712 struct EIP712Storage { /// @custom:oz-renamed-from _HASHED_NAME bytes32 _hashedName; /// @custom:oz-renamed-from _HASHED_VERSION bytes32 _hashedVersion; string _name; string _version; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100; function _getEIP712Storage() private pure returns (EIP712Storage storage $) { assembly { $.slot := EIP712StorageLocation } } /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ function __EIP712_init(string memory name, string memory version) internal onlyInitializing { __EIP712_init_unchained(name, version); } function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing { EIP712Storage storage $ = _getEIP712Storage(); $._name = name; $._version = version; // Reset prior values in storage if upgrading $._hashedName = 0; $._hashedVersion = 0; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { return _buildDomainSeparator(); } function _buildDomainSeparator() private view returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev See {IERC-5267}. */ function eip712Domain() public view virtual returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { EIP712Storage storage $ = _getEIP712Storage(); // If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized // and the EIP712 domain is not reliable, as it will be missing name and version. require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized"); return ( hex"0f", // 01111 _EIP712Name(), _EIP712Version(), block.chainid, address(this), bytes32(0), new uint256[](0) ); } /** * @dev The name parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712Name() internal view virtual returns (string memory) { EIP712Storage storage $ = _getEIP712Storage(); return $._name; } /** * @dev The version parameter for the EIP712 domain. * * NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs * are a concern. */ function _EIP712Version() internal view virtual returns (string memory) { EIP712Storage storage $ = _getEIP712Storage(); return $._version; } /** * @dev The hash of the name parameter for the EIP712 domain. * * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead. */ function _EIP712NameHash() internal view returns (bytes32) { EIP712Storage storage $ = _getEIP712Storage(); string memory name = _EIP712Name(); if (bytes(name).length > 0) { return keccak256(bytes(name)); } else { // If the name is empty, the contract may have been upgraded without initializing the new storage. // We return the name hash in storage if non-zero, otherwise we assume the name is empty by design. bytes32 hashedName = $._hashedName; if (hashedName != 0) { return hashedName; } else { return keccak256(""); } } } /** * @dev The hash of the version parameter for the EIP712 domain. * * NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead. */ function _EIP712VersionHash() internal view returns (bytes32) { EIP712Storage storage $ = _getEIP712Storage(); string memory version = _EIP712Version(); if (bytes(version).length > 0) { return keccak256(bytes(version)); } else { // If the version is empty, the contract may have been upgraded without initializing the new storage. // We return the version hash in storage if non-zero, otherwise we assume the version is empty by design. bytes32 hashedVersion = $._hashedVersion; if (hashedVersion != 0) { return hashedVersion; } else { return keccak256(""); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol"; import {Initializable} from "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */ abstract contract ERC165Upgradeable is Initializable, IERC165 { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Provides tracking nonces for addresses. Nonces will only increment. */ abstract contract NoncesUpgradeable is Initializable { /** * @dev The nonce used for an `account` is not the expected current nonce. */ error InvalidAccountNonce(address account, uint256 currentNonce); /// @custom:storage-location erc7201:openzeppelin.storage.Nonces struct NoncesStorage { mapping(address account => uint256) _nonces; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Nonces")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant NoncesStorageLocation = 0x5ab42ced628888259c08ac98db1eb0cf702fc1501344311d8b100cd1bfe4bb00; function _getNoncesStorage() private pure returns (NoncesStorage storage $) { assembly { $.slot := NoncesStorageLocation } } function __Nonces_init() internal onlyInitializing { } function __Nonces_init_unchained() internal onlyInitializing { } /** * @dev Returns the next unused nonce for an address. */ function nonces(address owner) public view virtual returns (uint256) { NoncesStorage storage $ = _getNoncesStorage(); return $._nonces[owner]; } /** * @dev Consumes a nonce. * * Returns the current value and increments nonce. */ function _useNonce(address owner) internal virtual returns (uint256) { NoncesStorage storage $ = _getNoncesStorage(); // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be // decremented or reset. This guarantees that the nonce never overflows. unchecked { // It is important to do x++ and not ++x here. return $._nonces[owner]++; } } /** * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`. */ function _useCheckedNonce(address owner, uint256 nonce) internal virtual { uint256 current = _useNonce(owner); if (nonce != current) { revert InvalidAccountNonce(owner, current); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol) pragma solidity ^0.8.20; import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol"; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /// @custom:storage-location erc7201:openzeppelin.storage.Pausable struct PausableStorage { bool _paused; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300; function _getPausableStorage() private pure returns (PausableStorage storage $) { assembly { $.slot := PausableStorageLocation } } /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); /** * @dev The operation failed because the contract is paused. */ error EnforcedPause(); /** * @dev The operation failed because the contract is not paused. */ error ExpectedPause(); /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { PausableStorage storage $ = _getPausableStorage(); $._paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { PausableStorage storage $ = _getPausableStorage(); return $._paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { if (paused()) { revert EnforcedPause(); } } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { if (!paused()) { revert ExpectedPause(); } } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { PausableStorage storage $ = _getPausableStorage(); $._paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { PausableStorage storage $ = _getPausableStorage(); $._paused = false; emit Unpaused(_msgSender()); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol) pragma solidity ^0.8.20; import {Initializable} from "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = 2; /// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard struct ReentrancyGuardStorage { uint256 _status; } // keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00; function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) { assembly { $.slot := ReentrancyGuardStorageLocation } } /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); $._status = NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); // On the first call to nonReentrant, _status will be NOT_ENTERED if ($._status == ENTERED) { revert ReentrancyGuardReentrantCall(); } // Any calls to nonReentrant after this point will fail $._status = ENTERED; } function _nonReentrantAfter() private { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) $._status = NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage(); return $._status == ENTERED; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol) pragma solidity ^0.8.20; import {IAccessControl} from "./IAccessControl.sol"; import {Context} from "../utils/Context.sol"; import {ERC165} from "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ```solidity * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ```solidity * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules} * to enforce additional security measures for this role. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address account => bool) hasRole; bytes32 adminRole; } mapping(bytes32 role => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with an {AccessControlUnauthorizedAccount} error including the required role. */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual returns (bool) { return _roles[role].hasRole[account]; } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()` * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier. */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account` * is missing `role`. */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert AccessControlUnauthorizedAccount(account, role); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleGranted} event. */ function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. * * May emit a {RoleRevoked} event. */ function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. * * May emit a {RoleRevoked} event. */ function renounceRole(bytes32 role, address callerConfirmation) public virtual { if (callerConfirmation != _msgSender()) { revert AccessControlBadConfirmation(); } _revokeRole(role, callerConfirmation); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted. * * Internal function without access restriction. * * May emit a {RoleGranted} event. */ function _grantRole(bytes32 role, address account) internal virtual returns (bool) { if (!hasRole(role, account)) { _roles[role].hasRole[account] = true; emit RoleGranted(role, account, _msgSender()); return true; } else { return false; } } /** * @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked. * * Internal function without access restriction. * * May emit a {RoleRevoked} event. */ function _revokeRole(bytes32 role, address account) internal virtual returns (bool) { if (hasRole(role, account)) { _roles[role].hasRole[account] = false; emit RoleRevoked(role, account, _msgSender()); return true; } else { return false; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/AccessControlDefaultAdminRules.sol) pragma solidity ^0.8.20; import {IAccessControlDefaultAdminRules} from "./IAccessControlDefaultAdminRules.sol"; import {AccessControl, IAccessControl} from "../AccessControl.sol"; import {SafeCast} from "../../utils/math/SafeCast.sol"; import {Math} from "../../utils/math/Math.sol"; import {IERC5313} from "../../interfaces/IERC5313.sol"; /** * @dev Extension of {AccessControl} that allows specifying special rules to manage * the `DEFAULT_ADMIN_ROLE` holder, which is a sensitive role with special permissions * over other roles that may potentially have privileged rights in the system. * * If a specific role doesn't have an admin role assigned, the holder of the * `DEFAULT_ADMIN_ROLE` will have the ability to grant it and revoke it. * * This contract implements the following risk mitigations on top of {AccessControl}: * * * Only one account holds the `DEFAULT_ADMIN_ROLE` since deployment until it's potentially renounced. * * Enforces a 2-step process to transfer the `DEFAULT_ADMIN_ROLE` to another account. * * Enforces a configurable delay between the two steps, with the ability to cancel before the transfer is accepted. * * The delay can be changed by scheduling, see {changeDefaultAdminDelay}. * * It is not possible to use another role to manage the `DEFAULT_ADMIN_ROLE`. * * Example usage: * * ```solidity * contract MyToken is AccessControlDefaultAdminRules { * constructor() AccessControlDefaultAdminRules( * 3 days, * msg.sender // Explicit initial `DEFAULT_ADMIN_ROLE` holder * ) {} * } * ``` */ abstract contract AccessControlDefaultAdminRules is IAccessControlDefaultAdminRules, IERC5313, AccessControl { // pending admin pair read/written together frequently address private _pendingDefaultAdmin; uint48 private _pendingDefaultAdminSchedule; // 0 == unset uint48 private _currentDelay; address private _currentDefaultAdmin; // pending delay pair read/written together frequently uint48 private _pendingDelay; uint48 private _pendingDelaySchedule; // 0 == unset /** * @dev Sets the initial values for {defaultAdminDelay} and {defaultAdmin} address. */ constructor(uint48 initialDelay, address initialDefaultAdmin) { if (initialDefaultAdmin == address(0)) { revert AccessControlInvalidDefaultAdmin(address(0)); } _currentDelay = initialDelay; _grantRole(DEFAULT_ADMIN_ROLE, initialDefaultAdmin); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlDefaultAdminRules).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC5313-owner}. */ function owner() public view virtual returns (address) { return defaultAdmin(); } /// /// Override AccessControl role management /// /** * @dev See {AccessControl-grantRole}. Reverts for `DEFAULT_ADMIN_ROLE`. */ function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { if (role == DEFAULT_ADMIN_ROLE) { revert AccessControlEnforcedDefaultAdminRules(); } super.grantRole(role, account); } /** * @dev See {AccessControl-revokeRole}. Reverts for `DEFAULT_ADMIN_ROLE`. */ function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { if (role == DEFAULT_ADMIN_ROLE) { revert AccessControlEnforcedDefaultAdminRules(); } super.revokeRole(role, account); } /** * @dev See {AccessControl-renounceRole}. * * For the `DEFAULT_ADMIN_ROLE`, it only allows renouncing in two steps by first calling * {beginDefaultAdminTransfer} to the `address(0)`, so it's required that the {pendingDefaultAdmin} schedule * has also passed when calling this function. * * After its execution, it will not be possible to call `onlyRole(DEFAULT_ADMIN_ROLE)` functions. * * NOTE: Renouncing `DEFAULT_ADMIN_ROLE` will leave the contract without a {defaultAdmin}, * thereby disabling any functionality that is only available for it, and the possibility of reassigning a * non-administrated role. */ function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) { if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { (address newDefaultAdmin, uint48 schedule) = pendingDefaultAdmin(); if (newDefaultAdmin != address(0) || !_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) { revert AccessControlEnforcedDefaultAdminDelay(schedule); } delete _pendingDefaultAdminSchedule; } super.renounceRole(role, account); } /** * @dev See {AccessControl-_grantRole}. * * For `DEFAULT_ADMIN_ROLE`, it only allows granting if there isn't already a {defaultAdmin} or if the * role has been previously renounced. * * NOTE: Exposing this function through another mechanism may make the `DEFAULT_ADMIN_ROLE` * assignable again. Make sure to guarantee this is the expected behavior in your implementation. */ function _grantRole(bytes32 role, address account) internal virtual override returns (bool) { if (role == DEFAULT_ADMIN_ROLE) { if (defaultAdmin() != address(0)) { revert AccessControlEnforcedDefaultAdminRules(); } _currentDefaultAdmin = account; } return super._grantRole(role, account); } /** * @dev See {AccessControl-_revokeRole}. */ function _revokeRole(bytes32 role, address account) internal virtual override returns (bool) { if (role == DEFAULT_ADMIN_ROLE && account == defaultAdmin()) { delete _currentDefaultAdmin; } return super._revokeRole(role, account); } /** * @dev See {AccessControl-_setRoleAdmin}. Reverts for `DEFAULT_ADMIN_ROLE`. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual override { if (role == DEFAULT_ADMIN_ROLE) { revert AccessControlEnforcedDefaultAdminRules(); } super._setRoleAdmin(role, adminRole); } /// /// AccessControlDefaultAdminRules accessors /// /** * @inheritdoc IAccessControlDefaultAdminRules */ function defaultAdmin() public view virtual returns (address) { return _currentDefaultAdmin; } /** * @inheritdoc IAccessControlDefaultAdminRules */ function pendingDefaultAdmin() public view virtual returns (address newAdmin, uint48 schedule) { return (_pendingDefaultAdmin, _pendingDefaultAdminSchedule); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function defaultAdminDelay() public view virtual returns (uint48) { uint48 schedule = _pendingDelaySchedule; return (_isScheduleSet(schedule) && _hasSchedulePassed(schedule)) ? _pendingDelay : _currentDelay; } /** * @inheritdoc IAccessControlDefaultAdminRules */ function pendingDefaultAdminDelay() public view virtual returns (uint48 newDelay, uint48 schedule) { schedule = _pendingDelaySchedule; return (_isScheduleSet(schedule) && !_hasSchedulePassed(schedule)) ? (_pendingDelay, schedule) : (0, 0); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function defaultAdminDelayIncreaseWait() public view virtual returns (uint48) { return 5 days; } /// /// AccessControlDefaultAdminRules public and internal setters for defaultAdmin/pendingDefaultAdmin /// /** * @inheritdoc IAccessControlDefaultAdminRules */ function beginDefaultAdminTransfer(address newAdmin) public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _beginDefaultAdminTransfer(newAdmin); } /** * @dev See {beginDefaultAdminTransfer}. * * Internal function without access restriction. */ function _beginDefaultAdminTransfer(address newAdmin) internal virtual { uint48 newSchedule = SafeCast.toUint48(block.timestamp) + defaultAdminDelay(); _setPendingDefaultAdmin(newAdmin, newSchedule); emit DefaultAdminTransferScheduled(newAdmin, newSchedule); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function cancelDefaultAdminTransfer() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _cancelDefaultAdminTransfer(); } /** * @dev See {cancelDefaultAdminTransfer}. * * Internal function without access restriction. */ function _cancelDefaultAdminTransfer() internal virtual { _setPendingDefaultAdmin(address(0), 0); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function acceptDefaultAdminTransfer() public virtual { (address newDefaultAdmin, ) = pendingDefaultAdmin(); if (_msgSender() != newDefaultAdmin) { // Enforce newDefaultAdmin explicit acceptance. revert AccessControlInvalidDefaultAdmin(_msgSender()); } _acceptDefaultAdminTransfer(); } /** * @dev See {acceptDefaultAdminTransfer}. * * Internal function without access restriction. */ function _acceptDefaultAdminTransfer() internal virtual { (address newAdmin, uint48 schedule) = pendingDefaultAdmin(); if (!_isScheduleSet(schedule) || !_hasSchedulePassed(schedule)) { revert AccessControlEnforcedDefaultAdminDelay(schedule); } _revokeRole(DEFAULT_ADMIN_ROLE, defaultAdmin()); _grantRole(DEFAULT_ADMIN_ROLE, newAdmin); delete _pendingDefaultAdmin; delete _pendingDefaultAdminSchedule; } /// /// AccessControlDefaultAdminRules public and internal setters for defaultAdminDelay/pendingDefaultAdminDelay /// /** * @inheritdoc IAccessControlDefaultAdminRules */ function changeDefaultAdminDelay(uint48 newDelay) public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _changeDefaultAdminDelay(newDelay); } /** * @dev See {changeDefaultAdminDelay}. * * Internal function without access restriction. */ function _changeDefaultAdminDelay(uint48 newDelay) internal virtual { uint48 newSchedule = SafeCast.toUint48(block.timestamp) + _delayChangeWait(newDelay); _setPendingDelay(newDelay, newSchedule); emit DefaultAdminDelayChangeScheduled(newDelay, newSchedule); } /** * @inheritdoc IAccessControlDefaultAdminRules */ function rollbackDefaultAdminDelay() public virtual onlyRole(DEFAULT_ADMIN_ROLE) { _rollbackDefaultAdminDelay(); } /** * @dev See {rollbackDefaultAdminDelay}. * * Internal function without access restriction. */ function _rollbackDefaultAdminDelay() internal virtual { _setPendingDelay(0, 0); } /** * @dev Returns the amount of seconds to wait after the `newDelay` will * become the new {defaultAdminDelay}. * * The value returned guarantees that if the delay is reduced, it will go into effect * after a wait that honors the previously set delay. * * See {defaultAdminDelayIncreaseWait}. */ function _delayChangeWait(uint48 newDelay) internal view virtual returns (uint48) { uint48 currentDelay = defaultAdminDelay(); // When increasing the delay, we schedule the delay change to occur after a period of "new delay" has passed, up // to a maximum given by defaultAdminDelayIncreaseWait, by default 5 days. For example, if increasing from 1 day // to 3 days, the new delay will come into effect after 3 days. If increasing from 1 day to 10 days, the new // delay will come into effect after 5 days. The 5 day wait period is intended to be able to fix an error like // using milliseconds instead of seconds. // // When decreasing the delay, we wait the difference between "current delay" and "new delay". This guarantees // that an admin transfer cannot be made faster than "current delay" at the time the delay change is scheduled. // For example, if decreasing from 10 days to 3 days, the new delay will come into effect after 7 days. return newDelay > currentDelay ? uint48(Math.min(newDelay, defaultAdminDelayIncreaseWait())) // no need to safecast, both inputs are uint48 : currentDelay - newDelay; } /// /// Private setters /// /** * @dev Setter of the tuple for pending admin and its schedule. * * May emit a DefaultAdminTransferCanceled event. */ function _setPendingDefaultAdmin(address newAdmin, uint48 newSchedule) private { (, uint48 oldSchedule) = pendingDefaultAdmin(); _pendingDefaultAdmin = newAdmin; _pendingDefaultAdminSchedule = newSchedule; // An `oldSchedule` from `pendingDefaultAdmin()` is only set if it hasn't been accepted. if (_isScheduleSet(oldSchedule)) { // Emit for implicit cancellations when another default admin was scheduled. emit DefaultAdminTransferCanceled(); } } /** * @dev Setter of the tuple for pending delay and its schedule. * * May emit a DefaultAdminDelayChangeCanceled event. */ function _setPendingDelay(uint48 newDelay, uint48 newSchedule) private { uint48 oldSchedule = _pendingDelaySchedule; if (_isScheduleSet(oldSchedule)) { if (_hasSchedulePassed(oldSchedule)) { // Materialize a virtual delay _currentDelay = _pendingDelay; } else { // Emit for implicit cancellations when another delay was scheduled. emit DefaultAdminDelayChangeCanceled(); } } _pendingDelay = newDelay; _pendingDelaySchedule = newSchedule; } /// /// Private helpers /// /** * @dev Defines if an `schedule` is considered set. For consistency purposes. */ function _isScheduleSet(uint48 schedule) private pure returns (bool) { return schedule != 0; } /** * @dev Defines if an `schedule` is considered passed. For consistency purposes. */ function _hasSchedulePassed(uint48 schedule) private view returns (bool) { return schedule < block.timestamp; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/extensions/IAccessControlDefaultAdminRules.sol) pragma solidity ^0.8.20; import {IAccessControl} from "../IAccessControl.sol"; /** * @dev External interface of AccessControlDefaultAdminRules declared to support ERC165 detection. */ interface IAccessControlDefaultAdminRules is IAccessControl { /** * @dev The new default admin is not a valid default admin. */ error AccessControlInvalidDefaultAdmin(address defaultAdmin); /** * @dev At least one of the following rules was violated: * * - The `DEFAULT_ADMIN_ROLE` must only be managed by itself. * - The `DEFAULT_ADMIN_ROLE` must only be held by one account at the time. * - Any `DEFAULT_ADMIN_ROLE` transfer must be in two delayed steps. */ error AccessControlEnforcedDefaultAdminRules(); /** * @dev The delay for transferring the default admin delay is enforced and * the operation must wait until `schedule`. * * NOTE: `schedule` can be 0 indicating there's no transfer scheduled. */ error AccessControlEnforcedDefaultAdminDelay(uint48 schedule); /** * @dev Emitted when a {defaultAdmin} transfer is started, setting `newAdmin` as the next * address to become the {defaultAdmin} by calling {acceptDefaultAdminTransfer} only after `acceptSchedule` * passes. */ event DefaultAdminTransferScheduled(address indexed newAdmin, uint48 acceptSchedule); /** * @dev Emitted when a {pendingDefaultAdmin} is reset if it was never accepted, regardless of its schedule. */ event DefaultAdminTransferCanceled(); /** * @dev Emitted when a {defaultAdminDelay} change is started, setting `newDelay` as the next * delay to be applied between default admin transfer after `effectSchedule` has passed. */ event DefaultAdminDelayChangeScheduled(uint48 newDelay, uint48 effectSchedule); /** * @dev Emitted when a {pendingDefaultAdminDelay} is reset if its schedule didn't pass. */ event DefaultAdminDelayChangeCanceled(); /** * @dev Returns the address of the current `DEFAULT_ADMIN_ROLE` holder. */ function defaultAdmin() external view returns (address); /** * @dev Returns a tuple of a `newAdmin` and an accept schedule. * * After the `schedule` passes, the `newAdmin` will be able to accept the {defaultAdmin} role * by calling {acceptDefaultAdminTransfer}, completing the role transfer. * * A zero value only in `acceptSchedule` indicates no pending admin transfer. * * NOTE: A zero address `newAdmin` means that {defaultAdmin} is being renounced. */ function pendingDefaultAdmin() external view returns (address newAdmin, uint48 acceptSchedule); /** * @dev Returns the delay required to schedule the acceptance of a {defaultAdmin} transfer started. * * This delay will be added to the current timestamp when calling {beginDefaultAdminTransfer} to set * the acceptance schedule. * * NOTE: If a delay change has been scheduled, it will take effect as soon as the schedule passes, making this * function returns the new delay. See {changeDefaultAdminDelay}. */ function defaultAdminDelay() external view returns (uint48); /** * @dev Returns a tuple of `newDelay` and an effect schedule. * * After the `schedule` passes, the `newDelay` will get into effect immediately for every * new {defaultAdmin} transfer started with {beginDefaultAdminTransfer}. * * A zero value only in `effectSchedule` indicates no pending delay change. * * NOTE: A zero value only for `newDelay` means that the next {defaultAdminDelay} * will be zero after the effect schedule. */ function pendingDefaultAdminDelay() external view returns (uint48 newDelay, uint48 effectSchedule); /** * @dev Starts a {defaultAdmin} transfer by setting a {pendingDefaultAdmin} scheduled for acceptance * after the current timestamp plus a {defaultAdminDelay}. * * Requirements: * * - Only can be called by the current {defaultAdmin}. * * Emits a DefaultAdminRoleChangeStarted event. */ function beginDefaultAdminTransfer(address newAdmin) external; /** * @dev Cancels a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}. * * A {pendingDefaultAdmin} not yet accepted can also be cancelled with this function. * * Requirements: * * - Only can be called by the current {defaultAdmin}. * * May emit a DefaultAdminTransferCanceled event. */ function cancelDefaultAdminTransfer() external; /** * @dev Completes a {defaultAdmin} transfer previously started with {beginDefaultAdminTransfer}. * * After calling the function: * * - `DEFAULT_ADMIN_ROLE` should be granted to the caller. * - `DEFAULT_ADMIN_ROLE` should be revoked from the previous holder. * - {pendingDefaultAdmin} should be reset to zero values. * * Requirements: * * - Only can be called by the {pendingDefaultAdmin}'s `newAdmin`. * - The {pendingDefaultAdmin}'s `acceptSchedule` should've passed. */ function acceptDefaultAdminTransfer() external; /** * @dev Initiates a {defaultAdminDelay} update by setting a {pendingDefaultAdminDelay} scheduled for getting * into effect after the current timestamp plus a {defaultAdminDelay}. * * This function guarantees that any call to {beginDefaultAdminTransfer} done between the timestamp this * method is called and the {pendingDefaultAdminDelay} effect schedule will use the current {defaultAdminDelay} * set before calling. * * The {pendingDefaultAdminDelay}'s effect schedule is defined in a way that waiting until the schedule and then * calling {beginDefaultAdminTransfer} with the new delay will take at least the same as another {defaultAdmin} * complete transfer (including acceptance). * * The schedule is designed for two scenarios: * * - When the delay is changed for a larger one the schedule is `block.timestamp + newDelay` capped by * {defaultAdminDelayIncreaseWait}. * - When the delay is changed for a shorter one, the schedule is `block.timestamp + (current delay - new delay)`. * * A {pendingDefaultAdminDelay} that never got into effect will be canceled in favor of a new scheduled change. * * Requirements: * * - Only can be called by the current {defaultAdmin}. * * Emits a DefaultAdminDelayChangeScheduled event and may emit a DefaultAdminDelayChangeCanceled event. */ function changeDefaultAdminDelay(uint48 newDelay) external; /** * @dev Cancels a scheduled {defaultAdminDelay} change. * * Requirements: * * - Only can be called by the current {defaultAdmin}. * * May emit a DefaultAdminDelayChangeCanceled event. */ function rollbackDefaultAdminDelay() external; /** * @dev Maximum time in seconds for an increase to {defaultAdminDelay} (that is scheduled using {changeDefaultAdminDelay}) * to take effect. Default to 5 days. * * When the {defaultAdminDelay} is scheduled to be increased, it goes into effect after the new delay has passed with * the purpose of giving enough time for reverting any accidental change (i.e. using milliseconds instead of seconds) * that may lock the contract. However, to avoid excessive schedules, the wait is capped by this function and it can * be overrode for a custom {defaultAdminDelay} increase scheduling. * * IMPORTANT: Make sure to add a reasonable amount of time while overriding this value, otherwise, * there's a risk of setting a high new delay that goes into effect almost immediately without the * possibility of human intervention in the case of an input error (eg. set milliseconds instead of seconds). */ function defaultAdminDelayIncreaseWait() external view returns (uint48); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/IAccessControl.sol) pragma solidity ^0.8.20; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev The `account` is missing a role. */ error AccessControlUnauthorizedAccount(address account, bytes32 neededRole); /** * @dev The caller of a function is not the expected one. * * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}. */ error AccessControlBadConfirmation(); /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `callerConfirmation`. */ function renounceRole(bytes32 role, address callerConfirmation) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.sol"; /** * @dev 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 initial owner is set to the address provided by the deployer. This can * later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ constructor(address initialOwner) { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol) pragma solidity ^0.8.20; import {Ownable} from "./Ownable.sol"; /** * @dev Contract module which provides access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is specified at deployment time in the constructor for `Ownable`. This * can later be changed with {transferOwnership} and {acceptOwnership}. * * This module is used through inheritance. It will make available all functions * from parent (Ownable). */ abstract contract Ownable2Step is Ownable { address private _pendingOwner; event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner); /** * @dev Returns the address of the pending owner. */ function pendingOwner() public view virtual returns (address) { return _pendingOwner; } /** * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one. * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual override onlyOwner { _pendingOwner = newOwner; emit OwnershipTransferStarted(owner(), newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner. * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual override { delete _pendingOwner; super._transferOwnership(newOwner); } /** * @dev The new owner accepts the ownership transfer. */ function acceptOwnership() public virtual { address sender = _msgSender(); if (pendingOwner() != sender) { revert OwnableUnauthorizedAccount(sender); } _transferOwnership(sender); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (governance/TimelockController.sol) pragma solidity ^0.8.20; import {AccessControl} from "../access/AccessControl.sol"; import {ERC721Holder} from "../token/ERC721/utils/ERC721Holder.sol"; import {ERC1155Holder} from "../token/ERC1155/utils/ERC1155Holder.sol"; import {Address} from "../utils/Address.sol"; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. */ contract TimelockController is AccessControl, ERC721Holder, ERC1155Holder { bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); bytes32 public constant CANCELLER_ROLE = keccak256("CANCELLER_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 id => uint256) private _timestamps; uint256 private _minDelay; enum OperationState { Unset, Waiting, Ready, Done } /** * @dev Mismatch between the parameters length for an operation call. */ error TimelockInvalidOperationLength(uint256 targets, uint256 payloads, uint256 values); /** * @dev The schedule operation doesn't meet the minimum delay. */ error TimelockInsufficientDelay(uint256 delay, uint256 minDelay); /** * @dev The current state of an operation is not as required. * The `expectedStates` is a bitmap with the bits enabled for each OperationState enum position * counting from right to left. * * See {_encodeStateBitmap}. */ error TimelockUnexpectedOperationState(bytes32 operationId, bytes32 expectedStates); /** * @dev The predecessor to an operation not yet done. */ error TimelockUnexecutedPredecessor(bytes32 predecessorId); /** * @dev The caller account is not authorized. */ error TimelockUnauthorizedCaller(address caller); /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled( bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay ); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when new proposal is scheduled with non-zero salt. */ event CallSalt(bytes32 indexed id, bytes32 salt); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with the following parameters: * * - `minDelay`: initial minimum delay in seconds for operations * - `proposers`: accounts to be granted proposer and canceller roles * - `executors`: accounts to be granted executor role * - `admin`: optional account to be granted admin role; disable with zero address * * IMPORTANT: The optional admin can aid with initial configuration of roles after deployment * without being subject to delay, but this role should be subsequently renounced in favor of * administration through timelocked proposals. Previous versions of this contract would assign * this admin to the deployer automatically and should be renounced as well. */ constructor(uint256 minDelay, address[] memory proposers, address[] memory executors, address admin) { // self administration _grantRole(DEFAULT_ADMIN_ROLE, address(this)); // optional admin if (admin != address(0)) { _grantRole(DEFAULT_ADMIN_ROLE, admin); } // register proposers and cancellers for (uint256 i = 0; i < proposers.length; ++i) { _grantRole(PROPOSER_ROLE, proposers[i]); _grantRole(CANCELLER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _grantRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface( bytes4 interfaceId ) public view virtual override(AccessControl, ERC1155Holder) returns (bool) { return super.supportsInterface(interfaceId); } /** * @dev Returns whether an id corresponds to a registered operation. This * includes both Waiting, Ready, and Done operations. */ function isOperation(bytes32 id) public view returns (bool) { return getOperationState(id) != OperationState.Unset; } /** * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready". */ function isOperationPending(bytes32 id) public view returns (bool) { OperationState state = getOperationState(id); return state == OperationState.Waiting || state == OperationState.Ready; } /** * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending". */ function isOperationReady(bytes32 id) public view returns (bool) { return getOperationState(id) == OperationState.Ready; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view returns (bool) { return getOperationState(id) == OperationState.Done; } /** * @dev Returns the timestamp at which an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256) { return _timestamps[id]; } /** * @dev Returns operation state. */ function getOperationState(bytes32 id) public view virtual returns (OperationState) { uint256 timestamp = getTimestamp(id); if (timestamp == 0) { return OperationState.Unset; } else if (timestamp == _DONE_TIMESTAMP) { return OperationState.Done; } else if (timestamp > block.timestamp) { return OperationState.Waiting; } else { return OperationState.Ready; } } /** * @dev Returns the minimum delay in seconds for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public pure virtual returns (bytes32) { return keccak256(abi.encode(targets, values, payloads, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits {CallSalt} if salt is nonzero, and {CallScheduled}. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); if (salt != bytes32(0)) { emit CallSalt(id, salt); } } /** * @dev Schedule an operation containing a batch of transactions. * * Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt, uint256 delay ) public virtual onlyRole(PROPOSER_ROLE) { if (targets.length != values.length || targets.length != payloads.length) { revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length); } bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], payloads[i], predecessor, delay); } if (salt != bytes32(0)) { emit CallSalt(id, salt); } } /** * @dev Schedule an operation that is to become valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { if (isOperation(id)) { revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Unset)); } uint256 minDelay = getMinDelay(); if (delay < minDelay) { revert TimelockInsufficientDelay(delay, minDelay); } _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'canceller' role. */ function cancel(bytes32 id) public virtual onlyRole(CANCELLER_ROLE) { if (!isOperationPending(id)) { revert TimelockUnexpectedOperationState( id, _encodeStateBitmap(OperationState.Waiting) | _encodeStateBitmap(OperationState.Ready) ); } delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function execute( address target, uint256 value, bytes calldata payload, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, payload, predecessor, salt); _beforeCall(id, predecessor); _execute(target, value, payload); emit CallExecuted(id, 0, target, value, payload); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function executeBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { if (targets.length != values.length || targets.length != payloads.length) { revert TimelockInvalidOperationLength(targets.length, payloads.length, values.length); } bytes32 id = hashOperationBatch(targets, values, payloads, predecessor, salt); _beforeCall(id, predecessor); for (uint256 i = 0; i < targets.length; ++i) { address target = targets[i]; uint256 value = values[i]; bytes calldata payload = payloads[i]; _execute(target, value, payload); emit CallExecuted(id, i, target, value, payload); } _afterCall(id); } /** * @dev Execute an operation's call. */ function _execute(address target, uint256 value, bytes calldata data) internal virtual { (bool success, bytes memory returndata) = target.call{value: value}(data); Address.verifyCallResult(success, returndata); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 id, bytes32 predecessor) private view { if (!isOperationReady(id)) { revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready)); } if (predecessor != bytes32(0) && !isOperationDone(predecessor)) { revert TimelockUnexecutedPredecessor(predecessor); } } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { if (!isOperationReady(id)) { revert TimelockUnexpectedOperationState(id, _encodeStateBitmap(OperationState.Ready)); } _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { address sender = _msgSender(); if (sender != address(this)) { revert TimelockUnauthorizedCaller(sender); } emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } /** * @dev Encodes a `OperationState` into a `bytes32` representation where each bit enabled corresponds to * the underlying position in the `OperationState` enum. For example: * * 0x000...1000 * ^^^^^^----- ... * ^---- Done * ^--- Ready * ^-- Waiting * ^- Unset */ function _encodeStateBitmap(OperationState operationState) internal pure returns (bytes32) { return bytes32(1 << uint8(operationState)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (governance/utils/IVotes.sol) pragma solidity ^0.8.20; /** * @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts. */ interface IVotes { /** * @dev The signature used has expired. */ error VotesExpiredSignature(uint256 expiry); /** * @dev Emitted when an account changes their delegate. */ event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /** * @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of voting units. */ event DelegateVotesChanged(address indexed delegate, uint256 previousVotes, uint256 newVotes); /** * @dev Returns the current amount of votes that `account` has. */ function getVotes(address account) external view returns (uint256); /** * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is * configured to use block numbers, this will return the value at the end of the corresponding block. */ function getPastVotes(address account, uint256 timepoint) external view returns (uint256); /** * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is * configured to use block numbers, this will return the value at the end of the corresponding block. * * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. * Votes that have not been delegated are still part of total supply, even though they would not participate in a * vote. */ function getPastTotalSupply(uint256 timepoint) external view returns (uint256); /** * @dev Returns the delegate that `account` has chosen. */ function delegates(address account) external view returns (address); /** * @dev Delegates votes from the sender to `delegatee`. */ function delegate(address delegatee) external; /** * @dev Delegates votes from signer to `delegatee`. */ function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (governance/utils/Votes.sol) pragma solidity ^0.8.20; import {IERC5805} from "../../interfaces/IERC5805.sol"; import {Context} from "../../utils/Context.sol"; import {Nonces} from "../../utils/Nonces.sol"; import {EIP712} from "../../utils/cryptography/EIP712.sol"; import {Checkpoints} from "../../utils/structs/Checkpoints.sol"; import {SafeCast} from "../../utils/math/SafeCast.sol"; import {ECDSA} from "../../utils/cryptography/ECDSA.sol"; import {Time} from "../../utils/types/Time.sol"; /** * @dev This is a base abstract contract that tracks voting units, which are a measure of voting power that can be * transferred, and provides a system of vote delegation, where an account can delegate its voting units to a sort of * "representative" that will pool delegated voting units from different accounts and can then use it to vote in * decisions. In fact, voting units _must_ be delegated in order to count as actual votes, and an account has to * delegate those votes to itself if it wishes to participate in decisions and does not have a trusted representative. * * This contract is often combined with a token contract such that voting units correspond to token units. For an * example, see {ERC721Votes}. * * The full history of delegate votes is tracked on-chain so that governance protocols can consider votes as distributed * at a particular block number to protect against flash loans and double voting. The opt-in delegate system makes the * cost of this history tracking optional. * * When using this module the derived contract must implement {_getVotingUnits} (for example, make it return * {ERC721-balanceOf}), and can use {_transferVotingUnits} to track a change in the distribution of those units (in the * previous example, it would be included in {ERC721-_update}). */ abstract contract Votes is Context, EIP712, Nonces, IERC5805 { using Checkpoints for Checkpoints.Trace208; bytes32 private constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping(address account => address) private _delegatee; mapping(address delegatee => Checkpoints.Trace208) private _delegateCheckpoints; Checkpoints.Trace208 private _totalCheckpoints; /** * @dev The clock was incorrectly modified. */ error ERC6372InconsistentClock(); /** * @dev Lookup to future votes is not available. */ error ERC5805FutureLookup(uint256 timepoint, uint48 clock); /** * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based * checkpoints (and voting), in which case {CLOCK_MODE} should be overridden as well to match. */ function clock() public view virtual returns (uint48) { return Time.blockNumber(); } /** * @dev Machine-readable description of the clock as specified in EIP-6372. */ // solhint-disable-next-line func-name-mixedcase function CLOCK_MODE() public view virtual returns (string memory) { // Check that the clock was not modified if (clock() != Time.blockNumber()) { revert ERC6372InconsistentClock(); } return "mode=blocknumber&from=default"; } /** * @dev Returns the current amount of votes that `account` has. */ function getVotes(address account) public view virtual returns (uint256) { return _delegateCheckpoints[account].latest(); } /** * @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is * configured to use block numbers, this will return the value at the end of the corresponding block. * * Requirements: * * - `timepoint` must be in the past. If operating using block numbers, the block must be already mined. */ function getPastVotes(address account, uint256 timepoint) public view virtual returns (uint256) { uint48 currentTimepoint = clock(); if (timepoint >= currentTimepoint) { revert ERC5805FutureLookup(timepoint, currentTimepoint); } return _delegateCheckpoints[account].upperLookupRecent(SafeCast.toUint48(timepoint)); } /** * @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is * configured to use block numbers, this will return the value at the end of the corresponding block. * * NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes. * Votes that have not been delegated are still part of total supply, even though they would not participate in a * vote. * * Requirements: * * - `timepoint` must be in the past. If operating using block numbers, the block must be already mined. */ function getPastTotalSupply(uint256 timepoint) public view virtual returns (uint256) { uint48 currentTimepoint = clock(); if (timepoint >= currentTimepoint) { revert ERC5805FutureLookup(timepoint, currentTimepoint); } return _totalCheckpoints.upperLookupRecent(SafeCast.toUint48(timepoint)); } /** * @dev Returns the current total supply of votes. */ function _getTotalSupply() internal view virtual returns (uint256) { return _totalCheckpoints.latest(); } /** * @dev Returns the delegate that `account` has chosen. */ function delegates(address account) public view virtual returns (address) { return _delegatee[account]; } /** * @dev Delegates votes from the sender to `delegatee`. */ function delegate(address delegatee) public virtual { address account = _msgSender(); _delegate(account, delegatee); } /** * @dev Delegates votes from signer to `delegatee`. */ function delegateBySig( address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s ) public virtual { if (block.timestamp > expiry) { revert VotesExpiredSignature(expiry); } address signer = ECDSA.recover( _hashTypedDataV4(keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry))), v, r, s ); _useCheckedNonce(signer, nonce); _delegate(signer, delegatee); } /** * @dev Delegate all of `account`'s voting units to `delegatee`. * * Emits events {IVotes-DelegateChanged} and {IVotes-DelegateVotesChanged}. */ function _delegate(address account, address delegatee) internal virtual { address oldDelegate = delegates(account); _delegatee[account] = delegatee; emit DelegateChanged(account, oldDelegate, delegatee); _moveDelegateVotes(oldDelegate, delegatee, _getVotingUnits(account)); } /** * @dev Transfers, mints, or burns voting units. To register a mint, `from` should be zero. To register a burn, `to` * should be zero. Total supply of voting units will be adjusted with mints and burns. */ function _transferVotingUnits(address from, address to, uint256 amount) internal virtual { if (from == address(0)) { _push(_totalCheckpoints, _add, SafeCast.toUint208(amount)); } if (to == address(0)) { _push(_totalCheckpoints, _subtract, SafeCast.toUint208(amount)); } _moveDelegateVotes(delegates(from), delegates(to), amount); } /** * @dev Moves delegated votes from one delegate to another. */ function _moveDelegateVotes(address from, address to, uint256 amount) private { if (from != to && amount > 0) { if (from != address(0)) { (uint256 oldValue, uint256 newValue) = _push( _delegateCheckpoints[from], _subtract, SafeCast.toUint208(amount) ); emit DelegateVotesChanged(from, oldValue, newValue); } if (to != address(0)) { (uint256 oldValue, uint256 newValue) = _push( _delegateCheckpoints[to], _add, SafeCast.toUint208(amount) ); emit DelegateVotesChanged(to, oldValue, newValue); } } } /** * @dev Get number of checkpoints for `account`. */ function _numCheckpoints(address account) internal view virtual returns (uint32) { return SafeCast.toUint32(_delegateCheckpoints[account].length()); } /** * @dev Get the `pos`-th checkpoint for `account`. */ function _checkpoints( address account, uint32 pos ) internal view virtual returns (Checkpoints.Checkpoint208 memory) { return _delegateCheckpoints[account].at(pos); } function _push( Checkpoints.Trace208 storage store, function(uint208, uint208) view returns (uint208) op, uint208 delta ) private returns (uint208, uint208) { return store.push(clock(), op(store.latest(), delta)); } function _add(uint208 a, uint208 b) private pure returns (uint208) { return a + b; } function _subtract(uint208 a, uint208 b) private pure returns (uint208) { return a - b; } /** * @dev Must return the voting units held by an account. */ function _getVotingUnits(address) internal view virtual returns (uint256); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/draft-IERC6093.sol) pragma solidity ^0.8.20; /** * @dev Standard ERC20 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 tokens. */ interface IERC20Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC20InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC20InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers. * @param spender Address that may be allowed to operate on tokens without being their owner. * @param allowance Amount of tokens a `spender` is allowed to operate with. * @param needed Minimum amount required to perform a transfer. */ error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC20InvalidApprover(address approver); /** * @dev Indicates a failure with the `spender` to be approved. Used in approvals. * @param spender Address that may be allowed to operate on tokens without being their owner. */ error ERC20InvalidSpender(address spender); } /** * @dev Standard ERC721 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens. */ interface IERC721Errors { /** * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-20. * Used in balance queries. * @param owner Address of the current owner of a token. */ error ERC721InvalidOwner(address owner); /** * @dev Indicates a `tokenId` whose `owner` is the zero address. * @param tokenId Identifier number of a token. */ error ERC721NonexistentToken(uint256 tokenId); /** * @dev Indicates an error related to the ownership over a particular token. Used in transfers. * @param sender Address whose tokens are being transferred. * @param tokenId Identifier number of a token. * @param owner Address of the current owner of a token. */ error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC721InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC721InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param tokenId Identifier number of a token. */ error ERC721InsufficientApproval(address operator, uint256 tokenId); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC721InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC721InvalidOperator(address operator); } /** * @dev Standard ERC1155 Errors * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 tokens. */ interface IERC1155Errors { /** * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. * @param balance Current balance for the interacting account. * @param needed Minimum amount required to perform a transfer. * @param tokenId Identifier number of a token. */ error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId); /** * @dev Indicates a failure with the token `sender`. Used in transfers. * @param sender Address whose tokens are being transferred. */ error ERC1155InvalidSender(address sender); /** * @dev Indicates a failure with the token `receiver`. Used in transfers. * @param receiver Address to which tokens are being transferred. */ error ERC1155InvalidReceiver(address receiver); /** * @dev Indicates a failure with the `operator`’s approval. Used in transfers. * @param operator Address that may be allowed to operate on tokens without being their owner. * @param owner Address of the current owner of a token. */ error ERC1155MissingApprovalForAll(address operator, address owner); /** * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals. * @param approver Address initiating an approval operation. */ error ERC1155InvalidApprover(address approver); /** * @dev Indicates a failure with the `operator` to be approved. Used in approvals. * @param operator Address that may be allowed to operate on tokens without being their owner. */ error ERC1155InvalidOperator(address operator); /** * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation. * Used in batch transfers. * @param idsLength Length of the array of token identifiers * @param valuesLength Length of the array of token amounts */ error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1271.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol) pragma solidity ^0.8.20; /** * @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC. */ interface IERC1967 { /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Emitted when the beacon is changed. */ event BeaconUpgraded(address indexed beacon); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol) pragma solidity ^0.8.20; import {IERC20} from "../token/ERC20/IERC20.sol"; import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol"; /** * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626]. */ interface IERC4626 is IERC20, IERC20Metadata { event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares); event Withdraw( address indexed sender, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); /** * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing. * * - MUST be an ERC-20 token contract. * - MUST NOT revert. */ function asset() external view returns (address assetTokenAddress); /** * @dev Returns the total amount of the underlying asset that is “managed” by Vault. * * - SHOULD include any compounding that occurs from yield. * - MUST be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT revert. */ function totalAssets() external view returns (uint256 totalManagedAssets); /** * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal * scenario where all the conditions are met. * * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT show any variations depending on the caller. * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. * - MUST NOT revert. * * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and * from. */ function convertToShares(uint256 assets) external view returns (uint256 shares); /** * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal * scenario where all the conditions are met. * * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT show any variations depending on the caller. * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. * - MUST NOT revert. * * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and * from. */ function convertToAssets(uint256 shares) external view returns (uint256 assets); /** * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver, * through a deposit call. * * - MUST return a limited value if receiver is subject to some deposit limit. * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited. * - MUST NOT revert. */ function maxDeposit(address receiver) external view returns (uint256 maxAssets); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given * current on-chain conditions. * * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called * in the same transaction. * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the * deposit would be accepted, regardless if the user has enough tokens approved, etc. * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by depositing. */ function previewDeposit(uint256 assets) external view returns (uint256 shares); /** * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens. * * - MUST emit the Deposit event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * deposit execution, and are accounted for during deposit. * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not * approving enough underlying tokens to the Vault contract, etc). * * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. */ function deposit(uint256 assets, address receiver) external returns (uint256 shares); /** * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call. * - MUST return a limited value if receiver is subject to some mint limit. * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted. * - MUST NOT revert. */ function maxMint(address receiver) external view returns (uint256 maxShares); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given * current on-chain conditions. * * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the * same transaction. * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint * would be accepted, regardless if the user has enough tokens approved, etc. * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by minting. */ function previewMint(uint256 shares) external view returns (uint256 assets); /** * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens. * * - MUST emit the Deposit event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint * execution, and are accounted for during mint. * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not * approving enough underlying tokens to the Vault contract, etc). * * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. */ function mint(uint256 shares, address receiver) external returns (uint256 assets); /** * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the * Vault, through a withdraw call. * * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. * - MUST NOT revert. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, * given current on-chain conditions. * * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if * called * in the same transaction. * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though * the withdrawal would be accepted, regardless if the user has enough shares, etc. * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by depositing. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares); /** * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver. * * - MUST emit the Withdraw event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * withdraw execution, and are accounted for during withdraw. * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner * not having enough shares, etc). * * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. * Those methods should be performed separately. */ function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares); /** * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, * through a redeem call. * * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. * - MUST NOT revert. */ function maxRedeem(address owner) external view returns (uint256 maxShares); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, * given current on-chain conditions. * * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the * same transaction. * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the * redemption would be accepted, regardless if the user has enough shares, etc. * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by redeeming. */ function previewRedeem(uint256 shares) external view returns (uint256 assets); /** * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver. * * - MUST emit the Withdraw event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * redeem execution, and are accounted for during redeem. * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner * not having enough shares, etc). * * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed. * Those methods should be performed separately. */ function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol) pragma solidity ^0.8.20; interface IERC5267 { /** * @dev MAY be emitted to signal that the domain could have changed. */ event EIP712DomainChanged(); /** * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712 * signature. */ function eip712Domain() external view returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5313.sol) pragma solidity ^0.8.20; /** * @dev Interface for the Light Contract Ownership Standard. * * A standardized minimal interface required to identify an account that controls a contract */ interface IERC5313 { /** * @dev Gets the address of the owner. */ function owner() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5805.sol) pragma solidity ^0.8.20; import {IVotes} from "../governance/utils/IVotes.sol"; import {IERC6372} from "./IERC6372.sol"; interface IERC5805 is IERC6372, IVotes {}
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC6372.sol) pragma solidity ^0.8.20; interface IERC6372 { /** * @dev Clock used for flagging checkpoints. Can be overridden to implement timestamp based checkpoints (and voting). */ function clock() external view returns (uint48); /** * @dev Description of the clock */ // solhint-disable-next-line func-name-mixedcase function CLOCK_MODE() external view returns (string memory); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.20; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeacon { /** * @dev Must return an address that can be used as a delegate call target. * * {UpgradeableBeacon} will check that this address is a contract. */ function implementation() external view returns (address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Proxy.sol) pragma solidity ^0.8.20; import {Proxy} from "../Proxy.sol"; import {ERC1967Utils} from "./ERC1967Utils.sol"; /** * @dev This contract implements an upgradeable proxy. It is upgradeable because calls are delegated to an * implementation address that can be changed. This address is stored in storage in the location specified by * https://eips.ethereum.org/EIPS/eip-1967[EIP1967], so that it doesn't conflict with the storage layout of the * implementation behind the proxy. */ contract ERC1967Proxy is Proxy { /** * @dev Initializes the upgradeable proxy with an initial implementation specified by `implementation`. * * If `_data` is nonempty, it's used as data in a delegate call to `implementation`. This will typically be an * encoded function call, and allows initializing the storage of the proxy like a Solidity constructor. * * Requirements: * * - If `data` is empty, `msg.value` must be zero. */ constructor(address implementation, bytes memory _data) payable { ERC1967Utils.upgradeToAndCall(implementation, _data); } /** * @dev Returns the current implementation address. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc` */ function _implementation() internal view virtual override returns (address) { return ERC1967Utils.getImplementation(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/ERC1967/ERC1967Utils.sol) pragma solidity ^0.8.20; import {IBeacon} from "../beacon/IBeacon.sol"; import {Address} from "../../utils/Address.sol"; import {StorageSlot} from "../../utils/StorageSlot.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. */ library ERC1967Utils { // We re-declare ERC-1967 events here because they can't be used directly from IERC1967. // This will be fixed in Solidity 0.8.21. At that point we should remove these events. /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Emitted when the beacon is changed. */ event BeaconUpgraded(address indexed beacon); /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev The `implementation` of the proxy is invalid. */ error ERC1967InvalidImplementation(address implementation); /** * @dev The `admin` of the proxy is invalid. */ error ERC1967InvalidAdmin(address admin); /** * @dev The `beacon` of the proxy is invalid. */ error ERC1967InvalidBeacon(address beacon); /** * @dev An upgrade function sees `msg.value > 0` that may be lost. */ error ERC1967NonPayable(); /** * @dev Returns the current implementation address. */ function getImplementation() internal view returns (address) { return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { if (newImplementation.code.length == 0) { revert ERC1967InvalidImplementation(newImplementation); } StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Performs implementation upgrade with additional setup call if data is nonempty. * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected * to avoid stuck value in the contract. * * Emits an {IERC1967-Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); if (data.length > 0) { Address.functionDelegateCall(newImplementation, data); } else { _checkNonPayable(); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Returns the current admin. * * TIP: To get this value clients can read directly from the storage slot shown below (specified by EIP1967) using * the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call. * `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103` */ function getAdmin() internal view returns (address) { return StorageSlot.getAddressSlot(ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { if (newAdmin == address(0)) { revert ERC1967InvalidAdmin(address(0)); } StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {IERC1967-AdminChanged} event. */ function changeAdmin(address newAdmin) internal { emit AdminChanged(getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1. */ // solhint-disable-next-line private-vars-leading-underscore bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Returns the current beacon. */ function getBeacon() internal view returns (address) { return StorageSlot.getAddressSlot(BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { if (newBeacon.code.length == 0) { revert ERC1967InvalidBeacon(newBeacon); } StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon; address beaconImplementation = IBeacon(newBeacon).implementation(); if (beaconImplementation.code.length == 0) { revert ERC1967InvalidImplementation(beaconImplementation); } } /** * @dev Change the beacon and trigger a setup call if data is nonempty. * This function is payable only if the setup call is performed, otherwise `msg.value` is rejected * to avoid stuck value in the contract. * * Emits an {IERC1967-BeaconUpgraded} event. * * CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since * it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for * efficiency. */ function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0) { Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data); } else { _checkNonPayable(); } } /** * @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract * if an upgrade doesn't perform an initialization call. */ function _checkNonPayable() private { if (msg.value > 0) { revert ERC1967NonPayable(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/Proxy.sol) pragma solidity ^0.8.20; /** * @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM * instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to * be specified by overriding the virtual {_implementation} function. * * Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a * different contract through the {_delegate} function. * * The success and return data of the delegated call will be returned back to the caller of the proxy. */ abstract contract Proxy { /** * @dev Delegates the current call to `implementation`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _delegate(address implementation) internal virtual { assembly { // Copy msg.data. We take full control of memory in this inline assembly // block because it will not return to Solidity code. We overwrite the // Solidity scratch pad at memory position 0. calldatacopy(0, 0, calldatasize()) // Call the implementation. // out and outsize are 0 because we don't know the size yet. let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize()) switch result // delegatecall returns 0 on error. case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } /** * @dev This is a virtual function that should be overridden so it returns the address to which the fallback * function and {_fallback} should delegate. */ function _implementation() internal view virtual returns (address); /** * @dev Delegates the current call to the address returned by `_implementation()`. * * This function does not return to its internal call site, it will return directly to the external caller. */ function _fallback() internal virtual { _delegate(_implementation()); } /** * @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other * function in the contract matches the call data. */ fallback() external payable virtual { _fallback(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol) pragma solidity ^0.8.20; import {ITransparentUpgradeableProxy} from "./TransparentUpgradeableProxy.sol"; import {Ownable} from "../../access/Ownable.sol"; /** * @dev This is an auxiliary contract meant to be assigned as the admin of a {TransparentUpgradeableProxy}. For an * explanation of why you would want to use this see the documentation for {TransparentUpgradeableProxy}. */ contract ProxyAdmin is Ownable { /** * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)` * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called, * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string. * If the getter returns `"5.0.0"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function * during an upgrade. */ string public constant UPGRADE_INTERFACE_VERSION = "5.0.0"; /** * @dev Sets the initial owner who can perform upgrades. */ constructor(address initialOwner) Ownable(initialOwner) {} /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. * - If `data` is empty, `msg.value` must be zero. */ function upgradeAndCall( ITransparentUpgradeableProxy proxy, address implementation, bytes memory data ) public payable virtual onlyOwner { proxy.upgradeToAndCall{value: msg.value}(implementation, data); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.20; import {IERC165} from "../../utils/introspection/IERC165.sol"; /** * @dev Interface that must be implemented by smart contracts in order to receive * ERC-1155 token transfers. */ interface IERC1155Receiver is IERC165 { /** * @dev Handles the receipt of a single ERC1155 token type. This function is * called at the end of a `safeTransferFrom` after the balance has been updated. * * NOTE: To accept the transfer, this must return * `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * (i.e. 0xf23a6e61, or its own function selector). * * @param operator The address which initiated the transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param id The ID of the token being transferred * @param value The amount of tokens being transferred * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** * @dev Handles the receipt of a multiple ERC1155 token types. This function * is called at the end of a `safeBatchTransferFrom` after the balances have * been updated. * * NOTE: To accept the transfer(s), this must return * `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * (i.e. 0xbc197c81, or its own function selector). * * @param operator The address which initiated the batch transfer (i.e. msg.sender) * @param from The address which previously owned the token * @param ids An array containing ids of each token being transferred (order and length must match values array) * @param values An array containing amounts of each token being transferred (order and length must match ids array) * @param data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC1155/utils/ERC1155Holder.sol) pragma solidity ^0.8.20; import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol"; import {IERC1155Receiver} from "../IERC1155Receiver.sol"; /** * @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC1155 tokens. * * IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be * stuck. */ abstract contract ERC1155Holder is ERC165, IERC1155Receiver { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId); } function onERC1155Received( address, address, uint256, uint256, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155Received.selector; } function onERC1155BatchReceived( address, address, uint256[] memory, uint256[] memory, bytes memory ) public virtual override returns (bytes4) { return this.onERC1155BatchReceived.selector; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC20Metadata} from "./extensions/IERC20Metadata.sol"; import {Context} from "../../utils/Context.sol"; import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * TIP: For a detailed writeup see our guide * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * The default value of {decimals} is 18. To change this, you should override * this function so it returns a different value. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. */ abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors { mapping(address account => uint256) private _balances; mapping(address account => mapping(address spender => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the default value returned by this function, unless * it's overridden. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `value`. */ function transfer(address to, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _transfer(owner, to, value); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 value) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `value`. * - the caller must have allowance for ``from``'s tokens of at least * `value`. */ function transferFrom(address from, address to, uint256 value) public virtual returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, value); _transfer(from, to, value); return true; } /** * @dev Moves a `value` amount of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _transfer(address from, address to, uint256 value) internal { if (from == address(0)) { revert ERC20InvalidSender(address(0)); } if (to == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(from, to, value); } /** * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from` * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding * this function. * * Emits a {Transfer} event. */ function _update(address from, address to, uint256 value) internal virtual { if (from == address(0)) { // Overflow check required: The rest of the code assumes that totalSupply never overflows _totalSupply += value; } else { uint256 fromBalance = _balances[from]; if (fromBalance < value) { revert ERC20InsufficientBalance(from, fromBalance, value); } unchecked { // Overflow not possible: value <= fromBalance <= totalSupply. _balances[from] = fromBalance - value; } } if (to == address(0)) { unchecked { // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply. _totalSupply -= value; } } else { unchecked { // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256. _balances[to] += value; } } emit Transfer(from, to, value); } /** * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0). * Relies on the `_update` mechanism * * Emits a {Transfer} event with `from` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead. */ function _mint(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidReceiver(address(0)); } _update(address(0), account, value); } /** * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply. * Relies on the `_update` mechanism. * * Emits a {Transfer} event with `to` set to the zero address. * * NOTE: This function is not virtual, {_update} should be overridden instead */ function _burn(address account, uint256 value) internal { if (account == address(0)) { revert ERC20InvalidSender(address(0)); } _update(account, address(0), value); } /** * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. * * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument. */ function _approve(address owner, address spender, uint256 value) internal { _approve(owner, spender, value, true); } /** * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event. * * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any * `Approval` event during `transferFrom` operations. * * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to * true using the following override: * ``` * function _approve(address owner, address spender, uint256 value, bool) internal virtual override { * super._approve(owner, spender, value, true); * } * ``` * * Requirements are the same as {_approve}. */ function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual { if (owner == address(0)) { revert ERC20InvalidApprover(address(0)); } if (spender == address(0)) { revert ERC20InvalidSpender(address(0)); } _allowances[owner][spender] = value; if (emitEvent) { emit Approval(owner, spender, value); } } /** * @dev Updates `owner` s allowance for `spender` based on spent `value`. * * Does not update the allowance value in case of infinite allowance. * Revert if not enough allowance is available. * * Does not emit an {Approval} event. */ function _spendAllowance(address owner, address spender, uint256 value) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { if (currentAllowance < value) { revert ERC20InsufficientAllowance(spender, currentAllowance, value); } unchecked { _approve(owner, spender, currentAllowance - value, false); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.20; import {ERC20} from "../ERC20.sol"; import {Context} from "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys a `value` amount of tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 value) public virtual { _burn(_msgSender(), value); } /** * @dev 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 least * `value`. */ function burnFrom(address account, uint256 value) public virtual { _spendAllowance(account, _msgSender(), value); _burn(account, value); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Permit.sol) pragma solidity ^0.8.20; import {IERC20Permit} from "./IERC20Permit.sol"; import {ERC20} from "../ERC20.sol"; import {ECDSA} from "../../../utils/cryptography/ECDSA.sol"; import {EIP712} from "../../../utils/cryptography/EIP712.sol"; import {Nonces} from "../../../utils/Nonces.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712, Nonces { bytes32 private constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Permit deadline has expired. */ error ERC2612ExpiredSignature(uint256 deadline); /** * @dev Mismatched signature. */ error ERC2612InvalidSigner(address signer, address owner); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @inheritdoc IERC20Permit */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual { if (block.timestamp > deadline) { revert ERC2612ExpiredSignature(deadline); } bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); if (signer != owner) { revert ERC2612InvalidSigner(signer, owner); } _approve(owner, spender, value); } /** * @inheritdoc IERC20Permit */ function nonces(address owner) public view virtual override(IERC20Permit, Nonces) returns (uint256) { return super.nonces(owner); } /** * @inheritdoc IERC20Permit */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view virtual returns (bytes32) { return _domainSeparatorV4(); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC20Votes.sol) pragma solidity ^0.8.20; import {ERC20} from "../ERC20.sol"; import {Votes} from "../../../governance/utils/Votes.sol"; import {Checkpoints} from "../../../utils/structs/Checkpoints.sol"; /** * @dev Extension of ERC20 to support Compound-like voting and delegation. This version is more generic than Compound's, * and supports token supply up to 2^208^ - 1, while COMP is limited to 2^96^ - 1. * * NOTE: This contract does not provide interface compatibility with Compound's COMP token. * * This extension keeps a history (checkpoints) of each account's vote power. Vote power can be delegated either * by calling the {delegate} function directly, or by providing a signature to be used with {delegateBySig}. Voting * power can be queried through the public accessors {getVotes} and {getPastVotes}. * * By default, token balance does not account for voting power. This makes transfers cheaper. The downside is that it * requires users to delegate to themselves in order to activate checkpoints and have their voting power tracked. */ abstract contract ERC20Votes is ERC20, Votes { /** * @dev Total supply cap has been exceeded, introducing a risk of votes overflowing. */ error ERC20ExceededSafeSupply(uint256 increasedSupply, uint256 cap); /** * @dev Maximum token supply. Defaults to `type(uint208).max` (2^208^ - 1). * * This maximum is enforced in {_update}. It limits the total supply of the token, which is otherwise a uint256, * so that checkpoints can be stored in the Trace208 structure used by {{Votes}}. Increasing this value will not * remove the underlying limitation, and will cause {_update} to fail because of a math overflow in * {_transferVotingUnits}. An override could be used to further restrict the total supply (to a lower value) if * additional logic requires it. When resolving override conflicts on this function, the minimum should be * returned. */ function _maxSupply() internal view virtual returns (uint256) { return type(uint208).max; } /** * @dev Move voting power when tokens are transferred. * * Emits a {IVotes-DelegateVotesChanged} event. */ function _update(address from, address to, uint256 value) internal virtual override { super._update(from, to, value); if (from == address(0)) { uint256 supply = totalSupply(); uint256 cap = _maxSupply(); if (supply > cap) { revert ERC20ExceededSafeSupply(supply, cap); } } _transferVotingUnits(from, to, value); } /** * @dev Returns the voting units of an `account`. * * WARNING: Overriding this function may compromise the internal vote accounting. * `ERC20Votes` assumes tokens map to voting units 1:1 and this is not easy to change. */ function _getVotingUnits(address account) internal view virtual override returns (uint256) { return balanceOf(account); } /** * @dev Get number of checkpoints for `account`. */ function numCheckpoints(address account) public view virtual returns (uint32) { return _numCheckpoints(account); } /** * @dev Get the `pos`-th checkpoint for `account`. */ function checkpoints(address account, uint32 pos) public view virtual returns (Checkpoints.Checkpoint208 memory) { return _checkpoints(account, pos); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol) pragma solidity ^0.8.20; import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol"; import {SafeERC20} from "../utils/SafeERC20.sol"; import {IERC4626} from "../../../interfaces/IERC4626.sol"; import {Math} from "../../../utils/math/Math.sol"; /** * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626]. * * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this * contract and not the "assets" token which is an independent contract. * * [CAUTION] * ==== * In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning * with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation * attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial * deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may * similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by * verifying the amount received is as expected, using a wrapper that performs these checks such as * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router]. * * Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()` * corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault * decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself * determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset * (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's * donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more * expensive than it is profitable. More details about the underlying math can be found * xref:erc4626.adoc#inflation-attack[here]. * * The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued * to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets * will cause the first user to exit to experience reduced losses in detriment to the last users that will experience * bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the * `_convertToShares` and `_convertToAssets` functions. * * To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide]. * ==== */ abstract contract ERC4626 is ERC20, IERC4626 { using Math for uint256; IERC20 private immutable _asset; uint8 private immutable _underlyingDecimals; /** * @dev Attempted to deposit more assets than the max amount for `receiver`. */ error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max); /** * @dev Attempted to mint more shares than the max amount for `receiver`. */ error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max); /** * @dev Attempted to withdraw more assets than the max amount for `receiver`. */ error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max); /** * @dev Attempted to redeem more shares than the max amount for `receiver`. */ error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max); /** * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777). */ constructor(IERC20 asset_) { (bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_); _underlyingDecimals = success ? assetDecimals : 18; _asset = asset_; } /** * @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way. */ function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) { (bool success, bytes memory encodedDecimals) = address(asset_).staticcall( abi.encodeCall(IERC20Metadata.decimals, ()) ); if (success && encodedDecimals.length >= 32) { uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256)); if (returnedDecimals <= type(uint8).max) { return (true, uint8(returnedDecimals)); } } return (false, 0); } /** * @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This * "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the * asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals. * * See {IERC20Metadata-decimals}. */ function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) { return _underlyingDecimals + _decimalsOffset(); } /** @dev See {IERC4626-asset}. */ function asset() public view virtual returns (address) { return address(_asset); } /** @dev See {IERC4626-totalAssets}. */ function totalAssets() public view virtual returns (uint256) { return _asset.balanceOf(address(this)); } /** @dev See {IERC4626-convertToShares}. */ function convertToShares(uint256 assets) public view virtual returns (uint256) { return _convertToShares(assets, Math.Rounding.Floor); } /** @dev See {IERC4626-convertToAssets}. */ function convertToAssets(uint256 shares) public view virtual returns (uint256) { return _convertToAssets(shares, Math.Rounding.Floor); } /** @dev See {IERC4626-maxDeposit}. */ function maxDeposit(address) public view virtual returns (uint256) { return type(uint256).max; } /** @dev See {IERC4626-maxMint}. */ function maxMint(address) public view virtual returns (uint256) { return type(uint256).max; } /** @dev See {IERC4626-maxWithdraw}. */ function maxWithdraw(address owner) public view virtual returns (uint256) { return _convertToAssets(balanceOf(owner), Math.Rounding.Floor); } /** @dev See {IERC4626-maxRedeem}. */ function maxRedeem(address owner) public view virtual returns (uint256) { return balanceOf(owner); } /** @dev See {IERC4626-previewDeposit}. */ function previewDeposit(uint256 assets) public view virtual returns (uint256) { return _convertToShares(assets, Math.Rounding.Floor); } /** @dev See {IERC4626-previewMint}. */ function previewMint(uint256 shares) public view virtual returns (uint256) { return _convertToAssets(shares, Math.Rounding.Ceil); } /** @dev See {IERC4626-previewWithdraw}. */ function previewWithdraw(uint256 assets) public view virtual returns (uint256) { return _convertToShares(assets, Math.Rounding.Ceil); } /** @dev See {IERC4626-previewRedeem}. */ function previewRedeem(uint256 shares) public view virtual returns (uint256) { return _convertToAssets(shares, Math.Rounding.Floor); } /** @dev See {IERC4626-deposit}. */ function deposit(uint256 assets, address receiver) public virtual returns (uint256) { uint256 maxAssets = maxDeposit(receiver); if (assets > maxAssets) { revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets); } uint256 shares = previewDeposit(assets); _deposit(_msgSender(), receiver, assets, shares); return shares; } /** @dev See {IERC4626-mint}. * * As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero. * In this case, the shares will be minted without requiring any assets to be deposited. */ function mint(uint256 shares, address receiver) public virtual returns (uint256) { uint256 maxShares = maxMint(receiver); if (shares > maxShares) { revert ERC4626ExceededMaxMint(receiver, shares, maxShares); } uint256 assets = previewMint(shares); _deposit(_msgSender(), receiver, assets, shares); return assets; } /** @dev See {IERC4626-withdraw}. */ function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) { uint256 maxAssets = maxWithdraw(owner); if (assets > maxAssets) { revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets); } uint256 shares = previewWithdraw(assets); _withdraw(_msgSender(), receiver, owner, assets, shares); return shares; } /** @dev See {IERC4626-redeem}. */ function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) { uint256 maxShares = maxRedeem(owner); if (shares > maxShares) { revert ERC4626ExceededMaxRedeem(owner, shares, maxShares); } uint256 assets = previewRedeem(shares); _withdraw(_msgSender(), receiver, owner, assets, shares); return assets; } /** * @dev Internal conversion function (from assets to shares) with support for rounding direction. */ function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) { return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding); } /** * @dev Internal conversion function (from shares to assets) with support for rounding direction. */ function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) { return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding); } /** * @dev Deposit/mint common workflow. */ function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual { // If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer, // calls the vault, which is assumed not malicious. // // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the // assets are transferred and before the shares are minted, which is a valid state. // slither-disable-next-line reentrancy-no-eth SafeERC20.safeTransferFrom(_asset, caller, address(this), assets); _mint(receiver, shares); emit Deposit(caller, receiver, assets, shares); } /** * @dev Withdraw/redeem common workflow. */ function _withdraw( address caller, address receiver, address owner, uint256 assets, uint256 shares ) internal virtual { if (caller != owner) { _spendAllowance(owner, caller, shares); } // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer, // calls the vault, which is assumed not malicious. // // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the // shares are burned and after the assets are transferred, which is a valid state. _burn(owner, shares); SafeERC20.safeTransfer(_asset, receiver, assets); emit Withdraw(caller, receiver, owner, assets, shares); } function _decimalsOffset() internal view virtual returns (uint8) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * ==== Security Considerations * * There are two important considerations concerning the use of `permit`. The first is that a valid permit signature * expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be * considered as an intention to spend the allowance in any specific way. The second is that because permits have * built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should * take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be * generally recommended is: * * ```solidity * function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public { * try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {} * doThing(..., value); * } * * function doThing(..., uint256 value) public { * token.safeTransferFrom(msg.sender, address(this), value); * ... * } * ``` * * Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of * `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also * {SafeERC20-safeTransferFrom}). * * Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so * contracts should have entry points that don't rely on permit. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. * * CAUTION: See Security Considerations above. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; import {IERC20Permit} from "../extensions/IERC20Permit.sol"; import {Address} from "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev An operation with an ERC20 token failed. */ error SafeERC20FailedOperation(address token); /** * @dev Indicates a failed `decreaseAllowance` request. */ error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value))); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); } /** * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no * value, non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { unchecked { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance < requestedDecrease) { revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); } forceApprove(token, spender, currentAllowance - requestedDecrease); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data); if (returndata.length != 0 && !abi.decode(returndata, (bool))) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.20; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be * reverted. * * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/utils/ERC721Holder.sol) pragma solidity ^0.8.20; import {IERC721Receiver} from "../IERC721Receiver.sol"; /** * @dev Implementation of the {IERC721Receiver} interface. * * Accepts all token transfers. * Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or * {IERC721-setApprovalForAll}. */ abstract contract ERC721Holder is IERC721Receiver { /** * @dev See {IERC721Receiver-onERC721Received}. * * Always returns `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received(address, address, uint256, bytes memory) public virtual returns (bytes4) { return this.onERC721Received.selector; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol) pragma solidity ^0.8.20; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev The ETH balance of the account is not enough to perform the operation. */ error AddressInsufficientBalance(address account); /** * @dev There's no code at `target` (it is not a contract). */ error AddressEmptyCode(address target); /** * @dev A call to an address target failed. The target may have reverted. */ error FailedInnerCall(); /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) { revert AddressInsufficientBalance(address(this)); } (bool success, ) = recipient.call{value: amount}(""); if (!success) { revert FailedInnerCall(); } } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason or custom error, it is bubbled * up by this function (like regular Solidity function calls). However, if * the call reverted with no returned reason, this function reverts with a * {FailedInnerCall} error. * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { if (address(this).balance < value) { revert AddressInsufficientBalance(address(this)); } (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target * was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an * unsuccessful call. */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata ) internal view returns (bytes memory) { if (!success) { _revert(returndata); } else { // only check if target is a contract if the call was successful and the return data is empty // otherwise we already know that it was a contract if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); } return returndata; } } /** * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the * revert reason or with a default {FailedInnerCall} error. */ function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) { if (!success) { _revert(returndata); } else { return returndata; } } /** * @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}. */ function _revert(bytes memory returndata) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert FailedInnerCall(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.20; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS } /** * @dev The signature derives the `address(0)`. */ error ECDSAInvalidSignature(); /** * @dev The signature has an invalid length. */ error ECDSAInvalidSignatureLength(uint256 length); /** * @dev The signature has an S value that is in the upper half order. */ error ECDSAInvalidSignatureS(bytes32 s); /** * @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not * return address(0) without also returning an error description. Errors are documented using an enum (error type) * and a bytes32 providing additional information about the error. * * If no error is returned, then the address can be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError, bytes32) { if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. /// @solidity memory-safe-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else { return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length)); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM precompile allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] */ function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError, bytes32) { unchecked { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); // We do not check for an overflow here since the shift operation results in 0 or 1. uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. */ function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs); _throwError(error, errorArg); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError, bytes32) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS, s); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature, bytes32(0)); } return (signer, RecoverError.NoError, bytes32(0)); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) { (address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s); _throwError(error, errorArg); return recovered; } /** * @dev Optionally reverts with the corresponding custom error according to the `error` argument provided. */ function _throwError(RecoverError error, bytes32 errorArg) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert ECDSAInvalidSignature(); } else if (error == RecoverError.InvalidSignatureLength) { revert ECDSAInvalidSignatureLength(uint256(errorArg)); } else if (error == RecoverError.InvalidSignatureS) { revert ECDSAInvalidSignatureS(errorArg); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/EIP712.sol) pragma solidity ^0.8.20; import {MessageHashUtils} from "./MessageHashUtils.sol"; import {ShortStrings, ShortString} from "../ShortStrings.sol"; import {IERC5267} from "../../interfaces/IERC5267.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the * separator from the immutable values, which is cheaper than accessing a cached version in cold storage. * * @custom:oz-upgrades-unsafe-allow state-variable-immutable */ abstract contract EIP712 is IERC5267 { using ShortStrings for *; bytes32 private constant TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"); // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _cachedDomainSeparator; uint256 private immutable _cachedChainId; address private immutable _cachedThis; bytes32 private immutable _hashedName; bytes32 private immutable _hashedVersion; ShortString private immutable _name; ShortString private immutable _version; string private _nameFallback; string private _versionFallback; /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { _name = name.toShortStringWithFallback(_nameFallback); _version = version.toShortStringWithFallback(_versionFallback); _hashedName = keccak256(bytes(name)); _hashedVersion = keccak256(bytes(version)); _cachedChainId = block.chainid; _cachedDomainSeparator = _buildDomainSeparator(); _cachedThis = address(this); } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _cachedThis && block.chainid == _cachedChainId) { return _cachedDomainSeparator; } else { return _buildDomainSeparator(); } } function _buildDomainSeparator() private view returns (bytes32) { return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash); } /** * @dev See {IERC-5267}. */ function eip712Domain() public view virtual returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { return ( hex"0f", // 01111 _EIP712Name(), _EIP712Version(), block.chainid, address(this), bytes32(0), new uint256[](0) ); } /** * @dev The name parameter for the EIP712 domain. * * NOTE: By default this function reads _name which is an immutable value. * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). */ // solhint-disable-next-line func-name-mixedcase function _EIP712Name() internal view returns (string memory) { return _name.toStringWithFallback(_nameFallback); } /** * @dev The version parameter for the EIP712 domain. * * NOTE: By default this function reads _version which is an immutable value. * It only reads from storage if necessary (in case the value is too large to fit in a ShortString). */ // solhint-disable-next-line func-name-mixedcase function _EIP712Version() internal view returns (string memory) { return _version.toStringWithFallback(_versionFallback); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.20; /** * @dev These functions deal with verification of Merkle Tree proofs. * * The tree and the proofs can be generated using our * https://github.com/OpenZeppelin/merkle-tree[JavaScript library]. * You will find a quickstart guide in the readme. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the Merkle tree could be reinterpreted as a leaf value. * OpenZeppelin's JavaScript library generates Merkle trees that are safe * against this attack out of the box. */ library MerkleProof { /** *@dev The multiproof provided is not valid. */ error MerkleProofInvalidMultiproof(); /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} */ function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details. */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details. */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction * proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another * leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false * respectively. * * CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree * is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the * tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer). */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the Merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. if (leavesLen + proofLen != totalHashes + 1) { revert MerkleProofInvalidMultiproof(); } // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { if (proofPos != proofLen) { revert MerkleProofInvalidMultiproof(); } unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof}. * * CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details. */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the Merkle tree. uint256 leavesLen = leaves.length; uint256 proofLen = proof.length; uint256 totalHashes = proofFlags.length; // Check proof validity. if (leavesLen + proofLen != totalHashes + 1) { revert MerkleProofInvalidMultiproof(); } // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value from the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]) : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { if (proofPos != proofLen) { revert MerkleProofInvalidMultiproof(); } unchecked { return hashes[totalHashes - 1]; } } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Sorts the pair (a, b) and hashes the result. */ function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } /** * @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory. */ function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/cryptography/MessageHashUtils.sol) pragma solidity ^0.8.20; import {Strings} from "../Strings.sol"; /** * @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing. * * The library provides methods for generating a hash of a message that conforms to the * https://eips.ethereum.org/EIPS/eip-191[EIP 191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712] * specifications. */ library MessageHashUtils { /** * @dev Returns the keccak256 digest of an EIP-191 signed data with version * `0x45` (`personal_sign` messages). * * The digest is calculated by prefixing a bytes32 `messageHash` with * `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method. * * NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with * keccak256, although any bytes32 value can be safely used because the final digest will * be re-hashed. * * See {ECDSA-recover}. */ function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) { /// @solidity memory-safe-assembly assembly { mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20) } } /** * @dev Returns the keccak256 digest of an EIP-191 signed data with version * `0x45` (`personal_sign` messages). * * The digest is calculated by prefixing an arbitrary `message` with * `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the * hash signed when using the https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] JSON-RPC method. * * See {ECDSA-recover}. */ function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) { return keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message)); } /** * @dev Returns the keccak256 digest of an EIP-191 signed data with version * `0x00` (data with intended validator). * * The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended * `validator` address. Then hashing the result. * * See {ECDSA-recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked(hex"19_00", validator, data)); } /** * @dev Returns the keccak256 digest of an EIP-712 typed data (EIP-191 version `0x01`). * * The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with * `\x19\x01` and hashing the result. It corresponds to the hash signed by the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712. * * See {ECDSA-recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, hex"19_01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) digest := keccak256(ptr, 0x42) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/ERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) { return interfaceId == type(IERC165).interfaceId; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev 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}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[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); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol) pragma solidity ^0.8.20; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Muldiv operation overflow. */ error MathOverflowedMulDiv(); enum Rounding { Floor, // Toward negative infinity Ceil, // Toward positive infinity Trunc, // Toward zero Expand // Away from zero } /** * @dev Returns the addition of two unsigned integers, with an overflow flag. */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the subtraction of two unsigned integers, with an overflow flag. */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow. return (a & b) + (a ^ b) / 2; } /** * @dev Returns the ceiling of the division of two numbers. * * This differs from standard division with `/` in that it rounds towards infinity instead * of rounding towards zero. */ function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) { if (b == 0) { // Guarantee the same behavior as in a regular Solidity division. return a / b; } // (a + b - 1) / b can overflow on addition, so we distribute. return a == 0 ? 0 : (a - 1) / b + 1; } /** * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or * denominator == 0. * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by * Uniswap Labs also under MIT license. */ function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) { unchecked { // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2^256 + prod0. uint256 prod0 = x * y; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(x, y, not(0)) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division. if (prod1 == 0) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. if (denominator <= prod1) { revert MathOverflowedMulDiv(); } /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0]. uint256 remainder; assembly { // Compute remainder using mulmod. remainder := mulmod(x, y, denominator) // Subtract 256 bit number from 512 bit number. prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator and compute largest power of two divisor of denominator. // Always >= 1. See https://cs.stackexchange.com/q/138556/92363. uint256 twos = denominator & (0 - denominator); assembly { // Divide denominator by twos. denominator := div(denominator, twos) // Divide [prod1 prod0] by twos. prod0 := div(prod0, twos) // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one. twos := add(div(sub(0, twos), twos), 1) } // Shift in bits from prod1 into prod0. prod0 |= prod1 * twos; // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for // four bits. That is, denominator * inv = 1 mod 2^4. uint256 inverse = (3 * denominator) ^ 2; // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also // works in modular arithmetic, doubling the correct bits in each step. inverse *= 2 - denominator * inverse; // inverse mod 2^8 inverse *= 2 - denominator * inverse; // inverse mod 2^16 inverse *= 2 - denominator * inverse; // inverse mod 2^32 inverse *= 2 - denominator * inverse; // inverse mod 2^64 inverse *= 2 - denominator * inverse; // inverse mod 2^128 inverse *= 2 - denominator * inverse; // inverse mod 2^256 // Because the division is now exact we can divide by multiplying with the modular inverse of denominator. // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inverse; return result; } } /** * @notice Calculates x * y / denominator with full precision, following the selected rounding direction. */ function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) { uint256 result = mulDiv(x, y, denominator); if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) { result += 1; } return result; } /** * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded * towards zero. * * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11). */ function sqrt(uint256 a) internal pure returns (uint256) { if (a == 0) { return 0; } // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target. // // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 1); // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128, // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision // into the expected uint128 result. unchecked { result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; result = (result + a / result) >> 1; return min(result, a / result); } } /** * @notice Calculates sqrt(a), following the selected rounding direction. */ function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = sqrt(a); return result + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10 of a positive value rounded towards zero. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256 of a positive value rounded towards zero. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0); } } /** * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers. */ function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) { return uint8(rounding) % 2 == 1; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.20; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeCast { /** * @dev Value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value); /** * @dev An int value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedIntToUint(int256 value); /** * @dev Value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedIntDowncast(uint8 bits, int256 value); /** * @dev An uint value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedUintToInt(uint256 value); /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits */ function toUint248(uint256 value) internal pure returns (uint248) { if (value > type(uint248).max) { revert SafeCastOverflowedUintDowncast(248, value); } return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits */ function toUint240(uint256 value) internal pure returns (uint240) { if (value > type(uint240).max) { revert SafeCastOverflowedUintDowncast(240, value); } return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits */ function toUint232(uint256 value) internal pure returns (uint232) { if (value > type(uint232).max) { revert SafeCastOverflowedUintDowncast(232, value); } return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { if (value > type(uint224).max) { revert SafeCastOverflowedUintDowncast(224, value); } return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits */ function toUint216(uint256 value) internal pure returns (uint216) { if (value > type(uint216).max) { revert SafeCastOverflowedUintDowncast(216, value); } return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits */ function toUint208(uint256 value) internal pure returns (uint208) { if (value > type(uint208).max) { revert SafeCastOverflowedUintDowncast(208, value); } return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits */ function toUint200(uint256 value) internal pure returns (uint200) { if (value > type(uint200).max) { revert SafeCastOverflowedUintDowncast(200, value); } return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { if (value > type(uint192).max) { revert SafeCastOverflowedUintDowncast(192, value); } return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits */ function toUint184(uint256 value) internal pure returns (uint184) { if (value > type(uint184).max) { revert SafeCastOverflowedUintDowncast(184, value); } return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits */ function toUint176(uint256 value) internal pure returns (uint176) { if (value > type(uint176).max) { revert SafeCastOverflowedUintDowncast(176, value); } return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits */ function toUint168(uint256 value) internal pure returns (uint168) { if (value > type(uint168).max) { revert SafeCastOverflowedUintDowncast(168, value); } return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits */ function toUint160(uint256 value) internal pure returns (uint160) { if (value > type(uint160).max) { revert SafeCastOverflowedUintDowncast(160, value); } return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits */ function toUint152(uint256 value) internal pure returns (uint152) { if (value > type(uint152).max) { revert SafeCastOverflowedUintDowncast(152, value); } return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits */ function toUint144(uint256 value) internal pure returns (uint144) { if (value > type(uint144).max) { revert SafeCastOverflowedUintDowncast(144, value); } return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits */ function toUint136(uint256 value) internal pure returns (uint136) { if (value > type(uint136).max) { revert SafeCastOverflowedUintDowncast(136, value); } return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { if (value > type(uint128).max) { revert SafeCastOverflowedUintDowncast(128, value); } return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits */ function toUint120(uint256 value) internal pure returns (uint120) { if (value > type(uint120).max) { revert SafeCastOverflowedUintDowncast(120, value); } return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits */ function toUint112(uint256 value) internal pure returns (uint112) { if (value > type(uint112).max) { revert SafeCastOverflowedUintDowncast(112, value); } return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits */ function toUint104(uint256 value) internal pure returns (uint104) { if (value > type(uint104).max) { revert SafeCastOverflowedUintDowncast(104, value); } return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { if (value > type(uint96).max) { revert SafeCastOverflowedUintDowncast(96, value); } return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits */ function toUint88(uint256 value) internal pure returns (uint88) { if (value > type(uint88).max) { revert SafeCastOverflowedUintDowncast(88, value); } return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits */ function toUint80(uint256 value) internal pure returns (uint80) { if (value > type(uint80).max) { revert SafeCastOverflowedUintDowncast(80, value); } return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits */ function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { if (value > type(uint64).max) { revert SafeCastOverflowedUintDowncast(64, value); } return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits */ function toUint56(uint256 value) internal pure returns (uint56) { if (value > type(uint56).max) { revert SafeCastOverflowedUintDowncast(56, value); } return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits */ function toUint48(uint256 value) internal pure returns (uint48) { if (value > type(uint48).max) { revert SafeCastOverflowedUintDowncast(48, value); } return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { if (value > type(uint40).max) { revert SafeCastOverflowedUintDowncast(40, value); } return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { if (value > type(uint32).max) { revert SafeCastOverflowedUintDowncast(32, value); } return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits */ function toUint24(uint256 value) internal pure returns (uint24) { if (value > type(uint24).max) { revert SafeCastOverflowedUintDowncast(24, value); } return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { if (value > type(uint16).max) { revert SafeCastOverflowedUintDowncast(16, value); } return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits */ function toUint8(uint256 value) internal pure returns (uint8) { if (value > type(uint8).max) { revert SafeCastOverflowedUintDowncast(8, value); } return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { if (value < 0) { revert SafeCastOverflowedIntToUint(value); } return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(248, value); } } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(240, value); } } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(232, value); } } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(224, value); } } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(216, value); } } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(208, value); } } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(200, value); } } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(192, value); } } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(184, value); } } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(176, value); } } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(168, value); } } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(160, value); } } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(144, value); } } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(136, value); } } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(128, value); } } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(112, value); } } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(104, value); } } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(96, value); } } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(88, value); } } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(80, value); } } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(72, value); } } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(64, value); } } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(56, value); } } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(48, value); } } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(40, value); } } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(32, value); } } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(24, value); } } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(16, value); } } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(8, value); } } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive if (value > uint256(type(int256).max)) { revert SafeCastOverflowedUintToInt(value); } return int256(value); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.20; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Nonces.sol) pragma solidity ^0.8.20; /** * @dev Provides tracking nonces for addresses. Nonces will only increment. */ abstract contract Nonces { /** * @dev The nonce used for an `account` is not the expected current nonce. */ error InvalidAccountNonce(address account, uint256 currentNonce); mapping(address account => uint256) private _nonces; /** * @dev Returns the next unused nonce for an address. */ function nonces(address owner) public view virtual returns (uint256) { return _nonces[owner]; } /** * @dev Consumes a nonce. * * Returns the current value and increments nonce. */ function _useNonce(address owner) internal virtual returns (uint256) { // For each account, the nonce has an initial value of 0, can only be incremented by one, and cannot be // decremented or reset. This guarantees that the nonce never overflows. unchecked { // It is important to do x++ and not ++x here. return _nonces[owner]++; } } /** * @dev Same as {_useNonce} but checking that `nonce` is the next valid for `owner`. */ function _useCheckedNonce(address owner, uint256 nonce) internal virtual { uint256 current = _useNonce(owner); if (nonce != current) { revert InvalidAccountNonce(owner, current); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { bool private _paused; /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); /** * @dev The operation failed because the contract is paused. */ error EnforcedPause(); /** * @dev The operation failed because the contract is not paused. */ error ExpectedPause(); /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { if (paused()) { revert EnforcedPause(); } } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { if (!paused()) { revert ExpectedPause(); } } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/ReentrancyGuard.sol) pragma solidity ^0.8.20; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant NOT_ENTERED = 1; uint256 private constant ENTERED = 2; uint256 private _status; /** * @dev Unauthorized reentrant call. */ error ReentrancyGuardReentrantCall(); constructor() { _status = NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { _nonReentrantBefore(); _; _nonReentrantAfter(); } function _nonReentrantBefore() private { // On the first call to nonReentrant, _status will be NOT_ENTERED if (_status == ENTERED) { revert ReentrancyGuardReentrantCall(); } // Any calls to nonReentrant after this point will fail _status = ENTERED; } function _nonReentrantAfter() private { // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = NOT_ENTERED; } /** * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a * `nonReentrant` function in the call stack. */ function _reentrancyGuardEntered() internal view returns (bool) { return _status == ENTERED; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/ShortStrings.sol) pragma solidity ^0.8.20; import {StorageSlot} from "./StorageSlot.sol"; // | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA | // | length | 0x BB | type ShortString is bytes32; /** * @dev This library provides functions to convert short memory strings * into a `ShortString` type that can be used as an immutable variable. * * Strings of arbitrary length can be optimized using this library if * they are short enough (up to 31 bytes) by packing them with their * length (1 byte) in a single EVM word (32 bytes). Additionally, a * fallback mechanism can be used for every other case. * * Usage example: * * ```solidity * contract Named { * using ShortStrings for *; * * ShortString private immutable _name; * string private _nameFallback; * * constructor(string memory contractName) { * _name = contractName.toShortStringWithFallback(_nameFallback); * } * * function name() external view returns (string memory) { * return _name.toStringWithFallback(_nameFallback); * } * } * ``` */ library ShortStrings { // Used as an identifier for strings longer than 31 bytes. bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF; error StringTooLong(string str); error InvalidShortString(); /** * @dev Encode a string of at most 31 chars into a `ShortString`. * * This will trigger a `StringTooLong` error is the input string is too long. */ function toShortString(string memory str) internal pure returns (ShortString) { bytes memory bstr = bytes(str); if (bstr.length > 31) { revert StringTooLong(str); } return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length)); } /** * @dev Decode a `ShortString` back to a "normal" string. */ function toString(ShortString sstr) internal pure returns (string memory) { uint256 len = byteLength(sstr); // using `new string(len)` would work locally but is not memory safe. string memory str = new string(32); /// @solidity memory-safe-assembly assembly { mstore(str, len) mstore(add(str, 0x20), sstr) } return str; } /** * @dev Return the length of a `ShortString`. */ function byteLength(ShortString sstr) internal pure returns (uint256) { uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF; if (result > 31) { revert InvalidShortString(); } return result; } /** * @dev Encode a string into a `ShortString`, or write it to storage if it is too long. */ function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) { if (bytes(value).length < 32) { return toShortString(value); } else { StorageSlot.getStringSlot(store).value = value; return ShortString.wrap(FALLBACK_SENTINEL); } } /** * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}. */ function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) { if (ShortString.unwrap(value) != FALLBACK_SENTINEL) { return toString(value); } else { return store; } } /** * @dev Return the length of a string that was encoded to `ShortString` or written to storage using * {setWithFallback}. * * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of * actual characters as the UTF-8 encoding of a single character can span over multiple bytes. */ function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) { if (ShortString.unwrap(value) != FALLBACK_SENTINEL) { return byteLength(value); } else { return bytes(store).length; } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/StorageSlot.sol) // This file was procedurally generated from scripts/generate/templates/StorageSlot.js. pragma solidity ^0.8.20; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ```solidity * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(newImplementation.code.length > 0); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } struct StringSlot { string value; } struct BytesSlot { bytes value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` with member `value` located at `slot`. */ function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `StringSlot` representation of the string storage pointer `store`. */ function getStringSlot(string storage store) internal pure returns (StringSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } /** * @dev Returns an `BytesSlot` with member `value` located at `slot`. */ function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := slot } } /** * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`. */ function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) { /// @solidity memory-safe-assembly assembly { r.slot := store.slot } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol) pragma solidity ^0.8.20; import {Math} from "./math/Math.sol"; import {SignedMath} from "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant HEX_DIGITS = "0123456789abcdef"; uint8 private constant ADDRESS_LENGTH = 20; /** * @dev The `value` string doesn't fit in the specified `length`. */ error StringsInsufficientHexLength(uint256 value, uint256 length); /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), HEX_DIGITS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toStringSigned(int256 value) internal pure returns (string memory) { return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { uint256 localValue = value; bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = HEX_DIGITS[localValue & 0xf]; localValue >>= 4; } if (localValue != 0) { revert StringsInsufficientHexLength(value, length); } return string(buffer); } /** * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal * representation. */ function toHexString(address addr) internal pure returns (string memory) { return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/structs/Checkpoints.sol) // This file was procedurally generated from scripts/generate/templates/Checkpoints.js. pragma solidity ^0.8.20; import {Math} from "../math/Math.sol"; /** * @dev This library defines the `Trace*` struct, for checkpointing values as they change at different points in * time, and later looking up past values by block number. See {Votes} as an example. * * To create a history of checkpoints define a variable type `Checkpoints.Trace*` in your contract, and store a new * checkpoint for the current transaction block using the {push} function. */ library Checkpoints { /** * @dev A value was attempted to be inserted on a past checkpoint. */ error CheckpointUnorderedInsertion(); struct Trace224 { Checkpoint224[] _checkpoints; } struct Checkpoint224 { uint32 _key; uint224 _value; } /** * @dev Pushes a (`key`, `value`) pair into a Trace224 so that it is stored as the checkpoint. * * Returns previous value and new value. * * IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint32).max` key set will disable the * library. */ function push(Trace224 storage self, uint32 key, uint224 value) internal returns (uint224, uint224) { return _insert(self._checkpoints, key, value); } /** * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if * there is none. */ function lowerLookup(Trace224 storage self, uint32 key) internal view returns (uint224) { uint256 len = self._checkpoints.length; uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len); return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero * if there is none. */ function upperLookup(Trace224 storage self, uint32 key) internal view returns (uint224) { uint256 len = self._checkpoints.length; uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero * if there is none. * * NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high * keys). */ function upperLookupRecent(Trace224 storage self, uint32 key) internal view returns (uint224) { uint256 len = self._checkpoints.length; uint256 low = 0; uint256 high = len; if (len > 5) { uint256 mid = len - Math.sqrt(len); if (key < _unsafeAccess(self._checkpoints, mid)._key) { high = mid; } else { low = mid + 1; } } uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints. */ function latest(Trace224 storage self) internal view returns (uint224) { uint256 pos = self._checkpoints.length; return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value * in the most recent checkpoint. */ function latestCheckpoint(Trace224 storage self) internal view returns (bool exists, uint32 _key, uint224 _value) { uint256 pos = self._checkpoints.length; if (pos == 0) { return (false, 0, 0); } else { Checkpoint224 memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); return (true, ckpt._key, ckpt._value); } } /** * @dev Returns the number of checkpoint. */ function length(Trace224 storage self) internal view returns (uint256) { return self._checkpoints.length; } /** * @dev Returns checkpoint at given position. */ function at(Trace224 storage self, uint32 pos) internal view returns (Checkpoint224 memory) { return self._checkpoints[pos]; } /** * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint, * or by updating the last one. */ function _insert(Checkpoint224[] storage self, uint32 key, uint224 value) private returns (uint224, uint224) { uint256 pos = self.length; if (pos > 0) { // Copying to memory is important here. Checkpoint224 memory last = _unsafeAccess(self, pos - 1); // Checkpoint keys must be non-decreasing. if (last._key > key) { revert CheckpointUnorderedInsertion(); } // Update or push new checkpoint if (last._key == key) { _unsafeAccess(self, pos - 1)._value = value; } else { self.push(Checkpoint224({_key: key, _value: value})); } return (last._value, value); } else { self.push(Checkpoint224({_key: key, _value: value})); return (0, value); } } /** * @dev Return the index of the last (most recent) checkpoint with key lower or equal than the search key, or `high` * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive * `high`. * * WARNING: `high` should not be greater than the array's length. */ function _upperBinaryLookup( Checkpoint224[] storage self, uint32 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = Math.average(low, high); if (_unsafeAccess(self, mid)._key > key) { high = mid; } else { low = mid + 1; } } return high; } /** * @dev Return the index of the first (oldest) checkpoint with key is greater or equal than the search key, or * `high` if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and * exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _lowerBinaryLookup( Checkpoint224[] storage self, uint32 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = Math.average(low, high); if (_unsafeAccess(self, mid)._key < key) { low = mid + 1; } else { high = mid; } } return high; } /** * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. */ function _unsafeAccess( Checkpoint224[] storage self, uint256 pos ) private pure returns (Checkpoint224 storage result) { assembly { mstore(0, self.slot) result.slot := add(keccak256(0, 0x20), pos) } } struct Trace208 { Checkpoint208[] _checkpoints; } struct Checkpoint208 { uint48 _key; uint208 _value; } /** * @dev Pushes a (`key`, `value`) pair into a Trace208 so that it is stored as the checkpoint. * * Returns previous value and new value. * * IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint48).max` key set will disable the * library. */ function push(Trace208 storage self, uint48 key, uint208 value) internal returns (uint208, uint208) { return _insert(self._checkpoints, key, value); } /** * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if * there is none. */ function lowerLookup(Trace208 storage self, uint48 key) internal view returns (uint208) { uint256 len = self._checkpoints.length; uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len); return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero * if there is none. */ function upperLookup(Trace208 storage self, uint48 key) internal view returns (uint208) { uint256 len = self._checkpoints.length; uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero * if there is none. * * NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high * keys). */ function upperLookupRecent(Trace208 storage self, uint48 key) internal view returns (uint208) { uint256 len = self._checkpoints.length; uint256 low = 0; uint256 high = len; if (len > 5) { uint256 mid = len - Math.sqrt(len); if (key < _unsafeAccess(self._checkpoints, mid)._key) { high = mid; } else { low = mid + 1; } } uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints. */ function latest(Trace208 storage self) internal view returns (uint208) { uint256 pos = self._checkpoints.length; return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value * in the most recent checkpoint. */ function latestCheckpoint(Trace208 storage self) internal view returns (bool exists, uint48 _key, uint208 _value) { uint256 pos = self._checkpoints.length; if (pos == 0) { return (false, 0, 0); } else { Checkpoint208 memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); return (true, ckpt._key, ckpt._value); } } /** * @dev Returns the number of checkpoint. */ function length(Trace208 storage self) internal view returns (uint256) { return self._checkpoints.length; } /** * @dev Returns checkpoint at given position. */ function at(Trace208 storage self, uint32 pos) internal view returns (Checkpoint208 memory) { return self._checkpoints[pos]; } /** * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint, * or by updating the last one. */ function _insert(Checkpoint208[] storage self, uint48 key, uint208 value) private returns (uint208, uint208) { uint256 pos = self.length; if (pos > 0) { // Copying to memory is important here. Checkpoint208 memory last = _unsafeAccess(self, pos - 1); // Checkpoint keys must be non-decreasing. if (last._key > key) { revert CheckpointUnorderedInsertion(); } // Update or push new checkpoint if (last._key == key) { _unsafeAccess(self, pos - 1)._value = value; } else { self.push(Checkpoint208({_key: key, _value: value})); } return (last._value, value); } else { self.push(Checkpoint208({_key: key, _value: value})); return (0, value); } } /** * @dev Return the index of the last (most recent) checkpoint with key lower or equal than the search key, or `high` * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive * `high`. * * WARNING: `high` should not be greater than the array's length. */ function _upperBinaryLookup( Checkpoint208[] storage self, uint48 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = Math.average(low, high); if (_unsafeAccess(self, mid)._key > key) { high = mid; } else { low = mid + 1; } } return high; } /** * @dev Return the index of the first (oldest) checkpoint with key is greater or equal than the search key, or * `high` if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and * exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _lowerBinaryLookup( Checkpoint208[] storage self, uint48 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = Math.average(low, high); if (_unsafeAccess(self, mid)._key < key) { low = mid + 1; } else { high = mid; } } return high; } /** * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. */ function _unsafeAccess( Checkpoint208[] storage self, uint256 pos ) private pure returns (Checkpoint208 storage result) { assembly { mstore(0, self.slot) result.slot := add(keccak256(0, 0x20), pos) } } struct Trace160 { Checkpoint160[] _checkpoints; } struct Checkpoint160 { uint96 _key; uint160 _value; } /** * @dev Pushes a (`key`, `value`) pair into a Trace160 so that it is stored as the checkpoint. * * Returns previous value and new value. * * IMPORTANT: Never accept `key` as a user input, since an arbitrary `type(uint96).max` key set will disable the * library. */ function push(Trace160 storage self, uint96 key, uint160 value) internal returns (uint160, uint160) { return _insert(self._checkpoints, key, value); } /** * @dev Returns the value in the first (oldest) checkpoint with key greater or equal than the search key, or zero if * there is none. */ function lowerLookup(Trace160 storage self, uint96 key) internal view returns (uint160) { uint256 len = self._checkpoints.length; uint256 pos = _lowerBinaryLookup(self._checkpoints, key, 0, len); return pos == len ? 0 : _unsafeAccess(self._checkpoints, pos)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero * if there is none. */ function upperLookup(Trace160 storage self, uint96 key) internal view returns (uint160) { uint256 len = self._checkpoints.length; uint256 pos = _upperBinaryLookup(self._checkpoints, key, 0, len); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the last (most recent) checkpoint with key lower or equal than the search key, or zero * if there is none. * * NOTE: This is a variant of {upperLookup} that is optimised to find "recent" checkpoint (checkpoints with high * keys). */ function upperLookupRecent(Trace160 storage self, uint96 key) internal view returns (uint160) { uint256 len = self._checkpoints.length; uint256 low = 0; uint256 high = len; if (len > 5) { uint256 mid = len - Math.sqrt(len); if (key < _unsafeAccess(self._checkpoints, mid)._key) { high = mid; } else { low = mid + 1; } } uint256 pos = _upperBinaryLookup(self._checkpoints, key, low, high); return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns the value in the most recent checkpoint, or zero if there are no checkpoints. */ function latest(Trace160 storage self) internal view returns (uint160) { uint256 pos = self._checkpoints.length; return pos == 0 ? 0 : _unsafeAccess(self._checkpoints, pos - 1)._value; } /** * @dev Returns whether there is a checkpoint in the structure (i.e. it is not empty), and if so the key and value * in the most recent checkpoint. */ function latestCheckpoint(Trace160 storage self) internal view returns (bool exists, uint96 _key, uint160 _value) { uint256 pos = self._checkpoints.length; if (pos == 0) { return (false, 0, 0); } else { Checkpoint160 memory ckpt = _unsafeAccess(self._checkpoints, pos - 1); return (true, ckpt._key, ckpt._value); } } /** * @dev Returns the number of checkpoint. */ function length(Trace160 storage self) internal view returns (uint256) { return self._checkpoints.length; } /** * @dev Returns checkpoint at given position. */ function at(Trace160 storage self, uint32 pos) internal view returns (Checkpoint160 memory) { return self._checkpoints[pos]; } /** * @dev Pushes a (`key`, `value`) pair into an ordered list of checkpoints, either by inserting a new checkpoint, * or by updating the last one. */ function _insert(Checkpoint160[] storage self, uint96 key, uint160 value) private returns (uint160, uint160) { uint256 pos = self.length; if (pos > 0) { // Copying to memory is important here. Checkpoint160 memory last = _unsafeAccess(self, pos - 1); // Checkpoint keys must be non-decreasing. if (last._key > key) { revert CheckpointUnorderedInsertion(); } // Update or push new checkpoint if (last._key == key) { _unsafeAccess(self, pos - 1)._value = value; } else { self.push(Checkpoint160({_key: key, _value: value})); } return (last._value, value); } else { self.push(Checkpoint160({_key: key, _value: value})); return (0, value); } } /** * @dev Return the index of the last (most recent) checkpoint with key lower or equal than the search key, or `high` * if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and exclusive * `high`. * * WARNING: `high` should not be greater than the array's length. */ function _upperBinaryLookup( Checkpoint160[] storage self, uint96 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = Math.average(low, high); if (_unsafeAccess(self, mid)._key > key) { high = mid; } else { low = mid + 1; } } return high; } /** * @dev Return the index of the first (oldest) checkpoint with key is greater or equal than the search key, or * `high` if there is none. `low` and `high` define a section where to do the search, with inclusive `low` and * exclusive `high`. * * WARNING: `high` should not be greater than the array's length. */ function _lowerBinaryLookup( Checkpoint160[] storage self, uint96 key, uint256 low, uint256 high ) private view returns (uint256) { while (low < high) { uint256 mid = Math.average(low, high); if (_unsafeAccess(self, mid)._key < key) { low = mid + 1; } else { high = mid; } } return high; } /** * @dev Access an element of the array without performing bounds check. The position is assumed to be within bounds. */ function _unsafeAccess( Checkpoint160[] storage self, uint256 pos ) private pure returns (Checkpoint160 storage result) { assembly { mstore(0, self.slot) result.slot := add(keccak256(0, 0x20), pos) } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (utils/types/Time.sol) pragma solidity ^0.8.20; import {Math} from "../math/Math.sol"; import {SafeCast} from "../math/SafeCast.sol"; /** * @dev This library provides helpers for manipulating time-related objects. * * It uses the following types: * - `uint48` for timepoints * - `uint32` for durations * * While the library doesn't provide specific types for timepoints and duration, it does provide: * - a `Delay` type to represent duration that can be programmed to change value automatically at a given point * - additional helper functions */ library Time { using Time for *; /** * @dev Get the block timestamp as a Timepoint. */ function timestamp() internal view returns (uint48) { return SafeCast.toUint48(block.timestamp); } /** * @dev Get the block number as a Timepoint. */ function blockNumber() internal view returns (uint48) { return SafeCast.toUint48(block.number); } // ==================================================== Delay ===================================================== /** * @dev A `Delay` is a uint32 duration that can be programmed to change value automatically at a given point in the * future. The "effect" timepoint describes when the transitions happens from the "old" value to the "new" value. * This allows updating the delay applied to some operation while keeping some guarantees. * * In particular, the {update} function guarantees that if the delay is reduced, the old delay still applies for * some time. For example if the delay is currently 7 days to do an upgrade, the admin should not be able to set * the delay to 0 and upgrade immediately. If the admin wants to reduce the delay, the old delay (7 days) should * still apply for some time. * * * The `Delay` type is 112 bits long, and packs the following: * * ``` * | [uint48]: effect date (timepoint) * | | [uint32]: value before (duration) * ↓ ↓ ↓ [uint32]: value after (duration) * 0xAAAAAAAAAAAABBBBBBBBCCCCCCCC * ``` * * NOTE: The {get} and {withUpdate} functions operate using timestamps. Block number based delays are not currently * supported. */ type Delay is uint112; /** * @dev Wrap a duration into a Delay to add the one-step "update in the future" feature */ function toDelay(uint32 duration) internal pure returns (Delay) { return Delay.wrap(duration); } /** * @dev Get the value at a given timepoint plus the pending value and effect timepoint if there is a scheduled * change after this timepoint. If the effect timepoint is 0, then the pending value should not be considered. */ function _getFullAt(Delay self, uint48 timepoint) private pure returns (uint32, uint32, uint48) { (uint32 valueBefore, uint32 valueAfter, uint48 effect) = self.unpack(); return effect <= timepoint ? (valueAfter, 0, 0) : (valueBefore, valueAfter, effect); } /** * @dev Get the current value plus the pending value and effect timepoint if there is a scheduled change. If the * effect timepoint is 0, then the pending value should not be considered. */ function getFull(Delay self) internal view returns (uint32, uint32, uint48) { return _getFullAt(self, timestamp()); } /** * @dev Get the current value. */ function get(Delay self) internal view returns (uint32) { (uint32 delay, , ) = self.getFull(); return delay; } /** * @dev Update a Delay object so that it takes a new duration after a timepoint that is automatically computed to * enforce the old delay at the moment of the update. Returns the updated Delay object and the timestamp when the * new delay becomes effective. */ function withUpdate( Delay self, uint32 newValue, uint32 minSetback ) internal view returns (Delay updatedDelay, uint48 effect) { uint32 value = self.get(); uint32 setback = uint32(Math.max(minSetback, value > newValue ? value - newValue : 0)); effect = timestamp() + setback; return (pack(value, newValue, effect), effect); } /** * @dev Split a delay into its components: valueBefore, valueAfter and effect (transition timepoint). */ function unpack(Delay self) internal pure returns (uint32 valueBefore, uint32 valueAfter, uint48 effect) { uint112 raw = Delay.unwrap(self); valueAfter = uint32(raw); valueBefore = uint32(raw >> 32); effect = uint48(raw >> 64); return (valueBefore, valueAfter, effect); } /** * @dev pack the components into a Delay object. */ function pack(uint32 valueBefore, uint32 valueAfter, uint48 effect) internal pure returns (Delay) { return Delay.wrap((uint112(effect) << 64) | (uint112(valueBefore) << 32) | uint112(valueAfter)); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import {ERC20Burnable} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol"; import {ERC20Votes} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Votes.sol"; import {Nonces} from "@openzeppelin/contracts/utils/Nonces.sol"; import "./IBARD.sol"; /** * @title ERC20 representation of Lombard Governance Token (BARD) * @author Lombard.Finance * @notice The contracts is a part of Lombard.Finace protocol */ contract BARD is Ownable2Step, ERC20Burnable, ERC20Permit, ERC20Votes, IBARD { // Maximum inflation rate per year (percentage) expressed as an integer uint256 public constant MAX_INFLATION = 10; // The frequency limit on inflationary mint invocations uint256 public constant MINT_WAIT_PERIOD = 365 days; //The last time the mint function was called uint256 public lastMintTimestamp; constructor( address _initialOwner, address _treasury ) ERC20("Lombard", "BARD") ERC20Permit("Lombard") Ownable(_initialOwner) { // The next mint after initial one not allowed until 1 year after deployment lastMintTimestamp = block.timestamp; // mint initial supply _mint(_treasury, 1_000_000_000 * 1 ether); } /** * @notice Mints new BARD tokens * @param to The address to mint tokens to * @param amount The amount of tokens to mint * @dev Only callable by the owner once per year. The amount must be less than the product of the maximum inflation rate and the current total supply. */ function mint(address to, uint256 amount) external onlyOwner { if (block.timestamp - lastMintTimestamp < MINT_WAIT_PERIOD) revert MintWaitPeriodNotClosed( MINT_WAIT_PERIOD - (block.timestamp - lastMintTimestamp) ); uint256 _maxInflationAmount = (totalSupply() * MAX_INFLATION) / 100; if (amount > _maxInflationAmount) revert MaxInflationExceeded(_maxInflationAmount); lastMintTimestamp = block.timestamp; _mint(to, amount); } /// @notice Prevents the owner from renouncing ownership function renounceOwnership() public view override onlyOwner { revert CantRenounceOwnership(); } /** * @dev Override of the _update function to satisfy both ERC20 and ERC20Votes */ function _update( address from, address to, uint256 value ) internal virtual override(ERC20, ERC20Votes) { super._update(from, to, value); } /** * @dev Override of the nonces function to satisfy both ERC20Permit and Nonces. These nonces are used for both token permits and voting delegation. */ function nonces( address owner ) public view virtual override(ERC20Permit, Nonces) returns (uint256) { return super.nonces(owner); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; interface IBARD { error MintWaitPeriodNotClosed(uint256 timeToWait); error MaxInflationExceeded(uint256 maxAllowedAmount); error CantRenounceOwnership(); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Ownable, Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract TokenDistributor is Ownable2Step { using SafeERC20 for IERC20; /*////////////////////////////////////////////////////////////// EVENTS //////////////////////////////////////////////////////////////*/ /// @notice Emitted when a user claims tokens. /// @param user The user address. /// @param amount The amount of tokens claimed. event Claimed(address indexed user, uint256 amount); /// @notice Emitted when the owner withdraws tokens. /// @param owner The owner address. /// @param amount The amount of tokens withdrawn. event Withdrawn(address indexed owner, uint256 amount); /*////////////////////////////////////////////////////////////// ERRORS //////////////////////////////////////////////////////////////*/ error InvalidAmount(); error AlreadyClaimed(); error InvalidProof(); error InvalidToken(); error EmptyProof(); error ClaimFinished(); error ClaimNotFinished(); /*////////////////////////////////////////////////////////////// IMMUTABLE STORAGE //////////////////////////////////////////////////////////////*/ /// @notice The merkle root hash. bytes32 public immutable MERKLE_ROOT; /// @notice The token contract. IERC20 public immutable TOKEN; /// @notice The timestamp when the claim period ends. uint256 public immutable CLAIM_END; /*////////////////////////////////////////////////////////////// STORAGE //////////////////////////////////////////////////////////////*/ /// @notice Mapping of claimed status. mapping(address user => bool claimed) public hasClaimed; /*////////////////////////////////////////////////////////////// CONSTRUCTOR //////////////////////////////////////////////////////////////*/ /// @notice Define the merkle root, base signer, token and owner. /// @param _merkleRoot The merkle root hash. /// @param _token The token address. /// @param _owner The owner address. /// @param _claimEnd The timestamp when the claim period ends. constructor(bytes32 _merkleRoot, address _token, address _owner, uint256 _claimEnd) Ownable(_owner) { if (_token == address(0)) revert InvalidToken(); MERKLE_ROOT = _merkleRoot; TOKEN = IERC20(_token); CLAIM_END = _claimEnd; } /*////////////////////////////////////////////////////////////// EXTERNAL FUNCTIONS //////////////////////////////////////////////////////////////*/ /// @notice Claim tokens using a signature and merkle proof. /// @param _account The account to claim tokens for. /// @param _amount Amount of tokens to claim. /// @param _merkleProof Merkle proof of claim. function claim(address _account, uint256 _amount, bytes32[] calldata _merkleProof) external { if (_amount == 0) revert InvalidAmount(); if (hasClaimed[_account]) revert AlreadyClaimed(); if (_merkleProof.length == 0) revert EmptyProof(); if (block.timestamp >= CLAIM_END) revert ClaimFinished(); // Generate the leaf bytes32 leaf = keccak256(bytes.concat(keccak256(abi.encode(_account, _amount)))); // Verify the merkle proof if (!MerkleProof.verify(_merkleProof, MERKLE_ROOT, leaf)) revert InvalidProof(); // Mark as claimed and send the tokens hasClaimed[_account] = true; TOKEN.safeTransfer(_account, _amount); emit Claimed(_account, _amount); } /// @notice Withdraw tokens from the contract. function withdraw() external onlyOwner { if (block.timestamp < CLAIM_END) revert ClaimNotFinished(); uint256 balance = TOKEN.balanceOf(address(this)); TOKEN.safeTransfer(msg.sender, balance); emit Withdrawn(msg.sender, balance); } }
// SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity 0.8.24; import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol"; import {AccessControlDefaultAdminRules} from "@openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol"; import {IBascule} from "./interfaces/IBascule.sol"; /// Bascule contract for preventing bridge hacks from hitting the chain. /// This is the on-chain component of an off-chain/on-chain system. /// The off-chain component watches all relevant chains and reports /// deposits to a deployment of this contract on *at most* one chain /// (to prevent replay attacks). Then, this contract records the relevant /// deposit transactions. Finally, when a bridge wants to withdraw funds, /// it can validate that a corresponding deposit took place using the /// validateWithdrawal function. /// /// @custom:security-contact [email protected] contract Bascule is IBascule, Pausable, AccessControlDefaultAdminRules { // Role that can pause withdrawal and deposit reporting bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // Role that can report deposit transactions to the history bytes32 public constant DEPOSIT_REPORTER_ROLE = keccak256("DEPOSIT_REPORTER_ROLE"); // Role that can validate withdrawals (and thus remove deposits from the history) bytes32 public constant WITHDRAWAL_VALIDATOR_ROLE = keccak256("WITHDRAWAL_VALIDATOR_ROLE"); // Role that can be used to change the validation threshold bytes32 public constant VALIDATION_GUARDIAN_ROLE = keccak256("VALIDATION_GUARDIAN_ROLE"); // The bascule validates all withdrawals whose amounts are greater than or // equal to this threshold. The bascule allows all withdrawals below this // threshold. The contract will still produce events that off-chain code can // use to monitor smaller withdrawals. This threshold can only be changed by // the guardian. // // When the threshold is zero (the default), the bascule validates all // withdrawals. // // NOTE: Raising this threshold should be done with extreme caution. In // particular, you MUST make sure that validateWithdrawal is called with a // correct withdrawal amount. uint256 private _validateThreshold; // Maximum number of batch deposits it's possible to make at once uint256 private _mMaxDeposits; // Mapping that tracks deposits on a different chain that can be used to // withdraw the corresponding funds on this chain. // // NOTE: The deposit identifier should be a hash with enough information to // uniquely identify the deposit transaction on the source chain and the // recipient, amount, and chain-id on this chain. // See README for more. mapping(bytes32 depositID => DepositState status) public depositHistory; // Describes the state of a deposit in the depositHistory. enum DepositState { UNREPORTED, // unreported must be '0' REPORTED, WITHDRAWN } /** * Event emitted when the validation threshold is updated. * @param oldThreshold The old threshold. * @param newThreshold The new threshold. */ event UpdateValidateThreshold(uint256 oldThreshold, uint256 newThreshold); /** * Event emitted when the maximum number of deposits once is changed. * @param numDeposits New maximum number of deposits. */ event MaxDepositsUpdated(uint256 numDeposits); /** * Event emitted when a batch of deposits is reported. * @param reportId The report identifier. This is a convenience to make off-chain state mangement easier. * @param numDeposits The number of deposits reported. */ event DepositsReported(bytes32 indexed reportId, uint256 numDeposits); /** * Event emitted when a withdrawal is allowed on this chain without validation. * @param depositID Unique identifier for a deposit that took place on another chain and was withdrawn on this chain. * @param withdrawalAmount Amount of the withdrawal. */ event WithdrawalNotValidated(bytes32 depositID, uint256 withdrawalAmount); /** * Error when trying to change the validation threshold to the same value. */ error SameValidationThreshold(); /** * Error when a deposit for a given depositID has already been reported. * @param depositID Unique identifier already stored in the depositHistory. */ error AlreadyReported(bytes32 depositID); /** * Error when batch deposit arguments are non-conforming. */ error BadDepositReport(); /** * Create a new Bascule. * @param aDefaultAdmin Address of the admin. This address should be controlled by a multisig. * @param aPauser Address of the account that may pause. * @param aDepositReporter Address of the account that may report deposits on the source chain. * @param aWithdrawalValidator Address of the account that may validate withdrawals. * @param aMaxDeposits Maximum number of deposits that can be reported at once. */ constructor( address aDefaultAdmin, address aPauser, address aDepositReporter, address aWithdrawalValidator, uint256 aMaxDeposits ) AccessControlDefaultAdminRules(3 days, aDefaultAdmin) { _grantRole(PAUSER_ROLE, aPauser); _grantRole(DEPOSIT_REPORTER_ROLE, aDepositReporter); _grantRole(WITHDRAWAL_VALIDATOR_ROLE, aWithdrawalValidator); _mMaxDeposits = aMaxDeposits; // By default, the bascule validates all withdrawals and does not grant // anyone the guardian role. This means that increasing the threshold (or // turning off validation) requires two steps: (1) grant role and (2) change // threshold. To preserve this invariant, we renounce the validation // guardian role when the threshold is raised. // // Initialize explicitly for readability/maintainability _validateThreshold = 0; // validate all } /// GETTERS /// /** * Returns the minimum threshold for validating withdrawals. */ function validateThreshold() public view returns (uint256) { return _validateThreshold; } /** * Get maximum number of deposits that can be reported at once. */ function maxDeposits() public view returns (uint256) { return _mMaxDeposits; } /// ACCESS CONTROL FUNCTIONS /// /** * Update the threshold for checking validation withdrawals. * Lowering the threshold means we validate more deposits; it only requires * the default admin role. Increasing the threshold means we validate fewer * deposits; it requires the validation guardian role (which the admin must * first grant), which is immediately renounced after the threshold is raised. * * NOTE: Raising this threshold should be done with extreme caution. In * particular, you MUST make sure that validateWithdrawal is called with a * correct withdrawal amount (i.e., the amount of the actual withdraw). * * Emits {UpdateValidateThreshold}. */ function updateValidateThreshold( uint256 newThreshold ) public whenNotPaused { if (newThreshold == validateThreshold()) { revert SameValidationThreshold(); } if (newThreshold < validateThreshold()) { if (!hasRole(DEFAULT_ADMIN_ROLE, _msgSender())) { revert AccessControlUnauthorizedAccount( _msgSender(), DEFAULT_ADMIN_ROLE ); } } else { if (!hasRole(VALIDATION_GUARDIAN_ROLE, _msgSender())) { revert AccessControlUnauthorizedAccount( _msgSender(), VALIDATION_GUARDIAN_ROLE ); } // Renounce the validation guardian role. This ensures the caller doesn't // have peristent privileges to effectively disable validation. renounceRole(VALIDATION_GUARDIAN_ROLE, _msgSender()); } // Actually update the threshold _updateValidateThreshold(newThreshold); } /** * Pause deposit reporting and withdrawal validation. */ function pause() public onlyRole(PAUSER_ROLE) { _pause(); } /** * Unpause deposit reporting and withdrawal validation. */ function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } /** * Set the maximum number of deposits that can be reported at once. * May only be invoked by the contract admin. * * @param aMaxDeposits New maximum number of deposits that can be reported at once. */ function setMaxDeposits( uint256 aMaxDeposits ) public whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { _mMaxDeposits = aMaxDeposits; emit MaxDepositsUpdated(aMaxDeposits); } /** * Report that a series of deposit has happened. * May only be invoked by the deposit reporter. * * @param reportId Unique identifier correponding to the report. * @param depositIDs Unique identifiers of the deposits on another chain. * * Emits {DepositsReported}. */ function reportDeposits( bytes32 reportId, bytes32[] calldata depositIDs ) public whenNotPaused onlyRole(DEPOSIT_REPORTER_ROLE) { // Make sure that the input arrays conform to length requirements uint256 numDeposits = depositIDs.length; if (numDeposits > maxDeposits()) { revert BadDepositReport(); } // Vet each set of depositID and withdrawalAddr and add to history // Explicitly init i for readability for (uint256 i = 0; i < numDeposits; ++i) { bytes32 depositID = depositIDs[i]; if (depositHistory[depositID] == DepositState.UNREPORTED) { depositHistory[depositID] = DepositState.REPORTED; } else { revert AlreadyReported(depositID); } } emit DepositsReported(reportId, numDeposits); } /** * Validate a withdrawal (before executing it) if the amount is above * threshold. * * This function checks if our accounting has recorded a deposit that * corresponds to this withdrawal request. A deposit can only be withdrawn * once. * * @param depositID Unique identifier of the deposit on another chain. * @param withdrawalAmount Amount of the withdrawal. * * Emits {WithdrawalValidated}. */ function validateWithdrawal( bytes32 depositID, uint256 withdrawalAmount ) public whenNotPaused onlyRole(WITHDRAWAL_VALIDATOR_ROLE) { DepositState status = depositHistory[depositID]; // Deposit found and not withdrawn if (status == DepositState.REPORTED) { depositHistory[depositID] = DepositState.WITHDRAWN; emit WithdrawalValidated(depositID, withdrawalAmount); return; } // Already withdrawn if (status == DepositState.WITHDRAWN) { revert AlreadyWithdrawn(depositID, withdrawalAmount); } // Not reported if (withdrawalAmount >= validateThreshold()) { // We disallow a withdrawal if it's not in the depositHistory and // the value is above the threshold. revert WithdrawalFailedValidation(depositID, withdrawalAmount); } // We don't have the depositID in the depositHistory, and the value of the // withdrawal is below the threshold, so we allow the withdrawal without // additional on-chain validation. emit WithdrawalNotValidated(depositID, withdrawalAmount); } /// PRIVATE FUNCTIONS /// /** * Update the validate threshold. * @param newThreshold New threshold. * * Emits {UpdateValidateThreshold}. */ function _updateValidateThreshold(uint256 newThreshold) internal { emit UpdateValidateThreshold(_validateThreshold, newThreshold); _validateThreshold = newThreshold; } }
// SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity 0.8.24; import "@openzeppelin/contracts/utils/Pausable.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol"; import "./interfaces/IBascule.sol"; /// Bascule contract for preventing bridge hacks from hitting the chain. /// This is the on-chain component of an off-chain/on-chain system. /// The off-chain component watches all relevant chains and reports /// deposits to a deployment of this contract on *at most* one chain /// (to prevent replay attacks). Then, this contract records the relevant /// deposit transactions. Finally, when a bridge wants to withdraw funds, /// it can validate that a corresponding deposit took place using the /// validateWithdrawal function. /// /// @custom:security-contact [email protected] contract BasculeV2 is IBascule, Pausable, AccessControlDefaultAdminRules { // Role that can pause withdrawal and deposit reporting bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // Role that can report deposit transactions to the history bytes32 public constant DEPOSIT_REPORTER_ROLE = keccak256("DEPOSIT_REPORTER_ROLE"); // Role that can validate withdrawals (and thus remove deposits from the history) bytes32 public constant WITHDRAWAL_VALIDATOR_ROLE = keccak256("WITHDRAWAL_VALIDATOR_ROLE"); // Role that can be used to change the validation threshold bytes32 public constant VALIDATION_GUARDIAN_ROLE = keccak256("VALIDATION_GUARDIAN_ROLE"); // The bascule validates all withdrawals whose amounts are greater than or // equal to this threshold. The bascule allows all withdrawals below this // threshold. The contract will still produce events that off-chain code can // use to monitor smaller withdrawals. This threshold can only be changed by // the guardian. // // When the threshold is zero (the default), the bascule validates all // withdrawals. // // NOTE: Raising this threshold should be done with extreme caution. In // particular, you MUST make sure that validateWithdrawal is called with a // correct withdrawal amount. uint256 private _validateThreshold; // Maximum number of batch deposits it's possible to make at once uint256 private _mMaxDeposits; // Mapping that tracks deposits on a different chain that can be used to // withdraw the corresponding funds on this chain. // // NOTE: The deposit identifier should be a hash with enough information to // uniquely identify the deposit transaction on the source chain and the // recipient, amount, and chain-id on this chain. // See README for more. mapping(bytes32 depositID => DepositState status) public depositHistory; // Describes the state of a deposit in the depositHistory. enum DepositState { UNREPORTED, // unreported must be '0' REPORTED, WITHDRAWN } /** * Event emitted when the validation threshold is updated. * @param oldThreshold The old threshold. * @param newThreshold The new threshold. */ event UpdateValidateThreshold(uint256 oldThreshold, uint256 newThreshold); /** * Event emitted when the maximum number of deposits is changed. * @param numDeposits New maximum number of deposits. */ event MaxDepositsUpdated(uint256 numDeposits); /** * Event emitted when a batch of deposits is reported. * @param reportId The report identifier. This is a convenience to make off-chain state mangement easier. * @param numDeposits The number of deposits reported. */ event DepositsReported(bytes32 indexed reportId, uint256 numDeposits); /** * Warning event emitted when a deposit was already reported. * @param depositID The ID of the already-reported deposit. */ event DepositAlreadyReported(bytes32 indexed depositID); /** * Event emitted when a withdrawal is allowed on this chain without validation. * @param depositID Unique identifier for a deposit that took place on another chain and was withdrawn on this chain. * @param withdrawalAmount Amount of the withdrawal. */ event WithdrawalNotValidated(bytes32 depositID, uint256 withdrawalAmount); /** * Error when trying to change the validation threshold to the same value. */ error SameValidationThreshold(); /** * Error when batch deposit arguments are non-conforming. */ error BadDepositReport(); /** * Create a new Bascule. * @param aDefaultAdmin Address of the admin. This address should be controlled by a multisig. * @param aPauser Address of the account that may pause. * @param aDepositReporter Address of the account that may report deposits on the source chain. * @param aWithdrawalValidator Address of the account that may validate withdrawals. * @param aMaxDeposits Maximum number of deposits that can be reported at once. */ constructor( address aDefaultAdmin, address aPauser, address aDepositReporter, address aWithdrawalValidator, uint256 aMaxDeposits ) AccessControlDefaultAdminRules(3 days, aDefaultAdmin) { _grantRole(PAUSER_ROLE, aPauser); _grantRole(DEPOSIT_REPORTER_ROLE, aDepositReporter); _grantRole(WITHDRAWAL_VALIDATOR_ROLE, aWithdrawalValidator); _mMaxDeposits = aMaxDeposits; // By default, the bascule validates all withdrawals and does not grant // anyone the guardian role. This means that increasing the threshold (or // turning off validation) requires two steps: (1) grant role and (2) change // threshold. To preserve this invariant, we renounce the validation // guardian role when the threshold is raised. // // Initialize explicitly for readability/maintainability _validateThreshold = 0; // validate all } /// GETTERS /// /** * Returns the minimum threshold for validating withdrawals. */ function validateThreshold() public view returns (uint256) { return _validateThreshold; } /** * Get maximum number of deposits that can be reported at once. */ function maxDeposits() public view returns (uint256) { return _mMaxDeposits; } /// ACCESS CONTROL FUNCTIONS /// /** * Pause deposit reporting and withdrawal validation. */ function pause() public onlyRole(PAUSER_ROLE) { _pause(); } /** * Unpause deposit reporting and withdrawal validation. */ function unpause() public onlyRole(PAUSER_ROLE) { _unpause(); } /** * Update the threshold for checking validation withdrawals. * Lowering the threshold means we validate more deposits; it only requires * the default admin role. Increasing the threshold means we validate fewer * deposits; it requires the validation guardian role (which the admin must * first grant), which is immediately renounced after the threshold is raised. * * NOTE: Raising this threshold should be done with extreme caution. In * particular, you MUST make sure that validateWithdrawal is called with a * correct withdrawal amount (i.e., the amount of the actual withdraw). * * Emits {UpdateValidateThreshold}. */ function updateValidateThreshold( uint256 newThreshold ) public whenNotPaused { // Retains the original reverting behavior of the original // for compatibility with off-chain code. if (newThreshold == validateThreshold()) { revert SameValidationThreshold(); } if (newThreshold < validateThreshold()) { if (!hasRole(DEFAULT_ADMIN_ROLE, _msgSender())) { revert AccessControlUnauthorizedAccount( _msgSender(), DEFAULT_ADMIN_ROLE ); } } else { if (!hasRole(VALIDATION_GUARDIAN_ROLE, _msgSender())) { revert AccessControlUnauthorizedAccount( _msgSender(), VALIDATION_GUARDIAN_ROLE ); } // Renounce the validation guardian role. This ensures the caller doesn't // have peristent privileges to effectively disable validation. renounceRole(VALIDATION_GUARDIAN_ROLE, _msgSender()); } // Actually update the threshold _updateValidateThreshold(newThreshold); } /** * Set the maximum number of deposits that can be reported at once. * May only be invoked by the contract admin. * * @param aMaxDeposits New maximum number of deposits that can be reported at once. */ function setMaxDeposits( uint256 aMaxDeposits ) public whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { _mMaxDeposits = aMaxDeposits; emit MaxDepositsUpdated(aMaxDeposits); } /** * Report that a series of deposit has happened. * May only be invoked by the deposit reporter. * * @param reportId Unique identifier correponding to the report. * @param depositIDs Unique identifiers of the deposits on another chain. * * Emits {DepositsReported}. */ function reportDeposits( bytes32 reportId, bytes32[] calldata depositIDs ) public whenNotPaused onlyRole(DEPOSIT_REPORTER_ROLE) { // Make sure that the input arrays conform to length requirements uint256 numDeposits = depositIDs.length; if (numDeposits > maxDeposits()) { revert BadDepositReport(); } // Vet each set of depositID and withdrawalAddr and add to history // Explicitly init i for readability for (uint256 i = 0; i < numDeposits; ++i) { bytes32 depositID = depositIDs[i]; if (depositHistory[depositID] == DepositState.UNREPORTED) { depositHistory[depositID] = DepositState.REPORTED; } else { // Only warn instead of reverting, unlike old contract emit DepositAlreadyReported(depositID); } } emit DepositsReported(reportId, numDeposits); } /** * Validate a withdrawal (before executing it) if the amount is above * threshold. * * This function checks if our accounting has recorded a deposit that * corresponds to this withdrawal request. A deposit can only be withdrawn * once. * * @param depositID Unique identifier of the deposit on another chain. * @param withdrawalAmount Amount of the withdrawal. * * Emits {WithdrawalValidated}. */ function validateWithdrawal( bytes32 depositID, uint256 withdrawalAmount ) public whenNotPaused onlyRole(WITHDRAWAL_VALIDATOR_ROLE) { DepositState status = depositHistory[depositID]; // Deposit found and not withdrawn if (status == DepositState.REPORTED) { depositHistory[depositID] = DepositState.WITHDRAWN; emit WithdrawalValidated(depositID, withdrawalAmount); return; } // Already withdrawn if (status == DepositState.WITHDRAWN) { revert AlreadyWithdrawn(depositID, withdrawalAmount); } // Not reported if (withdrawalAmount >= validateThreshold()) { // We disallow a withdrawal if it's not in the depositHistory and // the value is above the threshold. revert WithdrawalFailedValidation(depositID, withdrawalAmount); } // We don't have the depositID in the depositHistory, and the value of the // withdrawal is below the threshold, so we allow the withdrawal without // additional on-chain validation. // // Unlike in original Bascule, this contract records withdrawals // even when the validation threshold is raised. depositHistory[depositID] = DepositState.WITHDRAWN; emit WithdrawalNotValidated(depositID, withdrawalAmount); } /// PRIVATE FUNCTIONS /// /** * Update the validate threshold. * @param newThreshold New threshold. * * Emits {UpdateValidateThreshold}. */ function _updateValidateThreshold(uint256 newThreshold) internal { emit UpdateValidateThreshold(_validateThreshold, newThreshold); _validateThreshold = newThreshold; } }
// SPDX-License-Identifier: MIT // Compatible with OpenZeppelin Contracts ^5.0.0 pragma solidity 0.8.24; /// Interface of the Bascule contract as used by on-chain contracts. /// @custom:security-contact [email protected] interface IBascule { /** * Event emitted when a withdrawal is validated. * @param withdrawalAmount Amount of the withdrawal. * @param depositID Unique identifier for a deposit that took place on another chain and was withdrawn on this chain. */ event WithdrawalValidated(bytes32 depositID, uint256 withdrawalAmount); /** * Error on attempt to withdraw an already withdrawn deposit. * @param depositID Unique identifier for deposit that failed validation. * @param withdrawalAmount Amount of the withdrawal. */ error AlreadyWithdrawn(bytes32 depositID, uint256 withdrawalAmount); /** * Error when a withdrawal fails validation. * This means the corresponding deposit is not in the map. * @param depositID Unique identifier for deposit that failed validation. * @param withdrawalAmount Amount of the withdrawal. */ error WithdrawalFailedValidation( bytes32 depositID, uint256 withdrawalAmount ); /** * Validate a withdrawal (before executing it) if the amount is above * threshold. * * This function checks if our accounting has recorded a deposit that * corresponds to this withdrawal request. A deposit can only be withdrawn * once. * * @param depositID Unique identifier of the deposit on another chain. * @param withdrawalAmount Amount of the withdrawal. * * Emits {WithdrawalValidated}. */ function validateWithdrawal( bytes32 depositID, uint256 withdrawalAmount ) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IAdapter} from "./IAdapter.sol"; import {Context} from "@openzeppelin/contracts/utils/Context.sol"; import {IBridge, IBaseLBTC} from "../IBridge.sol"; /** * @title Abstract bridge adapter * @author Lombard.finance * @notice Implements basic communication with Bridge contract. * Should be extended with business logic of bridging protocols (e.g. CCIP, LayerZero). */ abstract contract AbstractAdapter is IAdapter, Context { error Adapter_ZeroAddress(); error Adapter_AddressIsEOA(); error NotBridge(); event BridgeChanged(IBridge indexed oldBridge, IBridge indexed newBridge); IBridge public override bridge; constructor(IBridge bridge_) { _notZero(address(bridge_)); bridge = bridge_; } function lbtc() public view returns (IBaseLBTC) { return bridge.lbtc(); } /// MODIFIERS /// modifier onlyBridge() { _onlyBridge(); _; } /// ONLY OWNER FUNCTIONS /// /** * @notice Change the bridge address * @param bridge_ New bridge address */ function changeBridge(IBridge bridge_) external { _onlyOwner(); _notZero(address(bridge_)); IBridge oldBridge = bridge; bridge = bridge_; emit BridgeChanged(oldBridge, bridge_); } /// PRIVATE FUNCTIONS /// function _onlyOwner() internal view virtual; function _onlyBridge() internal view { if (_msgSender() != address(bridge)) { revert NotBridge(); } } function _notZero(address addr) internal pure { if (addr == address(0)) { revert Adapter_ZeroAddress(); } } /** * @dev Called when data is received. */ function _receive(bytes32 fromChain, bytes memory payload) internal { bridge.receivePayload(fromChain, payload); } /** * @notice Sends a payload from the source to destination chain. * @param _toChain Destination chain's. * @param _payload The payload to send. * @param _refundAddress Address where refund fee */ function _deposit( bytes32 _toChain, bytes memory _payload, address _refundAddress ) internal virtual {} function deposit( address _fromAddress, bytes32 _toChain, bytes32 /* _toContract */, bytes32 /* _toAddress */, uint256 /* _amount */, bytes memory _payload ) external payable virtual override { _deposit(_toChain, _payload, _fromAddress); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC20} from "@chainlink/contracts-ccip/src/v0.8/vendor/openzeppelin-solidity/v4.8.3/contracts/token/ERC20/IERC20.sol"; import {IRouterClient} from "@chainlink/contracts-ccip/src/v0.8/ccip/interfaces/IRouterClient.sol"; import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol"; import {AbstractAdapter} from "./AbstractAdapter.sol"; import {IBridge} from "../IBridge.sol"; import {Pool} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Pool.sol"; import {LombardTokenPool} from "./TokenPool.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20 as OZIERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /** * @title CCIP bridge adapter * @author Lombard.finance * @notice CLAdapter present an intermediary to enforce TokenPool compatibility */ contract CLAdapter is AbstractAdapter, Ownable, ReentrancyGuard { error CLZeroChain(); error CLZeroChanSelector(); error CLAttemptToOverrideChainSelector(); error CLAttemptToOverrideChain(); error CLRefundFailed(address, uint256); error CLUnauthorizedTokenPool(address); error ZeroPayload(); error ReceiverTooBig(); error AmountOverflow(); error CLPayloadMismatch(); error CLWrongPayloadHashLength(); event CLChainSelectorSet(bytes32, uint64); event CLTokenPoolDeployed(address); mapping(bytes32 => uint64) public getRemoteChainSelector; mapping(uint64 => bytes32) public getChain; uint128 public getExecutionGasLimit; LombardTokenPool public tokenPool; // 1-to-1 with adapter // store last state uint256 internal _lastBurnedAmount; bytes internal _lastPayload; mapping(address => uint256) public refunds; modifier onlyTokenPool() { if (address(tokenPool) != _msgSender()) { revert CLUnauthorizedTokenPool(_msgSender()); } _; } /// @notice msg.sender gets the ownership of the contract given /// token pool implementation constructor( IBridge bridge_, uint128 executionGasLimit_, // address ccipRouter_, address[] memory allowlist_, address rmnProxy_ ) AbstractAdapter(bridge_) Ownable(_msgSender()) { _setExecutionGasLimit(executionGasLimit_); tokenPool = new LombardTokenPool( IERC20(address(bridge_.lbtc())), ccipRouter_, allowlist_, rmnProxy_, CLAdapter(this) ); tokenPool.transferOwnership(_msgSender()); emit CLTokenPoolDeployed(address(tokenPool)); } /// USER ACTIONS /// function withdrawRefund() external nonReentrant { uint256 refundAm = refunds[_msgSender()]; refunds[_msgSender()] = 0; (bool success, ) = payable(_msgSender()).call{value: refundAm}(""); if (!success) { revert CLRefundFailed(_msgSender(), refundAm); } } /** * @notice Calculate the fee to be paid for CCIP message routing. * @dev Ignores _toContract and _payload, because they're not a part of CCIP message. * @param _toChain Chain id of destination chain. * @param _toAddress Recipient address. * @param _amount The amount of LBTC to bridge. * @return The fee in native currency for CCIP message routing. */ function getFee( bytes32 _toChain, bytes32 /* _toContract, */, bytes32 _toAddress, uint256 _amount, bytes memory /* _payload */ ) public view override returns (uint256) { return IRouterClient(tokenPool.getRouter()).getFee( getRemoteChainSelector[_toChain], _buildCCIPMessage(abi.encodePacked(_toAddress), _amount) ); } function initiateDeposit( uint64 remoteChainSelector, bytes calldata receiver, uint256 amount ) external onlyTokenPool returns (uint256 lastBurnedAmount, bytes memory lastPayload) { SafeERC20.safeTransferFrom( OZIERC20(address(lbtc())), _msgSender(), address(this), amount ); if (_lastPayload.length > 0) { // just return if already initiated lastBurnedAmount = _lastBurnedAmount; lastPayload = _lastPayload; _lastPayload = new bytes(0); _lastBurnedAmount = 0; } else { if (receiver.length > 32) revert ReceiverTooBig(); if (amount >= 2 ** 64) revert AmountOverflow(); IERC20(address(lbtc())).approve(address(bridge), amount); (lastBurnedAmount, lastPayload) = bridge.deposit( getChain[remoteChainSelector], bytes32(receiver), uint64(amount) ); } bridge.lbtc().burn(lastBurnedAmount); } function deposit( address fromAddress, bytes32 _toChain, bytes32, bytes32 _toAddress, uint256 _amount, bytes memory _payload ) external payable virtual override { _onlyBridge(); // transfer assets from bridge SafeERC20.safeTransferFrom( OZIERC20(address(lbtc())), _msgSender(), address(this), _amount ); // if deposit was initiated by adapter do nothing if (fromAddress == address(this)) { return; } _lastBurnedAmount = _amount; _lastPayload = _payload; uint64 chainSelector = getRemoteChainSelector[_toChain]; Client.EVM2AnyMessage memory message = _buildCCIPMessage( abi.encodePacked(_toAddress), _amount ); address router = tokenPool.getRouter(); uint256 fee = IRouterClient(router).getFee(chainSelector, message); if (msg.value < fee) { revert NotEnoughToPayFee(fee); } if (msg.value > fee) { uint256 refundAm = msg.value - fee; refunds[fromAddress] += refundAm; } IERC20(address(lbtc())).approve(router, _amount); IRouterClient(router).ccipSend{value: fee}(chainSelector, message); } /// @dev same as `initiateWithdrawal` but without signatures opted in data function initWithdrawalNoSignatures( uint64 remoteSelector, bytes calldata onChainData ) external onlyTokenPool returns (uint64) { _receive(getChain[remoteSelector], onChainData); return bridge.withdraw(onChainData); } function initiateWithdrawal( uint64 remoteSelector, bytes calldata payloadHash, bytes calldata offchainData ) external onlyTokenPool returns (uint64) { if (payloadHash.length != 32) { revert CLWrongPayloadHashLength(); } (bytes memory payload, bytes memory proof) = abi.decode( offchainData, (bytes, bytes) ); /// verify hash, because payload from offchainData is untrusted /// and would be replaced during manual execution. /// Bypass other payload checks against CCIP message /// because payload can only be generated in deposit transaction if (bytes32(payloadHash[:32]) != sha256(payload)) { revert CLPayloadMismatch(); } _receive(getChain[remoteSelector], payload); bridge.authNotary(payload, proof); return bridge.withdraw(payload); } /// ONLY OWNER FUNCTIONS /// function setExecutionGasLimit(uint128 newVal) external onlyOwner { _setExecutionGasLimit(newVal); } /// PRIVATE FUNCTIONS /// function _buildCCIPMessage( bytes memory _receiver, uint256 _amount ) private view returns (Client.EVM2AnyMessage memory) { // Set the token amounts Client.EVMTokenAmount[] memory tokenAmounts = new Client.EVMTokenAmount[](1); tokenAmounts[0] = Client.EVMTokenAmount({ token: address(bridge.lbtc()), amount: _amount }); return Client.EVM2AnyMessage({ receiver: _receiver, data: "", tokenAmounts: tokenAmounts, extraArgs: Client._argsToBytes( Client.EVMExtraArgsV2({ gasLimit: getExecutionGasLimit, allowOutOfOrderExecution: true }) ), feeToken: address(0) // let's pay with native tokens }); } function _onlyOwner() internal view override onlyOwner {} function _setExecutionGasLimit(uint128 newVal) internal { emit ExecutionGasLimitSet(getExecutionGasLimit, newVal); getExecutionGasLimit = newVal; } /** * @notice Allows owner set chain selector for chain id * @param chain ABI encoded chain id * @param chainSelector Chain selector of chain id (https://docs.chain.link/ccip/directory/testnet/chain/) */ function setRemoteChainSelector( bytes32 chain, uint64 chainSelector ) external onlyOwner { if (chain == bytes32(0)) { revert CLZeroChain(); } if (chainSelector == 0) { revert CLZeroChain(); } if (getRemoteChainSelector[chain] != 0) { revert CLAttemptToOverrideChainSelector(); } if (getChain[chainSelector] != bytes32(0)) { revert CLAttemptToOverrideChain(); } getRemoteChainSelector[chain] = chainSelector; getChain[chainSelector] = chain; emit CLChainSelectorSet(chain, chainSelector); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBridge} from "../IBridge.sol"; interface IAdapter { /// @notice Thrown when msg.value is not enough to pay CCIP fee. error NotEnoughToPayFee(uint256 fee); event ExecutionGasLimitSet(uint128 indexed prevVal, uint128 indexed newVal); function bridge() external view returns (IBridge); function getFee( bytes32 _toChain, bytes32 _toContract, bytes32 _toAddress, uint256 _amount, bytes memory _payload ) external view returns (uint256); function deposit( address _fromAddress, bytes32 _toChain, bytes32 _toContract, bytes32 _toAddress, uint256 _amount, bytes memory _payload ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC20} from "@chainlink/contracts-ccip/src/v0.8/vendor/openzeppelin-solidity/v4.8.3/contracts/token/ERC20/IERC20.sol"; import {IRouterClient} from "@chainlink/contracts-ccip/src/v0.8/ccip/interfaces/IRouterClient.sol"; import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol"; import {IBridge} from "../IBridge.sol"; import {Pool} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Pool.sol"; import {TokenPool} from "@chainlink/contracts-ccip/src/v0.8/ccip/pools/TokenPool.sol"; import {CLAdapter} from "./CLAdapter.sol"; contract LombardTokenPool is TokenPool { CLAdapter public adapter; /// @notice msg.sender gets the ownership of the contract given /// token pool implementation constructor( IERC20 lbtc_, address ccipRouter_, address[] memory allowlist_, address rmnProxy_, CLAdapter adapter_ ) TokenPool(lbtc_, allowlist_, rmnProxy_, ccipRouter_) { adapter = adapter_; } /// @notice Burn the token in the pool /// @dev The _validateLockOrBurn check is an essential security check function lockOrBurn( Pool.LockOrBurnInV1 calldata lockOrBurnIn ) external virtual override returns (Pool.LockOrBurnOutV1 memory) { _validateLockOrBurn(lockOrBurnIn); // send out to burn i_token.approve(address(adapter), lockOrBurnIn.amount); (uint256 burnedAmount, bytes memory payload) = adapter.initiateDeposit( lockOrBurnIn.remoteChainSelector, lockOrBurnIn.receiver, lockOrBurnIn.amount ); emit Burned(lockOrBurnIn.originalSender, burnedAmount); bytes memory destPoolData = abi.encode(sha256(payload)); return Pool.LockOrBurnOutV1({ destTokenAddress: getRemoteToken( lockOrBurnIn.remoteChainSelector ), destPoolData: destPoolData }); } /// @notice Mint tokens from the pool to the recipient /// @dev The _validateReleaseOrMint check is an essential security check function releaseOrMint( Pool.ReleaseOrMintInV1 calldata releaseOrMintIn ) external virtual override returns (Pool.ReleaseOrMintOutV1 memory) { _validateReleaseOrMint(releaseOrMintIn); uint64 amount = adapter.initiateWithdrawal( releaseOrMintIn.remoteChainSelector, releaseOrMintIn.sourcePoolData, releaseOrMintIn.offchainTokenData ); emit Minted(msg.sender, releaseOrMintIn.receiver, uint256(amount)); return Pool.ReleaseOrMintOutV1({destinationAmount: uint256(amount)}); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {Actions} from "../libs/Actions.sol"; import {FeeUtils} from "../libs/FeeUtils.sol"; import {IAdapter} from "./adapters/IAdapter.sol"; import {IBridge, IBaseLBTC, INotaryConsortium} from "./IBridge.sol"; import {RateLimits} from "../libs/RateLimits.sol"; contract Bridge is IBridge, Ownable2StepUpgradeable, ReentrancyGuardUpgradeable { struct DestinationConfig { bytes32 bridgeContract; uint16 relativeCommission; // relative to amount commission to charge on bridge deposit uint64 absoluteCommission; // absolute commission to charge on bridge deposit IAdapter adapter; // adapter which should provide bridging logic (nullable) bool requireConsortium; // require notarization from consortium } struct Deposit { bytes payload; // content of Deposit bool adapterReceived; // true if payload received from adapter bool notarized; // true if payload notarized from consortium bool withdrawn; // true if payload already withdrawn } /// @custom:storage-location erc7201:lombardfinance.storage.Bridge struct BridgeStorage { address treasury; IBaseLBTC lbtc; // Increments with each cross chain operation and should be part of the payload // Makes each payload unique uint256 crossChainOperationsNonce; mapping(bytes32 => DestinationConfig) destinations; mapping(bytes32 => Deposit) deposits; INotaryConsortium consortium; // Rate limits mapping(bytes32 => RateLimits.Data) depositRateLimits; mapping(bytes32 => RateLimits.Data) withdrawRateLimits; } // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.Bridge")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant BRIDGE_STORAGE_LOCATION = 0x577a31cbb7f7b010ebd1a083e4c4899bcd53b83ce9c44e72ce3223baedbbb600; /// PUBLIC FUNCTIONS /// /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize( IBaseLBTC lbtc_, address treasury_, address owner_ ) external initializer { __Ownable_init(owner_); __Ownable2Step_init(); __ReentrancyGuard_init(); __Bridge_init(lbtc_, treasury_); } /// GETTERS /// function getTreasury() external view returns (address) { return _getBridgeStorage().treasury; } /** * @dev Get config of destination chain * @param toChain Chain id of the destination chain */ function getDestination( bytes32 toChain ) public view returns (DestinationConfig memory) { return _getBridgeStorage().destinations[toChain]; } function getDepositAbsoluteCommission( bytes32 toChain ) public view returns (uint64) { return _getBridgeStorage().destinations[toChain].absoluteCommission; } function getDepositRelativeCommission( bytes32 toChain ) public view returns (uint16) { return _getBridgeStorage().destinations[toChain].relativeCommission; } /** * @notice Returns the address of the configured adapter */ function getAdapter(bytes32 toChain) external view returns (IAdapter) { return _getBridgeStorage().destinations[toChain].adapter; } function consortium() external view override returns (INotaryConsortium) { return _getBridgeStorage().consortium; } function lbtc() public view override returns (IBaseLBTC) { return _getBridgeStorage().lbtc; } /** * @notice Calculates adapter fees. * @param toChain Chain id of destination chain. * @param toAddress Recipient address. * @param amount The amount of LBTC to bridge. * @return The fee in native currency paid to adapter. */ function getAdapterFee( bytes32 toChain, bytes32 toAddress, uint64 amount ) external view returns (uint256) { // return 0 if destination not set DestinationConfig memory destConfig = getDestination(toChain); if (destConfig.bridgeContract == bytes32(0)) { return 0; } // return 0 if adapter not set if (address(destConfig.adapter) == address(0)) { return 0; } return destConfig.adapter.getFee( toChain, destConfig.bridgeContract, toAddress, amount, // for some adapters payload length would affect fees new bytes(228) ); } /// ACTIONS /// /** * @notice Deposit LBTC to another chain. * @dev LBTC on source and destination chains are linked with independent supplies. * Burns tokens on source chain (to later mint on destination chain). * @param toChain One of many destination chain ID. * @param toAddress The address that will receive `amount` LBTC. * @param amount Amount of LBTC to be sent. */ function deposit( bytes32 toChain, bytes32 toAddress, uint64 amount ) external payable override nonReentrant returns (uint256, bytes memory) { // validate inputs // amount should be validated, because absolute commission can be not set if (amount == 0) { revert Bridge_ZeroAmount(); } if (toAddress == bytes32(0)) { revert Bridge_ZeroAddress(); } // it's not necessary to validate `toChain` because destination // for zero chain can't be set DestinationConfig memory destConfig = getDestination(toChain); if (destConfig.bridgeContract == bytes32(0)) { revert UnknownDestination(); } return _deposit(destConfig, toChain, toAddress, amount); } /** * @notice Notify the bridge about received payload from adapter. * @dev only adapter can call * @param fromChain The source where payload produced. * @param payload The payload received from bridge adapter. */ function receivePayload( bytes32 fromChain, bytes calldata payload ) external override { // validate inputs DestinationConfig memory destConf = getDestination(fromChain); if (destConf.bridgeContract == bytes32(0)) { revert UnknownDestination(); } // it also prevent to use method if adapter not set if (_msgSender() != address(destConf.adapter)) { revert UnknownAdapter(_msgSender()); } // payload validation if (bytes4(payload) != Actions.DEPOSIT_BRIDGE_ACTION) { revert UnexpectedAction(bytes4(payload)); } Actions.DepositBridgeAction memory action = Actions.depositBridge( payload[4:] ); if (destConf.bridgeContract != action.fromContract) { revert UnknownOriginContract( bytes32(action.fromChain), action.fromContract ); } BridgeStorage storage $ = _getBridgeStorage(); bytes32 payloadHash = sha256(payload); if ($.deposits[payloadHash].withdrawn) { revert PayloadAlreadyUsed(payloadHash); } $.deposits[payloadHash].adapterReceived = true; emit PayloadReceived(action.recipient, payloadHash, _msgSender()); } function authNotary( bytes calldata payload, bytes calldata proof ) external nonReentrant { // payload validation if (bytes4(payload) != Actions.DEPOSIT_BRIDGE_ACTION) { revert UnexpectedAction(bytes4(payload)); } Actions.DepositBridgeAction memory action = Actions.depositBridge( payload[4:] ); // Ensure that fromContract matches the bridgeContract DestinationConfig memory destConf = getDestination( bytes32(action.fromChain) ); if (destConf.bridgeContract != action.fromContract) { revert UnknownOriginContract( bytes32(action.fromChain), action.fromContract ); } bytes32 payloadHash = sha256(payload); BridgeStorage storage $ = _getBridgeStorage(); Deposit storage depositData = $.deposits[payloadHash]; // proof validation if (depositData.withdrawn) { revert PayloadAlreadyUsed(payloadHash); } depositData.notarized = true; $.consortium.checkProof(payloadHash, proof); emit PayloadNotarized(action.recipient, payloadHash); } /** * @notice Withdraw bridged LBTC */ function withdraw( bytes calldata payload ) external nonReentrant returns (uint64) { BridgeStorage storage $ = _getBridgeStorage(); // payload validation if (bytes4(payload) != Actions.DEPOSIT_BRIDGE_ACTION) { revert UnexpectedAction(bytes4(payload)); } Actions.DepositBridgeAction memory action = Actions.depositBridge( payload[4:] ); // Validate toContract if (action.toContract != address(this)) revert NotValidDestination(); // check rate limits RateLimits.updateLimit( $.withdrawRateLimits[bytes32(action.fromChain)], action.amount ); DestinationConfig memory destConf = $.destinations[ bytes32(action.fromChain) ]; if (destConf.bridgeContract == bytes32(0)) { revert UnknownDestination(); } bytes32 payloadHash = sha256(payload); Deposit storage depositData = $.deposits[payloadHash]; // validate required auth received if ( address(destConf.adapter) != address(0) && !depositData.adapterReceived ) { revert AdapterNotConfirmed(); } if (destConf.requireConsortium && !depositData.notarized) { revert ConsortiumNotConfirmed(); } // proof validation if (depositData.withdrawn) { revert PayloadAlreadyUsed(payloadHash); } depositData.withdrawn = true; lbtc().mint(action.recipient, action.amount); emit WithdrawFromBridge( action.recipient, payloadHash, payload, action.amount ); return action.amount; } /// ONLY OWNER /// /** * @param adapter Address of adapter if required (nullable) * @param requireConsortium Flag to require consortium for bridging */ function addDestination( bytes32 toChain, bytes32 toContract, uint16 relCommission, uint64 absCommission, IAdapter adapter, bool requireConsortium ) external onlyOwner { if (toContract == bytes32(0)) { revert ZeroContractHash(); } if (toChain == bytes32(0)) { revert ZeroChainId(); } if (!requireConsortium && address(adapter) == address(0)) { revert BadConfiguration(); } if (getDestination(toChain).bridgeContract != bytes32(0)) { revert KnownDestination(); } // do not allow 100% commission or higher values FeeUtils.validateCommission(relCommission); _getBridgeStorage().destinations[toChain] = DestinationConfig( toContract, relCommission, absCommission, adapter, requireConsortium ); emit DepositAbsoluteCommissionChanged(absCommission, toChain); emit DepositRelativeCommissionChanged(relCommission, toChain); // TODO: add more information to event emit BridgeDestinationAdded(toChain, toContract); } function removeDestination(bytes32 toChain) external onlyOwner { _validDestination(toChain); BridgeStorage storage $ = _getBridgeStorage(); delete $.destinations[toChain]; delete $.depositRateLimits[toChain]; delete $.withdrawRateLimits[toChain]; emit DepositAbsoluteCommissionChanged(0, toChain); emit DepositRelativeCommissionChanged(0, toChain); emit BridgeDestinationRemoved(toChain); emit RateLimitsChanged(toChain, 0, 0); } function changeDepositAbsoluteCommission( uint64 newValue, bytes32 chain ) external onlyOwner { _validDestination(chain); BridgeStorage storage $ = _getBridgeStorage(); $.destinations[chain].absoluteCommission = newValue; emit DepositAbsoluteCommissionChanged(newValue, chain); } function changeDepositRelativeCommission( uint16 newValue, bytes32 chain ) external onlyOwner { _validDestination(chain); FeeUtils.validateCommission(newValue); BridgeStorage storage $ = _getBridgeStorage(); $.destinations[chain].relativeCommission = newValue; emit DepositRelativeCommissionChanged(newValue, chain); } function changeAdapter( bytes32 chain, IAdapter newAdapter ) external onlyOwner { _changeAdapter(chain, newAdapter); } function changeConsortium(INotaryConsortium newVal) external onlyOwner { if (address(newVal) == address(0)) revert Bridge_ZeroAddress(); BridgeStorage storage $ = _getBridgeStorage(); emit ConsortiumChanged($.consortium, newVal); $.consortium = newVal; } function setRateLimits( RateLimits.Config[] memory depositRateLimits, RateLimits.Config[] memory withdrawRateLimits ) external onlyOwner { BridgeStorage storage $ = _getBridgeStorage(); for (uint256 i; i < depositRateLimits.length; i++) { DestinationConfig memory destConf = $.destinations[ depositRateLimits[i].chainId ]; if (destConf.bridgeContract == bytes32(0)) { revert UnknownDestination(); } RateLimits.checkRateLimitSanity(depositRateLimits[i].limit); RateLimits.setRateLimit( $.depositRateLimits[depositRateLimits[i].chainId], depositRateLimits[i] ); emit RateLimitsChanged( depositRateLimits[i].chainId, depositRateLimits[i].limit, depositRateLimits[i].window ); } for (uint256 i; i < withdrawRateLimits.length; i++) { DestinationConfig memory destConf = $.destinations[ withdrawRateLimits[i].chainId ]; if (destConf.bridgeContract == bytes32(0)) { revert UnknownDestination(); } RateLimits.checkRateLimitSanity(withdrawRateLimits[i].limit); RateLimits.setRateLimit( $.withdrawRateLimits[withdrawRateLimits[i].chainId], withdrawRateLimits[i] ); emit RateLimitsChanged( withdrawRateLimits[i].chainId, withdrawRateLimits[i].limit, withdrawRateLimits[i].window ); } } /// PRIVATE FUNCTIONS /// function __Bridge_init( IBaseLBTC lbtc_, address treasury_ ) internal onlyInitializing { _changeTreasury(treasury_); BridgeStorage storage $ = _getBridgeStorage(); $.lbtc = lbtc_; } function _deposit( DestinationConfig memory config, bytes32 toChain, bytes32 toAddress, uint64 amount ) internal returns (uint256, bytes memory) { BridgeStorage storage $ = _getBridgeStorage(); // check rate limits RateLimits.updateLimit($.depositRateLimits[toChain], amount); // relative fee uint256 fee = FeeUtils.getRelativeFee( amount, getDepositRelativeCommission(toChain) ); // absolute fee fee += config.absoluteCommission; if (fee >= amount) { revert AmountLessThanCommission(fee); } uint64 amountWithoutFee = amount - uint64(fee); address fromAddress = _msgSender(); // charge Lombard fees SafeERC20.safeTransferFrom( IERC20(address(lbtc())), fromAddress, $.treasury, fee ); // prepare bridge deposit payload bytes memory payload = abi.encodeWithSelector( Actions.DEPOSIT_BRIDGE_ACTION, bytes32(block.chainid), bytes32(uint256(uint160(address(this)))), toChain, config.bridgeContract, toAddress, amountWithoutFee, $.crossChainOperationsNonce++ ); if (address(config.adapter) != address(0)) { // transfer assets to bridge SafeERC20.safeTransferFrom( IERC20(address(lbtc())), fromAddress, address(this), amountWithoutFee ); // Approve spending by adapter IERC20(address(lbtc())).approve( address(config.adapter), amountWithoutFee ); // let adapter handle the deposit config.adapter.deposit{value: msg.value}( fromAddress, toChain, config.bridgeContract, toAddress, amountWithoutFee, payload ); } else { // burn assets if no adapter lbtc().burn(fromAddress, amountWithoutFee); } emit DepositToBridge(fromAddress, toAddress, sha256(payload), payload); return (amountWithoutFee, payload); } function _changeTreasury(address treasury_) internal { if (treasury_ == address(0)) revert Bridge_ZeroAddress(); BridgeStorage storage $ = _getBridgeStorage(); address previousTreasury = $.treasury; $.treasury = treasury_; emit TreasuryChanged(previousTreasury, treasury_); } function _changeAdapter(bytes32 toChain, IAdapter newAdapter) internal { if (address(newAdapter) == address(0)) { revert Bridge_ZeroAddress(); } DestinationConfig storage conf = _getBridgeStorage().destinations[ toChain ]; address previousAdapter = address(conf.adapter); conf.adapter = IAdapter(newAdapter); emit AdapterChanged(previousAdapter, newAdapter); } function _getBridgeStorage() private pure returns (BridgeStorage storage $) { assembly { $.slot := BRIDGE_STORAGE_LOCATION } } function _validDestination(bytes32 chain) internal view { BridgeStorage storage $ = _getBridgeStorage(); if ($.destinations[chain].bridgeContract == bytes32(0)) { revert NotValidDestination(); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBaseLBTC} from "../LBTC/IBaseLBTC.sol"; import "./adapters/IAdapter.sol"; import {IConsortiumConsumer, INotaryConsortium} from "../interfaces/IConsortiumConsumer.sol"; interface IBridge is IConsortiumConsumer { /// @notice Emitted when the destination is unknown. error UnknownDestination(); /// @notice Emitted when the zero address is used. error Bridge_ZeroAddress(); error Bridge_ZeroAmount(); /// @notice Emitted adapter is not set for destination without consortium error BadConfiguration(); /// @notice Emitted when the destination is already known. error KnownDestination(); /// @notice Emitted when the zero contract hash is used. error ZeroContractHash(); /// @notice Emitted when the chain id is invalid. error ZeroChainId(); /// @notice Emitted when the destination is not valid. error NotValidDestination(); /// @notice Emitted when amount is below commission error AmountLessThanCommission(uint256 commission); /// @notice Emitted when the origin contract is unknown. error UnknownOriginContract(bytes32 fromChain, bytes32 fromContract); /// @notice Emitted when the unexpected action is used. error UnexpectedAction(bytes4 action); error UnknownAdapter(address); error PayloadAlreadyUsed(bytes32); /// @notice Emitted no payload submitted by adapter error AdapterNotConfirmed(); /// @notice Emitted no payload submitted by consortium error ConsortiumNotConfirmed(); /// @notice Emitted when the deposit absolute commission is changed. event DepositAbsoluteCommissionChanged( uint64 newValue, bytes32 indexed chain ); /// @notice Emitted when the deposit relative commission is changed. event DepositRelativeCommissionChanged( uint16 newValue, bytes32 indexed chain ); /// @notice Emitted when a bridge destination is added. event BridgeDestinationAdded( bytes32 indexed chain, bytes32 indexed contractAddress ); /// @notice Emitted when a bridge destination is removed. event BridgeDestinationRemoved(bytes32 indexed chain); /// @notice Emitted when the adapter is changed. event AdapterChanged(address previousAdapter, IAdapter newAdapter); /// @notice Emitted when the is a deposit in the bridge event DepositToBridge( address indexed fromAddress, bytes32 indexed toAddress, bytes32 indexed payloadHash, bytes payload ); /// @notice Emitted when a withdraw is made from the bridge event WithdrawFromBridge( address indexed recipient, bytes32 indexed payloadHash, bytes payload, uint64 amount ); event PayloadReceived( address indexed recipient, bytes32 indexed payloadHash, address indexed adapter ); event PayloadNotarized( address indexed recipient, bytes32 indexed payloadHash ); event RateLimitsChanged( bytes32 indexed chainId, uint256 limit, uint256 window ); /// @notice Emitted when the treasury is changed. event TreasuryChanged(address previousTreasury, address newTreasury); function lbtc() external view returns (IBaseLBTC); function receivePayload(bytes32 fromChain, bytes calldata payload) external; function deposit( bytes32 toChain, bytes32 toAddress, uint64 amount ) external payable returns (uint256, bytes memory); function authNotary(bytes calldata payload, bytes calldata proof) external; function withdraw(bytes calldata payload) external returns (uint64); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {OFTAdapter} from "@layerzerolabs/oft-evm/contracts/OFTAdapter.sol"; import {EfficientRateLimiter} from "./EfficientRateLimiter.sol"; import {RateLimits} from "../../libs/RateLimits.sol"; /** * @title OFT Adapter contract with EfficientRateLimiter */ abstract contract EfficientRateLimitedOFTAdapter is OFTAdapter, EfficientRateLimiter { /** * @notice Sets the cross-chain tx rate limits for specific endpoints based on provided configurations. * It allows configuration of rate limits either for outbound or inbound directions. * This method is designed to be called by contract admins for updating the system's rate limiting behavior. * * @param _rateLimitConfigs An array of `RateLimits.Config` structs that specify the new rate limit settings. * Each struct includes an endpoint ID, the limit value, and the window duration. * @param direction The direction (`Outbound` or `Inbound`) specifies whether the endpoint ID passed should be considered a dstEid or srcEid. * This parameter determines which set of rate limits (outbound or inbound) will be updated for each endpoint. */ function setRateLimits( RateLimits.Config[] calldata _rateLimitConfigs, RateLimitDirection direction ) external onlyOwner { _setRateLimits(_rateLimitConfigs, direction); } function _debit( address _from, uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid ) internal virtual override returns (uint256 amountSentLD, uint256 amountReceivedLD) { (amountSentLD, amountReceivedLD) = super._debit( _from, _amountLD, _minAmountLD, _dstEid ); // Check and update the rate limit based on the destination endpoint ID (dstEid) and the amount in local decimals. _checkAndUpdateRateLimit( _dstEid, amountSentLD, RateLimitDirection.Outbound ); return (amountSentLD, amountReceivedLD); } function _credit( address _to, uint256 _amountLD, uint32 _srcEid ) internal virtual override returns (uint256 amountReceivedLD) { // Check and update the rate limit based on the source endpoint ID (srcEid) and the amount in local decimals from the message. _checkAndUpdateRateLimit( _srcEid, _amountLD, RateLimitDirection.Inbound ); amountReceivedLD = super._credit(_to, _amountLD, _srcEid); return amountReceivedLD; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {RateLimits} from "../../libs/RateLimits.sol"; /** * @title RateLimiter * @dev Abstract contract for implementing net rate limiting functionality. This effectively allows two operations to * offset each others net impact (e.g., inflow v.s. outflow of assets). It is designed to be inherited by other * contracts requiring rate limiting capabilities to protect resources or services from excessive use. * @dev A flexible rate limit that grows during congestive periods and shrinks during calm periods could give some * leeway when someone tries to forcefully congest the network, while still preventing huge amounts to be sent at once. */ abstract contract EfficientRateLimiter { // Tracks rate limits for outbound transactions to a dstEid. mapping(uint32 dstEid => RateLimits.Data limit) public outboundRateLimits; // Tracks rate limits for inbound transactions from a srcEid. mapping(uint32 srcEid => RateLimits.Data limit) public inboundRateLimits; // Define an enum to clearly distinguish between inbound and outbound rate limits. enum RateLimitDirection { Inbound, Outbound } /** * @notice Emitted when _setRateLimits occurs. * @param rateLimitConfigs An array of `RateLimits.Config` structs representing the rate limit configurations set per endpoint id. * - `eid`: The source / destination endpoint id (depending on direction). * - `limit`: This represents the maximum allowed amount within a given window. * - `window`: Defines the duration of the rate limiting window. * @param direction Specifies whether the outbound or inbound rates were changed. */ event RateLimitsChanged( RateLimits.Config[] rateLimitConfigs, RateLimitDirection direction ); /** * @notice Get the current amount that can be sent to this destination endpoint id for the given rate limit window. * @param _dstEid The destination endpoint id. * @return currentAmountInFlight The current amount that was sent in this window. * @return amountCanBeSent The amount that can be sent. */ function getAmountCanBeSent( uint32 _dstEid ) external view virtual returns (uint256 currentAmountInFlight, uint256 amountCanBeSent) { RateLimits.Data storage orl = outboundRateLimits[_dstEid]; return _amountCanBeSent( orl.amountInFlight, orl.lastUpdated, orl.limit, orl.window ); } /** * @notice Get the current amount that can be received from the source endpoint id for the given rate limit window. * @param _srcEid The source endpoint id. * @return currentAmountInFlight The current amount that has been received in this window. * @return amountCanBeReceived The amount that can be received. */ function getAmountCanBeReceived( uint32 _srcEid ) external view virtual returns (uint256 currentAmountInFlight, uint256 amountCanBeReceived) { RateLimits.Data storage irl = inboundRateLimits[_srcEid]; return _amountCanBeReceived( irl.amountInFlight, irl.lastUpdated, irl.limit, irl.window ); } /** * @notice Sets the Rate Limits. * @param _rateLimitConfigs A `RateLimits.Config[]` array representing the rate limit configurations for either outbound or inbound. * @param direction Indicates whether the rate limits being set are for outbound or inbound. */ function _setRateLimits( RateLimits.Config[] memory _rateLimitConfigs, RateLimitDirection direction ) internal virtual { for (uint256 i = 0; i < _rateLimitConfigs.length; i++) { RateLimits.Data storage rateLimit = direction == RateLimitDirection.Outbound ? outboundRateLimits[ uint32(uint256(_rateLimitConfigs[i].chainId)) ] : inboundRateLimits[ uint32(uint256(_rateLimitConfigs[i].chainId)) ]; // Checkpoint the existing rate limit to not retroactively apply the new decay rate. _checkAndUpdateRateLimit( uint32(uint256(_rateLimitConfigs[i].chainId)), 0, direction ); RateLimits.checkRateLimitSanity(_rateLimitConfigs[i].limit); // Does NOT reset the amountInFlight/lastUpdated of an existing rate limit. rateLimit.limit = _rateLimitConfigs[i].limit; rateLimit.window = _rateLimitConfigs[i].window; } emit RateLimitsChanged(_rateLimitConfigs, direction); } /** * @notice Checks current amount in flight and amount that can be sent for a given rate limit window. * @param _amountInFlight The amount in the current window. * @param _lastUpdated Timestamp representing the last time the rate limit was checked or updated. * @param _limit This represents the maximum allowed amount within a given window. * @param _window Defines the duration of the rate limiting window. * @return currentAmountInFlight The amount in the current window. * @return amountCanBeSent The amount that can be sent. */ function _amountCanBeSent( uint256 _amountInFlight, uint256 _lastUpdated, uint256 _limit, uint256 _window ) internal view virtual returns (uint256 currentAmountInFlight, uint256 amountCanBeSent) { (currentAmountInFlight, amountCanBeSent) = RateLimits .availableAmountToSend( _amountInFlight, _lastUpdated, _limit, _window ); } /** * @notice Checks current amount in flight and amount that can be sent for a given rate limit window. * @param _amountInFlight The amount in the current window. * @param _lastUpdated Timestamp representing the last time the rate limit was checked or updated. * @param _limit This represents the maximum allowed amount within a given window. * @param _window Defines the duration of the rate limiting window. * @return currentAmountInFlight The amount in the current window. * @return amountCanBeReceived The amount that can be received. */ function _amountCanBeReceived( uint256 _amountInFlight, uint256 _lastUpdated, uint256 _limit, uint256 _window ) internal view virtual returns (uint256 currentAmountInFlight, uint256 amountCanBeReceived) { (currentAmountInFlight, amountCanBeReceived) = RateLimits .availableAmountToSend( _amountInFlight, _lastUpdated, _limit, _window ); } /** * @notice Checks and updates the rate limit based on the endpoint ID and amount. * @param _eid The endpoint ID for which the rate limit needs to be checked and updated. * @param _amount The amount to add to the current amount in flight. * @param direction The direction (Outbound or Inbound) of the rate limits being checked. */ function _checkAndUpdateRateLimit( uint32 _eid, uint256 _amount, RateLimitDirection direction ) internal { // Select the correct mapping based on the direction of the rate limit RateLimits.Data storage rl = direction == RateLimitDirection.Outbound ? outboundRateLimits[_eid] : inboundRateLimits[_eid]; // Calculate current amount in flight and available capacity (uint256 currentAmountInFlight, uint256 availableCapacity) = RateLimits .availableAmountToSend( rl.amountInFlight, rl.lastUpdated, rl.limit, rl.window ); // Check if the requested amount exceeds the available capacity if (_amount > availableCapacity) { revert RateLimits.RateLimitExceeded(); } // Update the rate limit with the new amount in flight and the current timestamp rl.amountInFlight = currentAmountInFlight + _amount; rl.lastUpdated = block.timestamp; RateLimits.Data storage oppositeRL = direction == RateLimitDirection.Outbound ? inboundRateLimits[_eid] : outboundRateLimits[_eid]; ( uint256 otherCurrentAmountInFlight, uint256 otherAvailableCapacity ) = RateLimits.availableAmountToSend( oppositeRL.amountInFlight, oppositeRL.lastUpdated, oppositeRL.limit, oppositeRL.window ); unchecked { oppositeRL.amountInFlight = otherCurrentAmountInFlight > _amount ? otherCurrentAmountInFlight - _amount : 0; } oppositeRL.lastUpdated = block.timestamp; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {OFTAdapter, SafeERC20, IERC20} from "@layerzerolabs/oft-evm/contracts/OFTAdapter.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {EfficientRateLimitedOFTAdapter} from "./EfficientRateLimitedOFTAdapter.sol"; import {IBaseLBTC} from "../../LBTC/IBaseLBTC.sol"; contract LBTCBurnMintOFTAdapter is OFTAdapter, EfficientRateLimitedOFTAdapter { using SafeERC20 for IERC20; constructor( address _token, address _lzEndpoint, address _owner ) OFTAdapter(_token, _lzEndpoint, _owner) Ownable(_owner) {} function approvalRequired() external pure virtual override returns (bool) { return false; } /** * @dev Burns tokens from the sender's specified balance in this contract. * @param _from The address to debit from. * @param _amountLD The amount of tokens to send in local decimals. * @param _minAmountLD The minimum amount to send in local decimals. * @param _dstEid The destination chain ID. * @return amountSentLD The amount sent in local decimals. * @return amountReceivedLD The amount received in local decimals on the remote. */ function _debit( address _from, uint256 _amountLD, uint256 _minAmountLD, uint32 _dstEid ) internal virtual override(OFTAdapter, EfficientRateLimitedOFTAdapter) returns (uint256 amountSentLD, uint256 amountReceivedLD) { (amountSentLD, amountReceivedLD) = _debitView( _amountLD, _minAmountLD, _dstEid ); _checkAndUpdateRateLimit( _dstEid, amountSentLD, RateLimitDirection.Outbound ); IBaseLBTC(address(innerToken)).burn(_from, amountSentLD); } /** * @dev Credits tokens to the specified address. * @param _to The address to credit the tokens to. * @param _amountLD The amount of tokens to credit in local decimals. * @dev _srcEid The source chain ID. * @return amountReceivedLD The amount of tokens ACTUALLY received in local decimals. */ function _credit( address _to, uint256 _amountLD, uint32 _srcEid ) internal virtual override(OFTAdapter, EfficientRateLimitedOFTAdapter) returns (uint256 amountReceivedLD) { _checkAndUpdateRateLimit( _srcEid, _amountLD, RateLimitDirection.Inbound ); // @dev Mint the tokens and transfer to the recipient. IBaseLBTC(address(innerToken)).mint(_to, _amountLD); return _amountLD; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {OFTAdapter} from "@layerzerolabs/oft-evm/contracts/OFTAdapter.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {EfficientRateLimitedOFTAdapter} from "./EfficientRateLimitedOFTAdapter.sol"; import {IBaseLBTC} from "../../LBTC/IBaseLBTC.sol"; contract LBTCOFTAdapter is EfficientRateLimitedOFTAdapter { constructor( address _token, address _lzEndpoint, address _owner ) OFTAdapter(_token, _lzEndpoint, _owner) Ownable(_owner) {} /** * @dev Burns locked LBTC to prevent ability to withdraw from adapter. * Peer should be set to zero before calling this method. */ function empty() external onlyOwner { IBaseLBTC(address(innerToken)).burn( innerToken.balanceOf(address(this)) ); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol"; import {Actions} from "../libs/Actions.sol"; import {INotaryConsortium} from "./INotaryConsortium.sol"; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /// @title The contract utilizes consortium governance functions using multisignature verification /// @author Lombard.Finance /// @notice The contracts are a part of the Lombard.Finance protocol contract Consortium is Ownable2StepUpgradeable, INotaryConsortium { struct ValidatorSet { /// @notice addresses of the signers address[] validators; /// @notice weight of each signer uint256[] weights; /// @notice current threshold for signatures weight to be accepted uint256 weightThreshold; } /// @custom:storage-location erc7201:lombardfinance.storage.Consortium struct ConsortiumStorage { /// @notice Current epoch uint256 epoch; /// @notice Store the Validator set for each epoch mapping(uint256 => ValidatorSet) validatorSet; } // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.Consortium")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant CONSORTIUM_STORAGE_LOCATION = 0xbac09a3ab0e06910f94a49c10c16eb53146536ec1a9e948951735cde3a58b500; /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } /// @notice Initializes the consortium contract /// @param _owner - The address of the initial owner function initialize(address _owner) external initializer { __Ownable_init(_owner); __Ownable2Step_init(); __Consortium_init(); } /// ONLY OWNER FUNCTIONS /// /// @notice Sets the initial validator set from any epoch /// @param _initialValSet - The initial list of validators function setInitialValidatorSet( bytes calldata _initialValSet ) external onlyOwner { // Payload validation if (bytes4(_initialValSet) != Actions.NEW_VALSET) revert UnexpectedAction(bytes4(_initialValSet)); ConsortiumStorage storage $ = _getConsortiumStorage(); Actions.ValSetAction memory action = Actions.validateValSet( _initialValSet[4:] ); if ($.epoch != 0) { revert ValSetAlreadySet(); } _setValidatorSet( $, action.validators, action.weights, action.weightThreshold, action.epoch ); } /// USER ACTIONS /// /// @notice Validates the provided signature against the given hash /// @param _payloadHash the hash of the data to be signed /// @param _proof nonce, expiry and signatures to validate function checkProof( bytes32 _payloadHash, bytes calldata _proof ) public view override { _checkProof(_payloadHash, _proof); } function setNextValidatorSet( bytes calldata payload, bytes calldata proof ) external { // payload validation if (bytes4(payload) != Actions.NEW_VALSET) { revert UnexpectedAction(bytes4(payload)); } Actions.ValSetAction memory action = Actions.validateValSet( payload[4:] ); ConsortiumStorage storage $ = _getConsortiumStorage(); // check proof bytes32 payloadHash = sha256(payload); checkProof(payloadHash, proof); if (action.epoch != $.epoch + 1) revert InvalidEpoch(); _setValidatorSet( $, action.validators, action.weights, action.weightThreshold, action.epoch ); } /// GETTERS /// /// @notice Returns the validator for a given epoch /// @param epoch the epoch to get the threshold for function getValidatorSet( uint256 epoch ) external view returns (ValidatorSet memory) { return _getConsortiumStorage().validatorSet[epoch]; } /// @notice Returns the current epoch function curEpoch() external view returns (uint256) { return _getConsortiumStorage().epoch; } /// PRIVATE FUNCTIONS /// /// @notice Internal initializer for the consortium function __Consortium_init() internal onlyInitializing {} function _setValidatorSet( ConsortiumStorage storage $, address[] memory _validators, uint256[] memory _weights, uint256 _threshold, uint256 _epoch ) internal { // do not allow to rewrite existing valset if ($.validatorSet[_epoch].weightThreshold != 0) { revert InvalidEpoch(); } $.epoch = _epoch; $.validatorSet[_epoch] = ValidatorSet({ validators: _validators, weights: _weights, weightThreshold: _threshold }); emit ValidatorSetUpdated(_epoch, _validators, _weights, _threshold); } /// @dev Checks that `_proof` is correct /// @param _payloadHash data to be signed /// @param _proof encoding of signatures array /// @dev Negative weight means that the validator did not sign, any positive weight means that the validator signed function _checkProof( bytes32 _payloadHash, bytes calldata _proof ) internal view virtual { ConsortiumStorage storage $ = _getConsortiumStorage(); if ($.epoch == 0) { revert NoValidatorSet(); } // decode proof bytes[] memory signatures = abi.decode(_proof, (bytes[])); address[] storage validators = $.validatorSet[$.epoch].validators; uint256 length = validators.length; if (signatures.length != length) { revert LengthMismatch(); } uint256 weight = 0; uint256[] storage weights = $.validatorSet[$.epoch].weights; for (uint256 i; i < length; ++i) { // each signature preset R || S values // V is missed, because validators use Cosmos SDK keyring which is not signing in eth style // We only check signatures which are the expected 64 bytes long - we are expecting // a signatures array with the same amount of items as there are validators, but not all // validators will need to sign for a proof to be valid, so validators who have not signed // will have their corresponding signature set to 0 bytes. // In case of a malformed signature (i.e. length isn't 0 bytes but also isn't 64 bytes) // this signature will be discarded. if (signatures[i].length == 64) { // split signature by R and S values bytes memory sig = signatures[i]; bytes32 r; bytes32 s; // load the first 32 bytes (r) and the second 32 bytes (s) from the sig assembly { r := mload(add(sig, 0x20)) // first 32 bytes (offset 0x20) s := mload(add(sig, 0x40)) // next 32 bytes (offset 0x40) } if (r != bytes32(0) && s != bytes32(0)) { // try recover with V = 27 (address signer, ECDSA.RecoverError err, ) = ECDSA .tryRecover(_payloadHash, 27, r, s); // ignore if bad signature if (err != ECDSA.RecoverError.NoError) { continue; } // if signer doesn't match try V = 28 if (signer != validators[i]) { (signer, err, ) = ECDSA.tryRecover( _payloadHash, 28, r, s ); if (err != ECDSA.RecoverError.NoError) { continue; } if (signer != validators[i]) { continue; } } // signature accepted unchecked { weight += weights[i]; } } } } if (weight < $.validatorSet[$.epoch].weightThreshold) { revert NotEnoughSignatures(); } } /// @notice Retrieve the ConsortiumStorage struct from the specific storage slot function _getConsortiumStorage() private pure returns (ConsortiumStorage storage $) { assembly { $.slot := CONSORTIUM_STORAGE_LOCATION } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import "./IDepositNotarizationBlacklist.sol"; /** * @title DepositNotarizationBlacklist * @dev This contract allows to manage a blacklist of transaction outputs in order for notarization process * to ignore them. */ contract DepositNotarizationBlacklist is IDepositNotarizationBlacklist, AccessControlUpgradeable { bytes32 public constant ADD_BLACKLIST_ROLE = keccak256("ADD_BLACKLIST_ROLE"); bytes32 public constant REMOVE_BLACKLIST_ROLE = keccak256("REMOVE_BLACKLIST_ROLE"); mapping(bytes32 => mapping(uint32 => bool)) internal _blacklist; /** * @dev Constructor that disables initializers to prevent the implementation contract from being initialized. * @custom:oz-upgrades-unsafe-allow constructor */ constructor() { _disableInitializers(); } /** * @dev Initializes the contract setting the first owner. * @param admin The address of the default admin. */ function initialize(address admin) external initializer { __AccessControl_init(); _grantRole(DEFAULT_ADMIN_ROLE, admin); } /** * @notice Checks if a transaction output is blacklisted. * @param txId The transaction ID. * @param vout The output index. * @return True if the transaction output is blacklisted, false otherwise. */ function isBlacklisted( bytes32 txId, uint32 vout ) external view returns (bool) { return _blacklist[txId][vout]; } /** * @notice Adds transaction outputs to the blacklist. * @param txId The transaction ID. * @param vouts The array of output indices to be blacklisted. */ function addToBlacklist( bytes32 txId, uint32[] calldata vouts ) external onlyRole(ADD_BLACKLIST_ROLE) { for (uint i = 0; i < vouts.length; i++) { if (_blacklist[txId][vouts[i]]) { revert AlreadyBlacklisted(txId, vouts[i]); } _blacklist[txId][vouts[i]] = true; emit Blacklisted(txId, vouts[i], msg.sender); } } /** * @notice Removes transaction outputs from the blacklist. * @param txId The transaction ID. * @param vouts The array of output indices to be blacklisted. */ function removeFromBlacklist( bytes32 txId, uint32[] calldata vouts ) external onlyRole(REMOVE_BLACKLIST_ROLE) { for (uint i = 0; i < vouts.length; i++) { if (!_blacklist[txId][vouts[i]]) { revert AlreadyCleared(txId, vouts[i]); } _blacklist[txId][vouts[i]] = false; emit Cleared(txId, vouts[i], msg.sender); } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; interface IDepositNotarizationBlacklist { event Blacklisted( bytes32 indexed txId, uint32 indexed vout, address indexed operator ); event Cleared( bytes32 indexed txId, uint32 indexed vout, address indexed operator ); error AlreadyCleared(bytes32 txId, uint32 vout); error AlreadyBlacklisted(bytes32 txId, uint32 vout); function isBlacklisted( bytes32 txId, uint32 vout ) external view returns (bool); function addToBlacklist(bytes32 txId, uint32[] calldata vouts) external; function removeFromBlacklist( bytes32 txId, uint32[] calldata vouts ) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (governance/TimelockController.sol) pragma solidity 0.8.24; interface ITimelockController { /** * @dev Returns whether an id corresponds to a registered operation. This * includes both Waiting, Ready, and Done operations. */ function isOperation(bytes32 id) external view returns (bool); /** * @dev Returns whether an operation is pending or not. Note that a "pending" operation may also be "ready". */ function isOperationPending(bytes32 id) external view returns (bool); /** * @dev Returns whether an operation is ready for execution. Note that a "ready" operation is also "pending". */ function isOperationReady(bytes32 id) external view returns (bool); /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) external view returns (bool); /** * @dev Returns the timestamp at which an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) external view returns (uint256); /** * @dev Returns operation state. */ // function getOperationState(bytes32 id) public view virtual returns (OperationState); /** * @dev Returns the minimum delay in seconds for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() external view returns (uint256); /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt ) external pure returns (bytes32); /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) external pure returns (bytes32); /** * @dev Schedule an operation containing a single transaction. * * Emits {CallSalt} if salt is nonzero, and {CallScheduled}. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule( address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay ) external; /** * @dev Schedule an operation containing a batch of transactions. * * Emits {CallSalt} if salt is nonzero, and one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt, uint256 delay ) external; /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'canceller' role. */ function cancel(bytes32 id) external; /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function execute( address target, uint256 value, bytes calldata payload, bytes32 predecessor, bytes32 salt ) external; /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ // This function can reenter, but it doesn't pose a risk because _afterCall checks that the proposal is pending, // thus any modifications to the operation during reentrancy should be caught. // slither-disable-next-line reentrancy-eth function executeBatch( address[] calldata targets, uint256[] calldata values, bytes[] calldata payloads, bytes32 predecessor, bytes32 salt ) external payable; /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; interface INotaryConsortium { /// @dev Error thrown when signature payload is already used error PayloadAlreadyUsed(); /// @dev Error thrown when signatures length is not equal to signers length error LengthMismatch(); /// @dev Error thrown when there are not enough signatures error NotEnoughSignatures(); /// @dev Error thrown when unexpected action is used error UnexpectedAction(bytes4 action); /// @dev Event emitted when the validator set is updated event ValidatorSetUpdated( uint256 indexed epoch, address[] validators, uint256[] weights, uint256 threshold ); /// @dev Error thrown when validator set already set error ValSetAlreadySet(); /// @dev Error thrown when no validator set is set error NoValidatorSet(); /// @dev Error thrown when invalid epoch is provided error InvalidEpoch(); function checkProof( bytes32 _payloadHash, bytes calldata _proof ) external view; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {TimelockController} from "@openzeppelin/contracts/governance/TimelockController.sol"; /** * @title Use for Consortium * @author Lombard.Finance * @notice The contracts is a part of Lombard.Finance protocol. Executor is EOA controlled by decentralized consortium consensus mechanism. */ contract LombardTimeLock is TimelockController { constructor( uint256 minDelay, address[] memory proposers, address[] memory executors ) TimelockController(minDelay, proposers, executors, address(0)) {} }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.19; import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; contract VerifySignatureTest { using ECDSA for bytes32; function verifySignature( address signer, bytes32 messageHash, bytes memory signature ) public pure returns (bool) { return messageHash.recover(signature) == signer; } function recoverSigner( bytes32 messageHash, bytes memory signature ) public pure returns (address) { return messageHash.recover(signature); } function verifySignatureWithGas( address signer, bytes32 messageHash, bytes memory signature ) public view returns (bool, uint256) { uint256 gasBefore = gasleft(); bool isValid = messageHash.recover(signature) == signer; uint256 gasAfter = gasleft(); uint256 gasUsed = gasBefore - gasAfter; return (isValid, gasUsed); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {CREATE3} from "solmate/src/utils/CREATE3.sol"; import {TransparentUpgradeableProxy} from "@openzeppelin/contracts/proxy/transparent/TransparentUpgradeableProxy.sol"; import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol"; contract ProxyFactory is AccessControl { error ProxyFactory_ZeroAddress(); bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER_ROLE"); constructor(address admin, address deployer) { if (admin == address(0) || deployer == address(0)) { revert ProxyFactory_ZeroAddress(); } _grantRole(DEFAULT_ADMIN_ROLE, admin); _grantRole(DEPLOYER_ROLE, deployer); } function createTransparentProxy( address implementation, address admin, bytes memory data, bytes32 salt ) public onlyRole(DEPLOYER_ROLE) returns (address) { bytes memory bytecode = abi.encodePacked( type(TransparentUpgradeableProxy).creationCode, abi.encode(implementation, admin, data) ); address proxy = CREATE3.deploy(salt, bytecode, 0); return proxy; } function getDeployed(bytes32 salt) public view returns (address) { return CREATE3.getDeployed(salt); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBaseLBTC} from "../LBTC/IBaseLBTC.sol"; import {IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; interface LockedFBTC { function mintLockedFbtcRequest(uint256 amount) external returns (uint256); function redeemFbtcRequest( uint256 amount, bytes32 depositTxId, uint256 outputIndex ) external returns (bytes32, FBTCPartnerVault.Request memory); function confirmRedeemFbtc(uint256 amount) external; } /** * @title Partner Vault implementation for integration with FBTC * @author Lombard.Finance * @notice The contracts is a part of Lombard.Finace protocol */ contract FBTCPartnerVault is PausableUpgradeable, ReentrancyGuardUpgradeable, AccessControlUpgradeable { using SafeERC20 for IERC20; using SafeERC20 for IBaseLBTC; enum Operation { Nop, // starts from 1. Mint, Burn, CrosschainRequest, CrosschainConfirm } enum Status { Unused, Pending, Confirmed, Rejected } struct Request { Operation op; Status status; uint128 nonce; bytes32 srcChain; bytes srcAddress; bytes32 dstChain; bytes dstAddress; uint256 amount; uint256 fee; bytes extra; } /// @custom:storage-location erc7201:lombardfinance.storage.PartnerVault struct PartnerVaultStorage { IERC20 fbtc; IBaseLBTC lbtc; LockedFBTC lockedFbtc; uint256 stakeLimit; uint256 totalStake; bool allowMintLbtc; mapping(bytes32 => Request) pendingWithdrawals; } bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.PartnerVault")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant PARTNER_VAULT_STORAGE_LOCATION = 0xf2032fbd6c6daf0509f7b47277c23d318b85e97f8401e745afc792c2709cec00; error StakeLimitExceeded(); error ZeroAmount(); error InsufficientFunds(); error WithdrawalInProgress(); error NoWithdrawalInitiated(); error NoUnsetLockedFBTC(); error NoResetLockedFBTC(); event StakeLimitSet(uint256 newStakeLimit); event LockedFBTCSet(address lockedFbtc); event MintLBTCSet(bool shouldMint); event FBTCLocked( address indexed recipient, uint256 amountLocked, bool indexed lbtcMinted ); event WithdrawalDeleted( address indexed recipient, uint256 amount, bytes32 indexed depositTxId, uint256 indexed outputIndex ); event BurnInitiated( address indexed recipient, uint256 amount, bytes32 indexed depositTxId, uint256 indexed outputIndex ); event BurnFinalized( address indexed recipient, uint256 amount, bytes32 indexed depositTxId, uint256 indexed outputIndex ); /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize( address admin, address fbtc_, address lbtc_, uint256 stakeLimit_ ) external initializer { __Pausable_init(); __ReentrancyGuard_init(); __AccessControl_init(); _grantRole(DEFAULT_ADMIN_ROLE, admin); PartnerVaultStorage storage $ = _getPartnerVaultStorage(); $.fbtc = IERC20(fbtc_); $.lbtc = IBaseLBTC(lbtc_); $.stakeLimit = stakeLimit_; } /** * @notice Sets the address of the `lockedFbtc` contract, since this needs to be done after * deployment of the partner vault. * @param lockedFbtc_ The address at which the `lockedFbtc` contract lives */ function setLockedFbtc( address lockedFbtc_ ) external onlyRole(DEFAULT_ADMIN_ROLE) { if (lockedFbtc_ == address(0)) revert NoUnsetLockedFBTC(); PartnerVaultStorage storage $ = _getPartnerVaultStorage(); if (address($.lockedFbtc) != address(0)) revert NoResetLockedFBTC(); $.lockedFbtc = LockedFBTC(lockedFbtc_); emit LockedFBTCSet(lockedFbtc_); } /** * @notice Sets the LBTC minting functionality. * @param shouldMint Boolean value if we should mint or not */ function setAllowMintLbtc( bool shouldMint ) external onlyRole(DEFAULT_ADMIN_ROLE) { PartnerVaultStorage storage $ = _getPartnerVaultStorage(); $.allowMintLbtc = shouldMint; emit MintLBTCSet(shouldMint); } /** * @notice Sets the stake limit for the partner vault. * @param newStakeLimit The stake limit to use going forward */ function setStakeLimit( uint256 newStakeLimit ) external onlyRole(OPERATOR_ROLE) { _getPartnerVaultStorage().stakeLimit = newStakeLimit; emit StakeLimitSet(newStakeLimit); } /** * @notice Functionality to swap FBTC into LBTC. This function assumes that the sender has already * approved at least `amount` of satoshis of FBTC to this vault. * @param amount The amount of satoshis of FBTC to be locked * @return The amount of satoshis that are locked after the LockedFBTC contract takes a fee */ function mint( uint256 amount ) external nonReentrant whenNotPaused returns (uint256) { if (amount == 0) revert ZeroAmount(); PartnerVaultStorage storage $ = _getPartnerVaultStorage(); // First, we take the FBTC from the sender. $.fbtc.safeTransferFrom(_msgSender(), address(this), amount); // Then, we need to approve `amount` of satoshis to the LockedFBTC contract. $.fbtc.approve(address($.lockedFbtc), amount); // Now we can make the mintLockedFbtcRequest. uint256 amountLocked = $.lockedFbtc.mintLockedFbtcRequest(amount); if ($.totalStake + amountLocked > $.stakeLimit) revert StakeLimitExceeded(); $.totalStake += amountLocked; // At this point we have our locked FBTC minted to us. If the `allowMintLbtc` variable is // set to true, we also give the user some LBTC. Otherwise, this is done manually afterwards. if ($.allowMintLbtc) $.lbtc.mint(_msgSender(), amountLocked); emit FBTCLocked(_msgSender(), amountLocked, $.allowMintLbtc); return amountLocked; } /** * @notice Functionality to initiate a swap for LBTC into FBTC. This only initiates the withdrawal * request and needs to be finalized by `finalizeBurn` later on, once all the off-chain bookkeeping * is finalized as well. * @param recipient The recipient of the FBTC to be released * @param amount The amount of satoshis of FBTC to be released * @param depositTxId The transaction ID of the BTC deposit on the bitcoin network * @param amount The transaction output index to user's deposit address */ function initializeBurn( address recipient, uint256 amount, bytes32 depositTxId, uint256 outputIndex ) external nonReentrant whenNotPaused onlyRole(OPERATOR_ROLE) returns (bytes32, Request memory) { if (amount == 0) revert ZeroAmount(); PartnerVaultStorage storage $ = _getPartnerVaultStorage(); if (amount > $.totalStake) revert InsufficientFunds(); bytes32 key = keccak256( abi.encode(recipient, amount, depositTxId, outputIndex) ); if ($.pendingWithdrawals[key].amount != 0) revert WithdrawalInProgress(); // We only make a call to set the redeeming up first. We can only start moving tokens later // when all correct steps have been taken. (bytes32 hash, Request memory request) = $.lockedFbtc.redeemFbtcRequest( amount, depositTxId, outputIndex ); // Ensure that this caller can redeem for `amount` later when // all bookkeeping off-chain is done. $.pendingWithdrawals[key] = request; emit BurnInitiated(recipient, amount, depositTxId, outputIndex); return (hash, request); } /** * @notice Finalizes the withdrawal of LBTC back into FBTC. * @param recipient The recipient of the FBTC to be released * @param amount The amount of satoshis of FBTC to be released * @param depositTxId The transaction ID of the BTC deposit on the bitcoin network * @param amount The transaction output index to user's deposit address */ function finalizeBurn( address recipient, uint256 amount, bytes32 depositTxId, uint256 outputIndex ) external nonReentrant whenNotPaused onlyRole(OPERATOR_ROLE) { bytes32 key = keccak256( abi.encode(recipient, amount, depositTxId, outputIndex) ); PartnerVaultStorage storage $ = _getPartnerVaultStorage(); if ($.pendingWithdrawals[key].amount != amount) revert NoWithdrawalInitiated(); if (amount > $.totalStake) revert InsufficientFunds(); $.totalStake -= amount; delete $.pendingWithdrawals[key]; // First, take the LBTC back if the `allowMintLbtc` variable is set. If not, the LBTC will // be deducted from the user's balance and put in the vault to be burned manually later. if ($.allowMintLbtc) { $.lbtc.burn(recipient, amount); } else { IERC20(address($.lbtc)).safeTransferFrom( recipient, address(this), amount ); } // Next, we finalize the redeeming flow. $.lockedFbtc.confirmRedeemFbtc(amount); // Finally, we need to send the received FBTC back to the caller. $.fbtc.safeTransfer(recipient, amount); emit BurnFinalized(recipient, amount, depositTxId, outputIndex); } /** * @notice Allows an operator to remove a pending withdrawal request manually, in case it has been * rejected by the FBTC team. * @param recipient The recipient of the FBTC to be released * @param amount The amount of satoshis of FBTC to be released * @param depositTxId The transaction ID of the BTC deposit on the bitcoin network * @param amount The transaction output index to user's deposit address */ function removeWithdrawalRequest( address recipient, uint256 amount, bytes32 depositTxId, uint256 outputIndex ) external whenNotPaused onlyRole(OPERATOR_ROLE) { bytes32 key = keccak256( abi.encode(recipient, amount, depositTxId, outputIndex) ); PartnerVaultStorage storage $ = _getPartnerVaultStorage(); delete $.pendingWithdrawals[key]; emit WithdrawalDeleted(recipient, amount, depositTxId, outputIndex); } function pause() external onlyRole(PAUSER_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function stakeLimit() external view returns (uint256) { return _getPartnerVaultStorage().stakeLimit; } function allowMintLbtc() external view returns (bool) { return _getPartnerVaultStorage().allowMintLbtc; } function remainingStake() external view returns (uint256) { PartnerVaultStorage storage $ = _getPartnerVaultStorage(); if ($.totalStake > $.stakeLimit) return 0; return $.stakeLimit - $.totalStake; } function fbtc() external view returns (address) { PartnerVaultStorage storage $ = _getPartnerVaultStorage(); return address($.fbtc); } function lockedFbtc() external view returns (address) { PartnerVaultStorage storage $ = _getPartnerVaultStorage(); return address($.lockedFbtc); } function _getPartnerVaultStorage() internal pure returns (PartnerVaultStorage storage $) { assembly { $.slot := PARTNER_VAULT_STORAGE_LOCATION } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {ERC20PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IIBCVoucher} from "./IIBCVoucher.sol"; import {IBaseLBTC} from "../LBTC/IBaseLBTC.sol"; /// @title ERC20 intermediary token /// @author Lombard.Finance /// @notice The contracts is a part of Lombard.Finace protocol contract IBCVoucher is IIBCVoucher, ERC20PausableUpgradeable, ReentrancyGuardUpgradeable, AccessControlUpgradeable { using SafeERC20 for IERC20; /// @notice Simplified implementation of IBC rate limits: https://github.com/cosmos/ibc-apps/tree/modules/rate-limiting/v8.0.0/modules/rate-limiting struct RateLimit { uint64 supplyAtUpdate; uint64 limit; uint64 credit; uint64 startTime; uint64 window; // Window denominated in hours. uint64 epoch; uint16 threshold; // Denominated in BIPs (hundredths of a percentage) of the supply. } /// @custom:storage-location erc7201:lombardfinance.storage.IBCVoucher struct IBCVoucherStorage { string name; string symbol; IBaseLBTC lbtc; uint256 fee; address treasury; RateLimit rateLimit; } bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant RELAYER_ROLE = keccak256("RELAYER_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); uint256 public constant RATIO_MULTIPLIER = 10000; uint16 public constant MIN_RATE_LIMIT_WINDOW = 3600; // minimum window in seconds for the rate limit calculation // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.IBCVoucher")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant IBCVOUCHER_STORAGE_LOCATION = 0xbcdad5fb3ea2d152a63bdfe3b5528166cf47e4744fa97c998b76e45dac6f2800; /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize( IBaseLBTC _lbtc, address admin, uint256 _fee, address _treasury ) external initializer { __ERC20_init("", ""); __ERC20Pausable_init(); __ReentrancyGuard_init(); __AccessControl_init(); _grantRole(DEFAULT_ADMIN_ROLE, admin); __IBCVoucher_init( "IBC compatible LBTC Voucher", "iLBTCv", _lbtc, _fee, _treasury ); } function __IBCVoucher_init( string memory _name, string memory _symbol, IBaseLBTC _lbtc, uint256 _fee, address _treasury ) internal onlyInitializing { _changeNameAndSymbol(_name, _symbol); IBCVoucherStorage storage $ = _getIBCVoucherStorage(); $.lbtc = _lbtc; _setFee(_fee); _setTreasuryAddress(_treasury); } /// @notice Sets a rate limit for unwrapping the IBC Voucher. /// @param threshold The rate limit threshold in BIPs (hundredths of a percentage). /// @param window The rate limit window in seconds. function setRateLimit( uint16 threshold, uint64 window, uint64 startTime ) external onlyRole(DEFAULT_ADMIN_ROLE) { IBCVoucherStorage storage $ = _getIBCVoucherStorage(); if (threshold == 0) { revert ZeroThreshold(); } _setRateLimit($, threshold, window, 0, startTime); } function _resetRateLimit(uint64 epoch) internal { IBCVoucherStorage storage $ = _getIBCVoucherStorage(); _setRateLimit($, $.rateLimit.threshold, $.rateLimit.window, epoch, 0); } function _setRateLimit( IBCVoucherStorage storage $, uint16 threshold, uint64 window, uint64 epoch, uint64 startTime ) internal { uint256 totalSupply = totalSupply(); if (window != 0 && window < MIN_RATE_LIMIT_WINDOW) { revert TooLowWindow(); } if (threshold > RATIO_MULTIPLIER) { revert InconsistentThreshold(); } $.rateLimit.supplyAtUpdate = uint64(totalSupply); $.rateLimit.threshold = threshold; uint64 limit = uint64((threshold * totalSupply) / RATIO_MULTIPLIER); $.rateLimit.limit = limit; $.rateLimit.credit = limit; $.rateLimit.window = window; $.rateLimit.epoch = epoch; if (epoch == 0) { if (startTime > block.timestamp) { revert FutureStartTime(startTime, block.timestamp); } $.rateLimit.startTime = startTime; } emit RateLimitUpdated( $.rateLimit.limit, $.rateLimit.window, $.rateLimit.threshold ); } function wrap( uint256 amount ) external override nonReentrant onlyRole(RELAYER_ROLE) returns (uint256) { return _wrap(_msgSender(), _msgSender(), amount, 0); } function wrap( uint256 amount, uint256 minAmountOut ) external override nonReentrant onlyRole(RELAYER_ROLE) returns (uint256) { return _wrap(_msgSender(), _msgSender(), amount, minAmountOut); } function wrapTo( address recipient, uint256 amount ) external override nonReentrant onlyRole(RELAYER_ROLE) returns (uint256) { return _wrap(_msgSender(), recipient, amount, 0); } function wrapTo( address recipient, uint256 amount, uint256 minAmountOut ) external override nonReentrant onlyRole(RELAYER_ROLE) returns (uint256) { return _wrap(_msgSender(), recipient, amount, minAmountOut); } function _wrap( address from, address recipient, uint256 amount, uint256 minAmountOut ) internal returns (uint256) { IBCVoucherStorage storage $ = _getIBCVoucherStorage(); uint256 fee = $.fee; if (amount <= fee) { revert AmountTooLow(); } uint256 amountAfterFee = amount - fee; if (amountAfterFee < minAmountOut) { revert SlippageExceeded(amountAfterFee, minAmountOut); } if ($.rateLimit.window != 0) { uint64 epoch = uint64( (block.timestamp - $.rateLimit.startTime) / $.rateLimit.window ); if (epoch > $.rateLimit.epoch) { _resetRateLimit(epoch); } // Calculate net flow, so wrapping would reduce our flow. emit RateLimitOutflowIncreased( $.rateLimit.credit, uint64(amountAfterFee) ); $.rateLimit.credit += uint64(amountAfterFee); } IBaseLBTC _lbtc = $.lbtc; IERC20(address(_lbtc)).safeTransferFrom(from, address(this), amount); IERC20(address(_lbtc)).safeTransfer($.treasury, fee); _lbtc.burn(amountAfterFee); _mint(recipient, amountAfterFee); emit VoucherMinted(from, recipient, fee, amountAfterFee); return amountAfterFee; } function spend(uint256 amount) external override nonReentrant { _spend(_msgSender(), _msgSender(), amount); } function spendTo( address recipient, uint256 amount ) external override nonReentrant { _spend(_msgSender(), recipient, amount); } function spendFrom( address owner, uint256 amount ) external override nonReentrant onlyRole(OPERATOR_ROLE) { _spend(owner, owner, amount); } function _spend(address from, address recipient, uint256 amount) internal { IBCVoucherStorage storage $ = _getIBCVoucherStorage(); if ($.rateLimit.window != 0) { uint64 epoch = uint64( (block.timestamp - $.rateLimit.startTime) / $.rateLimit.window ); if (epoch > $.rateLimit.epoch) { _resetRateLimit(epoch); } if (uint64(amount) > $.rateLimit.credit) { revert RateLimitExceeded( $.rateLimit.limit, $.rateLimit.credit, uint64(amount) ); } emit RateLimitInflowIncreased($.rateLimit.credit, uint64(amount)); $.rateLimit.credit -= uint64(amount); } _burn(from, amount); $.lbtc.mint(recipient, amount); emit VoucherSpent(from, recipient, amount); } function pause() external onlyRole(PAUSER_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function setTreasuryAddress( address newTreasury ) external onlyRole(DEFAULT_ADMIN_ROLE) { _setTreasuryAddress(newTreasury); } function _setTreasuryAddress(address newTreasury) internal { if (newTreasury == address(0)) { revert ZeroAddress(); } IBCVoucherStorage storage $ = _getIBCVoucherStorage(); $.treasury = newTreasury; emit TreasuryUpdated($.treasury); } function setFee(uint256 newFee) external onlyRole(DEFAULT_ADMIN_ROLE) { _setFee(newFee); } function _setFee(uint256 newFee) internal { IBCVoucherStorage storage $ = _getIBCVoucherStorage(); $.fee = newFee; emit FeeUpdated($.fee); } function getTreasury() external view returns (address) { return _getIBCVoucherStorage().treasury; } function getFee() external view returns (uint256) { return _getIBCVoucherStorage().fee; } function lbtc() external view returns (address) { return address(_getIBCVoucherStorage().lbtc); } /// @dev Returns the name of the token. function name() public view virtual override returns (string memory) { return _getIBCVoucherStorage().name; } /// @dev Returns the symbol of the token, usually a shorter version of the name. function symbol() public view virtual override returns (string memory) { return _getIBCVoucherStorage().symbol; } /// @dev Returns the number of decimals used to get its user representation. /// Because LBTC represents BTC we use the same decimals. function decimals() public view virtual override returns (uint8) { return 8; } function leftoverAmount() public view returns (uint64) { IBCVoucherStorage storage $ = _getIBCVoucherStorage(); uint64 epoch = uint64( (block.timestamp - $.rateLimit.startTime) / $.rateLimit.window ); if (epoch > $.rateLimit.epoch) { return uint64( ($.rateLimit.threshold * totalSupply()) / RATIO_MULTIPLIER ); } return $.rateLimit.credit; } function rateLimitConfig() public view returns (RateLimit memory) { return _getIBCVoucherStorage().rateLimit; } function _changeNameAndSymbol( string memory name_, string memory symbol_ ) internal { IBCVoucherStorage storage $ = _getIBCVoucherStorage(); $.name = name_; $.symbol = symbol_; emit NameAndSymbolChanged(name_, symbol_); } function _getIBCVoucherStorage() private pure returns (IBCVoucherStorage storage $) { assembly { $.slot := IBCVOUCHER_STORAGE_LOCATION } } /// @dev Override of the _update function to satisfy ERC20PausableUpgradeable function _update( address from, address to, uint256 value ) internal virtual override(ERC20PausableUpgradeable) { super._update(from, to, value); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; interface IIBCVoucher { event NameAndSymbolChanged(string name, string symbol); event VoucherMinted( address indexed from, address indexed to, uint256 fee, uint256 amount ); event VoucherSpent( address indexed from, address indexed to, uint256 amount ); event TreasuryUpdated(address indexed newTreasury); event FeeUpdated(uint256 fee); event RateLimitUpdated(uint64 limit, uint64 window, uint64 threshold); event RateLimitInflowIncreased(uint64 oldCredit, uint amount); event RateLimitOutflowIncreased(uint64 oldCredit, uint amount); error AmountTooLow(); error ZeroAddress(); error RateLimitExceeded(uint64 limit, uint64 flow, uint64 amount); error ZeroThreshold(); error FutureStartTime(uint256 startTime, uint256 blockTimestamp); error TooLowWindow(); error InconsistentThreshold(); error SlippageExceeded(uint256 amountAfterFee, uint256 minAmountOut); /// @notice Gives voucher in exchange for LBTC accepting any current fee /// @dev Requires LBTC approval /// @param amount Amount of LBTC function wrap(uint256 amount) external returns (uint256); /// @notice Gives voucher in exchange for LBTC /// @dev Requires LBTC approval /// @param amount Amount of LBTC /// @param minAmountOut The minimum acceptable amount of LBTC to receive function wrap( uint256 amount, uint256 minAmountOut ) external returns (uint256); /// @notice Gives voucher to `recipient` in exchange for LBTC accepting any current fee /// @dev Requires LBTC approval /// @param recipient Recipient of Voucher /// @param amount Amount of LBTC function wrapTo( address recipient, uint256 amount ) external returns (uint256); /// @notice Gives voucher to `recipient` in exchange for LBTC /// @dev Requires LBTC approval /// @param recipient Recipient of Voucher /// @param amount Amount of LBTC /// @param minAmountOut The minimum acceptable amount of LBTC to receive function wrapTo( address recipient, uint256 amount, uint256 minAmountOut ) external returns (uint256); /// @notice Spends the voucher and gives LBTC back /// @dev No approval required, burns directly from message sender /// @param amount Amount of Voucher function spend(uint256 amount) external; /// @notice Spends the voucher and gives LBTC back to `recipient` /// @dev No approval required, burns directly from message sender /// @param recipient Recipient of LBTC /// @param amount Amount of Voucher function spendTo(address recipient, uint256 amount) external; /// @notice Spends the voucher and gives LBTC back /// @dev No approval required, burns directly from specified account. /// Only available to relayer role. /// @param owner Owner of Voucher /// @param amount Amount of Voucher function spendFrom(address owner, uint256 amount) external; /// @notice Returns the current wrapping fee function getFee() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {INotaryConsortium} from "../consortium/INotaryConsortium.sol"; /** * @title Consortium Consumer interface * @author Lombard.Finance * @notice Common interface for contracts who verify signatures with `INotaryConsortium` */ interface IConsortiumConsumer { event ConsortiumChanged( INotaryConsortium indexed prevVal, INotaryConsortium indexed newVal ); function changeConsortium(INotaryConsortium newVal) external; function consortium() external view returns (INotaryConsortium); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; // @dev deprecated interface for bindings interface IEfficientRateLimiterV1 { struct RateLimitConfig { uint32 eid; uint256 limit; uint256 window; } enum RateLimitDirection { Inbound, Outbound } function setRateLimits( RateLimitConfig[] calldata _rateLimitConfigs, RateLimitDirection direction ) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (proxy/transparent/ProxyAdmin.sol) pragma solidity 0.8.24; interface IProxyAdmin { /** * @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgrade(address)` * and `upgradeAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called, * while `upgradeAndCall` will invoke the `receive` function if the second argument is the empty byte string. * If the getter returns `"5.0.0"`, only `upgradeAndCall(address,bytes)` is present, and the second argument must * be the empty byte string if no function should be called, making it impossible to invoke the `receive` function * during an upgrade. */ function UPGRADE_INTERFACE_VERSION() external returns (string memory); /** * @dev Upgrades `proxy` to `implementation` and calls a function on the new implementation. * See {TransparentUpgradeableProxy-_dispatchUpgradeToAndCall}. * * Requirements: * * - This contract must be the admin of `proxy`. * - If `data` is empty, `msg.value` must be zero. */ function upgradeAndCall( address proxy, address implementation, bytes memory data ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; interface IBaseLBTC { error ZeroAddress(); error WithdrawalsDisabled(); error ScriptPubkeyUnsupported(); error AmountLessThanCommission(uint256 fee); error AmountBelowDustLimit(uint256 dustLimit); error InvalidDustFeeRate(); error UnexpectedAction(bytes4 action); error InvalidUserSignature(); error PayloadAlreadyUsed(); error InvalidInputLength(); error InvalidMintAmount(); event UnstakeRequest( address indexed fromAddress, bytes scriptPubKey, uint256 amount ); event WithdrawalsEnabled(bool); event NameAndSymbolChanged(string name, string symbol); event ConsortiumChanged(address indexed prevVal, address indexed newVal); event TreasuryAddressChanged( address indexed prevValue, address indexed newValue ); event BurnCommissionChanged( uint64 indexed prevValue, uint64 indexed newValue ); event DustFeeRateChanged(uint256 indexed oldRate, uint256 indexed newRate); event BasculeChanged(address indexed prevVal, address indexed newVal); event FeeCharged(uint256 indexed fee, bytes userSignature); event FeeChanged(uint256 indexed oldFee, uint256 indexed newFee); error FeeGreaterThanAmount(); event MintProofConsumed( address indexed recipient, bytes32 indexed payloadHash, bytes payload ); event BatchMintSkipped(bytes32 indexed payloadHash, bytes payload); function burn(uint256 amount) external; function burn(address from, uint256 amount) external; function mint(address to, uint256 amount) external; function getTreasury() external returns (address); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBaseLBTC} from "./IBaseLBTC.sol"; interface INativeLBTC is IBaseLBTC { error InvalidDestinationToken(address expected, address got); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IBaseLBTC} from "./IBaseLBTC.sol"; interface IStakedLBTC is IBaseLBTC { error UnauthorizedAccount(address account); event OperatorRoleTransferred( address indexed previousOperator, address indexed newOperator ); event ClaimerUpdated(address indexed claimer, bool isClaimer); event PauserRoleTransferred( address indexed previousPauser, address indexed newPauser ); event MinterUpdated(address indexed minter, bool isMinter); function mint(bytes calldata payload, bytes calldata proof) external; }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ERC20Upgradeable, IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {ERC20PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol"; import {ERC20PermitUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol"; import {Ownable2StepUpgradeable} from "@openzeppelin/contracts-upgradeable/access/Ownable2StepUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {BitcoinUtils, OutputType} from "../libs/BitcoinUtils.sol"; import {IBascule} from "../bascule/interfaces/IBascule.sol"; import {FeeUtils} from "../libs/FeeUtils.sol"; import {Consortium} from "../consortium/Consortium.sol"; import {Actions} from "../libs/Actions.sol"; import {EIP1271SignatureUtils} from "../libs/EIP1271SignatureUtils.sol"; import {IStakedLBTC} from "./IStakedLBTC.sol"; /** * @title ERC20 representation of Lombard Staked Bitcoin * @author Lombard.Finance * @notice This contract is part of the Lombard.Finance protocol */ contract LBTC is IStakedLBTC, ERC20PausableUpgradeable, Ownable2StepUpgradeable, ReentrancyGuardUpgradeable, ERC20PermitUpgradeable { /// @custom:storage-location erc7201:lombardfinance.storage.LBTC struct LBTCStorage { /// @dev is keccak256(payload[4:]) used /// @custom:oz-renamed-from usedProofs mapping(bytes32 => bool) legacyUsedPayloads; string name; string symbol; bool isWithdrawalsEnabled; address consortium; bool isWBTCEnabled; IERC20 wbtc; address treasury; /// @custom:oz-renamed-from destinations mapping(uint256 => address) __removed_destinations; /// @custom:oz-renamed-from depositCommission mapping(uint256 => uint16) __removed_depositCommission; /// @custom:oz-renamed-from usedBridgeProofs mapping(bytes32 => bool) __removed_usedBridgeProofs; /// @custom:oz-renamed-from globalNonce uint256 __removed_globalNonce; mapping(bytes32 => bytes32) __removed__destinations; mapping(bytes32 => uint16) __removed__depositRelativeCommission; mapping(bytes32 => uint64) __removed__depositAbsoluteCommission; uint64 burnCommission; // absolute commission to charge on burn (unstake) uint256 dustFeeRate; /// Bascule drawbridge used to confirm deposits before allowing withdrawals IBascule bascule; address pauser; mapping(address => bool) minters; mapping(address => bool) claimers; /// Maximum fee to apply on mints uint256 maximumFee; // @dev is sha256(payload) used mapping(bytes32 => bool) usedPayloads; address operator; } // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.LBTC")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant LBTC_STORAGE_LOCATION = 0xa9a2395ec4edf6682d754acb293b04902817fdb5829dd13adb0367ab3a26c700; /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } /// INTIALIZERS /// function initialize( address consortium_, uint64 burnCommission_, address treasury, address owner_ ) external initializer { __ERC20_init("", ""); __ERC20Pausable_init(); __Ownable_init(owner_); __Ownable2Step_init(); __ReentrancyGuard_init(); __LBTC_init( "Lombard Staked Bitcoin", "LBTC", consortium_, treasury, burnCommission_ ); LBTCStorage storage $ = _getLBTCStorage(); $.dustFeeRate = BitcoinUtils.DEFAULT_DUST_FEE_RATE; emit DustFeeRateChanged(0, $.dustFeeRate); } function reinitialize() external reinitializer(2) { __ERC20Permit_init("Lombard Staked Bitcoin"); } /// MODIFIER /// /** * PAUSE */ modifier onlyPauser() { _checkPauser(); _; } modifier onlyMinter() { if (!_getLBTCStorage().minters[_msgSender()]) { revert UnauthorizedAccount(_msgSender()); } _; } modifier onlyClaimer() { if (!_getLBTCStorage().claimers[_msgSender()]) { revert UnauthorizedAccount(_msgSender()); } _; } modifier onlyOperator() { if (_getLBTCStorage().operator != _msgSender()) { revert UnauthorizedAccount(_msgSender()); } _; } /// ONLY OWNER FUNCTIONS /// function toggleWithdrawals() external onlyOwner { LBTCStorage storage $ = _getLBTCStorage(); $.isWithdrawalsEnabled = !$.isWithdrawalsEnabled; emit WithdrawalsEnabled($.isWithdrawalsEnabled); } function changeNameAndSymbol( string calldata name_, string calldata symbol_ ) external onlyOwner { _changeNameAndSymbol(name_, symbol_); } function changeConsortium(address newVal) external onlyOwner { _changeConsortium(newVal); } /** * @notice Set the contract current fee for mint * @param fee New fee value * @dev zero allowed to disable fee */ function setMintFee(uint256 fee) external onlyOperator { LBTCStorage storage $ = _getLBTCStorage(); uint256 oldFee = $.maximumFee; $.maximumFee = fee; emit FeeChanged(oldFee, fee); } function changeTreasuryAddress(address newValue) external onlyOwner { _changeTreasuryAddress(newValue); } function changeBurnCommission(uint64 newValue) external onlyOwner { _changeBurnCommission(newValue); } function pause() external onlyPauser { _pause(); } function unpause() external onlyPauser { _unpause(); } function addMinter(address newMinter) external onlyOwner { _updateMinter(newMinter, true); } function removeMinter(address oldMinter) external onlyOwner { _updateMinter(oldMinter, false); } function addClaimer(address newClaimer) external onlyOwner { _updateClaimer(newClaimer, true); } function removeClaimer(address oldClaimer) external onlyOwner { _updateClaimer(oldClaimer, false); } /// @notice Change the dust fee rate used for dust limit calculations /// @dev Only the contract owner can call this function. The new rate must be positive. /// @param newRate The new dust fee rate (in satoshis per 1000 bytes) function changeDustFeeRate(uint256 newRate) external onlyOwner { if (newRate == 0) revert InvalidDustFeeRate(); LBTCStorage storage $ = _getLBTCStorage(); uint256 oldRate = $.dustFeeRate; $.dustFeeRate = newRate; emit DustFeeRateChanged(oldRate, newRate); } /** * Change the address of the Bascule drawbridge contract. * Setting the address to 0 disables the Bascule check. * @param newVal The new address. * * Emits a {BasculeChanged} event. */ function changeBascule(address newVal) external onlyOwner { _changeBascule(newVal); } function transferPauserRole(address newPauser) external onlyOwner { if (newPauser == address(0)) { revert ZeroAddress(); } _transferPauserRole(newPauser); } function transferOperatorRole(address newOperator) external onlyOwner { if (newOperator == address(0)) { revert ZeroAddress(); } _transferOperatorRole(newOperator); } /// GETTERS /// /** * @notice Returns the current maximum mint fee */ function getMintFee() external view returns (uint256) { return _getLBTCStorage().maximumFee; } /// @notice Calculate the amount that will be unstaked and check if it's above the dust limit /// @dev This function can be used by front-ends to verify burn amounts before submitting a transaction /// @param scriptPubkey The Bitcoin script public key as a byte array /// @param amount The amount of LBTC to be burned /// @return amountAfterFee The amount that will be unstaked (after deducting the burn commission) /// @return isAboveDust Whether the amountAfterFee is equal to or above the dust limit function calcUnstakeRequestAmount( bytes calldata scriptPubkey, uint256 amount ) external view returns (uint256 amountAfterFee, bool isAboveDust) { LBTCStorage storage $ = _getLBTCStorage(); (amountAfterFee, , , isAboveDust) = _calcFeeAndDustLimit( scriptPubkey, amount, $.burnCommission ); return (amountAfterFee, isAboveDust); } function consortium() external view virtual returns (address) { return _getLBTCStorage().consortium; } /** * @dev Returns the number of decimals used to get its user representation. * * Because LBTC repsents BTC we use the same decimals. * */ function decimals() public view virtual override returns (uint8) { return 8; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _getLBTCStorage().name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _getLBTCStorage().symbol; } function getTreasury() public view override returns (address) { return _getLBTCStorage().treasury; } function getBurnCommission() public view returns (uint64) { return _getLBTCStorage().burnCommission; } /// @notice Get the current dust fee rate /// @return The current dust fee rate (in satoshis per 1000 bytes) function getDustFeeRate() public view returns (uint256) { return _getLBTCStorage().dustFeeRate; } /** * Get Bascule contract. */ function Bascule() external view returns (IBascule) { return _getLBTCStorage().bascule; } function pauser() public view returns (address) { return _getLBTCStorage().pauser; } function operator() external view returns (address) { return _getLBTCStorage().operator; } function isMinter(address minter) external view returns (bool) { return _getLBTCStorage().minters[minter]; } function isClaimer(address claimer) external view returns (bool) { return _getLBTCStorage().claimers[claimer]; } /// USER ACTIONS /// /** * @notice Mint LBTC to the specified address * @param to The address to mint to * @param amount The amount of LBTC to mint * @dev Only callable by whitelisted minters */ function mint(address to, uint256 amount) external override onlyMinter { _mint(to, amount); } /** * @notice Mint LBTC in batches * @param to The addresses to mint to * @param amount The amounts of LBTC to mint * @dev Only callable by whitelisted minters */ function batchMint( address[] calldata to, uint256[] calldata amount ) external onlyMinter { if (to.length != amount.length) { revert InvalidInputLength(); } for (uint256 i; i < to.length; ++i) { _mint(to[i], amount[i]); } } /** * @notice Mint LBTC by proving a stake action happened * @param payload The message with the stake data * @param proof Signature of the consortium approving the mint */ function mint( bytes calldata payload, bytes calldata proof ) public nonReentrant { // payload validation if (bytes4(payload) != Actions.DEPOSIT_BTC_ACTION_V0) { revert UnexpectedAction(bytes4(payload)); } Actions.DepositBtcActionV0 memory action = Actions.depositBtcV0( payload[4:] ); _validateAndMint( action.recipient, action.amount, action.amount, payload, proof ); } /** * @notice Mint LBTC in batches by proving stake actions happened * @param payload The messages with the stake data * @param proof Signatures of the consortium approving the mints */ function batchMint( bytes[] calldata payload, bytes[] calldata proof ) external { if (payload.length != proof.length) { revert InvalidInputLength(); } for (uint256 i; i < payload.length; ++i) { // Pre-emptive check if payload was used. If so, we can skip the call. bytes32 payloadHash = sha256(payload[i]); bytes32 legacyPayloadHash = keccak256(payload[i][4:]); if (isPayloadUsed(payloadHash, legacyPayloadHash)) { emit BatchMintSkipped(payloadHash, payload[i]); continue; } mint(payload[i], proof[i]); } } /** * @notice Mint LBTC applying a commission to the amount * @dev Payload should be same as mint to avoid reusing them with and without fee * @param mintPayload The message with the stake data * @param proof Signature of the consortium approving the mint * @param feePayload Contents of the fee approval signed by the user * @param userSignature Signature of the user to allow Fee */ function mintWithFee( bytes calldata mintPayload, bytes calldata proof, bytes calldata feePayload, bytes calldata userSignature ) external onlyClaimer { _mintWithFee(mintPayload, proof, feePayload, userSignature); } /** * @notice Mint LBTC in batches proving stake actions happened * @param mintPayload The messages with the stake data * @param proof Signatures of the consortium approving the mints * @param feePayload Contents of the fee approvals signed by the user * @param userSignature Signatures of the user to allow Fees */ function batchMintWithFee( bytes[] calldata mintPayload, bytes[] calldata proof, bytes[] calldata feePayload, bytes[] calldata userSignature ) external onlyClaimer { uint256 length = mintPayload.length; if ( length != proof.length || length != feePayload.length || length != userSignature.length ) { revert InvalidInputLength(); } for (uint256 i; i < mintPayload.length; ++i) { // Pre-emptive check if payload was used. If so, we can skip the call. bytes32 payloadHash = sha256(mintPayload[i]); bytes32 legacyPayloadHash = keccak256(mintPayload[i][4:]); if (isPayloadUsed(payloadHash, legacyPayloadHash)) { emit BatchMintSkipped(payloadHash, mintPayload[i]); continue; } _mintWithFee( mintPayload[i], proof[i], feePayload[i], userSignature[i] ); } } /** * @dev Burns LBTC to initiate withdrawal of BTC to provided `scriptPubkey` with `amount` * * @param scriptPubkey scriptPubkey for output * @param amount Amount of LBTC to burn */ function redeem(bytes calldata scriptPubkey, uint256 amount) external { LBTCStorage storage $ = _getLBTCStorage(); if (!$.isWithdrawalsEnabled) { revert WithdrawalsDisabled(); } uint64 fee = $.burnCommission; ( uint256 amountAfterFee, bool isAboveFee, uint256 dustLimit, bool isAboveDust ) = _calcFeeAndDustLimit(scriptPubkey, amount, fee); if (!isAboveFee) { revert AmountLessThanCommission(fee); } if (!isAboveDust) { revert AmountBelowDustLimit(dustLimit); } address fromAddress = address(_msgSender()); _transfer(fromAddress, getTreasury(), fee); _burn(fromAddress, amountAfterFee); emit UnstakeRequest(fromAddress, scriptPubkey, amountAfterFee); } /** * @dev Burns LBTC * * @param amount Amount of LBTC to burn */ function burn(uint256 amount) external { _burn(_msgSender(), amount); } /** * @dev Allows minters to burn LBTC * * @param amount Amount of LBTC to burn */ function burn(address from, uint256 amount) external override onlyMinter { _burn(from, amount); } /** * @dev Returns whether a minting payload has been used already * * @param payloadHash The minting payload hash * @param legacyPayloadHash The legacy minting payload hash */ function isPayloadUsed( bytes32 payloadHash, bytes32 legacyPayloadHash ) public view returns (bool) { LBTCStorage storage $ = _getLBTCStorage(); return $.usedPayloads[payloadHash] || $.legacyUsedPayloads[legacyPayloadHash]; } /// PRIVATE FUNCTIONS /// function __LBTC_init( string memory name_, string memory symbol_, address consortium_, address treasury, uint64 burnCommission_ ) internal onlyInitializing { _changeNameAndSymbol(name_, symbol_); _changeConsortium(consortium_); _changeTreasuryAddress(treasury); _changeBurnCommission(burnCommission_); } function _changeNameAndSymbol( string memory name_, string memory symbol_ ) internal { LBTCStorage storage $ = _getLBTCStorage(); $.name = name_; $.symbol = symbol_; emit NameAndSymbolChanged(name_, symbol_); } function _changeConsortium(address newVal) internal { if (newVal == address(0)) { revert ZeroAddress(); } LBTCStorage storage $ = _getLBTCStorage(); emit ConsortiumChanged($.consortium, newVal); $.consortium = newVal; } function _validateAndMint( address recipient, uint256 amountToMint, uint256 depositAmount, bytes calldata payload, bytes calldata proof ) internal { LBTCStorage storage $ = _getLBTCStorage(); if (amountToMint > depositAmount) revert InvalidMintAmount(); /// make sure that hash of payload not used before /// need to check new sha256 hash and legacy keccak256 from payload without selector /// 2 checks made to prevent migration of contract state bytes32 payloadHash = sha256(payload); bytes32 legacyHash = keccak256(payload[4:]); if ($.usedPayloads[payloadHash] || $.legacyUsedPayloads[legacyHash]) { revert PayloadAlreadyUsed(); } Consortium($.consortium).checkProof(payloadHash, proof); $.usedPayloads[payloadHash] = true; // Confirm deposit against Bascule _confirmDeposit($, legacyHash, depositAmount); // Actually mint _mint(recipient, amountToMint); emit MintProofConsumed(recipient, payloadHash, payload); } function _changeBurnCommission(uint64 newValue) internal { LBTCStorage storage $ = _getLBTCStorage(); uint64 prevValue = $.burnCommission; $.burnCommission = newValue; emit BurnCommissionChanged(prevValue, newValue); } /** * @dev Checks that the deposit was validated by the Bascule drawbridge. * @param $ LBTC storage. * @param depositID The unique ID of the deposit. * @param amount The withdrawal amount. */ function _confirmDeposit( LBTCStorage storage $, bytes32 depositID, uint256 amount ) internal { IBascule bascule = $.bascule; if (address(bascule) != address(0)) { bascule.validateWithdrawal(depositID, amount); } } /** * Change the address of the Bascule drawbridge contract. * @param newVal The new address. * * Emits a {BasculeChanged} event. */ function _changeBascule(address newVal) internal { LBTCStorage storage $ = _getLBTCStorage(); emit BasculeChanged(address($.bascule), newVal); $.bascule = IBascule(newVal); } function _transferPauserRole(address newPauser) internal { LBTCStorage storage $ = _getLBTCStorage(); address oldPauser = $.pauser; $.pauser = newPauser; emit PauserRoleTransferred(oldPauser, newPauser); } function _transferOperatorRole(address newOperator) internal { LBTCStorage storage $ = _getLBTCStorage(); address oldOperator = $.operator; $.operator = newOperator; emit OperatorRoleTransferred(oldOperator, newOperator); } function _mintWithFee( bytes calldata mintPayload, bytes calldata proof, bytes calldata feePayload, bytes calldata userSignature ) internal nonReentrant { // mint payload validation if (bytes4(mintPayload) != Actions.DEPOSIT_BTC_ACTION_V0) { revert UnexpectedAction(bytes4(mintPayload)); } Actions.DepositBtcActionV0 memory mintAction = Actions.depositBtcV0( mintPayload[4:] ); // fee payload validation if (bytes4(feePayload) != Actions.FEE_APPROVAL_ACTION) { revert UnexpectedAction(bytes4(feePayload)); } Actions.FeeApprovalAction memory feeAction = Actions.feeApproval( feePayload[4:] ); LBTCStorage storage $ = _getLBTCStorage(); uint256 fee = $.maximumFee; if (fee > feeAction.fee) { fee = feeAction.fee; } if (fee >= mintAction.amount) { revert FeeGreaterThanAmount(); } { // Fee validation bytes32 digest = _hashTypedDataV4( keccak256( abi.encode( Actions.FEE_APPROVAL_EIP712_ACTION, block.chainid, feeAction.fee, feeAction.expiry ) ) ); if ( !EIP1271SignatureUtils.checkSignature( mintAction.recipient, digest, userSignature ) ) { revert InvalidUserSignature(); } } // modified payload to be signed _validateAndMint( mintAction.recipient, mintAction.amount - fee, mintAction.amount, mintPayload, proof ); // mint fee to treasury _mint($.treasury, fee); emit FeeCharged(fee, userSignature); } function _checkPauser() internal view { if (pauser() != _msgSender()) { revert UnauthorizedAccount(_msgSender()); } } function _updateMinter(address minter, bool _isMinter) internal { if (minter == address(0)) { revert ZeroAddress(); } _getLBTCStorage().minters[minter] = _isMinter; emit MinterUpdated(minter, _isMinter); } function _updateClaimer(address claimer, bool _isClaimer) internal { if (claimer == address(0)) { revert ZeroAddress(); } _getLBTCStorage().claimers[claimer] = _isClaimer; emit ClaimerUpdated(claimer, _isClaimer); } function _changeTreasuryAddress(address newValue) internal { if (newValue == address(0)) { revert ZeroAddress(); } LBTCStorage storage $ = _getLBTCStorage(); address prevValue = $.treasury; $.treasury = newValue; emit TreasuryAddressChanged(prevValue, newValue); } function _calcFeeAndDustLimit( bytes calldata scriptPubkey, uint256 amount, uint64 fee ) internal view returns (uint256, bool, uint256, bool) { OutputType outType = BitcoinUtils.getOutputType(scriptPubkey); if (outType == OutputType.UNSUPPORTED) { revert ScriptPubkeyUnsupported(); } if (amount <= fee) { return (0, false, 0, false); } LBTCStorage storage $ = _getLBTCStorage(); uint256 amountAfterFee = amount - fee; uint256 dustLimit = BitcoinUtils.getDustLimitForOutput( outType, scriptPubkey, $.dustFeeRate ); bool isAboveDust = amountAfterFee > dustLimit; return (amountAfterFee, true, dustLimit, isAboveDust); } function _getLBTCStorage() private pure returns (LBTCStorage storage $) { assembly { $.slot := LBTC_STORAGE_LOCATION } } /** * @dev Override of the _update function to satisfy both ERC20Upgradeable and ERC20PausableUpgradeable */ function _update( address from, address to, uint256 value ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._update(from, to, value); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {ERC20PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PausableUpgradeable.sol"; import {ERC20PermitUpgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20PermitUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {AccessControlDefaultAdminRulesUpgradeable} from "@openzeppelin/contracts-upgradeable/access/extensions/AccessControlDefaultAdminRulesUpgradeable.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {BitcoinUtils, OutputType} from "../libs/BitcoinUtils.sol"; import {IBascule} from "../bascule/interfaces/IBascule.sol"; import {INativeLBTC} from "./INativeLBTC.sol"; import {Consortium} from "../consortium/Consortium.sol"; import {Actions} from "../libs/Actions.sol"; import {EIP1271SignatureUtils} from "../libs/EIP1271SignatureUtils.sol"; /** * @title ERC20 representation of Liquid Bitcoin * @author Lombard.Finance * @notice This contract is part of the Lombard.Finance protocol */ contract NativeLBTC is INativeLBTC, ERC20PausableUpgradeable, ReentrancyGuardUpgradeable, ERC20PermitUpgradeable, AccessControlDefaultAdminRulesUpgradeable { /// @custom:storage-location erc7201:lombardfinance.storage.NativeLBTC struct NativeLBTCStorage { // slot: 20 + 8 + 1 | 29/32 address consortium; uint64 burnCommission; // absolute commission to charge on burn (unstake) bool isWithdrawalsEnabled; // slot: 20 | 20/32 address treasury; // slot: 20 | 20/32 IBascule bascule; // other slots by 32 string name; string symbol; uint256 dustFeeRate; uint256 maximumFee; mapping(bytes32 => bool) usedPayloads; // sha256(rawPayload) => used } // TODO: recalculate // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.NativeLBTC")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant NATIVE_LBTC_STORAGE_LOCATION = 0xb773c428c0cecc1b857b133b10e11481edd580cedc90e62754fff20b7c0d6000; bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); bytes32 public constant CLAIMER_ROLE = keccak256("CLAIMER_ROLE"); bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } /// INTIALIZERS /// function initialize( address consortium_, address treasury, string calldata _name, string calldata _symbol, address initialOwner ) external initializer { __AccessControlDefaultAdminRules_init(0, initialOwner); __ERC20_init("", ""); __ERC20Pausable_init(); __ReentrancyGuard_init(); __ERC20Permit_init(_name); __LBTC_init(_name, _symbol, consortium_, treasury); NativeLBTCStorage storage $ = _getNativeLBTCStorage(); $.dustFeeRate = BitcoinUtils.DEFAULT_DUST_FEE_RATE; emit DustFeeRateChanged(0, $.dustFeeRate); } /// ONLY OWNER FUNCTIONS /// function toggleWithdrawals() external onlyRole(DEFAULT_ADMIN_ROLE) { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); $.isWithdrawalsEnabled = !$.isWithdrawalsEnabled; emit WithdrawalsEnabled($.isWithdrawalsEnabled); } function changeNameAndSymbol( string calldata name_, string calldata symbol_ ) external onlyRole(DEFAULT_ADMIN_ROLE) { _changeNameAndSymbol(name_, symbol_); } function changeConsortium( address newVal ) external onlyRole(DEFAULT_ADMIN_ROLE) { _changeConsortium(newVal); } /** * @notice Set the contract current fee for mint * @param fee New fee value * @dev zero allowed to disable fee */ function setMintFee(uint256 fee) external onlyRole(OPERATOR_ROLE) { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); uint256 oldFee = $.maximumFee; $.maximumFee = fee; emit FeeChanged(oldFee, fee); } function changeTreasuryAddress( address newValue ) external onlyRole(DEFAULT_ADMIN_ROLE) { _changeTreasuryAddress(newValue); } function changeBurnCommission( uint64 newValue ) external onlyRole(DEFAULT_ADMIN_ROLE) { _changeBurnCommission(newValue); } function pause() external onlyRole(PAUSER_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /// @notice Change the dust fee rate used for dust limit calculations /// @dev Only the contract owner can call this function. The new rate must be positive. /// @param newRate The new dust fee rate (in satoshis per 1000 bytes) function changeDustFeeRate( uint256 newRate ) external onlyRole(DEFAULT_ADMIN_ROLE) { if (newRate == 0) revert InvalidDustFeeRate(); NativeLBTCStorage storage $ = _getNativeLBTCStorage(); uint256 oldRate = $.dustFeeRate; $.dustFeeRate = newRate; emit DustFeeRateChanged(oldRate, newRate); } /** * Change the address of the Bascule drawbridge contract. * Setting the address to 0 disables the Bascule check. * @param newVal The new address. * * Emits a {BasculeChanged} event. */ function changeBascule( address newVal ) external onlyRole(DEFAULT_ADMIN_ROLE) { _changeBascule(newVal); } /// GETTERS /// /** * @notice Returns the current maximum mint fee */ function getMintFee() external view returns (uint256) { return _getNativeLBTCStorage().maximumFee; } /// @notice Calculate the amount that will be unstaked and check if it's above the dust limit /// @dev This function can be used by front-ends to verify burn amounts before submitting a transaction /// @param scriptPubkey The Bitcoin script public key as a byte array /// @param amount The amount of NativeLBTC to be burned /// @return amountAfterFee The amount that will be unstaked (after deducting the burn commission) /// @return isAboveDust Whether the amountAfterFee is equal to or above the dust limit function calcUnstakeRequestAmount( bytes calldata scriptPubkey, uint256 amount ) external view returns (uint256 amountAfterFee, bool isAboveDust) { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); (amountAfterFee, , , isAboveDust) = _calcFeeAndDustLimit( scriptPubkey, amount, $.burnCommission ); return (amountAfterFee, isAboveDust); } function consortium() external view virtual returns (address) { return _getNativeLBTCStorage().consortium; } /** * @dev Returns the number of decimals used to get its user representation. * * Because NativeLBTC repsents BTC we use the same decimals. * */ function decimals() public view virtual override returns (uint8) { return 8; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _getNativeLBTCStorage().name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _getNativeLBTCStorage().symbol; } function getTreasury() public view override returns (address) { return _getNativeLBTCStorage().treasury; } function getBurnCommission() public view returns (uint64) { return _getNativeLBTCStorage().burnCommission; } /// @notice Get the current dust fee rate /// @return The current dust fee rate (in satoshis per 1000 bytes) function getDustFeeRate() public view returns (uint256) { return _getNativeLBTCStorage().dustFeeRate; } /** * Get Bascule contract. */ function Bascule() external view returns (IBascule) { return _getNativeLBTCStorage().bascule; } /// USER ACTIONS /// /** * @notice Mint NativeLBTC to the specified address * @param to The address to mint to * @param amount The amount of NativeLBTC to mint * @dev Only callable by whitelisted minters */ function mint( address to, uint256 amount ) external override onlyRole(MINTER_ROLE) { _mint(to, amount); } /** * @notice Mint NativeLBTC in batches * @param to The addresses to mint to * @param amount The amounts of NativeLBTC to mint * @dev Only callable by whitelisted minters */ function batchMint( address[] calldata to, uint256[] calldata amount ) external onlyRole(MINTER_ROLE) { if (to.length != amount.length) { revert InvalidInputLength(); } for (uint256 i; i < to.length; ++i) { _mint(to[i], amount[i]); } } /** * @notice Mint NativeLBTC by proving DepositV1 payload * @param payload The message with the stake data * @param proof Signature of the consortium approving the mint */ function mintV1( bytes calldata payload, bytes calldata proof ) public nonReentrant { // payload validation if (bytes4(payload) != Actions.DEPOSIT_BTC_ACTION_V1) { revert UnexpectedAction(bytes4(payload)); } Actions.DepositBtcActionV1 memory action = Actions.depositBtcV1( payload[4:] ); _assertToken(action.tokenAddress); _validateAndMint( action.recipient, action.amount, action.amount, payload, proof ); } /** * @notice Mint NativeLBTC in batches by DepositV1 payloads * @param payload The messages with the stake data * @param proof Signatures of the consortium approving the mints */ function batchMintV1( bytes[] calldata payload, bytes[] calldata proof ) external { if (payload.length != proof.length) { revert InvalidInputLength(); } for (uint256 i; i < payload.length; ++i) { // Pre-emptive check if payload was used. If so, we can skip the call. bytes32 payloadHash = sha256(payload[i]); if (isPayloadUsed(payloadHash)) { emit BatchMintSkipped(payloadHash, payload[i]); continue; } mintV1(payload[i], proof[i]); } } /** * @notice Mint NativeLBTC applying a commission to the amount * @dev Payload should be same as mint to avoid reusing them with and without fee * @param mintPayload DepositV1 payload * @param proof Signature of the consortium approving the mint * @param feePayload Contents of the fee approval signed by the user * @param userSignature Signature of the user to allow Fee */ function mintV1WithFee( bytes calldata mintPayload, bytes calldata proof, bytes calldata feePayload, bytes calldata userSignature ) external onlyRole(CLAIMER_ROLE) { _mintV1WithFee(mintPayload, proof, feePayload, userSignature); } /** * @notice Mint NativeLBTC in batches proving stake actions happened * @param mintPayload DepositV1 payloads * @param proof Signatures of the consortium approving the mints * @param feePayload Contents of the fee approvals signed by the user * @param userSignature Signatures of the user to allow Fees */ function batchMintV1WithFee( bytes[] calldata mintPayload, bytes[] calldata proof, bytes[] calldata feePayload, bytes[] calldata userSignature ) external onlyRole(CLAIMER_ROLE) { uint256 length = mintPayload.length; if ( length != proof.length || length != feePayload.length || length != userSignature.length ) { revert InvalidInputLength(); } for (uint256 i; i < mintPayload.length; ++i) { // Pre-emptive check if payload was used. If so, we can skip the call. bytes32 payloadHash = sha256(mintPayload[i]); if (isPayloadUsed(payloadHash)) { emit BatchMintSkipped(payloadHash, mintPayload[i]); continue; } _mintV1WithFee( mintPayload[i], proof[i], feePayload[i], userSignature[i] ); } } /** * @dev Burns NativeLBTC to initiate withdrawal of BTC to provided `scriptPubkey` with `amount` * * @param scriptPubkey scriptPubkey for output * @param amount Amount of NativeLBTC to burn */ function redeem(bytes calldata scriptPubkey, uint256 amount) external { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); if (!$.isWithdrawalsEnabled) { revert WithdrawalsDisabled(); } uint64 fee = $.burnCommission; ( uint256 amountAfterFee, bool isAboveFee, uint256 dustLimit, bool isAboveDust ) = _calcFeeAndDustLimit(scriptPubkey, amount, fee); if (!isAboveFee) { revert AmountLessThanCommission(fee); } if (!isAboveDust) { revert AmountBelowDustLimit(dustLimit); } address fromAddress = address(_msgSender()); _transfer(fromAddress, getTreasury(), fee); _burn(fromAddress, amountAfterFee); emit UnstakeRequest(fromAddress, scriptPubkey, amountAfterFee); } /** * @dev Burns NativeLBTC * * @param amount Amount of NativeLBTC to burn */ function burn(uint256 amount) external { _burn(_msgSender(), amount); } /** * @dev Allows minters to burn NativeLBTC * * @param amount Amount of NativeLBTC to burn */ function burn( address from, uint256 amount ) external override onlyRole(MINTER_ROLE) { _burn(from, amount); } /** * @dev Returns whether a minting payload has been used already * * @param payloadHash The minting payload hash */ function isPayloadUsed(bytes32 payloadHash) public view returns (bool) { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); return $.usedPayloads[payloadHash]; } /// PRIVATE FUNCTIONS /// function __LBTC_init( string memory name_, string memory symbol_, address consortium_, address treasury ) internal onlyInitializing { _changeNameAndSymbol(name_, symbol_); _changeConsortium(consortium_); _changeTreasuryAddress(treasury); } function _changeNameAndSymbol( string memory name_, string memory symbol_ ) internal { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); $.name = name_; $.symbol = symbol_; emit NameAndSymbolChanged(name_, symbol_); } function _changeConsortium(address newVal) internal { if (newVal == address(0)) { revert ZeroAddress(); } NativeLBTCStorage storage $ = _getNativeLBTCStorage(); emit ConsortiumChanged($.consortium, newVal); $.consortium = newVal; } function _assertToken(address token) internal view { if (token != address(this)) { revert InvalidDestinationToken(address(this), token); } } function _validateAndMint( address recipient, uint256 amountToMint, uint256 depositAmount, bytes calldata payload, bytes calldata proof ) internal { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); if (amountToMint > depositAmount) revert InvalidMintAmount(); /// make sure that hash of payload not used before /// need to check sha256 hash from payload without selector bytes32 payloadHash = sha256(payload); bytes32 legacyHash = keccak256(payload[4:]); // TODO: remove when bascule support sha256 if ($.usedPayloads[payloadHash]) { revert PayloadAlreadyUsed(); } Consortium($.consortium).checkProof(payloadHash, proof); $.usedPayloads[payloadHash] = true; // Confirm deposit against Bascule _confirmDeposit($, legacyHash, depositAmount); // Actually mint _mint(recipient, amountToMint); emit MintProofConsumed(recipient, payloadHash, payload); } function _changeBurnCommission(uint64 newValue) internal { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); uint64 prevValue = $.burnCommission; $.burnCommission = newValue; emit BurnCommissionChanged(prevValue, newValue); } /** * @dev Checks that the deposit was validated by the Bascule drawbridge. * @param $ NativeLBTC storage. * @param depositID The unique ID of the deposit. * @param amount The withdrawal amount. */ function _confirmDeposit( NativeLBTCStorage storage $, bytes32 depositID, uint256 amount ) internal { IBascule bascule = $.bascule; if (address(bascule) != address(0)) { bascule.validateWithdrawal(depositID, amount); } } /** * Change the address of the Bascule drawbridge contract. * @param newVal The new address. * * Emits a {BasculeChanged} event. */ function _changeBascule(address newVal) internal { NativeLBTCStorage storage $ = _getNativeLBTCStorage(); emit BasculeChanged(address($.bascule), newVal); $.bascule = IBascule(newVal); } function _mintV1WithFee( bytes calldata mintPayload, bytes calldata proof, bytes calldata feePayload, bytes calldata userSignature ) internal nonReentrant { // mint payload validation if (bytes4(mintPayload) != Actions.DEPOSIT_BTC_ACTION_V1) { revert UnexpectedAction(bytes4(mintPayload)); } Actions.DepositBtcActionV1 memory mintAction = Actions.depositBtcV1( mintPayload[4:] ); _assertToken(mintAction.tokenAddress); // fee payload validation if (bytes4(feePayload) != Actions.FEE_APPROVAL_ACTION) { revert UnexpectedAction(bytes4(feePayload)); } Actions.FeeApprovalAction memory feeAction = Actions.feeApproval( feePayload[4:] ); NativeLBTCStorage storage $ = _getNativeLBTCStorage(); uint256 fee = $.maximumFee; if (fee > feeAction.fee) { fee = feeAction.fee; } if (fee >= mintAction.amount) { revert FeeGreaterThanAmount(); } { // Fee validation bytes32 digest = _hashTypedDataV4( keccak256( abi.encode( Actions.FEE_APPROVAL_EIP712_ACTION, block.chainid, feeAction.fee, feeAction.expiry ) ) ); if ( !EIP1271SignatureUtils.checkSignature( mintAction.recipient, digest, userSignature ) ) { revert InvalidUserSignature(); } } // modified payload to be signed _validateAndMint( mintAction.recipient, mintAction.amount - fee, mintAction.amount, mintPayload, proof ); // mint fee to treasury _mint($.treasury, fee); emit FeeCharged(fee, userSignature); } function _changeTreasuryAddress(address newValue) internal { if (newValue == address(0)) { revert ZeroAddress(); } NativeLBTCStorage storage $ = _getNativeLBTCStorage(); address prevValue = $.treasury; $.treasury = newValue; emit TreasuryAddressChanged(prevValue, newValue); } function _calcFeeAndDustLimit( bytes calldata scriptPubkey, uint256 amount, uint64 fee ) internal view returns (uint256, bool, uint256, bool) { OutputType outType = BitcoinUtils.getOutputType(scriptPubkey); if (outType == OutputType.UNSUPPORTED) { revert ScriptPubkeyUnsupported(); } if (amount <= fee) { return (0, false, 0, false); } NativeLBTCStorage storage $ = _getNativeLBTCStorage(); uint256 amountAfterFee = amount - fee; uint256 dustLimit = BitcoinUtils.getDustLimitForOutput( outType, scriptPubkey, $.dustFeeRate ); bool isAboveDust = amountAfterFee > dustLimit; return (amountAfterFee, true, dustLimit, isAboveDust); } function _getNativeLBTCStorage() private pure returns (NativeLBTCStorage storage $) { assembly { $.slot := NATIVE_LBTC_STORAGE_LOCATION } } /** * @dev Override of the _update function to satisfy both ERC20Upgradeable and ERC20PausableUpgradeable */ function _update( address from, address to, uint256 value ) internal virtual override(ERC20Upgradeable, ERC20PausableUpgradeable) { super._update(from, to, value); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; library Actions { struct DepositBtcActionV0 { uint256 toChain; address recipient; uint256 amount; bytes32 txid; uint32 vout; } struct DepositBtcActionV1 { uint256 toChain; address recipient; uint256 amount; bytes32 txid; uint32 vout; address tokenAddress; } struct DepositBridgeAction { uint256 fromChain; bytes32 fromContract; uint256 toChain; address toContract; address recipient; uint64 amount; uint256 nonce; } struct ValSetAction { uint256 epoch; address[] validators; uint256[] weights; uint256 weightThreshold; uint256 height; } struct FeeApprovalAction { uint256 fee; uint256 expiry; } /// @dev Error thrown when invalid public key is provided error InvalidPublicKey(bytes pubKey); /// @dev Error thrown when signatures length is not equal to signers length error Actions_LengthMismatch(); /// @dev Error thrown when threshold is invalid error InvalidThreshold(); /// @dev Error thrown when validator set size is invalid error InvalidValidatorSetSize(); /// @dev Error thrown when zero validator is provided error ZeroValidator(); /// @dev Error thrown when wrong chain id is provided error WrongChainId(); /// @dev Error thrown when wrong contract is provided error WrongContract(); /// @dev Error thrown when zero address is provided error Actions_ZeroAddress(); /// @dev Error thrown when zero amount is provided error ZeroAmount(); /// @dev Error thrown when zero weight is provided error ZeroWeight(); /// @dev Error thrown when fee approval is expired error UserSignatureExpired(uint256 expiry); /// @dev Error thrown when amount is below fee error NotEnoughAmountToUseApproval(); /// @dev Error thrown when zero fee is used error ZeroFee(); /// @dev Error thrown when payload length is too big error InvalidPayloadSize(uint256 expected, uint256 actual); // bytes4(keccak256("feeApproval(uint256,uint256)")) bytes4 internal constant FEE_APPROVAL_ACTION = 0x8175ca94; // keccak256("feeApproval(uint256 chainId,uint256 fee,uint256 expiry)") bytes32 internal constant FEE_APPROVAL_EIP712_ACTION = 0x40ac9f6aa27075e64c1ed1ea2e831b20b8c25efdeb6b79fd0cf683c9a9c50725; // bytes4(keccak256("payload(bytes32,bytes32,uint64,bytes32,uint32)")) bytes4 internal constant DEPOSIT_BTC_ACTION_V0 = 0xf2e73f7c; // bytes4(keccak256("payload(bytes32,bytes32,uint64,bytes32,uint32,bytes32)")) bytes4 internal constant DEPOSIT_BTC_ACTION_V1 = 0xce25e7c2; // bytes4(keccak256("payload(bytes32,bytes32,bytes32,bytes32,bytes32,uint64,uint256)")) bytes4 internal constant DEPOSIT_BRIDGE_ACTION = 0x5c70a505; // bytes4(keccak256("payload(uint256,bytes[],uint256[],uint256,uint256)")) bytes4 internal constant NEW_VALSET = 0x4aab1d6f; /// @dev Maximum number of validators allowed in the consortium. /// @notice This value is determined by the minimum of CometBFT consensus limitations and gas considerations: /// - CometBFT has a hard limit of 10,000 validators (https://docs.cometbft.com/v0.38/spec/core/state) /// - Gas-based calculation: /// - Assumes 4281 gas per ECDSA signature verification /// - Uses a conservative 30 million gas block limit /// - Maximum possible signatures: 30,000,000 / 4,281 ≈ 7007 /// - Reverse calculated for BFT consensus (2/3 + 1): /// 7,007 = (10,509 * 2/3 + 1) rounded down /// - The lower value of 10,000 (CometBFT limit) and 10,509 (gas calculation) is chosen /// @dev This limit ensures compatibility with CometBFT while also considering gas limitations /// for signature verification within a single block. uint256 private constant MAX_VALIDATOR_SET_SIZE = 102; /// @dev Minimum number of validators allowed in the system. /// @notice While set to 1 to allow for non-distributed scenarios, this configuration /// does not provide Byzantine fault tolerance. For a truly distributed and /// fault-tolerant system, a minimum of 4 validators would be recommended to tolerate /// at least one Byzantine fault. uint256 private constant MIN_VALIDATOR_SET_SIZE = 1; /// @dev A constant representing the number of bytes for a slot of information in a payload. uint256 internal constant ABI_SLOT_SIZE = 32; /** * @notice Returns decoded deposit btc msg v0 * @dev Message should not contain the selector * @param payload Body of the mint payload */ function depositBtcV0( bytes memory payload ) internal view returns (DepositBtcActionV0 memory) { if (payload.length != ABI_SLOT_SIZE * 5) revert InvalidPayloadSize(ABI_SLOT_SIZE * 5, payload.length); ( uint256 toChain, address recipient, uint256 amount, bytes32 txid, uint32 vout ) = abi.decode(payload, (uint256, address, uint256, bytes32, uint32)); if (toChain != block.chainid) { revert WrongChainId(); } if (recipient == address(0)) { revert Actions_ZeroAddress(); } if (amount == 0) { revert ZeroAmount(); } return DepositBtcActionV0(toChain, recipient, amount, txid, vout); } /** * @notice Returns decoded deposit btc msg v1 * @dev Message should not contain the selector * @param payload Body of the mint payload */ function depositBtcV1( bytes memory payload ) internal view returns (DepositBtcActionV1 memory) { if (payload.length != ABI_SLOT_SIZE * 6) revert InvalidPayloadSize(ABI_SLOT_SIZE * 6, payload.length); ( uint256 toChain, address recipient, uint256 amount, bytes32 txid, uint32 vout, address tokenAddress ) = abi.decode( payload, (uint256, address, uint256, bytes32, uint32, address) ); if (toChain != block.chainid) { revert WrongChainId(); } if (recipient == address(0)) { revert Actions_ZeroAddress(); } if (amount == 0) { revert ZeroAmount(); } return DepositBtcActionV1( toChain, recipient, amount, txid, vout, tokenAddress ); } /** * @notice Returns decoded bridge payload * @dev Payload should not contain the selector * @param payload Body of the burn payload */ function depositBridge( bytes memory payload ) internal view returns (DepositBridgeAction memory) { if (payload.length != ABI_SLOT_SIZE * 7) revert InvalidPayloadSize(ABI_SLOT_SIZE * 7, payload.length); ( uint256 fromChain, bytes32 fromContract, uint256 toChain, address toContract, address recipient, uint64 amount, uint256 nonce ) = abi.decode( payload, (uint256, bytes32, uint256, address, address, uint64, uint256) ); if (toChain != block.chainid) { revert WrongChainId(); } if (recipient == address(0)) { revert Actions_ZeroAddress(); } if (amount == 0) { revert ZeroAmount(); } return DepositBridgeAction( fromChain, fromContract, toChain, toContract, recipient, amount, nonce ); } /** * @notice Returns decoded validator set * @dev Payload should not contain the selector * @param payload Body of the set validators set payload */ function validateValSet( bytes memory payload ) internal pure returns (ValSetAction memory) { ( uint256 epoch, bytes[] memory pubKeys, uint256[] memory weights, uint256 weightThreshold, uint256 height ) = abi.decode( payload, (uint256, bytes[], uint256[], uint256, uint256) ); // Since dynamic arrays can variably insert more slots of data for things such as data length, // offset etc., we will just encode the received variables again and check for a length match. bytes memory reEncodedPayload = abi.encode( epoch, pubKeys, weights, weightThreshold, height ); if (reEncodedPayload.length != payload.length) revert InvalidPayloadSize(payload.length, reEncodedPayload.length); if ( pubKeys.length < MIN_VALIDATOR_SET_SIZE || pubKeys.length > MAX_VALIDATOR_SET_SIZE ) revert InvalidValidatorSetSize(); if (pubKeys.length != weights.length) revert Actions_LengthMismatch(); if (weightThreshold == 0) revert InvalidThreshold(); uint256 sum = 0; for (uint256 i; i < weights.length; ) { if (weights[i] == 0) { revert ZeroWeight(); } sum += weights[i]; unchecked { ++i; } } if (sum < weightThreshold) revert InvalidThreshold(); address[] memory validators = pubKeysToAddress(pubKeys); return ValSetAction(epoch, validators, weights, weightThreshold, height); } function pubKeysToAddress( bytes[] memory _pubKeys ) internal pure returns (address[] memory) { address[] memory addresses = new address[](_pubKeys.length); for (uint256 i; i < _pubKeys.length; ) { // each pubkey represented as uncompressed if (_pubKeys[i].length == 65) { bytes memory data = _pubKeys[i]; // Ensure that first byte of pubkey is 0x04 if (_pubKeys[i][0] != 0x04) revert InvalidPublicKey(_pubKeys[i]); // create a new array with length - 1 (excluding the first 0x04 byte) bytes memory result = new bytes(data.length - 1); // use inline assembly for memory manipulation assembly { // calculate the start of the `result` and `data` in memory let resultData := add(result, 0x20) // points to the first byte of the result let dataStart := add(data, 0x21) // points to the second byte of data (skip 0x04) // copy 64 bytes from input (excluding the first byte) to result mstore(resultData, mload(dataStart)) // copy the first 32 bytes mstore(add(resultData, 0x20), mload(add(dataStart, 0x20))) // copy the next 32 bytes } addresses[i] = address(uint160(uint256(keccak256(result)))); } else { revert InvalidPublicKey(_pubKeys[i]); } unchecked { ++i; } } return addresses; } /** * @notice Returns decoded fee approval * @dev Payload should not contain the selector * @param payload Body of the fee approval payload */ function feeApproval( bytes memory payload ) internal view returns (FeeApprovalAction memory) { if (payload.length != ABI_SLOT_SIZE * 2) revert InvalidPayloadSize(ABI_SLOT_SIZE * 2, payload.length); (uint256 fee, uint256 expiry) = abi.decode(payload, (uint256, uint256)); if (block.timestamp > expiry) { revert UserSignatureExpired(expiry); } if (fee == 0) { revert ZeroFee(); } return FeeApprovalAction(fee, expiry); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; enum OutputType { UNSUPPORTED, P2TR, P2WPKH, P2WSH } bytes1 constant OP_0 = 0x00; bytes1 constant OP_1 = 0x51; bytes1 constant OP_DATA_32 = 0x20; bytes1 constant OP_DATA_20 = 0x14; uint256 constant BASE_SPEND_COST = 49; // 32 (txid) + 4 (vout) + 1 (scriptSig size) + 4 (nSequence) + 8 (amount) // Size of inputs spending different output types uint256 constant NON_WITNESS_INPUT_SIZE = 107; // Used for non-witness outputs (P2PKH, P2SH) uint256 constant WITNESS_INPUT_SIZE = 26; // floor(107 / 4), used for witness outputs (P2WPKH, P2WSH, P2TR) library BitcoinUtils { uint256 public constant DEFAULT_DUST_FEE_RATE = 3000; // Default value - 3 satoshis per byte function getOutputType( bytes calldata scriptPubkey ) internal pure returns (OutputType) { if ( scriptPubkey.length == 22 && scriptPubkey[0] == OP_0 && scriptPubkey[1] == OP_DATA_20 ) { return OutputType.P2WPKH; } if ( scriptPubkey.length == 34 && scriptPubkey[0] == OP_1 && scriptPubkey[1] == OP_DATA_32 ) { return OutputType.P2TR; } if ( scriptPubkey.length == 34 && scriptPubkey[0] == OP_0 && scriptPubkey[1] == OP_DATA_32 ) { return OutputType.P2WSH; } return OutputType.UNSUPPORTED; } /// @notice Compute the dust limit for a given Bitcoin script public key /// @dev The dust limit is the minimum payment to an address that is considered /// spendable under consensus rules. This function is based on Bitcoin Core's /// implementation. /// @param scriptPubkey The Bitcoin script public key as a byte array /// @param dustFeeRate The current dust fee rate (in satoshis per 1000 bytes) /// @return dustLimit The calculated dust limit in satoshis /// @custom:reference https://github.com/bitcoin/bitcoin/blob/43740f4971f45cd5499470b6a085b3ecd8b96d28/src/policy/policy.cpp#L54 function getDustLimitForOutput( OutputType outType, bytes calldata scriptPubkey, uint256 dustFeeRate ) internal pure returns (uint256 dustLimit) { uint256 spendCost = BASE_SPEND_COST; if ( outType == OutputType.P2TR || outType == OutputType.P2WPKH || outType == OutputType.P2WSH ) { // witness v0 and v1 has a cheaper payment formula spendCost += WITNESS_INPUT_SIZE; // The current addition creates a discrepancy of 1, and our final value should be 98 bytes. // Thus, we add 1 here. spendCost += 1; } else { spendCost += NON_WITNESS_INPUT_SIZE; } spendCost += scriptPubkey.length; // Calculate dust limit dustLimit = Math.ceilDiv(spendCost * dustFeeRate, 1000); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC1271} from "@openzeppelin/contracts/interfaces/IERC1271.sol"; import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol"; /** * @title Library of utilities for making EIP1271-compliant signature checks. * @author Lombard.Finance * @notice The contracts is a part of Lombard.Finace protocol */ library EIP1271SignatureUtils { // bytes4(keccak256("isValidSignature(bytes32,bytes)") bytes4 internal constant EIP1271_MAGICVALUE = 0x1626ba7e; bytes4 internal constant EIP1271_WRONGVALUE = 0xffffffff; /** * @notice Checks @param signature is a valid signature of @param digest from @param signer. * If the `signer` contains no code -- i.e. it is not (yet, at least) a contract address, then checks using standard ECDSA logic * Otherwise, passes on the signature to the signer to verify the signature and checks that it returns the `EIP1271_MAGICVALUE`. */ function checkSignature( address signer, bytes32 digest, bytes memory signature ) internal view returns (bool) { if (signer.code.length != 0) { if ( IERC1271(signer).isValidSignature(digest, signature) != EIP1271_MAGICVALUE ) { return false; } } else { if (ECDSA.recover(digest, signature) != signer) { return false; } } return true; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; library FeeUtils { uint256 constant MAX_COMMISSION = 10000; // 100% error AmountTooSmallToPayRelativeFee(); error BadCommission(); function calcRelativeFee( uint256 amount, uint16 relativeComs ) internal pure returns (uint256) { return Math.mulDiv( amount, relativeComs, MAX_COMMISSION, Math.Rounding.Ceil ); } function getRelativeFee( uint256 amount, uint16 relativeComs ) internal pure returns (uint256) { if (amount < relativeComs) revert AmountTooSmallToPayRelativeFee(); return calcRelativeFee(amount, relativeComs); } function validateCommission(uint16 commission) internal pure { if (commission >= MAX_COMMISSION) revert BadCommission(); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; library RateLimits { /** * @notice Rate Limit struct. * @param amountInFlight The amount in the current window. * @param lastUpdated Timestamp representing the last time the rate limit was checked or updated. * @param limit This represents the maximum allowed amount within a given window. * @param window Defines the duration of the rate limiting window. */ struct Data { uint256 amountInFlight; uint256 lastUpdated; uint256 limit; uint256 window; } /** * @notice Rate Limit Configuration struct. * @param chainId The destination endpoint id. * @param limit This represents the maximum allowed amount within a given window. * @param window Defines the duration of the rate limiting window. */ struct Config { bytes32 chainId; uint256 limit; uint256 window; } /// @notice Error that is thrown when an amount exceeds the rate_limit. error RateLimitExceeded(); /// @notice Error that is thrown when a rate limit seems to be malformed. error MalformedRateLimit(); function setRateLimit(Data storage rl, Config memory config) internal { // @dev Ensure we checkpoint the existing rate limit as to not retroactively apply the new decay rate. updateLimit(rl, 0); // @dev Does NOT reset the amountInFlight/lastUpdated of an existing rate limit. rl.limit = config.limit; rl.window = config.window; } function availableAmountToSend( Data memory rl ) internal view returns (uint256 currentAmountInFlight, uint256 amountCanBeSent) { return availableAmountToSend( rl.amountInFlight, rl.lastUpdated, rl.limit, rl.window ); } /** * @notice Checks current amount in flight and amount that can be sent for a given rate limit window. * @param _amountInFlight The total amount that was in flight at the last update. * @param _lastUpdated Timestamp representing the last time the rate limit was checked or updated. * @param _limit The maximum allowable amount within the specified window * @param _window Defines the duration of the rate limiting window. * @return currentAmountInFlight The amount in the current window. * @return amountCanBeSent The amount that can be sent. */ function availableAmountToSend( uint256 _amountInFlight, uint256 _lastUpdated, uint256 _limit, uint256 _window ) internal view returns (uint256 currentAmountInFlight, uint256 amountCanBeSent) { uint256 timeSinceLastDeposit = block.timestamp - _lastUpdated; if (timeSinceLastDeposit >= _window) { currentAmountInFlight = 0; amountCanBeSent = _limit; } else { uint256 decay = (_limit * timeSinceLastDeposit) / _window; currentAmountInFlight = _amountInFlight <= decay ? 0 : _amountInFlight - decay; amountCanBeSent = _limit <= currentAmountInFlight ? 0 : _limit - currentAmountInFlight; } } /** * @notice Verifies whether the specified amount falls within the rate limit constraints. * On successful verification, it updates amountInFlight and lastUpdated. If the amount exceeds * the rate limit, the operation reverts. * @param rl The rate limits to update. * @param _amount The amount to check and apply for rate limit constraints. */ function updateLimit(Data storage rl, uint256 _amount) internal { ( uint256 currentAmountInFlight, uint256 amountCanBeSent ) = availableAmountToSend(rl); if (_amount > amountCanBeSent) revert RateLimitExceeded(); rl.amountInFlight = currentAmountInFlight + _amount; rl.lastUpdated = block.timestamp; } function checkRateLimitSanity(uint256 limit) internal pure { if (limit == 0) revert RateLimits.MalformedRateLimit(); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {BARD} from "../BARD/BARD.sol"; /** * @title Mock implementation of LBTC token * @author Lombard.Finance * @notice Use only for testing */ contract BARDMock is BARD { constructor() BARD(address(1), address(2)) {} }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Context} from "@openzeppelin/contracts/utils/Context.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8); /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the token name. */ function name() external view returns (string memory); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer( address recipient, uint256 amount ) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance( address _owner, address spender ) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval( address indexed owner, address indexed spender, uint256 value ); } contract BTCBMock is IBEP20, Context { using Math for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; uint8 public _decimals; string public _symbol; string public _name; constructor() { _name = "BTCB Token"; _symbol = "BTCB"; _decimals = 18; } /** * @dev Returns the token decimals. */ function decimals() external view returns (uint8) { return _decimals; } /** * @dev Returns the token symbol. */ function symbol() external view returns (string memory) { return _symbol; } /** * @dev Returns the token name. */ function name() external view returns (string memory) { return _name; } /** * @dev See {BEP20-totalSupply}. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * @dev See {BEP20-balanceOf}. */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @dev See {BEP20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer( address recipient, uint256 amount ) external returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {BEP20-allowance}. */ function allowance( address owner, address spender ) external view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {BEP20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) external returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {BEP20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {BEP20}; * * Requirements: * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for `sender`'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool) { _transfer(sender, recipient, amount); (bool success, uint256 newAllowance) = Math.trySub( _allowances[sender][_msgSender()], amount ); require(success, "BEP20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), newAllowance); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance( address spender, uint256 addedValue ) public returns (bool) { _approve( _msgSender(), spender, _allowances[_msgSender()][spender] + addedValue ); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {BEP20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance( address spender, uint256 subtractedValue ) public returns (bool) { (bool success, uint256 newAllowance) = Math.trySub( _allowances[_msgSender()][spender], subtractedValue ); require(success, "BEP20: decreased allowance below zero"); _approve(_msgSender(), spender, newAllowance); return true; } /** * @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing * the total supply. * */ function mint(uint256 amount) public returns (bool) { _mint(_msgSender(), amount); return true; } /** * @dev Burn `amount` tokens and decreasing the total supply. */ function burn(uint256 amount) public returns (bool) { _burn(_msgSender(), amount); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); (bool success, uint256 newBalance) = Math.trySub( _balances[sender], amount ); require(success, "BEP20: transfer amount exceeds balance"); _balances[sender] = newBalance; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "BEP20: mint to the zero address"); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal { require(account != address(0), "BEP20: burn from the zero address"); (bool success, uint256 newBalance) = Math.trySub( _balances[account], amount ); require(success, "BEP20: burn amount exceeds balance"); _balances[account] = newBalance; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); (bool success, uint256 newAllowance) = Math.trySub( _allowances[account][_msgSender()], amount ); require(success, "BEP20: burn amount exceeds allowance"); _approve(account, _msgSender(), newAllowance); } /// @notice Mint tokens /// @param to The address to mint to /// @param amount The amount to mint /// @dev This function is used for testing purposes function mint(address to, uint256 amount) public { _mint(to, amount); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; // import artifacts to project import {MockRMN} from "@chainlink/contracts-ccip/src/v0.8/ccip/test/mocks/MockRMN.sol"; import {IAny2EVMMessageReceiver} from "@chainlink/contracts-ccip/src/v0.8/ccip/interfaces/IAny2EVMMessageReceiver.sol"; import {IRouter} from "@chainlink/contracts-ccip/src/v0.8/ccip/interfaces/IRouter.sol"; import {IRouterClient} from "@chainlink/contracts-ccip/src/v0.8/ccip/interfaces/IRouterClient.sol"; import {CallWithExactGas} from "@chainlink/contracts-ccip/src/v0.8/shared/call/CallWithExactGas.sol"; import {Client} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Client.sol"; import {Internal} from "@chainlink/contracts-ccip/src/v0.8/ccip/libraries/Internal.sol"; import {IERC20} from "@chainlink/contracts-ccip/src/v0.8/vendor/openzeppelin-solidity/v4.8.3/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@chainlink/contracts-ccip/src/v0.8/vendor/openzeppelin-solidity/v4.8.3/contracts/token/ERC20/utils/SafeERC20.sol"; import {ERC165Checker} from "@chainlink/contracts-ccip/src/v0.8/vendor/openzeppelin-solidity/v5.0.2/contracts/utils/introspection/ERC165Checker.sol"; contract MockCCIPRouter is IRouter, IRouterClient { using SafeERC20 for IERC20; using ERC165Checker for address; error InvalidAddress(bytes encodedAddress); error InvalidExtraArgsTag(); error ReceiverError(bytes err); event MessageExecuted( bytes32 messageId, uint64 sourceChainSelector, address offRamp, bytes32 calldataHash ); event MsgExecuted(bool success, bytes retData, uint256 gasUsed); uint16 public constant GAS_FOR_CALL_EXACT_CHECK = 5_000; uint32 public constant DEFAULT_GAS_LIMIT = 200_000; uint256 internal s_mockFeeTokenAmount; //use setFee() to change to non-zero to test fees function routeMessage( Client.Any2EVMMessage calldata message, uint16 gasForCallExactCheck, uint256 gasLimit, address receiver ) external returns (bool success, bytes memory retData, uint256 gasUsed) { return _routeMessage(message, gasForCallExactCheck, gasLimit, receiver); } function _routeMessage( Client.Any2EVMMessage memory message, uint16 gasForCallExactCheck, uint256 gasLimit, address receiver ) internal returns (bool success, bytes memory retData, uint256 gasUsed) { // There are three cases in which we skip calling the receiver: // 1. If the message data is empty AND the gas limit is 0. // This indicates a message that only transfers tokens. It is valid to only send tokens to a contract // that supports the IAny2EVMMessageReceiver interface, but without this first check we would call the // receiver without any gas, which would revert the transaction. // 2. If the receiver is not a contract. // 3. If the receiver is a contract but it does not support the IAny2EVMMessageReceiver interface. // // The ordering of these checks is important, as the first check is the cheapest to execute. if ( (message.data.length == 0 && gasLimit == 0) || receiver.code.length == 0 || !receiver.supportsInterface( type(IAny2EVMMessageReceiver).interfaceId ) ) { return (true, "", 0); } bytes memory data = abi.encodeWithSelector( IAny2EVMMessageReceiver.ccipReceive.selector, message ); (success, retData, gasUsed) = CallWithExactGas ._callWithExactGasSafeReturnData( data, receiver, gasLimit, gasForCallExactCheck, Internal.MAX_RET_BYTES ); // Event to assist testing, does not exist on real deployments emit MsgExecuted(success, retData, gasUsed); // Real router event emit MessageExecuted( message.messageId, message.sourceChainSelector, msg.sender, keccak256(data) ); return (success, retData, gasUsed); } /// @notice Sends the tx locally to the receiver instead of on the destination chain. /// @dev Ignores destinationChainSelector /// @dev Returns a mock message ID, which is not calculated from the message contents in the /// same way as the real message ID. function ccipSend( uint64 destinationChainSelector, Client.EVM2AnyMessage calldata message ) external payable returns (bytes32) { if (message.receiver.length != 32) revert InvalidAddress(message.receiver); uint256 decodedReceiver = abi.decode(message.receiver, (uint256)); // We want to disallow sending to address(0) and to precompiles, which exist on address(1) through address(9). if (decodedReceiver > type(uint160).max || decodedReceiver < 10) revert InvalidAddress(message.receiver); uint256 feeTokenAmount = getFee(destinationChainSelector, message); if (message.feeToken == address(0)) { if (msg.value < feeTokenAmount) revert InsufficientFeeTokenAmount(); } else { if (msg.value > 0) revert InvalidMsgValue(); IERC20(message.feeToken).safeTransferFrom( msg.sender, address(this), feeTokenAmount ); } address receiver = address(uint160(decodedReceiver)); uint256 gasLimit = _fromBytes(message.extraArgs).gasLimit; bytes32 mockMsgId = keccak256(abi.encode(message)); Client.Any2EVMMessage memory executableMsg = Client.Any2EVMMessage({ messageId: mockMsgId, sourceChainSelector: 16015286601757825753, // Sepolia sender: abi.encode(msg.sender), data: message.data, destTokenAmounts: message.tokenAmounts }); for (uint256 i = 0; i < message.tokenAmounts.length; ++i) { IERC20(message.tokenAmounts[i].token).safeTransferFrom( msg.sender, receiver, message.tokenAmounts[i].amount ); } (bool success, bytes memory retData, ) = _routeMessage( executableMsg, GAS_FOR_CALL_EXACT_CHECK, gasLimit, receiver ); if (!success) revert ReceiverError(retData); return mockMsgId; } function _fromBytes( bytes calldata extraArgs ) internal pure returns (Client.EVMExtraArgsV2 memory) { if (extraArgs.length == 0) { return Client.EVMExtraArgsV2({ gasLimit: DEFAULT_GAS_LIMIT, allowOutOfOrderExecution: true }); } if (bytes4(extraArgs) != Client.EVM_EXTRA_ARGS_V2_TAG) revert InvalidExtraArgsTag(); return abi.decode(extraArgs[4:], (Client.EVMExtraArgsV2)); } /// @notice Always returns true to make sure this check can be performed on any chain. function isChainSupported(uint64) external pure returns (bool supported) { return true; } /// @notice Returns an empty array. function getSupportedTokens( uint64 ) external pure returns (address[] memory tokens) { return new address[](0); } /// @notice Returns 0 as the fee is not supported in this mock contract. function getFee( uint64, Client.EVM2AnyMessage memory ) public view returns (uint256) { return s_mockFeeTokenAmount; } /// @notice Sets the fees returned by getFee but is only checked when using native fee tokens function setFee(uint256 feeAmount) external { s_mockFeeTokenAmount = feeAmount; } /// @notice Always returns address(1234567890) function getOnRamp( uint64 /* destChainSelector */ ) external pure returns (address onRampAddress) { return address(1234567890); } /// @notice Always returns true function isOffRamp( uint64, /* sourceChainSelector */ address /* offRamp */ ) external pure returns (bool) { return true; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Consortium} from "../consortium/Consortium.sol"; contract ConsortiumMock is Consortium { /// @dev override proof check to allow any proof function _checkProof( bytes32 _payloadHash, bytes calldata _proof ) internal view override {} }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract ERC4626Mock is ERC4626 { constructor(IERC20 asset_) ERC4626(asset_) ERC20("Kiln LBTC", "kLBTC") {} }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; import {FBTCPartnerVault} from "../fbtc/PartnerVault.sol"; /** * @title Mock implementation of LockedFBTC contract * @author Lombard.Finance * @notice Use only for testing */ contract LockedFBTCMock { IERC20 public immutable fbtc; constructor(address fbtc_) { fbtc = IERC20(fbtc_); } function mintLockedFbtcRequest(uint256 amount) external returns (uint256) { fbtc.transferFrom(msg.sender, address(this), amount); return amount; } function redeemFbtcRequest( uint256 amount, bytes32 depositTxId, uint256 outputIndex ) external pure returns (bytes32, FBTCPartnerVault.Request memory) { FBTCPartnerVault.Request memory request = FBTCPartnerVault.Request({ op: FBTCPartnerVault.Operation.Nop, status: FBTCPartnerVault.Status.Unused, nonce: 0, srcChain: bytes32("test"), srcAddress: bytes("test"), dstChain: bytes32("test"), dstAddress: bytes("test"), amount: amount, fee: 0, extra: bytes("extra") }); return (bytes32("test"), request); } function confirmRedeemFbtc(uint256 amount) external { fbtc.transfer(msg.sender, amount); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {EndpointV2Mock} from "@layerzerolabs/test-devtools-evm-hardhat/contracts/mocks/EndpointV2Mock.sol"; contract LZEndpointMock is EndpointV2Mock { constructor(uint32 _eid) EndpointV2Mock(_eid) {} }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {NativeLBTC} from "../LBTC/NativeLBTC.sol"; /** * @title Mock implementation of NativeLBTC token * @author Lombard.Finance * @notice Use only for testing */ contract NativeLBTCMock is NativeLBTC { function mintTo(address to, uint256 amount) external { _mint(to, amount); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; contract ProxyMock is Initializable { /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize() external initializer {} }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {LBTC} from "../LBTC/LBTC.sol"; /** * @title Mock implementation of StakedLBTC token * @author Lombard.Finance * @notice Use only for testing */ contract LBTCMock is LBTC { function mintTo(address to, uint256 amount) external { _mint(to, amount); } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; /** * @title Mock implementation of TellerWithMultiAssetSupport * @author Lombard.Finance * @notice Use only for testing */ contract TellerWithMultiAssetSupportMock is ERC20 { using FixedPointMathLib for uint256; error AmountBelowMinimumMint(uint256 minimumMint, uint256 shares); struct Asset { bool allowDeposits; bool allowWithdraws; uint16 sharePremium; } address public immutable vault; mapping(ERC20 => Asset) public assetData; constructor(address lbtc) ERC20("Staked LBTC", "LBTCv") { vault = address(this); Asset memory asset = Asset(true, true, 100); assetData[ERC20(lbtc)] = asset; } function decimals() public view override returns (uint8) { return 8; } function deposit( ERC20 depositAsset, uint256 depositAmount, uint256 minimumMint ) external returns (uint256) { uint256 shares = depositAmount.mulDivDown( 1e4 - assetData[depositAsset].sharePremium, 1e4 ); if (shares < minimumMint) { revert AmountBelowMinimumMint(minimumMint, shares); } // Transfer assets in depositAsset.transferFrom(_msgSender(), address(this), depositAmount); _mint(msg.sender, shares); return shares; } function bulkDeposit( ERC20 depositAsset, uint256 depositAmount, uint256 minimumMint, address to ) external returns (uint256) { uint256 shares = depositAmount.mulDivDown( 1e4 - assetData[depositAsset].sharePremium, 1e4 ); if (shares < minimumMint) { revert AmountBelowMinimumMint(minimumMint, shares); } // Transfer assets in depositAsset.transferFrom(_msgSender(), address(this), depositAmount); _mint(to, shares); return shares; } } /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) /// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol) library FixedPointMathLib { /*////////////////////////////////////////////////////////////// SIMPLIFIED FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ uint256 internal constant MAX_UINT256 = 2 ** 256 - 1; uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s. function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down. } function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up. } function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down. } function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) { return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up. } /*////////////////////////////////////////////////////////////// LOW LEVEL FIXED POINT OPERATIONS //////////////////////////////////////////////////////////////*/ function mulDivDown( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero( mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y))))) ) { revert(0, 0) } // Divide x * y by the denominator. z := div(mul(x, y), denominator) } } function mulDivUp( uint256 x, uint256 y, uint256 denominator ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y)) if iszero( mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y))))) ) { revert(0, 0) } // If x * y modulo the denominator is strictly greater than 0, // 1 is added to round up the division of x * y by the denominator. z := add( gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator) ) } } function rpow( uint256 x, uint256 n, uint256 scalar ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { switch x case 0 { switch n case 0 { // 0 ** 0 = 1 z := scalar } default { // 0 ** n = 0 z := 0 } } default { switch mod(n, 2) case 0 { // If n is even, store scalar in z for now. z := scalar } default { // If n is odd, store x in z for now. z := x } // Shifting right by 1 is like dividing by 2. let half := shr(1, scalar) for { // Shift n right by 1 before looping to halve it. n := shr(1, n) } n { // Shift n right by 1 each iteration to halve it. n := shr(1, n) } { // Revert immediately if x ** 2 would overflow. // Equivalent to iszero(eq(div(xx, x), x)) here. if shr(128, x) { revert(0, 0) } // Store x squared. let xx := mul(x, x) // Round to the nearest number. let xxRound := add(xx, half) // Revert if xx + half overflowed. if lt(xxRound, xx) { revert(0, 0) } // Set x to scaled xxRound. x := div(xxRound, scalar) // If n is even: if mod(n, 2) { // Compute z * x. let zx := mul(z, x) // If z * x overflowed: if iszero(eq(div(zx, x), z)) { // Revert if x is non-zero. if iszero(iszero(x)) { revert(0, 0) } } // Round to the nearest number. let zxRound := add(zx, half) // Revert if zx + half overflowed. if lt(zxRound, zx) { revert(0, 0) } // Return properly scaled zxRound. z := div(zxRound, scalar) } } } } } /*////////////////////////////////////////////////////////////// GENERAL NUMBER UTILITIES //////////////////////////////////////////////////////////////*/ function sqrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { let y := x // We start y at x, which will help us make our initial estimate. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // We check y >= 2^(k + 8) but shift right by k bits // each branch to ensure that if x >= 256, then y >= 256. if iszero(lt(y, 0x10000000000000000000000000000000000)) { y := shr(128, y) z := shl(64, z) } if iszero(lt(y, 0x1000000000000000000)) { y := shr(64, y) z := shl(32, z) } if iszero(lt(y, 0x10000000000)) { y := shr(32, y) z := shl(16, z) } if iszero(lt(y, 0x1000000)) { y := shr(16, y) z := shl(8, z) } // Goal was to get z*z*y within a small factor of x. More iterations could // get y in a tighter range. Currently, we will have y in [256, 256*2^16). // We ensured y >= 256 so that the relative difference between y and y+1 is small. // That's not possible if x < 256 but we can just verify those cases exhaustively. // Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256. // Correctness can be checked exhaustively for x < 256, so we assume y >= 256. // Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps. // For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range // (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256. // Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate // sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18. // There is no overflow risk here since y < 2^136 after the first branch above. z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If x+1 is a perfect square, the Babylonian method cycles between // floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division // Since the ceil is rare, we save gas on the assignment and repeat division in the rare case. // If you don't care whether the floor or ceil square root is returned, you can remove this statement. z := sub(z, lt(div(x, z), z)) } } function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Mod x by y. Note this will return // 0 instead of reverting if y is zero. z := mod(x, y) } } function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { // Divide x by y. Note this will return // 0 instead of reverting if y is zero. r := div(x, y) } } function unsafeDivUp( uint256 x, uint256 y ) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Add 1 to x * y if x % y > 0. Note this will // return 0 instead of reverting if y is zero. z := add(gt(mod(x, y), 0), div(x, y)) } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {ERC20Upgradeable} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol"; /** * @title Mock implementation of WBTC token * @author Lombard.Finance * @notice Use only for testing */ contract WBTCMock is ERC20Upgradeable { uint8 _decimals; /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize() external initializer { __ERC20_init("Wrapped BTC Mock", "WBTCMOCK"); _decimals = 8; } function setDecimals(uint8 decimals_) external { _decimals = decimals_; } function mint(address to, uint256 amount) external { _mint(to, amount); } function decimals() public view virtual override returns (uint8) { return _decimals; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {FeeUtils} from "../../../contracts/libs/FeeUtils.sol"; interface ILBTC is IERC20Metadata { function mint(address to, uint256 amount) external; } contract BTCBPMM is PausableUpgradeable, AccessControlUpgradeable { using SafeERC20 for IERC20Metadata; using SafeERC20 for ILBTC; struct PMMStorage { IERC20Metadata btcb; ILBTC lbtc; uint256 multiplier; uint256 divider; uint256 stakeLimit; uint256 totalStake; address withdrawAddress; uint16 relativeFee; } bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.BTCBPMM")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant PMM_STORAGE_LOCATION = 0x75814abe757fd1afd999e293d51fa6528839552b73d81c6cc151470e3106f500; error StakeLimitExceeded(); error UnauthorizedAccount(address account); error ZeroAmount(); event StakeLimitSet(uint256 newStakeLimit); event WithdrawalAddressSet(address newWithdrawAddress); event RelativeFeeChanged(uint16 oldRelativeFee, uint16 newRelativeFee); /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function initialize( address _lbtc, address _btcb, address admin, uint256 _stakeLimit, address withdrawAddress, uint16 _relativeFee ) external initializer { __Pausable_init(); __AccessControl_init(); __BTCBPMM_init( _lbtc, _btcb, admin, _stakeLimit, withdrawAddress, _relativeFee ); } /// USER ACTIONS /// function swapBTCBToLBTC(uint256 amount) external whenNotPaused { PMMStorage storage $ = _getPMMStorage(); ILBTC lbtc = $.lbtc; IERC20Metadata btcb = $.btcb; uint256 multiplier = $.multiplier; uint256 divider = $.divider; uint256 amountLBTC = ((amount * multiplier) / divider); uint256 amountBTCB = ((amountLBTC * divider) / multiplier); if (amountLBTC == 0) revert ZeroAmount(); if ($.totalStake + amountLBTC > $.stakeLimit) revert StakeLimitExceeded(); // relative fee uint256 fee = FeeUtils.getRelativeFee(amountLBTC, $.relativeFee); $.totalStake += amountLBTC; btcb.safeTransferFrom(_msgSender(), address(this), amountBTCB); lbtc.mint(_msgSender(), amountLBTC - fee); lbtc.mint(address(this), fee); } /// ACCESS CONTROL FUNCTIONS /// function withdrawBTCB( uint256 amount ) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { PMMStorage storage $ = _getPMMStorage(); $.btcb.safeTransfer($.withdrawAddress, amount); } function withdrawLBTC( uint256 amount ) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { PMMStorage storage $ = _getPMMStorage(); $.lbtc.safeTransfer($.withdrawAddress, amount); } function setWithdrawalAddress( address newWithdrawAddress ) external onlyRole(DEFAULT_ADMIN_ROLE) { _getPMMStorage().withdrawAddress = newWithdrawAddress; emit WithdrawalAddressSet(newWithdrawAddress); } function setStakeLimit( uint256 newStakeLimit ) external onlyRole(DEFAULT_ADMIN_ROLE) { _getPMMStorage().stakeLimit = newStakeLimit; emit StakeLimitSet(newStakeLimit); } function setRelativeFee( uint16 newRelativeFee ) external onlyRole(DEFAULT_ADMIN_ROLE) { FeeUtils.validateCommission(newRelativeFee); PMMStorage storage $ = _getPMMStorage(); uint16 oldRelativeFee = $.relativeFee; $.relativeFee = newRelativeFee; emit RelativeFeeChanged(oldRelativeFee, newRelativeFee); } function pause() external onlyRole(PAUSER_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } /// GETTERS /// function stakeLimit() external view returns (uint256) { return _getPMMStorage().stakeLimit; } function relativeFee() external view returns (uint16) { return _getPMMStorage().relativeFee; } function remainingStake() external view returns (uint256) { PMMStorage storage $ = _getPMMStorage(); if ($.totalStake > $.stakeLimit) return 0; return $.stakeLimit - $.totalStake; } function withdrawalAddress() external view returns (address) { return _getPMMStorage().withdrawAddress; } /// PRIVATE FUNCTIONS /// function __BTCBPMM_init( address _lbtc, address _btcb, address admin, uint256 _stakeLimit, address withdrawAddress, uint16 _relativeFee ) internal onlyInitializing { _grantRole(DEFAULT_ADMIN_ROLE, admin); FeeUtils.validateCommission(_relativeFee); PMMStorage storage $ = _getPMMStorage(); $.stakeLimit = _stakeLimit; $.withdrawAddress = withdrawAddress; $.lbtc = ILBTC(_lbtc); $.btcb = IERC20Metadata(_btcb); $.relativeFee = _relativeFee; uint256 lbtcDecimals = $.lbtc.decimals(); uint256 btcbDecimals = $.btcb.decimals(); if (lbtcDecimals <= btcbDecimals) { $.divider = 10 ** (btcbDecimals - lbtcDecimals); $.multiplier = 1; } else { $.multiplier = 10 ** (lbtcDecimals - btcbDecimals); $.divider = 1; } } function _getPMMStorage() private pure returns (PMMStorage storage $) { assembly { $.slot := PMM_STORAGE_LOCATION } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {FeeUtils} from "../../contracts/libs/FeeUtils.sol"; interface ILBTC is IERC20Metadata { function mint(address to, uint256 amount) external; } contract CBBTCPMM is PausableUpgradeable, AccessControlUpgradeable { using SafeERC20 for IERC20Metadata; using SafeERC20 for ILBTC; struct PMMStorage { IERC20Metadata cbbtc; ILBTC lbtc; uint256 multiplier; uint256 divider; uint256 stakeLimit; uint256 totalStake; address withdrawAddress; uint16 relativeFee; } bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.CBBTCPMM")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant PMM_STORAGE_LOCATION = 0x41c6bdd99210344dba22372f555bef55094fdfda50b5100d427f58faa7ee0900; error StakeLimitExceeded(); error UnauthorizedAccount(address account); error ZeroAmount(); event StakeLimitSet(uint256 newStakeLimit); event WithdrawalAddressSet(address newWithdrawAddress); event RelativeFeeChanged(uint16 oldRelativeFee, uint16 newRelativeFee); /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } function __CBBTCPMM_init( address _lbtc, address _cbbtc, address admin, uint256 _stakeLimit, address withdrawAddress, uint16 _relativeFee ) internal onlyInitializing { _grantRole(DEFAULT_ADMIN_ROLE, admin); FeeUtils.validateCommission(_relativeFee); PMMStorage storage $ = _getPMMStorage(); $.stakeLimit = _stakeLimit; $.withdrawAddress = withdrawAddress; $.lbtc = ILBTC(_lbtc); $.cbbtc = IERC20Metadata(_cbbtc); $.relativeFee = _relativeFee; uint256 lbtcDecimals = $.lbtc.decimals(); uint256 cbbtcDecimals = $.cbbtc.decimals(); if (lbtcDecimals <= cbbtcDecimals) { $.divider = 10 ** (cbbtcDecimals - lbtcDecimals); $.multiplier = 1; } else { $.multiplier = 10 ** (lbtcDecimals - cbbtcDecimals); $.divider = 1; } } function initialize( address _lbtc, address _cbbtc, address admin, uint256 _stakeLimit, address withdrawAddress, uint16 _relativeFee ) external initializer { __Pausable_init(); __AccessControl_init(); __CBBTCPMM_init( _lbtc, _cbbtc, admin, _stakeLimit, withdrawAddress, _relativeFee ); } function swapCBBTCToLBTC(uint256 amount) external whenNotPaused { PMMStorage storage $ = _getPMMStorage(); ILBTC lbtc = $.lbtc; IERC20Metadata cbbtc = $.cbbtc; uint256 multiplier = $.multiplier; uint256 divider = $.divider; uint256 amountLBTC = ((amount * multiplier) / divider); uint256 amountCBBTC = ((amountLBTC * divider) / multiplier); if (amountLBTC == 0) revert ZeroAmount(); if ($.totalStake + amountLBTC > $.stakeLimit) revert StakeLimitExceeded(); // relative fee uint256 fee = FeeUtils.getRelativeFee(amountLBTC, $.relativeFee); $.totalStake += amountLBTC; cbbtc.safeTransferFrom(_msgSender(), address(this), amountCBBTC); lbtc.mint(_msgSender(), amountLBTC - fee); lbtc.mint(address(this), fee); } function withdrawCBBTC( uint256 amount ) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { PMMStorage storage $ = _getPMMStorage(); $.cbbtc.safeTransfer($.withdrawAddress, amount); } function withdrawLBTC( uint256 amount ) external whenNotPaused onlyRole(DEFAULT_ADMIN_ROLE) { PMMStorage storage $ = _getPMMStorage(); $.lbtc.safeTransfer($.withdrawAddress, amount); } function setWithdrawalAddress( address newWithdrawAddress ) external onlyRole(DEFAULT_ADMIN_ROLE) { _getPMMStorage().withdrawAddress = newWithdrawAddress; emit WithdrawalAddressSet(newWithdrawAddress); } function setStakeLimit( uint256 newStakeLimit ) external onlyRole(OPERATOR_ROLE) { _getPMMStorage().stakeLimit = newStakeLimit; emit StakeLimitSet(newStakeLimit); } function setRelativeFee( uint16 newRelativeFee ) external onlyRole(DEFAULT_ADMIN_ROLE) { FeeUtils.validateCommission(newRelativeFee); PMMStorage storage $ = _getPMMStorage(); uint16 oldRelativeFee = $.relativeFee; $.relativeFee = newRelativeFee; emit RelativeFeeChanged(oldRelativeFee, newRelativeFee); } function pause() external onlyRole(PAUSER_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function stakeLimit() external view returns (uint256) { return _getPMMStorage().stakeLimit; } function relativeFee() external view returns (uint16) { return _getPMMStorage().relativeFee; } function remainingStake() external view returns (uint256) { PMMStorage storage $ = _getPMMStorage(); if ($.totalStake > $.stakeLimit) return 0; return $.stakeLimit - $.totalStake; } function withdrawalAddress() external view returns (address) { return _getPMMStorage().withdrawAddress; } function _getPMMStorage() private pure returns (PMMStorage storage $) { assembly { $.slot := PMM_STORAGE_LOCATION } } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; interface IPoR { /// @notice Error thrown when the lengths of the arrays do not match. error ArrayLengthMismatch(); /// @notice Error thrown when the address already exists. error AddressAlreadyExists(string addressStr); /// @notice Error thrown when the address does not exist. error AddressDoesNotExist(string addressStr); /// @notice Error thrown when the message or signature is invalid. error InvalidMessageSignature( string addressStr, string messageOrPath, bytes signature ); /// @notice Error thrown when the root pubkey is invalid. error InvalidRootPubkey(); /// @notice Error thrown when the root pubkey id is invalid. error InvalidRootPubkeyId(bytes32 id); /// @notice Error thrown when the root pubkey already exists. error RootPubkeyAlreadyExists(bytes pubkey); /// @notice Error thrown when the root pubkey does not exist. error RootPubkeyDoesNotExist(bytes pubkey); /// @notice Error thrown when the root pubkey cannot be deleted. error RootPubkeyCannotBeDeleted(); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {IPoR} from "./IPoR.sol"; contract PoR is AccessControlUpgradeable, IPoR { struct AddressData { string addressStr; bytes32 rootPkId; string messageOrDerivationData; bytes signature; } struct RootPubkeyData { bytes pubkey; /// @notice Number of derived from this root pubkey. uint256 derivedAddressesCount; } /// @custom:storage-location erc7201:lombardfinance.storage.PoR struct PORStorage { /// @notice Mapping from id to index in rootPubkeyData. /// @dev id is keccak256 of the pubkey mapping(bytes32 => RootPubkeyData) idToPubkeyData; /// @notice Data associated to each address. AddressData[] addressData; /// @notice Mapping to track index of each address. /// @dev contains index + 1 to avoid 0 index mapping(string => uint256) addressIndex; } // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.PoR")) - 1)) & ~bytes32(uint256(0xff)) bytes32 constant POR_STORAGE_LOCATION = 0x2820bf7f0bcf92e901021c9470a614652331fbef5e77eebe7a3799436b598900; bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE"); function initialize(address _owner) public initializer { __AccessControl_init(); _grantRole(DEFAULT_ADMIN_ROLE, _owner); } /// ACCESS CONTROL FUNCTIONS /// /// @notice Adds a root pubkey to the Proof of Reserve (PoR). /// @param _pubkey Root pubkey. function addRootPubkey( bytes calldata _pubkey ) external onlyRole(DEFAULT_ADMIN_ROLE) { if (_pubkey.length != 65) { revert InvalidRootPubkey(); } PORStorage storage $ = _getPORStorage(); bytes32 rootPkId = keccak256(_pubkey); if ($.idToPubkeyData[rootPkId].pubkey.length != 0) { revert RootPubkeyAlreadyExists(_pubkey); } $.idToPubkeyData[rootPkId] = RootPubkeyData({ pubkey: _pubkey, derivedAddressesCount: 0 }); } /// @notice Deletes a root pubkey from the Proof of Reserve (PoR). /// @param _pubkey Root pubkey to delete. function deleteRootPubkey( bytes calldata _pubkey ) external onlyRole(DEFAULT_ADMIN_ROLE) { PORStorage storage $ = _getPORStorage(); bytes32 rootPkId = keccak256(_pubkey); RootPubkeyData storage rootPubkeyData = $.idToPubkeyData[rootPkId]; if (rootPubkeyData.pubkey.length == 0) { revert RootPubkeyDoesNotExist(_pubkey); } if (rootPubkeyData.derivedAddressesCount != 0) { revert RootPubkeyCannotBeDeleted(); } delete $.idToPubkeyData[rootPkId]; } /// @notice Adds multiple entries to the arrays. /// @param _addresses Array of addresses in string format. /// @param _rootPkIds Array of root pubkey ids. /// @param _messagesOrDerivationData Array of messages to sign or derivation paths. /// @param _signatures Array of signed messages. /// @dev _rootPkIds should be bytes32(0) if the address is not derived from a root pubkey. /// @dev _signatures should be empty if _rootPkIds is not empty as there is no message to sign. function addAddresses( string[] calldata _addresses, bytes32[] calldata _rootPkIds, string[] calldata _messagesOrDerivationData, bytes[] calldata _signatures ) external onlyRole(OPERATOR_ROLE) { if ( _addresses.length != _rootPkIds.length || _addresses.length != _messagesOrDerivationData.length || _addresses.length != _signatures.length ) { revert ArrayLengthMismatch(); } PORStorage storage $ = _getPORStorage(); // Access the storage for (uint256 i = 0; i < _addresses.length; i++) { // Check if address exists already if ($.addressIndex[_addresses[i]] != 0) { revert AddressAlreadyExists(_addresses[i]); } bool derived = _rootPkIds[i] != bytes32(0); if (derived && $.idToPubkeyData[_rootPkIds[i]].pubkey.length == 0) { revert InvalidRootPubkeyId(_rootPkIds[i]); } // Store data $.addressData.push( AddressData({ addressStr: _addresses[i], rootPkId: _rootPkIds[i], messageOrDerivationData: _messagesOrDerivationData[i], signature: _signatures[i] }) ); $.addressIndex[_addresses[i]] = $.addressData.length; // Store the index + 1 if (derived) { $.idToPubkeyData[_rootPkIds[i]].derivedAddressesCount++; } } } /// @notice Deletes multiple entries from the Proof of Reserve (PoR) by address. /// @dev Non-existing addresses are ignored. /// @param _addresses Array of addresses to delete from the PoR. function deleteAddresses( string[] calldata _addresses ) external onlyRole(DEFAULT_ADMIN_ROLE) { PORStorage storage $ = _getPORStorage(); // Access the storage uint256 length = $.addressData.length; for (uint256 i; i < _addresses.length; ) { string calldata _address = _addresses[i]; uint256 index = $.addressIndex[_address]; // Get the index of the address if (index != 0) { bytes32 rootPkId = $.addressData[index - 1].rootPkId; if (rootPkId != bytes32(0)) { $.idToPubkeyData[rootPkId].derivedAddressesCount--; } if (index != length) { // Remove the address, message, and signature $.addressData[index - 1] = $.addressData[length - 1]; $.addressIndex[ $.addressData[length - 1].addressStr ] = index; } // remove data $.addressData.pop(); delete $.addressIndex[_address]; unchecked { length--; } } unchecked { ++i; } } } /// @notice Updates messages and signatures for a given set of addresses. /// @dev Assumes messages are being added so signatures cannot be empty. /// @param _addresses Array of addresses to update. /// @param _messages Array of new messages. /// @param _signatures Array of new signatures. function updateMessageSignature( string[] calldata _addresses, string[] calldata _messages, bytes[] calldata _signatures ) external onlyRole(OPERATOR_ROLE) { PORStorage storage $ = _getPORStorage(); if ( _addresses.length != _messages.length || _addresses.length != _signatures.length ) { revert ArrayLengthMismatch(); } for (uint256 i; i < _addresses.length; ) { uint256 index = $.addressIndex[_addresses[i]]; if (index == 0) { revert AddressDoesNotExist(_addresses[i]); } if (bytes(_messages[i]).length == 0 || _signatures[i].length == 0) { revert InvalidMessageSignature( _addresses[i], _messages[i], _signatures[i] ); } AddressData storage addressData = $.addressData[index - 1]; addressData.messageOrDerivationData = _messages[i]; addressData.signature = _signatures[i]; unchecked { ++i; } } } /// GETTERS /// /// @notice Returns the number of addresses in the Proof of Reserve (PoR). /// @return Number of addresses. function getPoRAddressListLength() external view returns (uint256) { return _getPORStorage().addressData.length; } /// @notice Returns data for a given set of addresses. /// @dev Default/empty data is returned for non-existing addresses. /// @param _addresses Array of addresses to get data for. /// @return rootPkIds Array of root pubkey ids. /// @return messagesOrPaths Array of messages or derivation paths. /// @return signatures Array of signatures. function getPoRSignatureMessages( string[] calldata _addresses ) external view returns (bytes32[] memory, string[] memory, bytes[] memory) { PORStorage storage $ = _getPORStorage(); bytes32[] memory rootPkIds = new bytes32[](_addresses.length); string[] memory messagesOrPaths = new string[](_addresses.length); bytes[] memory signatures = new bytes[](_addresses.length); for (uint256 i; i < _addresses.length; ) { uint256 index = $.addressIndex[_addresses[i]]; if (index != 0) { AddressData storage addressData = $.addressData[index - 1]; rootPkIds[i] = addressData.rootPkId; messagesOrPaths[i] = addressData.messageOrDerivationData; signatures[i] = addressData.signature; } unchecked { ++i; } } return (rootPkIds, messagesOrPaths, signatures); } /// @notice Returns addresses and data in a range. /// @param _start Start index. /// @param _end End index. /// @return addresses Array of addresses. /// @return rootPkIds Array of root pubkey ids. /// @return messagesOrPaths Array of messages or derivation paths. /// @return signatures Array of signatures. function getPoRAddressSignatureMessages( uint256 _start, uint256 _end ) external view returns ( string[] memory, bytes32[] memory, string[] memory, bytes[] memory ) { PORStorage storage $ = _getPORStorage(); if (_end >= $.addressData.length) { _end = $.addressData.length - 1; } if (_start > _end) { return ( new string[](0), new bytes32[](0), new string[](0), new bytes[](0) ); } string[] memory addresses = new string[](_end - _start + 1); bytes32[] memory rootPkIds = new bytes32[](_end - _start + 1); string[] memory messagesOrPaths = new string[](_end - _start + 1); bytes[] memory signatures = new bytes[](_end - _start + 1); for (uint256 i; _start <= _end; ) { AddressData storage addressData = $.addressData[_start]; addresses[i] = addressData.addressStr; rootPkIds[i] = addressData.rootPkId; messagesOrPaths[i] = addressData.messageOrDerivationData; signatures[i] = addressData.signature; unchecked { ++i; ++_start; } } return (addresses, rootPkIds, messagesOrPaths, signatures); } /// @notice Returns all addresses data. /// @return All addresses data. function getPoRAddressSignatureMessages() external view returns (AddressData[] memory) { PORStorage storage $ = _getPORStorage(); return $.addressData; } /// @notice Function to get the storage reference function _getPORStorage() private pure returns (PORStorage storage $) { assembly { $.slot := POR_STORAGE_LOCATION } } /// @notice Returns public key for a given id /// @param _id Root pubkey id. function getRootPubkey(bytes32 _id) external view returns (bytes memory) { return _getPORStorage().idToPubkeyData[_id].pubkey; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IDepositor} from "../IDepositor.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; /** * @title Depositor for an ERC4626 vault. * @author Lombard.Finance * @notice This contract is part of the Lombard.Finance protocol */ contract ERC4626Depositor is IDepositor, ReentrancyGuard { using SafeERC20 for IERC20; /// @dev error thrown when the passed depositAmount is zero error ZeroAssets(); error ApproveFailed(); error UnauthorizedAccount(address account); error MinimumMintNotMet(uint256 minimumMint, uint256 shares); IERC4626 public immutable vault; IERC20 public immutable depositAsset; address public immutable stakeAndBake; constructor(IERC4626 vault_, IERC20 depositAsset_, address stakeAndBake_) { vault = vault_; depositAsset = depositAsset_; stakeAndBake = stakeAndBake_; } modifier onlyStakeAndBake() { if (stakeAndBake != msg.sender) { revert UnauthorizedAccount(msg.sender); } _; } /** * @notice Deposit function. * @param owner The address of the user who will receive the shares * @param depositAmount The amount of tokens to deposit to the vault * @param depositPayload The ABI encoded parameters for the vault deposit function * @dev depositPayload encodes the minimumMint for the vault */ function deposit( address owner, uint256 depositAmount, bytes calldata depositPayload ) external nonReentrant onlyStakeAndBake returns (bytes memory) { uint256 minimumMint = abi.decode(depositPayload, (uint256)); // Take the owner's LBTC. depositAsset.safeTransferFrom(msg.sender, address(this), depositAmount); // Give the vault the needed allowance. depositAsset.safeIncreaseAllowance(address(vault), depositAmount); // Deposit and obtain vault shares. uint256 shares = vault.deposit(depositAmount, owner); // Ensure minimumMint is reached. if (shares < minimumMint) { revert MinimumMintNotMet(minimumMint, shares); } bytes memory ret = abi.encode(shares); return ret; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; /** * @title Interface to abstract over specifics of depositing into a vault. * This just makes sure that any vault contract allowed in the `StakeAndBake` contract * takes a variable size byte array so that we can independently specify the decoding * and contract call. * @author Lombard.Finance * @notice This contract is part of the Lombard.Finance protocol */ interface IDepositor { /** * @notice Deposit function interface. * @param owner The address of the user who will receive the shares * @param depositPayload Optional ABI encoded parameters needed for a vault deposit call */ function deposit( address owner, uint256 depositAmount, bytes calldata depositPayload ) external returns (bytes memory); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title An interface over the TellerWithMultiAssetSupport contract. * @author Lombard.Finance * @notice This contract is part of the Lombard.Finance protocol */ interface ITeller { function deposit( IERC20 depositAsset, uint256 depositAmount, uint256 minimumMint ) external returns (uint256 shares); function bulkDeposit( IERC20 depositAsset, uint256 depositAmount, uint256 minimumMint, address to ) external returns (uint256 shares); function vault() external view returns (address); }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IDepositor} from "../IDepositor.sol"; import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import {TellerWithMultiAssetSupportMock} from "../../../mock/TellerWithMultiAssetSupportMock.sol"; import {ITeller} from "./ITeller.sol"; /** * @title Depositor for the `BoringVault` vault. * @author Lombard.Finance * @notice This contract is part of the Lombard.Finance protocol */ contract TellerWithMultiAssetSupportDepositor is IDepositor, ReentrancyGuard { using SafeERC20 for IERC20; /// @dev error thrown when the passed depositAmount is zero error ZeroAssets(); error ApproveFailed(); error UnauthorizedAccount(address account); ITeller public immutable teller; IERC20 public immutable depositAsset; address public immutable stakeAndBake; address public immutable vault; constructor(ITeller teller_, IERC20 depositAsset_, address stakeAndBake_) { teller = teller_; depositAsset = depositAsset_; stakeAndBake = stakeAndBake_; address vault_ = teller.vault(); vault = vault_; } modifier onlyStakeAndBake() { if (stakeAndBake != msg.sender) { revert UnauthorizedAccount(msg.sender); } _; } /** * @notice Deposit function. * @param owner The address of the user who will receive the shares * @param depositAmount The amount of tokens to deposit to the vault * @param depositPayload The ABI encoded parameters for the vault deposit function * @dev depositPayload encodes the minimumMint for the teller */ function deposit( address owner, uint256 depositAmount, bytes calldata depositPayload ) external nonReentrant onlyStakeAndBake returns (bytes memory) { uint256 minimumMint = abi.decode(depositPayload, (uint256)); // Take the owner's LBTC. depositAsset.safeTransferFrom(msg.sender, address(this), depositAmount); // Give the vault the needed allowance. depositAsset.safeIncreaseAllowance(vault, depositAmount); // Deposit and obtain vault shares. uint256 shares = teller.bulkDeposit( depositAsset, depositAmount, minimumMint, owner ); bytes memory ret = abi.encode(shares); return ret; } }
// SPDX-License-Identifier: MIT pragma solidity 0.8.24; import {IStakedLBTC} from "../LBTC/IStakedLBTC.sol"; import {AccessControlUpgradeable} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; import {IDepositor} from "./depositor/IDepositor.sol"; import {Actions} from "../libs/Actions.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol"; /** * @title Convenience contract for users who wish to * stake their BTC and deposit it in a vault in the same transaction. * @author Lombard.Finance * @notice This contract is a part of the Lombard.Finance protocol */ contract StakeAndBake is AccessControlUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable { /// @dev error thrown when the remaining amount after taking a fee is zero error ZeroDepositAmount(); /// @dev error thrown when operator is changed to zero address error ZeroAddress(); /// @dev error thrown when fee is attempted to be set above hardcoded maximum error FeeGreaterThanMaximum(uint256 fee); /// @dev error thrown when no depositor is set error NoDepositorSet(); /// @dev error thrown when collecting funds from user fails error CollectingFundsFailed(); /// @dev error thrown when sending the fee fails error SendingFeeFailed(); /// @dev error thrown when approving to the depositor fails error ApprovalFailed(); /// @dev error thrown when stakeAndBakeInternal is called by anyone other than self error CallerNotSelf(address caller); event DepositorSet(address indexed depositor); event BatchStakeAndBakeReverted(uint256 indexed index, string message); event FeeChanged(uint256 newFee); event GasLimitChanged(uint256 newGasLimit); struct StakeAndBakeData { /// @notice Contents of permit approval signed by the user bytes permitPayload; /// @notice Contains the parameters needed to complete a deposit bytes depositPayload; /// @notice The message with the stake data bytes mintPayload; /// @notice Signature of the consortium approving the mint bytes proof; } /// @custom:storage-location erc7201:lombardfinance.storage.StakeAndBake struct StakeAndBakeStorage { IStakedLBTC lbtc; IDepositor depositor; uint256 fee; uint256 gasLimit; } bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE"); bytes32 public constant FEE_OPERATOR_ROLE = keccak256("FEE_OPERATOR_ROLE"); bytes32 public constant CLAIMER_ROLE = keccak256("CLAIMER_ROLE"); // keccak256(abi.encode(uint256(keccak256("lombardfinance.storage.StakeAndBake")) - 1)) & ~bytes32(uint256(0xff)) bytes32 private constant STAKE_AND_BAKE_STORAGE_LOCATION = 0xd0321c9642a0f7a5931cd62db04cb9e2c0d32906ef8824eece128a7ad5e4f500; uint256 public constant MAXIMUM_FEE = 100000; /// @dev https://docs.openzeppelin.com/upgrades-plugins/1.x/writing-upgradeable#initializing_the_implementation_contract /// @custom:oz-upgrades-unsafe-allow constructor constructor() { _disableInitializers(); } modifier depositorSet() { if (address(_getStakeAndBakeStorage().depositor) == address(0)) { revert NoDepositorSet(); } _; } function initialize( IStakedLBTC lbtc_, address owner_, address operator_, uint256 fee_, address claimer_, address pauser_, uint256 gasLimit_ ) external initializer { if (fee_ > MAXIMUM_FEE) revert FeeGreaterThanMaximum(fee_); __ReentrancyGuard_init(); __Pausable_init(); __AccessControl_init(); _grantRole(DEFAULT_ADMIN_ROLE, owner_); _grantRole(FEE_OPERATOR_ROLE, operator_); _grantRole(PAUSER_ROLE, pauser_); _grantRole(CLAIMER_ROLE, claimer_); // We need the stake and bake contract to hold a claimer role as well, for when we call // `batchStakeAndBake`. _grantRole(CLAIMER_ROLE, address(this)); StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); $.lbtc = lbtc_; $.fee = fee_; $.gasLimit = gasLimit_; } /** * @notice Sets the claiming fee * @param fee The fee to set */ function setFee(uint256 fee) external onlyRole(FEE_OPERATOR_ROLE) { if (fee > MAXIMUM_FEE) revert FeeGreaterThanMaximum(fee); StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); $.fee = fee; emit FeeChanged(fee); } /** * @notice Sets the maximum gas limit for a batch stake and bake call * @param gasLimit The gas limit to set */ function setGasLimit( uint256 gasLimit ) external onlyRole(DEFAULT_ADMIN_ROLE) { StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); $.gasLimit = gasLimit; emit GasLimitChanged(gasLimit); } /** * @notice Sets a depositor, allowing the contract to `stakeAndBake` to it. * @param depositor The address of the depositor abstraction we use to deposit to the vault */ function setDepositor( address depositor ) external onlyRole(DEFAULT_ADMIN_ROLE) { if (depositor == address(0)) revert ZeroAddress(); StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); $.depositor = IDepositor(depositor); emit DepositorSet(depositor); } /** * @notice Mint LBTC and stake directly into a given vault in batches. */ function batchStakeAndBake( StakeAndBakeData[] calldata data ) external onlyRole(CLAIMER_ROLE) depositorSet whenNotPaused returns (bytes[] memory) { StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); bytes[] memory ret = new bytes[](data.length); for (uint256 i; i < data.length; ) { try this.stakeAndBakeInternal{gas: $.gasLimit}(data[i]) returns ( bytes memory b ) { ret[i] = b; } catch Error(string memory message) { emit BatchStakeAndBakeReverted(i, message); } unchecked { i++; } } return ret; } function stakeAndBakeInternal( StakeAndBakeData calldata data ) external returns (bytes memory) { if (_msgSender() != address(this)) { revert CallerNotSelf(_msgSender()); } return _stakeAndBake(data); } /** * @notice Mint LBTC and stake directly into a given vault. * @param data The bundled data needed to execute this function */ function stakeAndBake( StakeAndBakeData calldata data ) external nonReentrant onlyRole(CLAIMER_ROLE) depositorSet whenNotPaused returns (bytes memory) { return _stakeAndBake(data); } function getStakeAndBakeFee() external view returns (uint256) { StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); return $.fee; } function getStakeAndBakeDepositor() external view returns (IDepositor) { StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); return $.depositor; } function pause() external onlyRole(PAUSER_ROLE) { _pause(); } function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) { _unpause(); } function _deposit( uint256 permitAmount, uint256 feeAmount, address owner, bytes calldata depositPayload ) internal returns (bytes memory) { StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); uint256 remainingAmount = permitAmount - feeAmount; // Since a vault could only work with msg.sender, the depositor needs to own the LBTC. // The depositor should then send the staked vault shares back to the `owner`. if ( !IERC20(address($.lbtc)).approve( address($.depositor), remainingAmount ) ) revert ApprovalFailed(); // Finally, deposit LBTC to the given vault. return $.depositor.deposit(owner, remainingAmount, depositPayload); } function _stakeAndBake( StakeAndBakeData calldata data ) internal returns (bytes memory) { StakeAndBakeStorage storage $ = _getStakeAndBakeStorage(); // First, mint the LBTC. $.lbtc.mint(data.mintPayload, data.proof); ( uint256 permitAmount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) = abi.decode( data.permitPayload, (uint256, uint256, uint8, bytes32, bytes32) ); // Check the recipient. Actions.DepositBtcActionV0 memory action = Actions.depositBtcV0( data.mintPayload[4:] ); address owner = action.recipient; // We check if we can simply use transferFrom. // Otherwise, we permit the depositor to transfer the minted value. if ( IERC20(address($.lbtc)).allowance(owner, address(this)) < permitAmount ) IERC20Permit(address($.lbtc)).permit( owner, address(this), permitAmount, deadline, v, r, s ); if ( !IERC20(address($.lbtc)).transferFrom( owner, address(this), permitAmount ) ) revert CollectingFundsFailed(); // Take the current maximum fee from the user. uint256 feeAmount = $.fee; if (feeAmount > 0) { if ( !IERC20(address($.lbtc)).transfer( $.lbtc.getTreasury(), feeAmount ) ) revert SendingFeeFailed(); } if (permitAmount > feeAmount) { return _deposit(permitAmount, feeAmount, owner, data.depositPayload); } else { revert ZeroDepositAmount(); } } function _getStakeAndBakeStorage() private pure returns (StakeAndBakeStorage storage $) { assembly { $.slot := STAKE_AND_BAKE_STORAGE_LOCATION } } }
// SPDX-License-Identifier: Unlicense /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.8.0 <0.9.0; library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes.slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes.slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes.slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes.slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) { require(_bytes.length >= _start + 2, "toUint16_outOfBounds"); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) { require(_bytes.length >= _start + 4, "toUint32_outOfBounds"); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) { require(_bytes.length >= _start + 8, "toUint64_outOfBounds"); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) { require(_bytes.length >= _start + 12, "toUint96_outOfBounds"); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) { require(_bytes.length >= _start + 16, "toUint128_outOfBounds"); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) { require(_bytes.length >= _start + 32, "toUint256_outOfBounds"); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) { require(_bytes.length >= _start + 32, "toBytes32_outOfBounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equal_nonAligned(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let endMinusWord := add(_preBytes, length) let mc := add(_preBytes, 0x20) let cc := add(_postBytes, 0x20) for { // the next line is the loop condition: // while(uint256(mc < endWord) + cb == 2) } eq(add(lt(mc, endMinusWord), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } // Only if still successful // For <1 word tail bytes if gt(success, 0) { // Get the remainder of length/32 // length % 32 = AND(length, 32 - 1) let numTailBytes := and(length, 0x1f) let mcRem := mload(mc) let ccRem := mload(cc) for { let i := 0 // the next line is the loop condition: // while(uint256(i < numTailBytes) + cb == 2) } eq(add(lt(i, numTailBytes), cb), 2) { i := add(i, 1) } { if iszero(eq(byte(i, mcRem), byte(i, ccRem))) { // unsuccess: success := 0 cb := 0 } } } } default { // unsuccess: success := 0 } } return success; } function equalStorage( bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes.slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; /// @notice Library for converting between addresses and bytes32 values. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/Bytes32AddressLib.sol) library Bytes32AddressLib { function fromLast20Bytes(bytes32 bytesValue) internal pure returns (address) { return address(uint160(uint256(bytesValue))); } function fillLast12Bytes(address addressValue) internal pure returns (bytes32) { return bytes32(bytes20(addressValue)); } }
// SPDX-License-Identifier: AGPL-3.0-only pragma solidity >=0.8.0; import {Bytes32AddressLib} from "./Bytes32AddressLib.sol"; /// @notice Deploy to deterministic addresses without an initcode factor. /// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/CREATE3.sol) /// @author Modified from 0xSequence (https://github.com/0xSequence/create3/blob/master/contracts/Create3.sol) library CREATE3 { using Bytes32AddressLib for bytes32; //--------------------------------------------------------------------------------// // Opcode | Opcode + Arguments | Description | Stack View // //--------------------------------------------------------------------------------// // 0x36 | 0x36 | CALLDATASIZE | size // // 0x3d | 0x3d | RETURNDATASIZE | 0 size // // 0x3d | 0x3d | RETURNDATASIZE | 0 0 size // // 0x37 | 0x37 | CALLDATACOPY | // // 0x36 | 0x36 | CALLDATASIZE | size // // 0x3d | 0x3d | RETURNDATASIZE | 0 size // // 0x34 | 0x34 | CALLVALUE | value 0 size // // 0xf0 | 0xf0 | CREATE | newContract // //--------------------------------------------------------------------------------// // Opcode | Opcode + Arguments | Description | Stack View // //--------------------------------------------------------------------------------// // 0x67 | 0x67XXXXXXXXXXXXXXXX | PUSH8 bytecode | bytecode // // 0x3d | 0x3d | RETURNDATASIZE | 0 bytecode // // 0x52 | 0x52 | MSTORE | // // 0x60 | 0x6008 | PUSH1 08 | 8 // // 0x60 | 0x6018 | PUSH1 18 | 24 8 // // 0xf3 | 0xf3 | RETURN | // //--------------------------------------------------------------------------------// bytes internal constant PROXY_BYTECODE = hex"67_36_3d_3d_37_36_3d_34_f0_3d_52_60_08_60_18_f3"; bytes32 internal constant PROXY_BYTECODE_HASH = keccak256(PROXY_BYTECODE); function deploy( bytes32 salt, bytes memory creationCode, uint256 value ) internal returns (address deployed) { bytes memory proxyChildBytecode = PROXY_BYTECODE; address proxy; /// @solidity memory-safe-assembly assembly { // Deploy a new contract with our pre-made bytecode via CREATE2. // We start 32 bytes into the code to avoid copying the byte length. proxy := create2(0, add(proxyChildBytecode, 32), mload(proxyChildBytecode), salt) } require(proxy != address(0), "DEPLOYMENT_FAILED"); deployed = getDeployed(salt); (bool success, ) = proxy.call{value: value}(creationCode); require(success && deployed.code.length != 0, "INITIALIZATION_FAILED"); } function getDeployed(bytes32 salt) internal view returns (address) { return getDeployed(salt, address(this)); } function getDeployed(bytes32 salt, address creator) internal pure returns (address) { address proxy = keccak256( abi.encodePacked( // Prefix: bytes1(0xFF), // Creator: creator, // Salt: salt, // Bytecode hash: PROXY_BYTECODE_HASH ) ).fromLast20Bytes(); return keccak256( abi.encodePacked( // 0xd6 = 0xc0 (short RLP prefix) + 0x16 (length of: 0x94 ++ proxy ++ 0x01) // 0x94 = 0x80 + 0x14 (0x14 = the length of an address, 20 bytes, in hex) hex"d6_94", proxy, hex"01" // Nonce of the proxy contract (1) ) ).fromLast20Bytes(); } }
{ "optimizer": { "enabled": true, "runs": 200 }, "evmVersion": "paris", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } }, "metadata": { "useLiteralContent": true } }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[{"internalType":"address","name":"_logic","type":"address"},{"internalType":"address","name":"initialOwner","type":"address"},{"internalType":"bytes","name":"_data","type":"bytes"}],"stateMutability":"payable","type":"constructor"},{"inputs":[{"internalType":"address","name":"target","type":"address"}],"name":"AddressEmptyCode","type":"error"},{"inputs":[{"internalType":"address","name":"admin","type":"address"}],"name":"ERC1967InvalidAdmin","type":"error"},{"inputs":[{"internalType":"address","name":"implementation","type":"address"}],"name":"ERC1967InvalidImplementation","type":"error"},{"inputs":[],"name":"ERC1967NonPayable","type":"error"},{"inputs":[],"name":"FailedInnerCall","type":"error"},{"inputs":[],"name":"ProxyDeniedAdminAccess","type":"error"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"previousAdmin","type":"address"},{"indexed":false,"internalType":"address","name":"newAdmin","type":"address"}],"name":"AdminChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"implementation","type":"address"}],"name":"Upgraded","type":"event"},{"stateMutability":"payable","type":"fallback"}]
Contract Creation Code
60a060405260405162000eb138038062000eb18339810160408190526200002691620003cd565b82816200003482826200009c565b505081604051620000459062000366565b6001600160a01b039091168152602001604051809103906000f08015801562000072573d6000803e3d6000fd5b506001600160a01b0316608052620000936200008d60805190565b62000102565b505050620004cb565b620000a78262000174565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a2805115620000f457620000ef8282620001f4565b505050565b620000fe62000271565b5050565b7f7e644d79422f17c01e4894b5f4f588d331ebfa28653d42ae832dc59e38c9798f6200014460008051602062000e91833981519152546001600160a01b031690565b604080516001600160a01b03928316815291841660208301520160405180910390a1620001718162000293565b50565b806001600160a01b03163b600003620001b057604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b807f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc5b80546001600160a01b0319166001600160a01b039290921691909117905550565b6060600080846001600160a01b031684604051620002139190620004ad565b600060405180830381855af49150503d806000811462000250576040519150601f19603f3d011682016040523d82523d6000602084013e62000255565b606091505b50909250905062000268858383620002d6565b95945050505050565b3415620002915760405163b398979f60e01b815260040160405180910390fd5b565b6001600160a01b038116620002bf57604051633173bdd160e11b815260006004820152602401620001a7565b8060008051602062000e91833981519152620001d3565b606082620002ef57620002e9826200033c565b62000335565b81511580156200030757506001600160a01b0384163b155b156200033257604051639996b31560e01b81526001600160a01b0385166004820152602401620001a7565b50805b9392505050565b8051156200034d5780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b610524806200096d83390190565b80516001600160a01b03811681146200038c57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b83811015620003c4578181015183820152602001620003aa565b50506000910152565b600080600060608486031215620003e357600080fd5b620003ee8462000374565b9250620003fe6020850162000374565b60408501519092506001600160401b03808211156200041c57600080fd5b818601915086601f8301126200043157600080fd5b81518181111562000446576200044662000391565b604051601f8201601f19908116603f0116810190838211818310171562000471576200047162000391565b816040528281528960208487010111156200048b57600080fd5b6200049e836020830160208801620003a7565b80955050505050509250925092565b60008251620004c1818460208701620003a7565b9190910192915050565b608051610487620004e66000396000601001526104876000f3fe608060405261000c61000e565b005b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316330361007b576000356001600160e01b03191663278f794360e11b14610071576040516334ad5dbb60e21b815260040160405180910390fd5b610079610083565b565b6100796100b2565b6000806100933660048184610312565b8101906100a09190610352565b915091506100ae82826100c2565b5050565b6100796100bd61011d565b610155565b6100cb82610179565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a28051156101155761011082826101f5565b505050565b6100ae61026b565b60006101507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b905090565b3660008037600080366000845af43d6000803e808015610174573d6000f35b3d6000fd5b806001600160a01b03163b6000036101b457604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060600080846001600160a01b0316846040516102129190610422565b600060405180830381855af49150503d806000811461024d576040519150601f19603f3d011682016040523d82523d6000602084013e610252565b606091505b509150915061026285838361028a565b95945050505050565b34156100795760405163b398979f60e01b815260040160405180910390fd5b60608261029f5761029a826102e9565b6102e2565b81511580156102b657506001600160a01b0384163b155b156102df57604051639996b31560e01b81526001600160a01b03851660048201526024016101ab565b50805b9392505050565b8051156102f95780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b6000808585111561032257600080fd5b8386111561032f57600080fd5b5050820193919092039150565b634e487b7160e01b600052604160045260246000fd5b6000806040838503121561036557600080fd5b82356001600160a01b038116811461037c57600080fd5b9150602083013567ffffffffffffffff8082111561039957600080fd5b818501915085601f8301126103ad57600080fd5b8135818111156103bf576103bf61033c565b604051601f8201601f19908116603f011681019083821181831017156103e7576103e761033c565b8160405282815288602084870101111561040057600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b6000825160005b818110156104435760208186018101518583015201610429565b50600092019182525091905056fea26469706673582212207c04fe3c3cef41d5f6d933f80ad4a80d11946f2012ee4851259e2a7b2f172dd964736f6c63430008180033608060405234801561001057600080fd5b5060405161052438038061052483398101604081905261002f916100be565b806001600160a01b03811661005e57604051631e4fbdf760e01b81526000600482015260240160405180910390fd5b6100678161006e565b50506100ee565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6000602082840312156100d057600080fd5b81516001600160a01b03811681146100e757600080fd5b9392505050565b610427806100fd6000396000f3fe60806040526004361061004a5760003560e01c8063715018a61461004f5780638da5cb5b146100665780639623609d14610093578063ad3cb1cc146100a6578063f2fde38b146100e4575b600080fd5b34801561005b57600080fd5b50610064610104565b005b34801561007257600080fd5b506000546040516001600160a01b0390911681526020015b60405180910390f35b6100646100a1366004610272565b610118565b3480156100b257600080fd5b506100d7604051806040016040528060058152602001640352e302e360dc1b81525081565b60405161008a919061038e565b3480156100f057600080fd5b506100646100ff3660046103a8565b610187565b61010c6101ca565b61011660006101f7565b565b6101206101ca565b60405163278f794360e11b81526001600160a01b03841690634f1ef28690349061015090869086906004016103c5565b6000604051808303818588803b15801561016957600080fd5b505af115801561017d573d6000803e3d6000fd5b5050505050505050565b61018f6101ca565b6001600160a01b0381166101be57604051631e4fbdf760e01b8152600060048201526024015b60405180910390fd5b6101c7816101f7565b50565b6000546001600160a01b031633146101165760405163118cdaa760e01b81523360048201526024016101b5565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6001600160a01b03811681146101c757600080fd5b634e487b7160e01b600052604160045260246000fd5b60008060006060848603121561028757600080fd5b833561029281610247565b925060208401356102a281610247565b9150604084013567ffffffffffffffff808211156102bf57600080fd5b818601915086601f8301126102d357600080fd5b8135818111156102e5576102e561025c565b604051601f8201601f19908116603f0116810190838211818310171561030d5761030d61025c565b8160405282815289602084870101111561032657600080fd5b8260208601602083013760006020848301015280955050505050509250925092565b6000815180845260005b8181101561036e57602081850181015186830182015201610352565b506000602082860101526020601f19601f83011685010191505092915050565b6020815260006103a16020830184610348565b9392505050565b6000602082840312156103ba57600080fd5b81356103a181610247565b6001600160a01b03831681526040602082018190526000906103e990830184610348565b94935050505056fea2646970667358221220fbb172d3650779ee368ff37e42257dffa11bfe6d620061350fa6488a5ad312b864736f6c63430008180033b53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103000000000000000000000000c832183d4d5fc5831daac892a93dbbfd798034e30000000000000000000000006676c650053f3f60d38530e717a80ed48435d070000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000846294c311000000000000000000000000dad58dfa5c1a7a34419afdbe1f0d610efeea95e400000000000000000000000000000000000000000000000000000000000003e80000000000000000000000006676c650053f3f60d38530e717a80ed48435d0700000000000000000000000006676c650053f3f60d38530e717a80ed48435d07000000000000000000000000000000000000000000000000000000000
Deployed Bytecode
0x608060405261000c61000e565b005b7f000000000000000000000000720f9608f37060dd1d762d23d11acd9c86971fe56001600160a01b0316330361007b576000356001600160e01b03191663278f794360e11b14610071576040516334ad5dbb60e21b815260040160405180910390fd5b610079610083565b565b6100796100b2565b6000806100933660048184610312565b8101906100a09190610352565b915091506100ae82826100c2565b5050565b6100796100bd61011d565b610155565b6100cb82610179565b6040516001600160a01b038316907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a28051156101155761011082826101f5565b505050565b6100ae61026b565b60006101507f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc546001600160a01b031690565b905090565b3660008037600080366000845af43d6000803e808015610174573d6000f35b3d6000fd5b806001600160a01b03163b6000036101b457604051634c9c8ce360e01b81526001600160a01b03821660048201526024015b60405180910390fd5b7f360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc80546001600160a01b0319166001600160a01b0392909216919091179055565b6060600080846001600160a01b0316846040516102129190610422565b600060405180830381855af49150503d806000811461024d576040519150601f19603f3d011682016040523d82523d6000602084013e610252565b606091505b509150915061026285838361028a565b95945050505050565b34156100795760405163b398979f60e01b815260040160405180910390fd5b60608261029f5761029a826102e9565b6102e2565b81511580156102b657506001600160a01b0384163b155b156102df57604051639996b31560e01b81526001600160a01b03851660048201526024016101ab565b50805b9392505050565b8051156102f95780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b6000808585111561032257600080fd5b8386111561032f57600080fd5b5050820193919092039150565b634e487b7160e01b600052604160045260246000fd5b6000806040838503121561036557600080fd5b82356001600160a01b038116811461037c57600080fd5b9150602083013567ffffffffffffffff8082111561039957600080fd5b818501915085601f8301126103ad57600080fd5b8135818111156103bf576103bf61033c565b604051601f8201601f19908116603f011681019083821181831017156103e7576103e761033c565b8160405282815288602084870101111561040057600080fd5b8260208601602083013760006020848301015280955050505050509250929050565b6000825160005b818110156104435760208186018101518583015201610429565b50600092019182525091905056fea26469706673582212207c04fe3c3cef41d5f6d933f80ad4a80d11946f2012ee4851259e2a7b2f172dd964736f6c63430008180033
Constructor Arguments (ABI-Encoded and is the last bytes of the Contract Creation Code above)
000000000000000000000000c832183d4d5fc5831daac892a93dbbfd798034e30000000000000000000000006676c650053f3f60d38530e717a80ed48435d070000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000846294c311000000000000000000000000dad58dfa5c1a7a34419afdbe1f0d610efeea95e400000000000000000000000000000000000000000000000000000000000003e80000000000000000000000006676c650053f3f60d38530e717a80ed48435d0700000000000000000000000006676c650053f3f60d38530e717a80ed48435d07000000000000000000000000000000000000000000000000000000000
-----Decoded View---------------
Arg [0] : _logic (address): 0xC832183d4d5fc5831daaC892a93dBBfd798034E3
Arg [1] : initialOwner (address): 0x6676c650053F3F60D38530E717A80ed48435d070
Arg [2] : _data (bytes): 0x6294c311000000000000000000000000dad58dfa5c1a7a34419afdbe1f0d610efeea95e400000000000000000000000000000000000000000000000000000000000003e80000000000000000000000006676c650053f3f60d38530e717a80ed48435d0700000000000000000000000006676c650053f3f60d38530e717a80ed48435d070
-----Encoded View---------------
9 Constructor Arguments found :
Arg [0] : 000000000000000000000000c832183d4d5fc5831daac892a93dbbfd798034e3
Arg [1] : 0000000000000000000000006676c650053f3f60d38530e717a80ed48435d070
Arg [2] : 0000000000000000000000000000000000000000000000000000000000000060
Arg [3] : 0000000000000000000000000000000000000000000000000000000000000084
Arg [4] : 6294c311000000000000000000000000dad58dfa5c1a7a34419afdbe1f0d610e
Arg [5] : feea95e400000000000000000000000000000000000000000000000000000000
Arg [6] : 000003e80000000000000000000000006676c650053f3f60d38530e717a80ed4
Arg [7] : 8435d0700000000000000000000000006676c650053f3f60d38530e717a80ed4
Arg [8] : 8435d07000000000000000000000000000000000000000000000000000000000
Deployed Bytecode Sourcemap
4145:2226:108:-:0;;;2649:11:105;:9;:11::i;:::-;4145:2226:108;5581:369;5426:6;-1:-1:-1;;;;;5642:27:108;:10;:27;5638:306;;5689:7;;-1:-1:-1;;;;;;5689:7:108;-1:-1:-1;;;5689:65:108;5685:201;;5781:24;;-1:-1:-1;;;5781:24:108;;;;;;;;;;;5685:201;5844:27;:25;:27::i;:::-;5581:369::o;5638:306::-;5916:17;:15;:17::i;6152:217::-;6208:25;;6267:12;:8;6276:1;6267:8;6208:25;6267:12;:::i;:::-;6256:42;;;;;;;:::i;:::-;6207:91;;;;6308:54;6338:17;6357:4;6308:29;:54::i;:::-;6197:172;;6152:217::o;2323:83:105:-;2371:28;2381:17;:15;:17::i;:::-;2371:9;:28::i;2779:335:104:-;2870:37;2889:17;2870:18;:37::i;:::-;2922:27;;-1:-1:-1;;;;;2922:27:104;;;;;;;;2964:11;;:15;2960:148;;2995:53;3024:17;3043:4;2995:28;:53::i;:::-;;6197:172:108;;6152:217::o;2960:148:104:-;3079:18;:16;:18::i;1581:132:103:-;1648:7;1674:32;1327:66:104;2035:53;-1:-1:-1;;;;;2035:53:104;;1957:138;1674:32:103;1667:39;;1581:132;:::o;949:895:105:-;1287:14;1284:1;1281;1268:34;1501:1;1498;1482:14;1479:1;1463:14;1456:5;1443:60;1577:16;1574:1;1571;1556:38;1615:6;1682:66;;;;1797:16;1794:1;1787:27;1682:66;1717:16;1714:1;1707:27;2186:281:104;2263:17;-1:-1:-1;;;;;2263:29:104;;2296:1;2263:34;2259:119;;2320:47;;-1:-1:-1;;;2320:47:104;;-1:-1:-1;;;;;1754:32:205;;2320:47:104;;;1736:51:205;1709:18;;2320:47:104;;;;;;;;2259:119;1327:66;2387:73;;-1:-1:-1;;;;;;2387:73:104;-1:-1:-1;;;;;2387:73:104;;;;;;;;;;2186:281::o;4106:253:122:-;4189:12;4214;4228:23;4255:6;-1:-1:-1;;;;;4255:19:122;4275:4;4255:25;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;4213:67;;;;4297:55;4324:6;4332:7;4341:10;4297:26;:55::i;:::-;4290:62;4106:253;-1:-1:-1;;;;;4106:253:122:o;6598:122:104:-;6648:9;:13;6644:70;;6684:19;;-1:-1:-1;;;6684:19:104;;;;;;;;;;;4625:582:122;4769:12;4798:7;4793:408;;4821:19;4829:10;4821:7;:19::i;:::-;4793:408;;;5045:17;;:22;:49;;;;-1:-1:-1;;;;;;5071:18:122;;;:23;5045:49;5041:119;;;5121:24;;-1:-1:-1;;;5121:24:122;;-1:-1:-1;;;;;1754:32:205;;5121:24:122;;;1736:51:205;1709:18;;5121:24:122;1590:203:205;5041:119:122;-1:-1:-1;5180:10:122;4793:408;4625:582;;;;;:::o;5743:516::-;5874:17;;:21;5870:383;;6102:10;6096:17;6158:15;6145:10;6141:2;6137:19;6130:44;5870:383;6225:17;;-1:-1:-1;;;6225:17:122;;;;;;;;;;;14:331:205;119:9;130;172:8;160:10;157:24;154:44;;;194:1;191;184:12;154:44;223:6;213:8;210:20;207:40;;;243:1;240;233:12;207:40;-1:-1:-1;;269:23:205;;;314:25;;;;;-1:-1:-1;14:331:205:o;350:127::-;411:10;406:3;402:20;399:1;392:31;442:4;439:1;432:15;466:4;463:1;456:15;482:1103;567:6;575;628:2;616:9;607:7;603:23;599:32;596:52;;;644:1;641;634:12;596:52;670:23;;-1:-1:-1;;;;;722:31:205;;712:42;;702:70;;768:1;765;758:12;702:70;791:5;-1:-1:-1;847:2:205;832:18;;819:32;870:18;900:14;;;897:34;;;927:1;924;917:12;897:34;965:6;954:9;950:22;940:32;;1010:7;1003:4;999:2;995:13;991:27;981:55;;1032:1;1029;1022:12;981:55;1068:2;1055:16;1090:2;1086;1083:10;1080:36;;;1096:18;;:::i;:::-;1171:2;1165:9;1139:2;1225:13;;-1:-1:-1;;1221:22:205;;;1245:2;1217:31;1213:40;1201:53;;;1269:18;;;1289:22;;;1266:46;1263:72;;;1315:18;;:::i;:::-;1355:10;1351:2;1344:22;1390:2;1382:6;1375:18;1430:7;1425:2;1420;1416;1412:11;1408:20;1405:33;1402:53;;;1451:1;1448;1441:12;1402:53;1507:2;1502;1498;1494:11;1489:2;1481:6;1477:15;1464:46;1552:1;1547:2;1542;1534:6;1530:15;1526:24;1519:35;1573:6;1563:16;;;;;;;482:1103;;;;;:::o;1798:412::-;1927:3;1965:6;1959:13;1990:1;2000:129;2014:6;2011:1;2008:13;2000:129;;;2112:4;2096:14;;;2092:25;;2086:32;2073:11;;;2066:53;2029:12;2000:129;;;-1:-1:-1;2184:1:205;2148:16;;2173:13;;;-1:-1:-1;2148:16:205;1798:412;-1:-1:-1;1798:412:205:o
Swarm Source
ipfs://fbb172d3650779ee368ff37e42257dffa11bfe6d620061350fa6488a5ad312b8
[ Download: CSV Export ]
[ Download: CSV Export ]
A token is a representation of an on-chain or off-chain asset. The token page shows information such as price, total supply, holders, transfers and social links. Learn more about this page in our Knowledge Base.