Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xe2ce6a9F4813A70c01ff862C02530C687d531e93
Balance 0 ETH
Nonce 1
Code Size 7113 bytes
Last Active
Indexed Transactions 1 (24,460,12224,460,122)
Gas Used (indexed) 114,542
External Etherscan · Sourcify

Contract Bytecode

7113 bytes
0x608080604052600436101561001357600080fd5b600090813560e01c908163146ca531146113b45750806317c4de35146113445780631b5c56001461131e5780633394e86f1461096d578063350580ea146108835780634154e9251461080f57806342cde4e8146107e757806343c184b0146107c95780634a7acd83146107a25780636e16014f14610784578063715018a61461071457806373e66cf5146106d057806379ba5097146106285780637ecebe00146105f057806384b0196e146104b157806386c1ff681461040b5780638da5cb5b146103e55780638f2d2aee14610397578063c36e9bea14610349578063d8bff5a514610311578063e30c3978146102ea578063ee04cd241461026d578063f0232d0a1461024f578063f2fde38b146101d8578063f4ab9adf1461017c5763f9643c041461013f57600080fd5b3461017957806003193601126101795760206040517f86f3f3b2f2d44d88b37dcc943aa8f35251495d6d41abbcfc14d2491329bc8dc38152f35b80fd5b5034610179576020366003190112610179576001600160a01b0361019e6113dd565b6101a66114da565b166101b081611a98565b507fa636f4a11e2d3ba7f89d042ecb0a6b886716e98cd49d8fd876ee0f73bced42b88280a280f35b5034610179576020366003190112610179576101f26113dd565b6101fa6114da565b6001600160a01b03809116908173ffffffffffffffffffffffffffffffffffffffff1960015416176001558254167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e227008380a380f35b50346101795780600319360112610179576020600b54604051908152f35b50346101795760203660031901126101795760043565ffffffffffff81168091036102e65761029a6114da565b600181106102b55765ffffffffffff19600c541617600c5580f35b602490604051907fc2ac01980000000000000000000000000000000000000000000000000000000082526004820152fd5b5080fd5b503461017957806003193601126101795760206001600160a01b0360015416604051908152f35b50346101795760203660031901126101795760406020916001600160a01b036103386113dd565b168152600a83522054604051908152f35b5034610179576020366003190112610179577f2bf3a0c0ead867e8a35e395cd20afcbd246e8b23fcad4520bf437548ba34c4be60206004356103896114da565b80600d55604051908152a180f35b5034610179576020366003190112610179577f91c8f3fd4ad69ea6a579e6e009ed2af628735d4ae7ea9d2752e400ab7930e11760206004356103d76114da565b80600755604051908152a180f35b50346101795780600319360112610179576001600160a01b036020915416604051908152f35b5034610179576020366003190112610179576001600160a01b0361042d6113dd565b6104356114da565b1661043f816119ab565b50808252600a6020526040822054610479575b7fa14a79af012d1756818f9bd59ccfc9ad185a71df86b9392d9059d9e6faf6d6448280a280f35b600b54801561049d5760001901600b55808252600a60205260006040832055610452565b602483634e487b7160e01b81526011600452fd5b50346101795780600319360112610179576104eb7f4e6176557064617465720000000000000000000000000000000000000000000a61178f565b906105157f312e302e300000000000000000000000000000000000000000000000000000056118d3565b9060405190602090602083019383851067ffffffffffffffff8611176105da5792849260206105908896610582986040528585526040519889987f0f000000000000000000000000000000000000000000000000000000000000008a5260e0858b015260e08a01906113f8565b9088820360408a01526113f8565b924660608801523060808801528460a088015286840360c088015251928381520193925b8281106105c357505050500390f35b8351855286955093810193928101926001016105b4565b634e487b7160e01b600052604160045260246000fd5b50346101795760203660031901126101795760406020916001600160a01b036106176113dd565b168152600483522054604051908152f35b50346101795780600319360112610179576001546001600160a01b0333818316036106a05773ffffffffffffffffffffffffffffffffffffffff198092166001556000549133908316176000553391167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a380f35b60246040517f118cdaa7000000000000000000000000000000000000000000000000000000008152336004820152fd5b503461017957806003193601126101795760206040516001600160a01b037f000000000000000000000000c314b8637b05a294ae9d9c29300d5f667c748bad168152f35b503461017957806003193601126101795761072d6114da565b60006001600160a01b0373ffffffffffffffffffffffffffffffffffffffff19806001541660015582549081168355167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b50346101795780600319360112610179576020600d54604051908152f35b503461017957806003193601126101795760206001600160a01b0360095416604051908152f35b50346101795780600319360112610179576020600754604051908152f35b5034610179578060031936011261017957602067ffffffffffffffff60085416604051908152f35b5034610179576020366003190112610179576004356001600160a01b0381168091036102e65761083d6114da565b8073ffffffffffffffffffffffffffffffffffffffff1960095416176009557f3308b9900606ee9c819f2790e08e5d12cf2b2f4b967d8f49786567ee8ac523238280a280f35b5034610179578060031936011261017957600580546108a1816114c2565b926108af6040519485611484565b8184526108bb826114c2565b6020938585019391601f1901368537825b82811061091d5750505060405193838594850191818652518092526040850193925b8281106108fd57505050500390f35b83516001600160a01b0316855286955093810193928101926001016108ee565b61092b819795969497611742565b90549086518310156109595760031b1c6001600160a01b031681831b860185015293959294936001016108cc565b602489634e487b7160e01b81526032600452fd5b50346101795760a0366003190112610179576109876113dd565b6024356001600160a01b0381168103610f495767ffffffffffffffff6064351660643503610f495767ffffffffffffffff60843511610f4957366023608435011215610f495767ffffffffffffffff6084356004013511610f495736602460843560040135608435010111610f49576001600160a01b038216835260066020526040832054156112f4576001600160a01b037f000000000000000000000000c314b8637b05a294ae9d9c29300d5f667c748bad166001600160a01b038216036112925760443515801561126e575b61123c5767ffffffffffffffff60085460401c168067ffffffffffffffff60643516036111f95750610b8c6042610b95926001600160a01b0385168652600460205260408620805490600182019055604051906001600160a01b0360208301937f86f3f3b2f2d44d88b37dcc943aa8f35251495d6d41abbcfc14d2491329bc8dc38552166040830152604435606083015267ffffffffffffffff60643516608083015260a082015260a08152610b0a8161144c565b519020610b156114ee565b90604051917f190100000000000000000000000000000000000000000000000000000000000083526002830152602282015220610b57608435600401356114a6565b90610b656040519283611484565b60843560048101358084529060240160208401378560206084356004013584010152611608565b90929192611644565b6001600160a01b038083169116036111cf576001600160a01b0381168252600a6020526040822054156111b8575b6001600160a01b0381168252600a60205260443560408320557fe105ba82d5ab62952997f7283bfbb3447c28777284ef38f5efeb42f3c3f505f96001600160a01b0360405192169180610c326064356044358390929167ffffffffffffffff6020916040840195845216910152565b0390a2600b5460085467ffffffffffffffff8116821015610c51578280f35b6005548392600019918490815b81811061114b575050811561113757049267ffffffffffffffff91610c8291611735565b9160401c169060075481106000146110fb57506001600160a01b036009541665ffffffffffff6040517fd84a70a30000000000000000000000000000000000000000000000000000000081526001600160a01b037f000000000000000000000000c314b8637b05a294ae9d9c29300d5f667c748bad1660048201528142166024820152604081604481865afa8691816110b5575b50610fa9575090503d15610fa2573d610d2e816114a6565b90610d3c6040519283611484565b81523d85602083013e5b602081805181010312610f9e5760208101517fffffffff000000000000000000000000000000000000000000000000000000008116809103610f9a577f80fc84740000000000000000000000000000000000000000000000000000000003610f58575083906001600160a01b036009541690610dc681600c541642611712565b1690803b15610f4957604051636dd0e0d360e01b81527f000000000000000000000000c314b8637b05a294ae9d9c29300d5f667c748bad6001600160a01b031660048201526024810186905265ffffffffffff92909216604483015282908290606490829084905af18015610f4d57610f35575b50505b60085467ffffffffffffffff8160401c1667ffffffffffffffff8114610f21576fffffffffffffffff000000000000000060017fffffffffffffffffffffffffffffffff0000000000000000ffffffffffffffff920160401b1691161760085582600b55825b600554811015610edd57806001600160a01b03610ec1600193611742565b90549060031b1c168552600a6020526000604086205501610ea3565b506040805192835267ffffffffffffffff9190911660208301527f3f0dbda102b25f9171f7c00ceaf1f4d33590f96c54613ab7a5a08141f1cb528b91a15b38808280f35b602485634e487b7160e01b81526011600452fd5b610f3e90611438565b610f49578238610e3a565b8280fd5b6040513d84823e3d90fd5b610f96906040519182917f08c379a00000000000000000000000000000000000000000000000000000000083526020600484015260248301906113f8565b0390fd5b8580fd5b8480fd5b6060610d46565b84818111156110a75790610fbc91611735565b600d548082116110705750509081610fd98693600c541642611712565b16813b15610f4957604051636dd0e0d360e01b81527f000000000000000000000000c314b8637b05a294ae9d9c29300d5f667c748bad6001600160a01b031660048201526024810186905265ffffffffffff91909116604482015291908290606490829084905af1801561106557611052575b50610e3d565b61105e90939193611438565b913861104c565b6040513d86823e3d90fd5b60449250604051917f9b338fe800000000000000000000000000000000000000000000000000000000835260048301526024820152fd5b6110b091611735565b610fbc565b9091506040813d6040116110f3575b816110d160409383611484565b810103126110ef5760208151910151838116036110ef579038610d16565b8680fd5b3d91506110c4565b916060917f7a2f5c19a69cfa66e805a7af5d201df38ea927b0061be0cb15b7217af94531869360405192835260208301526040820152a1610f1b565b602486634e487b7160e01b81526012600452fd5b6001600160a01b0361115c82611742565b90549060031b1c168852600a60205260408820549283156111ae578361118191611712565b928581106111a6575b87811161119d575b506001905b01610c5e565b96506001611192565b94508461118a565b9250600190611197565b600b54600019811461049d57600101600b55610bc3565b60046040517f8baa579f000000000000000000000000000000000000000000000000000000008152fd5b604490604051907f2341ec20000000000000000000000000000000000000000000000000000000008252600482015267ffffffffffffffff606435166024820152fd5b60246040517f21bf4f800000000000000000000000000000000000000000000000000000000081526044356004820152fd5b50780100000000000000000000000000000000000000000000000060443511610a55565b6044906001600160a01b03604051917ffd9271e8000000000000000000000000000000000000000000000000000000008352817f000000000000000000000000c314b8637b05a294ae9d9c29300d5f667c748bad166004840152166024820152fd5b60046040517f8ba2d958000000000000000000000000000000000000000000000000000000008152fd5b5034610179578060031936011261017957602065ffffffffffff600c5416604051908152f35b50346101795760203660031901126101795760043567ffffffffffffffff81168091036102e65760207f8ec0f9701c6f540597310d23ddd952a203d0532c49b652e60b09cb01fb69ff50916113976114da565b8067ffffffffffffffff196008541617600855604051908152a180f35b9050346102e657816003193601126102e65760209067ffffffffffffffff60085460401c168152f35b600435906001600160a01b03821682036113f357565b600080fd5b919082519283825260005b848110611424575050826000602080949584010152601f8019910116010190565b602081830181015184830182015201611403565b67ffffffffffffffff81116105da57604052565b60c0810190811067ffffffffffffffff8211176105da57604052565b6040810190811067ffffffffffffffff8211176105da57604052565b90601f8019910116810190811067ffffffffffffffff8211176105da57604052565b67ffffffffffffffff81116105da57601f01601f191660200190565b67ffffffffffffffff81116105da5760051b60200190565b6001600160a01b036000541633036106a057565b6001600160a01b037f000000000000000000000000e2ce6a9f4813a70c01ff862c02530c687d531e93163014806115df575b15611549577ffbd1df453899fab4ff13f324f3a97876456e35498cdd359923bba7a7718e875490565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f0b043fda80e76945229995162c5d94e77bd48504ac435f0487333f837e2e43ab60408201527f06c015bd22b4c69690933c1058878ebdfef31f9aaae40bbe86d8a09fe1b2972c60608201524660808201523060a082015260a081526115d98161144c565b51902090565b507f00000000000000000000000000000000000000000000000000000000000000014614611520565b81519190604183036116395761163292506020820151906060604084015193015160001a90611b03565b9192909190565b505060009160029190565b60048110156116fc5780611656575050565b600181036116885760046040517ff645eedf000000000000000000000000000000000000000000000000000000008152fd5b600281036116c157602482604051907ffce698f70000000000000000000000000000000000000000000000000000000082526004820152fd5b6003146116cb5750565b602490604051907fd78bce0c0000000000000000000000000000000000000000000000000000000082526004820152fd5b634e487b7160e01b600052602160045260246000fd5b9190820180921161171f57565b634e487b7160e01b600052601160045260246000fd5b9190820391821161171f57565b6005548110156117795760056000527f036b6384b5eca791c62761152d0c79bb0604c104a5fb6f4eb0703f3154bb3db00190600090565b634e487b7160e01b600052603260045260246000fd5b60ff81146117e55760ff811690601f82116117bb57604051916117b183611468565b8252602082015290565b60046040517fb3512b0c000000000000000000000000000000000000000000000000000000008152fd5b5060405160006002549060018260011c90600184169384156118c9575b60209485841081146118b557838752869493929181156118955750600114611836575b505061183392500382611484565b90565b9093915060026000527f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace936000915b81831061187d57505061183393508201013880611825565b85548784018501529485019486945091830191611865565b91505061183394925060ff191682840152151560051b8201013880611825565b602485634e487b7160e01b81526022600452fd5b91607f1691611802565b60ff81146118f55760ff811690601f82116117bb57604051916117b183611468565b5060405160006003549060018260011c90600184169384156119a1575b60209485841081146118b55783875286949392918115611895575060011461194257505061183392500382611484565b9093915060036000527fc2575a0e9e593c00f959f8c92f12db2869c3395a3b0502d05e2516446f71f85b936000915b81831061198957505061183393508201013880611825565b85548784018501529485019486945091830191611971565b91607f1691611912565b6000818152600660205260408120549091908015611a935760001990808201818111610f215760055490838201918211611a7f57818103611a34575b5050506005548015611a20578101906119ff82611742565b909182549160031b1b19169055600555815260066020526040812055600190565b602484634e487b7160e01b81526031600452fd5b611a69611a43611a5293611742565b90549060031b1c928392611742565b819391549060031b91821b91600019901b19161790565b90558452600660205260408420553880806119e7565b602486634e487b7160e01b81526011600452fd5b505090565b600081815260066020526040812054611afe5760055468010000000000000000811015611aea579082611ad6611a5284600160409601600555611742565b905560055492815260066020522055600190565b602482634e487b7160e01b81526041600452fd5b905090565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411611b8757926020929160ff608095604051948552168484015260408301526060820152600092839182805260015afa15611b7b5780516001600160a01b03811615611b7257918190565b50809160019190565b604051903d90823e3d90fd5b5050506000916003919056fea26469706673582212201de6d26da01e91bfb9cc727d536a6b1bcc02ff0850f601a06f3a35ba3f2e8ea064736f6c63430008180033

Verified Source Code Full Match

Compiler: v0.8.24+commit.e11b9ed9 EVM: paris Optimization: Yes (1000 runs)
Ownable.sol 100 lines
// 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);
    }
}
Ownable2Step.sol 59 lines
// 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);
    }
}
IERC5267.sol 28 lines
// 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
        );
}
Context.sol 28 lines
// 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;
    }
}
ECDSA.sol 174 lines
// 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);
        }
    }
}
EIP712.sol 160 lines
// 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);
    }
}
MessageHashUtils.sol 86 lines
// 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)
        }
    }
}
Math.sol 415 lines
// 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;
    }
}
SignedMath.sol 43 lines
// 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);
        }
    }
}
Nonces.sol 46 lines
// 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);
        }
    }
}
ShortStrings.sol 123 lines
// 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;
        }
    }
}
StorageSlot.sol 135 lines
// 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
        }
    }
}
Strings.sol 94 lines
// 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));
    }
}
EnumerableSet.sol 378 lines
// 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;
    }
}
IVaultNav.sol 28 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

interface IVaultNav {
    event NavUpdated(address indexed lsd, uint256 nav, uint256 timestamp);
    event SetNavUpdater(address indexed lsd, address updater);

    error NavNotFound(uint48 _timestamp);
    error InvalidNavUpdater(address updater);
    error NavInvalidValue(uint256 nav);
    error TimestampTooLarge();
    error InvalidUpdatePeriod();
    error NavUpdateInvalidTimestamp();

    function appendNav(address lsd, uint256 nav, uint48 timestamp) external;
    function setNavUpdater(address lsd, address updater) external;
    function getNavByTimestamp(
        address vaultType,
        uint48 timestamp
    ) external view returns (uint256 nav, uint48 updateTime);

    function lsdToTokenE18AtTime(address _lsd, uint256 _amount, uint48 _timestamp) external view returns (uint256);
    function tokenE18ToLsdAtTime(
        address _lsd,
        uint256 _tokenAmountE18,
        uint48 _timestamp
    ) external view returns (uint256);
}
NavUpdater.sol 323 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

import { Ownable2Step } from "@openzeppelin/contracts/access/Ownable2Step.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { EIP712 } from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import { Nonces } from "@openzeppelin/contracts/utils/Nonces.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import { IVaultNav } from "../IVaultNav.sol";

/// @title NavUpdater
/// @notice This contract manages the updating of NAV (Net Asset Value) for LSD tokens
/// @dev Implements a multi-signature mechanism for NAV updates
contract NavUpdater is Ownable2Step, EIP712, Nonces {
    using EnumerableSet for EnumerableSet.AddressSet;

    /// @dev The EIP-712 typehash for the UpdateNav function
    bytes32 public constant UPDATE_NAV_TYPEHASH =
        keccak256("UpdateNav(address lsd,uint256 nav,uint64 roundID,uint256 nonce)");

    /// @notice The address of the LSD token for which this contract updates the NAV
    address public immutable LSD;

    /// @dev Set of addresses eligible to vote on NAV values
    EnumerableSet.AddressSet private _voters;

    /// @notice The maximum allowed difference between the highest and lowest NAV values from voters
    uint256 public maxNavDiff;

    /// @notice The minimum number of voters required to update the NAV value
    uint64 public threshold;

    /// @notice The current voting round ID
    uint64 public round;

    /// @notice The VaultNav contract interface
    IVaultNav public vaultNav;

    /// @notice Mapping of voter addresses to their submitted NAV values for the current round
    mapping(address voter => uint256 nav) public votes;

    /// @notice The number of voters who have submitted votes for the current round
    uint256 public votedCount;

    /// @notice The effective delay for updating the NAV.
    uint48 public effectiveDelay;

    /// @notice The maximum allowed difference between NAV values per round.
    uint256 public maxPerRoundNavDiff;

    /// @notice Emitted when the VaultNav address is updated
    event VaultNavUpdated(address indexed newVaultNav);

    /// @notice Emitted when a new voter is added
    event VoterAdded(address indexed voter);

    /// @notice Emitted when a voter is removed
    event VoterRemoved(address indexed voter);

    /// @notice Emitted when the maximum NAV difference is updated
    event MaxNavDiffUpdated(uint256 newMaxNavDiff);

    /// @notice Emitted when the voting threshold is updated
    event ThresholdUpdated(uint64 newThreshold);

    /// @notice Emitted when a new NAV vote is submitted
    event NavVoteSubmitted(address indexed voter, uint256 nav, uint64 round);

    /// @notice Emitted when the NAV is updated
    event NavUpdated(uint256 newNav, uint64 round);

    /// @notice Emitted when the NAV update fails
    event NavUpdateFailed(uint256 nav, uint256 navDiff, uint64 round);

    /// @notice Emitted when the maximum allowed difference between NAV values per round is updated
    event MaxPerRoundNavDiffUpdated(uint256 newMaxPerRoundNavDiff);

    /// @dev Thrown when the provided signature is invalid
    error InvalidSignature();

    /// @dev Thrown when an invalid signer attempts to vote
    error InvalidVoter();

    /// @dev Thrown when an invalid voting round is provided
    /// @param expected The expected round number
    /// @param got The provided round number
    error InvalidVoteRound(uint64 expected, uint64 got);

    /// @dev Thrown when an invalid LSD address is provided
    /// @param expected The expected LSD address
    /// @param got The provided LSD address
    error InvalidLSD(address expected, address got);

    /// @dev Thrown when an invalid NAV value is provided
    /// @param nav The invalid NAV value
    error InvalidNav(uint256 nav);

    /// @dev Thrown when an invalid effective delay is provided, e.g. less than 1 second.
    error InvalidEffectiveDelay(uint48 delay);

    /// @dev Thrown when the NAV difference is out of range of maxPerRoundNavDiff.
    error NavDiffIsOutOfRange(uint256 diff, uint256 maxDiff);

    /// @notice Initializes the NavUpdater contract
    /// @param _owner The address of the contract owner
    /// @param _signers An array of initial voter addresses
    /// @param _vaultNav The address of the VaultNav contract
    /// @param _lsd The address of the LSD token
    /// @param _maxNavDiff The maximum allowed difference between NAV votes
    /// @param _threshold The minimum number of votes required to update the NAV
    constructor(
        address _owner, // solhint-disable-line no-unused-vars
        address[] memory _signers,
        IVaultNav _vaultNav,
        address _lsd,
        uint256 _maxNavDiff,
        uint64 _threshold,
        uint48 _effectiveDelay,
        uint256 _maxPerRoundNavDiff
    ) Ownable(_owner) EIP712("NavUpdater", "1.0.0") {
        for (uint256 i = 0; i < _signers.length; i++) {
            _voters.add(_signers[i]);
        }
        vaultNav = _vaultNav;
        LSD = _lsd;
        maxNavDiff = _maxNavDiff;
        threshold = _threshold;
        effectiveDelay = _effectiveDelay;
        maxPerRoundNavDiff = _maxPerRoundNavDiff;
    }

    /// @notice Sets a new VaultNav contract address
    /// @param _vaultNavAddress The address of the new VaultNav contract
    function setVaultNav(IVaultNav _vaultNavAddress) external onlyOwner {
        vaultNav = _vaultNavAddress;
        emit VaultNavUpdated(address(_vaultNavAddress));
    }

    /// @notice Adds a new voter
    /// @param _voter The address of the new voter
    function addVoter(address _voter) external onlyOwner {
        _voters.add(_voter);
        emit VoterAdded(_voter);
    }

    /// @notice Removes a voter
    /// @param _voter The address of the voter to remove
    function removeVoter(address _voter) external onlyOwner {
        _voters.remove(_voter);
        // remove votes if the voter has voted for this round.
        if (votes[_voter] != 0) {
            votedCount--;
            delete votes[_voter];
        }
        emit VoterRemoved(_voter);
    }

    /// @notice Sets the maximum allowed difference between NAV votes
    /// @param _maxNavDiff The new maximum NAV difference
    function setMaxNavDiff(uint256 _maxNavDiff) external onlyOwner {
        maxNavDiff = _maxNavDiff;
        emit MaxNavDiffUpdated(_maxNavDiff);
    }

    /// @notice Sets the minimum number of votes required to update the NAV
    /// @param _threshold The new threshold value
    function setThreshold(uint64 _threshold) external onlyOwner {
        threshold = _threshold;
        emit ThresholdUpdated(_threshold);
    }

    /// @notice Sets the effective delay for updating the NAV
    /// @param _effectiveDelay The new effective delay value
    function setEffectiveDelay(uint48 _effectiveDelay) external onlyOwner {
        if (_effectiveDelay < 1) {
            revert InvalidEffectiveDelay(_effectiveDelay);
        }
        effectiveDelay = _effectiveDelay;
    }

    /// @notice Sets the maximum allowed difference between NAV values per round, the diff
    /// is computed from abs((new_nav * 1e18 / old_nav) - 1e18).
    /// @dev Emits a `MaxPerRoundNavDiffUpdated` event
    /// @param _maxPerRoundNavDiff The new maximum allowed difference
    function setMaxPerRoundNavDiff(uint256 _maxPerRoundNavDiff) external onlyOwner {
        maxPerRoundNavDiff = _maxPerRoundNavDiff;
        emit MaxPerRoundNavDiffUpdated(_maxPerRoundNavDiff);
    }

    /// @notice Submits a NAV update vote and try to update the NAV if the threshold is reached.
    /// In general, we trust signers to submit valid NAV values, so we just need to make sure
    /// that if they made any mistake, like voted for too large or too small value),
    /// they will be able to correct it by sending another vote.
    /// In the worst case, owner can always remove the signer from the list.
    /// @param _signer The address of the signer
    /// @param _lsd The address of the LSD token
    /// @param _nav The proposed NAV value
    /// @param _round The current voting round
    /// @param _signature The signature of the voter
    function updateNav(address _signer, address _lsd, uint256 _nav, uint64 _round, bytes calldata _signature) external {
        if (!_voters.contains(_signer)) {
            revert InvalidVoter();
        }
        if (_lsd != LSD) {
            revert InvalidLSD(LSD, _lsd);
        }
        // prevent _nav overflow during summation and zero value
        if (_nav == 0 || _nav > 2 ** 192) {
            revert InvalidNav(_nav);
        }
        if (_round != round) {
            revert InvalidVoteRound(round, _round);
        }

        // verify the signature
        bytes32 hash = _hashTypedDataV4(
            keccak256(abi.encode(UPDATE_NAV_TYPEHASH, _lsd, _nav, _round, _useNonce(_signer)))
        );
        if (ECDSA.recover(hash, _signature) != _signer) {
            revert InvalidSignature();
        }

        // update vote
        if (votes[_signer] == 0) {
            // A new vote
            votedCount++;
        }
        votes[_signer] = _nav;
        emit NavVoteSubmitted(_signer, _nav, _round);

        // try to update the NAV, if possible
        _tryUpdateNav();
    }

    /// @notice Returns the list of voters
    function voters() external view returns (address[] memory) {
        address[] memory voters_ = new address[](_voters.length());
        for (uint256 i = 0; i < _voters.length(); i++) {
            voters_[i] = _voters.at(i);
        }
        return voters_;
    }

    /// @notice Tries to update the NAV if the threshold is reached
    /// and the NAV difference is within the limit.
    function _tryUpdateNav() private {
        if (votedCount >= threshold) {
            (uint256 newNav, uint256 maxDiff) = _calculateAverageNav();
            uint64 _round = round;
            if (maxDiff < maxNavDiff) {
                _updateNav(newNav);
                _completeRound();
                emit NavUpdated(newNav, _round);
            } else {
                emit NavUpdateFailed(newNav, maxDiff, _round);
            }
        }
    }

    /// @dev Updates the NAV value in the VaultNav contract
    /// @param _nav The new NAV value to set
    function _updateNav(uint256 _nav) private {
        try vaultNav.getNavByTimestamp(LSD, uint48(block.timestamp)) returns (uint256 lastNav, uint48 updateTime) {
            uint256 valueDiff = 0;
            if (_nav > lastNav) {
                valueDiff = _nav - lastNav;
            } else {
                valueDiff = lastNav - _nav;
            }
            if (valueDiff > maxPerRoundNavDiff) {
                revert NavDiffIsOutOfRange(valueDiff, maxPerRoundNavDiff);
            }
            vaultNav.appendNav(LSD, _nav, uint48(block.timestamp + effectiveDelay));
        } catch (bytes memory reason) {
            bytes4 errorSelector = abi.decode(reason, (bytes4));

            // if the NAV is not found, append the new NAV directly
            // normally this only happens when a new vault is created
            if (errorSelector == IVaultNav.NavNotFound.selector) {
                vaultNav.appendNav(LSD, _nav, uint48(block.timestamp + effectiveDelay));
            } else {
                revert(string(reason));
            }
        }
    }

    /// @dev Completes the current voting round and prepares for the next
    function _completeRound() private {
        round++;
        votedCount = 0;
        for (uint256 i = 0; i < _voters.length(); i++) {
            delete votes[_voters.at(i)];
        }
    }

    /// @notice Calculates the average NAV and the maximum difference between NAV votes
    /// @dev This function iterates through all votes, calculates the sum, and finds the min and max NAV values
    /// @return _nav The calculated average NAV
    /// @return _maxDiff The difference between the highest and lowest NAV votes
    function _calculateAverageNav() private view returns (uint256 _nav, uint256 _maxDiff) {
        uint256 sum = 0;
        uint256 minNav = type(uint256).max;
        uint256 maxNav = 0;

        for (uint256 i = 0; i < _voters.length(); i++) {
            address voter = _voters.at(i);
            uint256 nav = votes[voter];
            // Skip voters that did not submit a vote in this round
            if (nav == 0) {
                continue;
            }
            sum += nav;
            if (nav < minNav) {
                minNav = nav;
            }
            if (nav > maxNav) {
                maxNav = nav;
            }
        }
        return (sum / votedCount, maxNav - minNav);
    }
}

Read Contract

LSD 0x73e66cf5 → address
UPDATE_NAV_TYPEHASH 0xf9643c04 → bytes32
effectiveDelay 0x1b5c5600 → uint48
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
maxNavDiff 0x43c184b0 → uint256
maxPerRoundNavDiff 0x6e16014f → uint256
nonces 0x7ecebe00 → uint256
owner 0x8da5cb5b → address
pendingOwner 0xe30c3978 → address
round 0x146ca531 → uint64
threshold 0x42cde4e8 → uint64
vaultNav 0x4a7acd83 → address
votedCount 0xf0232d0a → uint256
voters 0x350580ea → address[]
votes 0xd8bff5a5 → uint256

Write Contract 11 functions

These functions modify contract state and require a wallet transaction to execute.

acceptOwnership 0x79ba5097
No parameters
addVoter 0xf4ab9adf
address _voter
removeVoter 0x86c1ff68
address _voter
renounceOwnership 0x715018a6
No parameters
setEffectiveDelay 0xee04cd24
uint48 _effectiveDelay
setMaxNavDiff 0x8f2d2aee
uint256 _maxNavDiff
setMaxPerRoundNavDiff 0xc36e9bea
uint256 _maxPerRoundNavDiff
setThreshold 0x17c4de35
uint64 _threshold
setVaultNav 0x4154e925
address _vaultNavAddress
transferOwnership 0xf2fde38b
address newOwner
updateNav 0x3394e86f
address _signer
address _lsd
uint256 _nav
uint64 _round
bytes _signature

Top Interactions

AddressTxnsSentReceived
0xdD4F3294...7a98 1 1

Recent Transactions

CSV
|
Hash Method Block Age From/To Value Txn Fee Type
0x767d7e63...6f70a3 0x3394e86f 24,460,122 IN 0xdD4F3294...7a98 0 ETH 0.000006475641 ETH Legacy