More Info
Private Name Tags
ContractCreator
Transaction Hash |
Method
|
Block
|
From
|
To
|
|||||
---|---|---|---|---|---|---|---|---|---|
Latest 25 internal transactions (View All)
Advanced mode:
Parent Transaction Hash | Block | From | To | |||
---|---|---|---|---|---|---|
327392980 | 5 days ago | 0.00025723 ETH | ||||
327383278 | 5 days ago | 0.00030435 ETH | ||||
327241381 | 5 days ago | 0.00022535 ETH | ||||
322404954 | 19 days ago | 0.00020825 ETH | ||||
321163309 | 23 days ago | 0.00020695 ETH | ||||
314041029 | 44 days ago | 0.00018821 ETH | ||||
314039722 | 44 days ago | 0.00018521 ETH | ||||
314039609 | 44 days ago | 0.00018221 ETH | ||||
314032237 | 44 days ago | 0.00066055 ETH | ||||
314025736 | 44 days ago | 0.00019248 ETH | ||||
314025445 | 44 days ago | 0.00021048 ETH | ||||
314023070 | 44 days ago | 0.00025347 ETH | ||||
314021438 | 44 days ago | 0.0004486 ETH | ||||
314021238 | 44 days ago | 0.00036779 ETH | ||||
314019688 | 44 days ago | 0.00018214 ETH | ||||
314019617 | 44 days ago | 0.00018214 ETH | ||||
314019540 | 44 days ago | 0.00018214 ETH | ||||
314018575 | 44 days ago | 0.00018214 ETH | ||||
314017451 | 44 days ago | 0.00018547 ETH | ||||
314016536 | 44 days ago | 0.00018547 ETH | ||||
314016271 | 44 days ago | 0.00018213 ETH | ||||
314016021 | 44 days ago | 0.00018213 ETH | ||||
314015957 | 44 days ago | 0.00018213 ETH | ||||
314015825 | 44 days ago | 0.00018213 ETH | ||||
314014292 | 44 days ago | 0.00019344 ETH |
Loading...
Loading
Contract Source Code Verified (Exact Match)
Contract Name:
AnimeClaimer
Compiler Version
v0.8.24+commit.e11b9ed9
Optimization Enabled:
Yes with 200 runs
Other Settings:
cancun EvmVersion
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; import {OAppRead} from "@layerzerolabs/oapp-evm/contracts/oapp/OAppRead.sol"; import {OAppOptionsType3} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OAppOptionsType3.sol"; import {MessagingFee, Origin} from "@layerzerolabs/oapp-evm/contracts/oapp/OApp.sol"; import {MessagingReceipt} from "@layerzerolabs/oapp-evm/contracts/oapp/OAppSender.sol"; import {OptionsBuilder} from "@layerzerolabs/oapp-evm/contracts/oapp/libs/OptionsBuilder.sol"; import { ReadCodecV1, EVMCallRequestV1 } from "@layerzerolabs/oapp-evm/contracts/oapp/libs/ReadCodecV1.sol"; import {FixedPointMathLib as Math} from "solady/src/utils/FixedPointMathLib.sol"; import {Bitmap} from "solady/src/utils/g/LibBitmap.sol"; import {ReentrancyGuardTransient} from "solady/src/utils/ReentrancyGuardTransient.sol"; import {EfficientHashLib} from "solady/src/utils/EfficientHashLib.sol"; import {SafeCastLib} from "solady/src/utils/SafeCastLib.sol"; import {ECDSA} from "solady/src/utils/ECDSA.sol"; import {MerkleProofLib} from "solady/src/utils/MerkleProofLib.sol"; import {SafeTransferLib} from "solady/src/utils/SafeTransferLib.sol"; import {AddressCast} from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/AddressCast.sol"; import {ClaimChecker} from "./ClaimChecker.sol"; /// @notice Anime claimer contract. contract AnimeClaimer is OAppRead, OAppOptionsType3, ReentrancyGuardTransient { using OptionsBuilder for bytes; /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* STRUCTS */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev Used for doing a vesting claim. struct VestingConfig { // The NFT collection. address nft; // The token ID of in the NFT collection. // If the `uuid` is non-zero, the `tokenId` used in the Merkle leaf will be zero. uint256 tokenId; // For cases where the token ID has not been assigned when the Merkle tree is constructed // (i.e. elementals). Leave it as `bytes32(0)` if not required. // This should be unique per `(nft, tokenId)` pair. // If this is not `bytes32(0)`, the signature will be used to verify that the signer // has approved `keccak256(abi.encode(uuid, nft, tokenId))`. bytes32 uuid; // The collector's address. // If this vesting config is used to represent the tokens for a collector, // the `nft` and `tokenId` should not be set. address collector; // For multiple streams or seasons. // If there's no need for multiple streams, just leave this as zero, always. uint8 streamId; // Start timestamp of the vesting. uint256 start; // End timestamp of the vesting. uint256 end; // Amount of tokens allocated for the vesting. uint256 allocation; // To prove that there is a leaf representing the config in the Merkle tree. bytes32[] proof; // To verify that the `uuid` is mapped to `(nft, tokenId)`. // Ignored if `uuid` is `bytes32(0)`. bytes signature; } /// @dev For storing the vesting config for loading in `_claimBatch`. Only 2 SSTOREs. struct VestingConfigStorage { address nft; uint24 tokenId; uint8 streamId; uint32 start; uint32 end; address collector; uint96 allocation; } /// @dev Query result to be used in back and front end. struct VestingInfo { // Amount of tokens that has been withdrawn. uint256 withdrawn; // Amount of tokens that has been vested. uint256 vested; } /// @dev Vesting state in storage. struct VestingState { // Amount of tokens that has been withdrawn. uint256 withdrawn; } /// @dev Parameters for the claim L1 check. struct ClaimL1CheckParameters { uint256[] packedNFTIds; // `uint256(uint160(nft)) | (id << 160)`. address[] collectors; uint256 numNFTs; uint256 numCollectors; } /// @dev Parameters for the claim submitted on L2. struct ClaimParameters { address claimer; uint64 claimTimestamp; uint32 numConfigs; mapping(uint256 => VestingConfigStorage) configs; } /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* STORAGE */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ struct AnimeClaimerStorage { // [CONFIG] The address authorized to set the anime token, // LZ gas/calldata params, pause/unpause, and daily withdraw limit. // MUST be configured. address manager; // [CONFIG] The maximum amount of token withdrawable across all accounts in a single day. // MUST be configured before claims. uint96 dailyTotalWithdrawnLimit; // [CONFIG] Whether the contract is paused. Starts paused. // MUST be unpaused before claims. bool paused; // [CONFIG] How old a claim request can be for it to still be executed. // MUST be configured before claims. uint32 claimRequestExecutionWindow; // [CONFIG] The expected amount of base gas required for the token release on L2. // Defaults to a reasonable, over-compensated setting of 400k. // Any extra overallocated is returned to the sender anyways. // MUST be non-zero for claims. MAY be reconfigured. uint32 expectedBaseGasRequired; // [CONFIG] The expected amount of gas required for the token release on L2 // for each NFT / collector. // Defaults to a reasonable, over-compensated setting of 100k. // Any extra overallocated is returned to the sender anyways. // MUST be non-zero for claims. MAY be reconfigured. uint32 expectedUnitGasRequired; // [CONFIG] The expected amount of calldata size for the token release on L2. // Defaults to a reasonable, over-compensated setting of 128. // MUST be non-zero for claims. MAY be reconfigured. uint32 expectedCalldataSize; // [STATE] The current claim nonce. uint48 claimNonce; // [STATE] The last withdrawn unix day, for emergency guard. uint32 lastWithdrawnDay; // [STATE] Total amount of token withdrawn on `lastWithdrawnDay`. uint96 dailyTotalWithdrawn; // [CONFIG] The address of the private key used to sign // `keccak256(abi.encode(uuid, nft, tokenId))`. // MUST be configured. address uuidSigner; // [STATE] Mapping of `keccak256(abi.encode(nft, tokenId, collector, streamId))` // to the vesting state. mapping(bytes32 => VestingState) vestingStates; // [STATE] Mapping of a `(nft, tokenId)` pair to the `uuid` of a vesting config, // or NO_UUID_SENTINEL if there's no uuid for the nft. mapping(address => mapping(uint256 => bytes32)) nftToUUID; // [STATE] Mapping of a uuid to the packed NFT ID. // Packed NFT ID: `uint256(uint160(nft)) | (id << 160)` mapping(bytes32 => uint256) uuidToPackedNftID; // [CONFIG] The vesting Merkle root. // MUST be configured before claims. bytes32 vestingRoot; // [CONFIG] Address of the anime token. // MUST be unpaused before claims. address animeToken; // [STATE] Mapping of request ID to claim parameters. mapping(uint256 => ClaimParameters) claimParameters; // [STATE] A bitmap of used claim nonces. Bitmap usedNonces; // [CONFIG] The address of the claim checker contract. // MUST be configured. address claimChecker; // [CONFIG] The LayerZero read channel. // DEFAULTS To 4294967295. // MUST be configured. uint32 lzReadChannel; // [CONFIG] The number of confirmations to wait for lzRead. // DEFAULTS To 3. // MUST be configured. uint16 lzReadConfirmations; // [CONFIG] The maximum number of configs that can be claimed in a single request. // DEFAULTS To 50. // MUST be configured. uint8 maxConfigsPerRequest; } function _getAnimeClaimerStorage() internal pure returns (AnimeClaimerStorage storage $) { /// @solidity memory-safe-assembly assembly { // `uint72(bytes9(keccak256("ANIME_CLAIMER_STORAGE")))`. $.slot := 0x62dc72c6d15e6284df // Truncate to 9 bytes to reduce bytecode size. } } /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* EVENTS */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev `amount` of Anime has been released to `to`. event Released(uint256 indexed claimNonce, address indexed to, uint256 amount); /// @dev Emitted when any state changing admin function has been accessed. event AdminAccessed(address indexed caller, bytes msgData); /// @dev Emitted when a vesting has been withdrawn. event VestWithdrawn( address indexed nft, uint256 indexed tokenId, address indexed collector, uint256 streamId, uint256 amount ); /// @dev Emitted when daily total withdrawn limit was reached. event DailyTotalWithdrawnLimitReached(); /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* CUSTOM ERRORS */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev Cannot be performed when the contract is paused. error Paused(); /// @dev The vesting config must have one of `nft` and `collector` as a non-zero address. error InvalidVestingConfig(); /// @dev The `(nft, tokenId)` in the config must match the existing `(nft, tokenId)` for the uuid. /// Also, the `uuid` in the config must match the existing `uuid` for the `(nft, tokenId)` pair. error InvalidNftTokenIdUuidLink(); /// @dev The current chain ID is not supported. error UnsupportedChainId(); /// @dev The Merkle proof provided is invalid. error InvalidProof(); /// @dev The ECDSA signature provided is invalid. error InvalidSignature(); /// @dev For safety guardrails. error ExceedDailyTotalWithdrawnLimit(); /// @dev Not authorized to call the function. error Unauthorized(); /// @dev Cannot send tokens to the zero address. error ToIsZeroAddress(); /// @dev Contract is not ready for claim. error NotReadyForClaim(); /// @dev The UUID signer is the zero address. error UUIDSignerZeroAddress(); /// @dev The nonce has already been used. error NonceAlreadyUsed(); /// @dev The claim request is too old. error ClaimRequestTooOld(); /// @dev The number of configs in the request exceeds the maximum. error MaxConfigsPerRequestExceeded(); /// @dev Zero configs passed in for claim. error ZeroConfigs(); /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* CONSTANTS */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev For Arbitrum. address internal constant _LZ_ENDPOINT = 0x1a44076050125825900e736c501f859c50fE728c; /// @dev For Arbitrum Sepolia. address internal constant _LZ_TESTNET_ENDPOINT = 0x6EDCE65403992e310A62460808c4b910D972f10f; /// @dev See: https://chainlist.org/chain/42161 uint256 internal constant _CHAIN_ID_ARBITRUM = 42161; /// @dev See: https://chainlist.org/chain/421614 uint256 internal constant _CHAIN_ID_ARBITRUM_SEPOLIA = 421614; /// @dev See: https://docs.layerzero.network/v2/developers/evm/technical-reference/deployed-contracts uint32 internal constant _LZ_EID_ETHEREUM = 30101; /// @dev See: https://docs.layerzero.network/v2/developers/evm/technical-reference/deployed-contracts uint32 internal constant _LZ_EID_SEPOLIA = 40161; /// @dev Used to track in nftToUUID storage, for when an nft-level VestingConfig has no UUID. // UUIDs only use the lower 128 bits, so this will not clash with an actual uuid. bytes32 constant NO_UUID_SENTINEL = bytes32(uint256(1) << 128); /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* CONSTRUCTOR */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ constructor() OAppRead(_lzEndpoint(), msg.sender) Ownable(msg.sender) { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); $.paused = true; $.claimRequestExecutionWindow = 1 hours; $.expectedBaseGasRequired = 400000; $.expectedUnitGasRequired = 100000; $.expectedCalldataSize = 128; $.lzReadChannel = 4294967295; $.lzReadConfirmations = 3; $.maxConfigsPerRequest = 50; _setPeer($.lzReadChannel, AddressCast.toBytes32(address(this))); } /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* INITIATING CLAIM */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev Initiates a claim request, which will be fulfilled via `_lzReceive`. function requestClaim(VestingConfig[] calldata configs) public payable nonReentrant returns (MessagingReceipt memory) { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); if (!readyForClaim()) revert NotReadyForClaim(); if ($.paused) revert Paused(); if (configs.length > $.maxConfigsPerRequest) revert MaxConfigsPerRequestExceeded(); if (configs.length == 0) revert ZeroConfigs(); _validateRequestClaim(configs); ClaimL1CheckParameters memory checks = _getClaimChecksFromVestingConfigs(configs); uint256 claimNonce = $.claimNonce++; _saveClaimParameters(claimNonce, configs); return _lzSend( $.lzReadChannel, _getCmd(claimNonce, checks.packedNFTIds, checks.collectors, $.claimChecker), _lzOptions(configs.length), MessagingFee(msg.value, 0), payable(msg.sender) ); } /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* CLAIM RELEASE */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev Allows a user to claim a batch. function _claimBatch(uint256 claimNonce) internal { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); (VestingConfig[] memory configs, address claimer, uint64 claimTimestamp) = _loadClaimParameters(claimNonce); if (claimer == address(0)) revert ToIsZeroAddress(); // Just in case. if ($.paused) revert Paused(); if ($.usedNonces.get(claimNonce)) revert NonceAlreadyUsed(); if (claimTimestamp < block.timestamp - $.claimRequestExecutionWindow) { revert ClaimRequestTooOld(); } $.usedNonces.set(claimNonce); _resetDailyTotalWithdrawnIfNewDay(); if ($.dailyTotalWithdrawnLimit <= $.dailyTotalWithdrawn) { revert ExceedDailyTotalWithdrawnLimit(); } uint256 totalWithdrawn; uint256 dailyRemainder = $.dailyTotalWithdrawnLimit - $.dailyTotalWithdrawn; for (uint256 i; i < configs.length; ++i) { VestingConfig memory c = configs[i]; VestingState storage s = _getVestingState(c.nft, c.tokenId, c.collector, c.streamId); // The amount to withdraw is capped by the remaining daily limit. uint256 withdrawAmount = Math.min(_vested(c, claimTimestamp) - uint256(s.withdrawn), dailyRemainder - totalWithdrawn); totalWithdrawn += withdrawAmount; s.withdrawn += withdrawAmount; emit VestWithdrawn(c.nft, c.tokenId, c.collector, c.streamId, withdrawAmount); if (totalWithdrawn == dailyRemainder) { emit DailyTotalWithdrawnLimitReached(); break; } } if (totalWithdrawn != 0) { _incrementDailyTotalWithdrawn(totalWithdrawn); SafeTransferLib.safeTransfer($.animeToken, claimer, totalWithdrawn); emit Released(claimNonce, claimer, totalWithdrawn); } } /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* LAYERZERO FUNCTIONS */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev Constructs the read command to call the `checkClaims` function. function _getCmd( uint256 claimNonce, uint256[] memory packedNFTIds, address[] memory collectors, address targetContractAddress ) internal view returns (bytes memory) { // Create an array of EVMCallRequestV1 with a single read request EVMCallRequestV1[] memory readRequests = new EVMCallRequestV1[](1); readRequests[0] = EVMCallRequestV1({ appRequestLabel: 1, // Application-specific label for tracking. targetEid: _lzDstEid(), // Endpoint ID of the target chain. isBlockNum: false, // Use timestamp instead of block number. blockNumOrTimestamp: uint64(block.timestamp), // Timestamp to read the state at. confirmations: _getAnimeClaimerStorage().lzReadConfirmations, // Number of confirmations to wait for finality. to: targetContractAddress, // Address of the contract to call. callData: abi.encodeCall( ClaimChecker.checkClaims, (claimNonce, msg.sender, packedNFTIds, collectors, _isContract(msg.sender)) ) }); // No compute logic needed; encode the command with appLabel 0 return ReadCodecV1.encode(0, readRequests); } /// @dev For LayerZero to fulfill the release. function _lzReceive( Origin calldata, /*origin*/ bytes32, /*guid*/ bytes calldata payload, address, /*executor*/ bytes calldata /*extraData*/ ) internal override { (uint256 claimNonce, bool authorized) = abi.decode(payload, (uint256, bool)); if (!authorized) revert Unauthorized(); _claimBatch(claimNonce); } /// @dev Returns the LayerZero options. function _lzOptions(uint256 numConfigs) internal view returns (bytes memory) { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); uint256 gasRequired = $.expectedBaseGasRequired + numConfigs * $.expectedUnitGasRequired; return OptionsBuilder.newOptions().addExecutorLzReadOption( uint32(gasRequired), // Gas limit for the L2 `_lzReceive`. uint32($.expectedCalldataSize), // Calldata size of what's returned. 0 // `msg.value`. Zero as we are not funding any contract on ethereum. ); } /// @dev Returns the amount of ETH in wei that needs to be passed into `requestForClaim`. function quoteForClaim(VestingConfig[] calldata configs) public view returns (uint256) { ClaimL1CheckParameters memory checks = _getClaimChecksFromVestingConfigs(configs); return quoteForClaim(checks.numNFTs, checks.numCollectors); } /// @dev Returns the amount of ETH in wei that needs to be passed into `requestForClaim`. function quoteForClaim(uint256 numNFTAllos, uint256 numCollectorAllos) public view returns (uint256) { uint256[] memory nfts = new uint256[](numNFTAllos); address[] memory collectors = new address[](numCollectorAllos); return _quoteForClaim(uint160(address(this)), nfts, collectors); } /// @dev Returns the amount of ETH in wei needed for the LayerZero read. function _quoteForClaim( uint256 claimNonce, uint256[] memory packedNFTIds, address[] memory collectors ) internal view returns (uint256) { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); bytes memory cmd = _getCmd(claimNonce, packedNFTIds, collectors, $.claimChecker); bool payInLzToken = false; bytes memory options = _lzOptions(packedNFTIds.length + collectors.length); return _quote($.lzReadChannel, cmd, options, payInLzToken).nativeFee; } /// @dev Returns the LayerZero endpoint. function _lzEndpoint() internal view returns (address) { if (block.chainid == _CHAIN_ID_ARBITRUM) return _LZ_ENDPOINT; if (block.chainid == _CHAIN_ID_ARBITRUM_SEPOLIA) return _LZ_TESTNET_ENDPOINT; revert UnsupportedChainId(); } /// @dev Returns the LayerZero destination EID. function _lzDstEid() internal view returns (uint32) { if (block.chainid == _CHAIN_ID_ARBITRUM) return _LZ_EID_ETHEREUM; if (block.chainid == _CHAIN_ID_ARBITRUM_SEPOLIA) return _LZ_EID_SEPOLIA; revert UnsupportedChainId(); } /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* PUBLIC VIEW FUNCTIONS */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev Returns whether the contract has been correctly set up for claim. function readyForClaim() public view returns (bool) { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); if ($.manager == address(0)) return false; if ($.claimRequestExecutionWindow == 0) return false; if ($.dailyTotalWithdrawnLimit == 0) return false; if ($.expectedBaseGasRequired == 0) return false; if ($.expectedUnitGasRequired == 0) return false; if ($.expectedCalldataSize == 0) return false; if ($.vestingRoot == bytes32(0)) return false; if ($.animeToken == address(0)) return false; if ($.claimChecker == address(0)) return false; if ($.uuidSigner == address(0)) return false; if ($.lzReadChannel == 0) return false; if ($.lzReadConfirmations == 0) return false; if ($.maxConfigsPerRequest == 0) return false; return true; } /// @dev Returns a list of vesting infos. Assumes all vesting configs are valid. function vestingInfos(VestingConfig[] calldata configs) public view returns (VestingInfo[] memory infos) { infos = new VestingInfo[](configs.length); for (uint256 i; i < configs.length; ++i) { VestingConfig calldata c = configs[i]; VestingState storage s = _getVestingState(c.nft, c.tokenId, c.collector, c.streamId); infos[i].vested = _vested(c, block.timestamp); infos[i].withdrawn = s.withdrawn; } } function validateVestingConfig(VestingConfig calldata c, bytes32 root) public pure { // Validate the proof. bytes32 hash = EfficientHashLib.hash( uint160(c.nft), (c.uuid != bytes32(0) ? uint256(0) : c.tokenId), uint256(c.uuid), uint160(c.collector), c.streamId, c.start, c.end, c.allocation ); if (!MerkleProofLib.verifyCalldata(c.proof, root, hash)) { revert InvalidProof(); } } /// @dev Returns the `block.timestamp`. function currentTimestamp() public view returns (uint256) { return block.timestamp; } /// @dev Returns if `claimNonce` has been claimed. function nonceIsUsed(uint256 claimNonce) public view returns (bool) { return _getAnimeClaimerStorage().usedNonces.get(claimNonce); } /// @dev Returns the vesting Merkle root. function vestingRoot() public view returns (bytes32) { return _getAnimeClaimerStorage().vestingRoot; } /// @dev Returns the current claim nonce. function currentClaimNonce() public view returns (uint256) { return _getAnimeClaimerStorage().claimNonce; } /// @dev Returns the expected amount of base gas required. function expectedBaseGasRequired() public view returns (uint256) { return _getAnimeClaimerStorage().expectedBaseGasRequired; } /// @dev Returns the expected amount of gas required for each NFT / collector. function expectedUnitGasRequired() public view returns (uint256) { return _getAnimeClaimerStorage().expectedUnitGasRequired; } /// @dev Returns the expected calldata size for the token release on L2. function expectedCalldataSize() public view returns (uint256) { return _getAnimeClaimerStorage().expectedCalldataSize; } /// @dev Returns the maximum amount that can be withdrawn across all accounts in a single day. function dailyTotalWithdrawnLimit() public view returns (uint256) { return _getAnimeClaimerStorage().dailyTotalWithdrawnLimit; } /// @dev Returns the amount that has been withdrawn across all accounts in a single day. function dailyTotalWithdrawn() public view returns (uint256) { return _getAnimeClaimerStorage().dailyTotalWithdrawn; } /// @dev Returns the account authorized to set the anime token, expected L2 gas, and pause/unpause. function manager() public view returns (address) { return _getAnimeClaimerStorage().manager; } /// @dev Returns the address of the private key used to sign `keccak256(abi.encode(uuid, nft, tokenId))`. function uuidSigner() public view returns (address) { return _getAnimeClaimerStorage().uuidSigner; } /// @dev Returns whether the contract is paused. function isPaused() public view returns (bool) { return _getAnimeClaimerStorage().paused; } /// @dev Returns the Anime token address. function animeToken() public view returns (address) { return _getAnimeClaimerStorage().animeToken; } /// @dev Returns the address of the claim checker contract. function claimChecker() public view returns (address) { return _getAnimeClaimerStorage().claimChecker; } /// @dev Returns the LayerZero read channel. function lzReadChannel() public view returns (uint32) { return _getAnimeClaimerStorage().lzReadChannel; } /// @dev Returns the number of confirmations required for the LayerZero read. function lzReadConfirmations() public view returns (uint16) { return _getAnimeClaimerStorage().lzReadConfirmations; } /// @dev Returns the maximum number of configs that can be claimed in a single request. function maxConfigsPerRequest() public view returns (uint8) { return _getAnimeClaimerStorage().maxConfigsPerRequest; } /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* ADMIN FUNCTIONS */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev Sets the amount of gas required to peform the token claim. function setExpectedBaseGasRequired(uint256 required) public onlyOwnerOrManager { _logAdminAccess(); _getAnimeClaimerStorage().expectedBaseGasRequired = SafeCastLib.toUint32(required); } /// @dev Sets the amount of gas required to peform the token claim for each NFT / collector. function setExpectedUnitGasRequired(uint256 required) public onlyOwnerOrManager { _logAdminAccess(); _getAnimeClaimerStorage().expectedUnitGasRequired = SafeCastLib.toUint32(required); } /// @dev Sets the expected calldata size for the token release on L2. function setExpectedCalldataSize(uint256 size) public onlyOwnerOrManager { _logAdminAccess(); _getAnimeClaimerStorage().expectedCalldataSize = SafeCastLib.toUint32(size); } /// @dev Sets the paused status. function setPaused(bool paused) public onlyOwnerOrManager { if (!paused) { if (!readyForClaim()) revert NotReadyForClaim(); } _logAdminAccess(); _getAnimeClaimerStorage().paused = paused; } /// @dev Sets an alternate account authorized to perform a subset of admin functions. function setManager(address _manager) public onlyOwnerOrManager { _logAdminAccess(); _getAnimeClaimerStorage().manager = _manager; } /// @dev MUST be called before unpausing. function setAnimeToken(address token) public onlyOwnerOrManager { _logAdminAccess(); _getAnimeClaimerStorage().animeToken = token; } /// @dev Sets the claim request execution window. function setClaimRequestExecutionWindow(uint32 window) public onlyOwner { _logAdminAccess(); _getAnimeClaimerStorage().claimRequestExecutionWindow = window; } /// @dev Sets the Merkle root for the vesting configs. function setVestingRoot(bytes32 root) public onlyOwner { _logAdminAccess(); _getAnimeClaimerStorage().vestingRoot = root; } /// @dev Sets the maximum amount that can be withdrawn across all accounts in a single day. function setDailyTotalWithdrawnLimit(uint256 limit) public onlyOwner { _logAdminAccess(); _getAnimeClaimerStorage().dailyTotalWithdrawnLimit = SafeCastLib.toUint96(limit); } /// @dev Sets the UUID signer. function setUUIDSigner(address signer) public onlyOwner { if (signer == address(0)) revert UUIDSignerZeroAddress(); _logAdminAccess(); _getAnimeClaimerStorage().uuidSigner = signer; } /// @dev Sets the (nft, tokenId) pair to UUID mapping in case a /// previous mapping needs to be corrected. function setNFTToUUID(address nft, uint256 tokenId, bytes32 uuid) public onlyOwner { _logAdminAccess(); _getAnimeClaimerStorage().nftToUUID[nft][tokenId] = uuid; } /// @dev Sets the UUID to (nft, tokenId) pair mapping in case a /// previous mapping needs to be corrected. function setUUIDToPackedNftID(bytes32 uuid, address nft, uint256 tokenId) public onlyOwner { _logAdminAccess(); _getAnimeClaimerStorage().uuidToPackedNftID[uuid] = _packedNftID(nft, tokenId); } /// @dev Sets the address of the claim checker contract. function setClaimChecker(address newClaimChecker) public onlyOwner { _logAdminAccess(); _getAnimeClaimerStorage().claimChecker = newClaimChecker; } /// @dev Withdraws ETH in the contract. function withdrawETH(address to, uint256 amount) public onlyOwner { _logAdminAccess(); if (to == address(0)) revert ToIsZeroAddress(); SafeTransferLib.safeTransferETH(to, amount); } /// @dev Withdraws ERC20 in the contract. function withdrawERC20(address token, address to, uint256 amount) public onlyOwner { _logAdminAccess(); if (to == address(0)) revert ToIsZeroAddress(); SafeTransferLib.safeTransfer(token, to, amount); } /// @dev Sets the LayerZero read channel. function setReadChannel(uint32 channelId, bool active) public override onlyOwner { _logAdminAccess(); AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); _setPeer(channelId, active ? AddressCast.toBytes32(address(this)) : bytes32(0)); if (active) $.lzReadChannel = channelId; } /// @dev Sets the LayerZero read confirmations. function setReadConfirmations(uint16 confirmations) public onlyOwner { _logAdminAccess(); AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); $.lzReadConfirmations = confirmations; } /// @dev Sets the maximum number of configs that can be claimed in a single request. function setMaxConfigsPerRequest(uint8 _maxConfigsPerRequest) public onlyOwnerOrManager { _logAdminAccess(); AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); $.maxConfigsPerRequest = _maxConfigsPerRequest; } /*«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-«-*/ /* INTERNAL HELPERS */ /*-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»-»*/ /// @dev Guards a function so that it can be called by only either the owner /// or the manager account. modifier onlyOwnerOrManager() { if (msg.sender != owner()) { if (msg.sender != _getAnimeClaimerStorage().manager) revert Unauthorized(); } _; } /// @dev Validates Merkle proofs and signatures for an array of vesting configs function _validateRequestClaim(VestingConfig[] calldata configs) internal { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); bytes32 root = $.vestingRoot; for (uint256 i; i < configs.length; ++i) { VestingConfig calldata c = configs[i]; validateVestingConfig(c, root); bool isForNFT = c.nft != address(0); // If the `uuid` is set, then we must validate the signature. if (c.uuid != bytes32(0)) { // The `uuid` parameter can only be set if the config is for a NFT. if (!isForNFT) revert InvalidVestingConfig(); // Equivalent to `keccak256(abi.encode(c.uuid, c.nft, c.tokenId))`. bytes32 hash = EfficientHashLib.hash(uint256(c.uuid), uint160(c.nft), c.tokenId); hash = ECDSA.toEthSignedMessageHash(hash); // `recoverCalldata` will revert if the recovered address is `address(0)`. if (ECDSA.recoverCalldata(hash, c.signature) != $.uuidSigner) revert InvalidSignature(); // Commit the uuid to a specific (nft, tokenId) pair. // This additional store is to prevent a malicious actor from // claiming for a specific uuid with multiple tokenIds if the uuid signer is compromised. uint256 packedNftID = _packedNftID(c.nft, c.tokenId); if ($.uuidToPackedNftID[c.uuid] != 0) { if ($.uuidToPackedNftID[c.uuid] != packedNftID) revert InvalidNftTokenIdUuidLink(); } else { $.uuidToPackedNftID[c.uuid] = packedNftID; } } if (isForNFT) { // If the `(nft, tokenId)` pair has already been claimed, // then this claim's uuid info must match its uuid info from a previous claim. // This additional store is to prevent a malicious actor from // claiming for multiple `uuid`s // for the same `(nft, tokenId)` pair in case uuid signer is compromised. bytes32 uuidInfoForConfig = (c.uuid != bytes32(0)) ? c.uuid : NO_UUID_SENTINEL; if ($.nftToUUID[c.nft][c.tokenId] != bytes32(0)) { if ($.nftToUUID[c.nft][c.tokenId] != uuidInfoForConfig) revert InvalidNftTokenIdUuidLink(); } else { $.nftToUUID[c.nft][c.tokenId] = uuidInfoForConfig; } } } } /// @dev Saves the claim parameters. function _saveClaimParameters(uint256 claimNonce, VestingConfig[] calldata configs) internal { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); ClaimParameters storage claimParameters = $.claimParameters[claimNonce]; claimParameters.claimer = msg.sender; claimParameters.numConfigs = SafeCastLib.toUint32(configs.length); claimParameters.claimTimestamp = uint64(block.timestamp); for (uint256 i; i < configs.length; ++i) { // Exclude the proofs, uuids, signatures, since they've already been checked. VestingConfigStorage storage dst = claimParameters.configs[i]; VestingConfig calldata src = configs[i]; dst.nft = src.nft; dst.tokenId = SafeCastLib.toUint24(src.tokenId); dst.streamId = SafeCastLib.toUint8(src.streamId); dst.start = SafeCastLib.toUint32(src.start); dst.end = SafeCastLib.toUint32(src.end); dst.collector = src.collector; dst.allocation = SafeCastLib.toUint96(src.allocation); } } /// @dev Loads the claim parameters. function _loadClaimParameters(uint256 claimNonce) internal view returns (VestingConfig[] memory, address, uint64) { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); ClaimParameters storage claimParameters = $.claimParameters[claimNonce]; address to = claimParameters.claimer; uint64 claimTimestamp = claimParameters.claimTimestamp; VestingConfig[] memory configs = new VestingConfig[](claimParameters.numConfigs); for (uint256 i; i < configs.length; ++i) { VestingConfigStorage storage src = claimParameters.configs[i]; VestingConfig memory dst = configs[i]; dst.nft = src.nft; dst.tokenId = src.tokenId; dst.streamId = src.streamId; dst.start = src.start; dst.end = src.end; dst.collector = src.collector; dst.allocation = src.allocation; } return (configs, to, claimTimestamp); } /// @dev Returns the L1 claim checks from the vesting configs. function _getClaimChecksFromVestingConfigs(VestingConfig[] calldata configs) internal pure returns (ClaimL1CheckParameters memory) { uint256 numNFTs; uint256 numCollectors; for (uint256 i; i < configs.length; ++i) { VestingConfig calldata c = configs[i]; bool isForCollector = c.collector != address(0); bool isForNFT = c.nft != address(0); if (isForCollector == isForNFT) revert InvalidVestingConfig(); if (isForCollector) numCollectors++; if (isForNFT) numNFTs++; } ClaimL1CheckParameters memory checks; checks.packedNFTIds = new uint256[](numNFTs); checks.collectors = new address[](numCollectors); for (uint256 i; i < configs.length; ++i) { VestingConfig calldata c = configs[i]; bool isForCollector = c.collector != address(0); bool isForNFT = c.nft != address(0); if (isForCollector) { checks.collectors[checks.numCollectors++] = c.collector; } if (isForNFT) { checks.packedNFTIds[checks.numNFTs++] = _packedNftID(c.nft, c.tokenId); } } return checks; } /// @dev Returns a storage pointer to a vesting state. function _getVestingState(address nft, uint256 tokenId, address collector, uint256 streamId) internal view returns (VestingState storage) { // Equivalent to `keccak256(abi.encode(nft, tokenId, collector, streamId))`. bytes32 hash = EfficientHashLib.hash(uint160(nft), tokenId, uint160(collector), streamId); return _getAnimeClaimerStorage().vestingStates[hash]; } /// @dev Returns the amount of Anime tokens that has been vested by a certain timestamp. function _vested(VestingConfig memory c, uint256 timestamp) internal pure returns (uint256) { uint256 start = c.start; uint256 end = c.end; uint256 duration = end - start; uint256 allocation = c.allocation; if (timestamp <= start) return 0; if (timestamp >= end) return allocation; // Linear interpolation formula for linear vesting. return allocation * (timestamp - start) / duration; } /// @dev Increments the total withdrawn across all accounts /// in a day. /// Total daily withdrawn should never exceed the limit, /// because we cap the amount that can be withdrawn in `_claimBatch`. function _incrementDailyTotalWithdrawn(uint256 amount) internal { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); uint256 total = $.dailyTotalWithdrawn + amount; $.dailyTotalWithdrawn = SafeCastLib.toUint96(total); } /// @dev Checks if the daily total withdrawn limit has been reached. function _resetDailyTotalWithdrawnIfNewDay() internal { AnimeClaimerStorage storage $ = _getAnimeClaimerStorage(); uint256 currentDay = block.timestamp / 86400; if (currentDay != $.lastWithdrawnDay) { $.lastWithdrawnDay = uint32(currentDay); $.dailyTotalWithdrawn = 0; } } /// @dev Logs admin access. function _logAdminAccess() internal { emit AdminAccessed(msg.sender, msg.data); } /// @dev Imperfect check on whether address is a smart contract. function _isContract(address addr) internal view returns (bool) { if (tx.origin != msg.sender) return true; uint256 codeSize; assembly { codeSize := extcodesize(addr) } return codeSize > 0; } /// @dev Packs an NFT address and token ID into a single uint256. function _packedNftID(address nft, uint256 tokenId) internal pure returns (uint256) { return uint256(uint160(nft)) | (tokenId << 160); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol"; library ExecutorOptions { using CalldataBytesLib for bytes; uint8 internal constant WORKER_ID = 1; uint8 internal constant OPTION_TYPE_LZRECEIVE = 1; uint8 internal constant OPTION_TYPE_NATIVE_DROP = 2; uint8 internal constant OPTION_TYPE_LZCOMPOSE = 3; uint8 internal constant OPTION_TYPE_ORDERED_EXECUTION = 4; uint8 internal constant OPTION_TYPE_LZREAD = 5; error Executor_InvalidLzReceiveOption(); error Executor_InvalidNativeDropOption(); error Executor_InvalidLzComposeOption(); error Executor_InvalidLzReadOption(); /// @dev decode the next executor option from the options starting from the specified cursor /// @param _options [executor_id][executor_option][executor_id][executor_option]... /// executor_option = [option_size][option_type][option] /// option_size = len(option_type) + len(option) /// executor_id: uint8, option_size: uint16, option_type: uint8, option: bytes /// @param _cursor the cursor to start decoding from /// @return optionType the type of the option /// @return option the option of the executor /// @return cursor the cursor to start decoding the next executor option function nextExecutorOption( bytes calldata _options, uint256 _cursor ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) { unchecked { // skip worker id cursor = _cursor + 1; // read option size uint16 size = _options.toU16(cursor); cursor += 2; // read option type optionType = _options.toU8(cursor); // startCursor and endCursor are used to slice the option from _options uint256 startCursor = cursor + 1; // skip option type uint256 endCursor = cursor + size; option = _options[startCursor:endCursor]; cursor += size; } } function decodeLzReceiveOption(bytes calldata _option) internal pure returns (uint128 gas, uint128 value) { if (_option.length != 16 && _option.length != 32) revert Executor_InvalidLzReceiveOption(); gas = _option.toU128(0); value = _option.length == 32 ? _option.toU128(16) : 0; } function decodeNativeDropOption(bytes calldata _option) internal pure returns (uint128 amount, bytes32 receiver) { if (_option.length != 48) revert Executor_InvalidNativeDropOption(); amount = _option.toU128(0); receiver = _option.toB32(16); } function decodeLzComposeOption( bytes calldata _option ) internal pure returns (uint16 index, uint128 gas, uint128 value) { if (_option.length != 18 && _option.length != 34) revert Executor_InvalidLzComposeOption(); index = _option.toU16(0); gas = _option.toU128(2); value = _option.length == 34 ? _option.toU128(18) : 0; } function decodeLzReadOption( bytes calldata _option ) internal pure returns (uint128 gas, uint32 calldataSize, uint128 value) { if (_option.length != 20 && _option.length != 36) revert Executor_InvalidLzReadOption(); gas = _option.toU128(0); calldataSize = _option.toU32(16); value = _option.length == 36 ? _option.toU128(20) : 0; } function encodeLzReceiveOption(uint128 _gas, uint128 _value) internal pure returns (bytes memory) { return _value == 0 ? abi.encodePacked(_gas) : abi.encodePacked(_gas, _value); } function encodeNativeDropOption(uint128 _amount, bytes32 _receiver) internal pure returns (bytes memory) { return abi.encodePacked(_amount, _receiver); } function encodeLzComposeOption(uint16 _index, uint128 _gas, uint128 _value) internal pure returns (bytes memory) { return _value == 0 ? abi.encodePacked(_index, _gas) : abi.encodePacked(_index, _gas, _value); } function encodeLzReadOption( uint128 _gas, uint32 _calldataSize, uint128 _value ) internal pure returns (bytes memory) { return _value == 0 ? abi.encodePacked(_gas, _calldataSize) : abi.encodePacked(_gas, _calldataSize, _value); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; import { BytesLib } from "solidity-bytes-utils/contracts/BytesLib.sol"; import { BitMap256 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/messagelib/libs/BitMaps.sol"; import { CalldataBytesLib } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/CalldataBytesLib.sol"; library DVNOptions { using CalldataBytesLib for bytes; using BytesLib for bytes; uint8 internal constant WORKER_ID = 2; uint8 internal constant OPTION_TYPE_PRECRIME = 1; error DVN_InvalidDVNIdx(); error DVN_InvalidDVNOptions(uint256 cursor); /// @dev group dvn options by its idx /// @param _options [dvn_id][dvn_option][dvn_id][dvn_option]... /// dvn_option = [option_size][dvn_idx][option_type][option] /// option_size = len(dvn_idx) + len(option_type) + len(option) /// dvn_id: uint8, dvn_idx: uint8, option_size: uint16, option_type: uint8, option: bytes /// @return dvnOptions the grouped options, still share the same format of _options /// @return dvnIndices the dvn indices function groupDVNOptionsByIdx( bytes memory _options ) internal pure returns (bytes[] memory dvnOptions, uint8[] memory dvnIndices) { if (_options.length == 0) return (dvnOptions, dvnIndices); uint8 numDVNs = getNumDVNs(_options); // if there is only 1 dvn, we can just return the whole options if (numDVNs == 1) { dvnOptions = new bytes[](1); dvnOptions[0] = _options; dvnIndices = new uint8[](1); dvnIndices[0] = _options.toUint8(3); // dvn idx return (dvnOptions, dvnIndices); } // otherwise, we need to group the options by dvn_idx dvnIndices = new uint8[](numDVNs); dvnOptions = new bytes[](numDVNs); unchecked { uint256 cursor = 0; uint256 start = 0; uint8 lastDVNIdx = 255; // 255 is an invalid dvn_idx while (cursor < _options.length) { ++cursor; // skip worker_id // optionLength asserted in getNumDVNs (skip check) uint16 optionLength = _options.toUint16(cursor); cursor += 2; // dvnIdx asserted in getNumDVNs (skip check) uint8 dvnIdx = _options.toUint8(cursor); // dvnIdx must equal to the lastDVNIdx for the first option // so it is always skipped in the first option // this operation slices out options whenever the scan finds a different lastDVNIdx if (lastDVNIdx == 255) { lastDVNIdx = dvnIdx; } else if (dvnIdx != lastDVNIdx) { uint256 len = cursor - start - 3; // 3 is for worker_id and option_length bytes memory opt = _options.slice(start, len); _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, opt); // reset the start and lastDVNIdx start += len; lastDVNIdx = dvnIdx; } cursor += optionLength; } // skip check the cursor here because the cursor is asserted in getNumDVNs // if we have reached the end of the options, we need to process the last dvn uint256 size = cursor - start; bytes memory op = _options.slice(start, size); _insertDVNOptions(dvnOptions, dvnIndices, lastDVNIdx, op); // revert dvnIndices to start from 0 for (uint8 i = 0; i < numDVNs; ++i) { --dvnIndices[i]; } } } function _insertDVNOptions( bytes[] memory _dvnOptions, uint8[] memory _dvnIndices, uint8 _dvnIdx, bytes memory _newOptions ) internal pure { // dvnIdx starts from 0 but default value of dvnIndices is 0, // so we tell if the slot is empty by adding 1 to dvnIdx if (_dvnIdx == 255) revert DVN_InvalidDVNIdx(); uint8 dvnIdxAdj = _dvnIdx + 1; for (uint256 j = 0; j < _dvnIndices.length; ++j) { uint8 index = _dvnIndices[j]; if (dvnIdxAdj == index) { _dvnOptions[j] = abi.encodePacked(_dvnOptions[j], _newOptions); break; } else if (index == 0) { // empty slot, that means it is the first time we see this dvn _dvnIndices[j] = dvnIdxAdj; _dvnOptions[j] = _newOptions; break; } } } /// @dev get the number of unique dvns /// @param _options the format is the same as groupDVNOptionsByIdx function getNumDVNs(bytes memory _options) internal pure returns (uint8 numDVNs) { uint256 cursor = 0; BitMap256 bitmap; // find number of unique dvn_idx unchecked { while (cursor < _options.length) { ++cursor; // skip worker_id uint16 optionLength = _options.toUint16(cursor); cursor += 2; if (optionLength < 2) revert DVN_InvalidDVNOptions(cursor); // at least 1 byte for dvn_idx and 1 byte for option_type uint8 dvnIdx = _options.toUint8(cursor); // if dvnIdx is not set, increment numDVNs // max num of dvns is 255, 255 is an invalid dvn_idx // The order of the dvnIdx is not required to be sequential, as enforcing the order may weaken // the composability of the options. e.g. if we refrain from enforcing the order, an OApp that has // already enforced certain options can append additional options to the end of the enforced // ones without restrictions. if (dvnIdx == 255) revert DVN_InvalidDVNIdx(); if (!bitmap.get(dvnIdx)) { ++numDVNs; bitmap = bitmap.set(dvnIdx); } cursor += optionLength; } } if (cursor != _options.length) revert DVN_InvalidDVNOptions(cursor); } /// @dev decode the next dvn option from _options starting from the specified cursor /// @param _options the format is the same as groupDVNOptionsByIdx /// @param _cursor the cursor to start decoding /// @return optionType the type of the option /// @return option the option /// @return cursor the cursor to start decoding the next option function nextDVNOption( bytes calldata _options, uint256 _cursor ) internal pure returns (uint8 optionType, bytes calldata option, uint256 cursor) { unchecked { // skip worker id cursor = _cursor + 1; // read option size uint16 size = _options.toU16(cursor); cursor += 2; // read option type optionType = _options.toU8(cursor + 1); // skip dvn_idx // startCursor and endCursor are used to slice the option from _options uint256 startCursor = cursor + 2; // skip option type and dvn_idx uint256 endCursor = cursor + size; option = _options[startCursor:endCursor]; cursor += size; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { IMessageLibManager } from "./IMessageLibManager.sol"; import { IMessagingComposer } from "./IMessagingComposer.sol"; import { IMessagingChannel } from "./IMessagingChannel.sol"; import { IMessagingContext } from "./IMessagingContext.sol"; struct MessagingParams { uint32 dstEid; bytes32 receiver; bytes message; bytes options; bool payInLzToken; } struct MessagingReceipt { bytes32 guid; uint64 nonce; MessagingFee fee; } struct MessagingFee { uint256 nativeFee; uint256 lzTokenFee; } struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; } interface ILayerZeroEndpointV2 is IMessageLibManager, IMessagingComposer, IMessagingChannel, IMessagingContext { event PacketSent(bytes encodedPayload, bytes options, address sendLibrary); event PacketVerified(Origin origin, address receiver, bytes32 payloadHash); event PacketDelivered(Origin origin, address receiver); event LzReceiveAlert( address indexed receiver, address indexed executor, Origin origin, bytes32 guid, uint256 gas, uint256 value, bytes message, bytes extraData, bytes reason ); event LzTokenSet(address token); event DelegateSet(address sender, address delegate); function quote(MessagingParams calldata _params, address _sender) external view returns (MessagingFee memory); function send( MessagingParams calldata _params, address _refundAddress ) external payable returns (MessagingReceipt memory); function verify(Origin calldata _origin, address _receiver, bytes32 _payloadHash) external; function verifiable(Origin calldata _origin, address _receiver) external view returns (bool); function initializable(Origin calldata _origin, address _receiver) external view returns (bool); function lzReceive( Origin calldata _origin, address _receiver, bytes32 _guid, bytes calldata _message, bytes calldata _extraData ) external payable; // oapp can burn messages partially by calling this function with its own business logic if messages are verified in order function clear(address _oapp, Origin calldata _origin, bytes32 _guid, bytes calldata _message) external; function setLzToken(address _lzToken) external; function lzToken() external view returns (address); function nativeToken() external view returns (address); function setDelegate(address _delegate) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { Origin } from "./ILayerZeroEndpointV2.sol"; interface ILayerZeroReceiver { function allowInitializePath(Origin calldata _origin) external view returns (bool); function nextNonce(uint32 _eid, bytes32 _sender) external view returns (uint64); function lzReceive( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; struct SetConfigParam { uint32 eid; uint32 configType; bytes config; } interface IMessageLibManager { struct Timeout { address lib; uint256 expiry; } event LibraryRegistered(address newLib); event DefaultSendLibrarySet(uint32 eid, address newLib); event DefaultReceiveLibrarySet(uint32 eid, address newLib); event DefaultReceiveLibraryTimeoutSet(uint32 eid, address oldLib, uint256 expiry); event SendLibrarySet(address sender, uint32 eid, address newLib); event ReceiveLibrarySet(address receiver, uint32 eid, address newLib); event ReceiveLibraryTimeoutSet(address receiver, uint32 eid, address oldLib, uint256 timeout); function registerLibrary(address _lib) external; function isRegisteredLibrary(address _lib) external view returns (bool); function getRegisteredLibraries() external view returns (address[] memory); function setDefaultSendLibrary(uint32 _eid, address _newLib) external; function defaultSendLibrary(uint32 _eid) external view returns (address); function setDefaultReceiveLibrary(uint32 _eid, address _newLib, uint256 _gracePeriod) external; function defaultReceiveLibrary(uint32 _eid) external view returns (address); function setDefaultReceiveLibraryTimeout(uint32 _eid, address _lib, uint256 _expiry) external; function defaultReceiveLibraryTimeout(uint32 _eid) external view returns (address lib, uint256 expiry); function isSupportedEid(uint32 _eid) external view returns (bool); function isValidReceiveLibrary(address _receiver, uint32 _eid, address _lib) external view returns (bool); /// ------------------- OApp interfaces ------------------- function setSendLibrary(address _oapp, uint32 _eid, address _newLib) external; function getSendLibrary(address _sender, uint32 _eid) external view returns (address lib); function isDefaultSendLibrary(address _sender, uint32 _eid) external view returns (bool); function setReceiveLibrary(address _oapp, uint32 _eid, address _newLib, uint256 _gracePeriod) external; function getReceiveLibrary(address _receiver, uint32 _eid) external view returns (address lib, bool isDefault); function setReceiveLibraryTimeout(address _oapp, uint32 _eid, address _lib, uint256 _expiry) external; function receiveLibraryTimeout(address _receiver, uint32 _eid) external view returns (address lib, uint256 expiry); function setConfig(address _oapp, address _lib, SetConfigParam[] calldata _params) external; function getConfig( address _oapp, address _lib, uint32 _eid, uint32 _configType ) external view returns (bytes memory config); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IMessagingChannel { event InboundNonceSkipped(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce); event PacketNilified(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash); event PacketBurnt(uint32 srcEid, bytes32 sender, address receiver, uint64 nonce, bytes32 payloadHash); function eid() external view returns (uint32); // this is an emergency function if a message cannot be verified for some reasons // required to provide _nextNonce to avoid race condition function skip(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce) external; function nilify(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external; function burn(address _oapp, uint32 _srcEid, bytes32 _sender, uint64 _nonce, bytes32 _payloadHash) external; function nextGuid(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (bytes32); function inboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64); function outboundNonce(address _sender, uint32 _dstEid, bytes32 _receiver) external view returns (uint64); function inboundPayloadHash( address _receiver, uint32 _srcEid, bytes32 _sender, uint64 _nonce ) external view returns (bytes32); function lazyInboundNonce(address _receiver, uint32 _srcEid, bytes32 _sender) external view returns (uint64); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IMessagingComposer { event ComposeSent(address from, address to, bytes32 guid, uint16 index, bytes message); event ComposeDelivered(address from, address to, bytes32 guid, uint16 index); event LzComposeAlert( address indexed from, address indexed to, address indexed executor, bytes32 guid, uint16 index, uint256 gas, uint256 value, bytes message, bytes extraData, bytes reason ); function composeQueue( address _from, address _to, bytes32 _guid, uint16 _index ) external view returns (bytes32 messageHash); function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external; function lzCompose( address _from, address _to, bytes32 _guid, uint16 _index, bytes calldata _message, bytes calldata _extraData ) external payable; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IMessagingContext { function isSendingMessage() external view returns (bool); function getSendContext() external view returns (uint32 dstEid, address sender); }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; library AddressCast { error AddressCast_InvalidSizeForAddress(); error AddressCast_InvalidAddress(); function toBytes32(bytes calldata _addressBytes) internal pure returns (bytes32 result) { if (_addressBytes.length > 32) revert AddressCast_InvalidAddress(); result = bytes32(_addressBytes); unchecked { uint256 offset = 32 - _addressBytes.length; result = result >> (offset * 8); } } function toBytes32(address _address) internal pure returns (bytes32 result) { result = bytes32(uint256(uint160(_address))); } function toBytes(bytes32 _addressBytes32, uint256 _size) internal pure returns (bytes memory result) { if (_size == 0 || _size > 32) revert AddressCast_InvalidSizeForAddress(); result = new bytes(_size); unchecked { uint256 offset = 256 - _size * 8; assembly { mstore(add(result, 32), shl(offset, _addressBytes32)) } } } function toAddress(bytes32 _addressBytes32) internal pure returns (address result) { result = address(uint160(uint256(_addressBytes32))); } function toAddress(bytes calldata _addressBytes) internal pure returns (address result) { if (_addressBytes.length != 20) revert AddressCast_InvalidAddress(); result = address(bytes20(_addressBytes)); } }
// SPDX-License-Identifier: LZBL-1.2 pragma solidity ^0.8.20; library CalldataBytesLib { function toU8(bytes calldata _bytes, uint256 _start) internal pure returns (uint8) { return uint8(_bytes[_start]); } function toU16(bytes calldata _bytes, uint256 _start) internal pure returns (uint16) { unchecked { uint256 end = _start + 2; return uint16(bytes2(_bytes[_start:end])); } } function toU32(bytes calldata _bytes, uint256 _start) internal pure returns (uint32) { unchecked { uint256 end = _start + 4; return uint32(bytes4(_bytes[_start:end])); } } function toU64(bytes calldata _bytes, uint256 _start) internal pure returns (uint64) { unchecked { uint256 end = _start + 8; return uint64(bytes8(_bytes[_start:end])); } } function toU128(bytes calldata _bytes, uint256 _start) internal pure returns (uint128) { unchecked { uint256 end = _start + 16; return uint128(bytes16(_bytes[_start:end])); } } function toU256(bytes calldata _bytes, uint256 _start) internal pure returns (uint256) { unchecked { uint256 end = _start + 32; return uint256(bytes32(_bytes[_start:end])); } } function toAddr(bytes calldata _bytes, uint256 _start) internal pure returns (address) { unchecked { uint256 end = _start + 20; return address(bytes20(_bytes[_start:end])); } } function toB32(bytes calldata _bytes, uint256 _start) internal pure returns (bytes32) { unchecked { uint256 end = _start + 32; return bytes32(_bytes[_start:end]); } } }
// SPDX-License-Identifier: MIT // modified from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/BitMaps.sol pragma solidity ^0.8.20; type BitMap256 is uint256; using BitMaps for BitMap256 global; library BitMaps { /** * @dev Returns whether the bit at `index` is set. */ function get(BitMap256 bitmap, uint8 index) internal pure returns (bool) { uint256 mask = 1 << index; return BitMap256.unwrap(bitmap) & mask != 0; } /** * @dev Sets the bit at `index`. */ function set(BitMap256 bitmap, uint8 index) internal pure returns (BitMap256) { uint256 mask = 1 << index; return BitMap256.wrap(BitMap256.unwrap(bitmap) | mask); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { ILayerZeroEndpointV2 } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol"; /** * @title IOAppCore */ interface IOAppCore { // Custom error messages error OnlyPeer(uint32 eid, bytes32 sender); error NoPeer(uint32 eid); error InvalidEndpointCall(); error InvalidDelegate(); // Event emitted when a peer (OApp) is set for a corresponding endpoint event PeerSet(uint32 eid, bytes32 peer); /** * @notice Retrieves the OApp version information. * @return senderVersion The version of the OAppSender.sol contract. * @return receiverVersion The version of the OAppReceiver.sol contract. */ function oAppVersion() external view returns (uint64 senderVersion, uint64 receiverVersion); /** * @notice Retrieves the LayerZero endpoint associated with the OApp. * @return iEndpoint The LayerZero endpoint as an interface. */ function endpoint() external view returns (ILayerZeroEndpointV2 iEndpoint); /** * @notice Retrieves the peer (OApp) associated with a corresponding endpoint. * @param _eid The endpoint ID. * @return peer The peer address (OApp instance) associated with the corresponding endpoint. */ function peers(uint32 _eid) external view returns (bytes32 peer); /** * @notice Sets the peer address (OApp instance) for a corresponding endpoint. * @param _eid The endpoint ID. * @param _peer The address of the peer to be associated with the corresponding endpoint. */ function setPeer(uint32 _eid, bytes32 _peer) external; /** * @notice Sets the delegate address for the OApp Core. * @param _delegate The address of the delegate to be set. */ function setDelegate(address _delegate) external; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; /** * @dev Struct representing enforced option parameters. */ struct EnforcedOptionParam { uint32 eid; // Endpoint ID uint16 msgType; // Message Type bytes options; // Additional options } /** * @title IOAppOptionsType3 * @dev Interface for the OApp with Type 3 Options, allowing the setting and combining of enforced options. */ interface IOAppOptionsType3 { // Custom error message for invalid options error InvalidOptions(bytes options); // Event emitted when enforced options are set event EnforcedOptionSet(EnforcedOptionParam[] _enforcedOptions); /** * @notice Sets enforced options for specific endpoint and message type combinations. * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options. */ function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) external; /** * @notice Combines options for a given endpoint and message type. * @param _eid The endpoint ID. * @param _msgType The OApp message type. * @param _extraOptions Additional options passed by the caller. * @return options The combination of caller specified options AND enforced options. */ function combineOptions( uint32 _eid, uint16 _msgType, bytes calldata _extraOptions ) external view returns (bytes memory options); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { ILayerZeroReceiver, Origin } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroReceiver.sol"; interface IOAppReceiver is ILayerZeroReceiver { /** * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint. * @param _origin The origin information containing the source endpoint and sender address. * - srcEid: The source chain endpoint ID. * - sender: The sender address on the src chain. * - nonce: The nonce of the message. * @param _message The lzReceive payload. * @param _sender The sender address. * @return isSender Is a valid sender. * * @dev Applications can optionally choose to implement a separate composeMsg sender that is NOT the bridging layer. * @dev The default sender IS the OAppReceiver implementer. */ function isComposeMsgSender( Origin calldata _origin, bytes calldata _message, address _sender ) external view returns (bool isSender); }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IOAppOptionsType3, EnforcedOptionParam } from "../interfaces/IOAppOptionsType3.sol"; /** * @title OAppOptionsType3 * @dev Abstract contract implementing the IOAppOptionsType3 interface with type 3 options. */ abstract contract OAppOptionsType3 is IOAppOptionsType3, Ownable { uint16 internal constant OPTION_TYPE_3 = 3; // @dev The "msgType" should be defined in the child contract. mapping(uint32 eid => mapping(uint16 msgType => bytes enforcedOption)) public enforcedOptions; /** * @dev Sets the enforced options for specific endpoint and message type combinations. * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options. * * @dev Only the owner/admin of the OApp can call this function. * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc. * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType. * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose(). */ function setEnforcedOptions(EnforcedOptionParam[] calldata _enforcedOptions) public virtual onlyOwner { _setEnforcedOptions(_enforcedOptions); } /** * @dev Sets the enforced options for specific endpoint and message type combinations. * @param _enforcedOptions An array of EnforcedOptionParam structures specifying enforced options. * * @dev Provides a way for the OApp to enforce things like paying for PreCrime, AND/OR minimum dst lzReceive gas amounts etc. * @dev These enforced options can vary as the potential options/execution on the remote may differ as per the msgType. * eg. Amount of lzReceive() gas necessary to deliver a lzCompose() message adds overhead you dont want to pay * if you are only making a standard LayerZero message ie. lzReceive() WITHOUT sendCompose(). */ function _setEnforcedOptions(EnforcedOptionParam[] memory _enforcedOptions) internal virtual { for (uint256 i = 0; i < _enforcedOptions.length; i++) { // @dev Enforced options are only available for optionType 3, as type 1 and 2 dont support combining. _assertOptionsType3(_enforcedOptions[i].options); enforcedOptions[_enforcedOptions[i].eid][_enforcedOptions[i].msgType] = _enforcedOptions[i].options; } emit EnforcedOptionSet(_enforcedOptions); } /** * @notice Combines options for a given endpoint and message type. * @param _eid The endpoint ID. * @param _msgType The OAPP message type. * @param _extraOptions Additional options passed by the caller. * @return options The combination of caller specified options AND enforced options. * * @dev If there is an enforced lzReceive option: * - {gasLimit: 200k, msg.value: 1 ether} AND a caller supplies a lzReceive option: {gasLimit: 100k, msg.value: 0.5 ether} * - The resulting options will be {gasLimit: 300k, msg.value: 1.5 ether} when the message is executed on the remote lzReceive() function. * @dev This presence of duplicated options is handled off-chain in the verifier/executor. */ function combineOptions( uint32 _eid, uint16 _msgType, bytes calldata _extraOptions ) public view virtual returns (bytes memory) { bytes memory enforced = enforcedOptions[_eid][_msgType]; // No enforced options, pass whatever the caller supplied, even if it's empty or legacy type 1/2 options. if (enforced.length == 0) return _extraOptions; // No caller options, return enforced if (_extraOptions.length == 0) return enforced; // @dev If caller provided _extraOptions, must be type 3 as its the ONLY type that can be combined. if (_extraOptions.length >= 2) { _assertOptionsType3(_extraOptions); // @dev Remove the first 2 bytes containing the type from the _extraOptions and combine with enforced. return bytes.concat(enforced, _extraOptions[2:]); } // No valid set of options was found. revert InvalidOptions(_extraOptions); } /** * @dev Internal function to assert that options are of type 3. * @param _options The options to be checked. */ function _assertOptionsType3(bytes memory _options) internal pure virtual { uint16 optionsType; assembly { optionsType := mload(add(_options, 2)) } if (optionsType != OPTION_TYPE_3) revert InvalidOptions(_options); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { BytesLib } from "solidity-bytes-utils/contracts/BytesLib.sol"; import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; import { ExecutorOptions } from "@layerzerolabs/lz-evm-messagelib-v2/contracts/libs/ExecutorOptions.sol"; import { DVNOptions } from "@layerzerolabs/lz-evm-messagelib-v2/contracts/uln/libs/DVNOptions.sol"; /** * @title OptionsBuilder * @dev Library for building and encoding various message options. */ library OptionsBuilder { using SafeCast for uint256; using BytesLib for bytes; // Constants for options types uint16 internal constant TYPE_1 = 1; // legacy options type 1 uint16 internal constant TYPE_2 = 2; // legacy options type 2 uint16 internal constant TYPE_3 = 3; // Custom error message error InvalidSize(uint256 max, uint256 actual); error InvalidOptionType(uint16 optionType); // Modifier to ensure only options of type 3 are used modifier onlyType3(bytes memory _options) { if (_options.toUint16(0) != TYPE_3) revert InvalidOptionType(_options.toUint16(0)); _; } /** * @dev Creates a new options container with type 3. * @return options The newly created options container. */ function newOptions() internal pure returns (bytes memory) { return abi.encodePacked(TYPE_3); } /** * @dev Adds an executor LZ receive option to the existing options. * @param _options The existing options container. * @param _gas The gasLimit used on the lzReceive() function in the OApp. * @param _value The msg.value passed to the lzReceive() function in the OApp. * @return options The updated options container. * * @dev When multiples of this option are added, they are summed by the executor * eg. if (_gas: 200k, and _value: 1 ether) AND (_gas: 100k, _value: 0.5 ether) are sent in an option to the LayerZeroEndpoint, * that becomes (300k, 1.5 ether) when the message is executed on the remote lzReceive() function. */ function addExecutorLzReceiveOption( bytes memory _options, uint128 _gas, uint128 _value ) internal pure onlyType3(_options) returns (bytes memory) { bytes memory option = ExecutorOptions.encodeLzReceiveOption(_gas, _value); return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZRECEIVE, option); } /** * @dev Adds an executor native drop option to the existing options. * @param _options The existing options container. * @param _amount The amount for the native value that is airdropped to the 'receiver'. * @param _receiver The receiver address for the native drop option. * @return options The updated options container. * * @dev When multiples of this option are added, they are summed by the executor on the remote chain. */ function addExecutorNativeDropOption( bytes memory _options, uint128 _amount, bytes32 _receiver ) internal pure onlyType3(_options) returns (bytes memory) { bytes memory option = ExecutorOptions.encodeNativeDropOption(_amount, _receiver); return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_NATIVE_DROP, option); } // /** // * @dev Adds an executor native drop option to the existing options. // * @param _options The existing options container. // * @param _amount The amount for the native value that is airdropped to the 'receiver'. // * @param _receiver The receiver address for the native drop option. // * @return options The updated options container. // * // * @dev When multiples of this option are added, they are summed by the executor on the remote chain. // */ function addExecutorLzReadOption( bytes memory _options, uint128 _gas, uint32 _size, uint128 _value ) internal pure onlyType3(_options) returns (bytes memory) { bytes memory option = ExecutorOptions.encodeLzReadOption(_gas, _size, _value); return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZREAD, option); } /** * @dev Adds an executor LZ compose option to the existing options. * @param _options The existing options container. * @param _index The index for the lzCompose() function call. * @param _gas The gasLimit for the lzCompose() function call. * @param _value The msg.value for the lzCompose() function call. * @return options The updated options container. * * @dev When multiples of this option are added, they are summed PER index by the executor on the remote chain. * @dev If the OApp sends N lzCompose calls on the remote, you must provide N incremented indexes starting with 0. * ie. When your remote OApp composes (N = 3) messages, you must set this option for index 0,1,2 */ function addExecutorLzComposeOption( bytes memory _options, uint16 _index, uint128 _gas, uint128 _value ) internal pure onlyType3(_options) returns (bytes memory) { bytes memory option = ExecutorOptions.encodeLzComposeOption(_index, _gas, _value); return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_LZCOMPOSE, option); } /** * @dev Adds an executor ordered execution option to the existing options. * @param _options The existing options container. * @return options The updated options container. */ function addExecutorOrderedExecutionOption( bytes memory _options ) internal pure onlyType3(_options) returns (bytes memory) { return addExecutorOption(_options, ExecutorOptions.OPTION_TYPE_ORDERED_EXECUTION, bytes("")); } /** * @dev Adds a DVN pre-crime option to the existing options. * @param _options The existing options container. * @param _dvnIdx The DVN index for the pre-crime option. * @return options The updated options container. */ function addDVNPreCrimeOption( bytes memory _options, uint8 _dvnIdx ) internal pure onlyType3(_options) returns (bytes memory) { return addDVNOption(_options, _dvnIdx, DVNOptions.OPTION_TYPE_PRECRIME, bytes("")); } /** * @dev Adds an executor option to the existing options. * @param _options The existing options container. * @param _optionType The type of the executor option. * @param _option The encoded data for the executor option. * @return options The updated options container. */ function addExecutorOption( bytes memory _options, uint8 _optionType, bytes memory _option ) internal pure onlyType3(_options) returns (bytes memory) { return abi.encodePacked( _options, ExecutorOptions.WORKER_ID, _option.length.toUint16() + 1, // +1 for optionType _optionType, _option ); } /** * @dev Adds a DVN option to the existing options. * @param _options The existing options container. * @param _dvnIdx The DVN index for the DVN option. * @param _optionType The type of the DVN option. * @param _option The encoded data for the DVN option. * @return options The updated options container. */ function addDVNOption( bytes memory _options, uint8 _dvnIdx, uint8 _optionType, bytes memory _option ) internal pure onlyType3(_options) returns (bytes memory) { return abi.encodePacked( _options, DVNOptions.WORKER_ID, _option.length.toUint16() + 2, // +2 for optionType and dvnIdx _dvnIdx, _optionType, _option ); } /** * @dev Encodes legacy options of type 1. * @param _executionGas The gasLimit value passed to lzReceive(). * @return legacyOptions The encoded legacy options. */ function encodeLegacyOptionsType1(uint256 _executionGas) internal pure returns (bytes memory) { if (_executionGas > type(uint128).max) revert InvalidSize(type(uint128).max, _executionGas); return abi.encodePacked(TYPE_1, _executionGas); } /** * @dev Encodes legacy options of type 2. * @param _executionGas The gasLimit value passed to lzReceive(). * @param _nativeForDst The amount of native air dropped to the receiver. * @param _receiver The _nativeForDst receiver address. * @return legacyOptions The encoded legacy options of type 2. */ function encodeLegacyOptionsType2( uint256 _executionGas, uint256 _nativeForDst, bytes memory _receiver // @dev Use bytes instead of bytes32 in legacy type 2 for _receiver. ) internal pure returns (bytes memory) { if (_executionGas > type(uint128).max) revert InvalidSize(type(uint128).max, _executionGas); if (_nativeForDst > type(uint128).max) revert InvalidSize(type(uint128).max, _nativeForDst); if (_receiver.length > 32) revert InvalidSize(32, _receiver.length); return abi.encodePacked(TYPE_2, _executionGas, _nativeForDst, _receiver); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { SafeCast } from "@openzeppelin/contracts/utils/math/SafeCast.sol"; struct EVMCallRequestV1 { uint16 appRequestLabel; // Label identifying the application or type of request (can be use in lzCompute) uint32 targetEid; // Target endpoint ID (representing a target blockchain) bool isBlockNum; // True if the request = block number, false if timestamp uint64 blockNumOrTimestamp; // Block number or timestamp to use in the request uint16 confirmations; // Number of block confirmations on top of the requested block number or timestamp before the view function can be called address to; // Address of the target contract on the target chain bytes callData; // Calldata for the contract call } struct EVMCallComputeV1 { uint8 computeSetting; // Compute setting (0 = map only, 1 = reduce only, 2 = map reduce) uint32 targetEid; // Target endpoint ID (representing a target blockchain) bool isBlockNum; // True if the request = block number, false if timestamp uint64 blockNumOrTimestamp; // Block number or timestamp to use in the request uint16 confirmations; // Number of block confirmations on top of the requested block number or timestamp before the view function can be called address to; // Address of the target contract on the target chain } library ReadCodecV1 { using SafeCast for uint256; uint16 internal constant CMD_VERSION = 1; uint8 internal constant REQUEST_VERSION = 1; uint16 internal constant RESOLVER_TYPE_SINGLE_VIEW_EVM_CALL = 1; uint8 internal constant COMPUTE_VERSION = 1; uint16 internal constant COMPUTE_TYPE_SINGLE_VIEW_EVM_CALL = 1; error InvalidVersion(); error InvalidType(); function decode( bytes calldata _cmd ) internal pure returns (uint16 appCmdLabel, EVMCallRequestV1[] memory evmCallRequests, EVMCallComputeV1 memory compute) { uint256 offset = 0; uint16 cmdVersion = uint16(bytes2(_cmd[offset:offset + 2])); offset += 2; if (cmdVersion != CMD_VERSION) revert InvalidVersion(); appCmdLabel = uint16(bytes2(_cmd[offset:offset + 2])); offset += 2; (evmCallRequests, offset) = decodeRequestsV1(_cmd, offset); // decode the compute if it exists if (offset < _cmd.length) { (compute, ) = decodeEVMCallComputeV1(_cmd, offset); } } function decodeRequestsV1( bytes calldata _cmd, uint256 _offset ) internal pure returns (EVMCallRequestV1[] memory evmCallRequests, uint256 newOffset) { newOffset = _offset; uint16 requestCount = uint16(bytes2(_cmd[newOffset:newOffset + 2])); newOffset += 2; evmCallRequests = new EVMCallRequestV1[](requestCount); for (uint16 i = 0; i < requestCount; i++) { uint8 requestVersion = uint8(_cmd[newOffset]); newOffset += 1; if (requestVersion != REQUEST_VERSION) revert InvalidVersion(); uint16 appRequestLabel = uint16(bytes2(_cmd[newOffset:newOffset + 2])); newOffset += 2; uint16 resolverType = uint16(bytes2(_cmd[newOffset:newOffset + 2])); newOffset += 2; if (resolverType == RESOLVER_TYPE_SINGLE_VIEW_EVM_CALL) { (EVMCallRequestV1 memory request, uint256 nextOffset) = decodeEVMCallRequestV1( _cmd, newOffset, appRequestLabel ); newOffset = nextOffset; evmCallRequests[i] = request; } else { revert InvalidType(); } } } function decodeEVMCallRequestV1( bytes calldata _cmd, uint256 _offset, uint16 _appRequestLabel ) internal pure returns (EVMCallRequestV1 memory request, uint256 newOffset) { newOffset = _offset; request.appRequestLabel = _appRequestLabel; uint16 requestSize = uint16(bytes2(_cmd[newOffset:newOffset + 2])); newOffset += 2; request.targetEid = uint32(bytes4(_cmd[newOffset:newOffset + 4])); newOffset += 4; request.isBlockNum = uint8(_cmd[newOffset]) == 1; newOffset += 1; request.blockNumOrTimestamp = uint64(bytes8(_cmd[newOffset:newOffset + 8])); newOffset += 8; request.confirmations = uint16(bytes2(_cmd[newOffset:newOffset + 2])); newOffset += 2; request.to = address(bytes20(_cmd[newOffset:newOffset + 20])); newOffset += 20; uint16 callDataSize = requestSize - 35; request.callData = _cmd[newOffset:newOffset + callDataSize]; newOffset += callDataSize; } function decodeEVMCallComputeV1( bytes calldata _cmd, uint256 _offset ) internal pure returns (EVMCallComputeV1 memory compute, uint256 newOffset) { newOffset = _offset; uint8 computeVersion = uint8(_cmd[newOffset]); newOffset += 1; if (computeVersion != COMPUTE_VERSION) revert InvalidVersion(); uint16 computeType = uint16(bytes2(_cmd[newOffset:newOffset + 2])); newOffset += 2; if (computeType != COMPUTE_TYPE_SINGLE_VIEW_EVM_CALL) revert InvalidType(); compute.computeSetting = uint8(_cmd[newOffset]); newOffset += 1; compute.targetEid = uint32(bytes4(_cmd[newOffset:newOffset + 4])); newOffset += 4; compute.isBlockNum = uint8(_cmd[newOffset]) == 1; newOffset += 1; compute.blockNumOrTimestamp = uint64(bytes8(_cmd[newOffset:newOffset + 8])); newOffset += 8; compute.confirmations = uint16(bytes2(_cmd[newOffset:newOffset + 2])); newOffset += 2; compute.to = address(bytes20(_cmd[newOffset:newOffset + 20])); newOffset += 20; } function decodeCmdAppLabel(bytes calldata _cmd) internal pure returns (uint16) { uint256 offset = 0; uint16 cmdVersion = uint16(bytes2(_cmd[offset:offset + 2])); offset += 2; if (cmdVersion != CMD_VERSION) revert InvalidVersion(); return uint16(bytes2(_cmd[offset:offset + 2])); } function decodeRequestV1AppRequestLabel(bytes calldata _request) internal pure returns (uint16) { uint256 offset = 0; uint8 requestVersion = uint8(_request[offset]); offset += 1; if (requestVersion != REQUEST_VERSION) revert InvalidVersion(); return uint16(bytes2(_request[offset:offset + 2])); } function encode( uint16 _appCmdLabel, EVMCallRequestV1[] memory _evmCallRequests, EVMCallComputeV1 memory _evmCallCompute ) internal pure returns (bytes memory) { bytes memory cmd = encode(_appCmdLabel, _evmCallRequests); if (_evmCallCompute.targetEid != 0) { // if eid is 0, it means no compute cmd = appendEVMCallComputeV1(cmd, _evmCallCompute); } return cmd; } function encode( uint16 _appCmdLabel, EVMCallRequestV1[] memory _evmCallRequests ) internal pure returns (bytes memory) { bytes memory cmd = abi.encodePacked(CMD_VERSION, _appCmdLabel, _evmCallRequests.length.toUint16()); for (uint256 i = 0; i < _evmCallRequests.length; i++) { cmd = appendEVMCallRequestV1(cmd, _evmCallRequests[i]); } return cmd; } // todo: optimize this with Buffer function appendEVMCallRequestV1( bytes memory _cmd, EVMCallRequestV1 memory _request ) internal pure returns (bytes memory) { bytes memory newCmd = abi.encodePacked( _cmd, REQUEST_VERSION, _request.appRequestLabel, RESOLVER_TYPE_SINGLE_VIEW_EVM_CALL, (_request.callData.length + 35).toUint16(), _request.targetEid ); return abi.encodePacked( newCmd, _request.isBlockNum, _request.blockNumOrTimestamp, _request.confirmations, _request.to, _request.callData ); } function appendEVMCallComputeV1( bytes memory _cmd, EVMCallComputeV1 memory _compute ) internal pure returns (bytes memory) { return abi.encodePacked( _cmd, COMPUTE_VERSION, COMPUTE_TYPE_SINGLE_VIEW_EVM_CALL, _compute.computeSetting, _compute.targetEid, _compute.isBlockNum, _compute.blockNumOrTimestamp, _compute.confirmations, _compute.to ); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; // @dev Import the 'MessagingFee' and 'MessagingReceipt' so it's exposed to OApp implementers // solhint-disable-next-line no-unused-import import { OAppSender, MessagingFee, MessagingReceipt } from "./OAppSender.sol"; // @dev Import the 'Origin' so it's exposed to OApp implementers // solhint-disable-next-line no-unused-import import { OAppReceiver, Origin } from "./OAppReceiver.sol"; import { OAppCore } from "./OAppCore.sol"; /** * @title OApp * @dev Abstract contract serving as the base for OApp implementation, combining OAppSender and OAppReceiver functionality. */ abstract contract OApp is OAppSender, OAppReceiver { /** * @dev Constructor to initialize the OApp with the provided endpoint and owner. * @param _endpoint The address of the LOCAL LayerZero endpoint. * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. */ constructor(address _endpoint, address _delegate) OAppCore(_endpoint, _delegate) {} /** * @notice Retrieves the OApp version information. * @return senderVersion The version of the OAppSender.sol implementation. * @return receiverVersion The version of the OAppReceiver.sol implementation. */ function oAppVersion() public pure virtual override(OAppSender, OAppReceiver) returns (uint64 senderVersion, uint64 receiverVersion) { return (SENDER_VERSION, RECEIVER_VERSION); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; import { IOAppCore, ILayerZeroEndpointV2 } from "./interfaces/IOAppCore.sol"; /** * @title OAppCore * @dev Abstract contract implementing the IOAppCore interface with basic OApp configurations. */ abstract contract OAppCore is IOAppCore, Ownable { // The LayerZero endpoint associated with the given OApp ILayerZeroEndpointV2 public immutable endpoint; // Mapping to store peers associated with corresponding endpoints mapping(uint32 eid => bytes32 peer) public peers; /** * @dev Constructor to initialize the OAppCore with the provided endpoint and delegate. * @param _endpoint The address of the LOCAL Layer Zero endpoint. * @param _delegate The delegate capable of making OApp configurations inside of the endpoint. * * @dev The delegate typically should be set as the owner of the contract. */ constructor(address _endpoint, address _delegate) { endpoint = ILayerZeroEndpointV2(_endpoint); if (_delegate == address(0)) revert InvalidDelegate(); endpoint.setDelegate(_delegate); } /** * @notice Sets the peer address (OApp instance) for a corresponding endpoint. * @param _eid The endpoint ID. * @param _peer The address of the peer to be associated with the corresponding endpoint. * * @dev Only the owner/admin of the OApp can call this function. * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp. * @dev Set this to bytes32(0) to remove the peer address. * @dev Peer is a bytes32 to accommodate non-evm chains. */ function setPeer(uint32 _eid, bytes32 _peer) public virtual onlyOwner { _setPeer(_eid, _peer); } /** * @notice Sets the peer address (OApp instance) for a corresponding endpoint. * @param _eid The endpoint ID. * @param _peer The address of the peer to be associated with the corresponding endpoint. * * @dev Indicates that the peer is trusted to send LayerZero messages to this OApp. * @dev Set this to bytes32(0) to remove the peer address. * @dev Peer is a bytes32 to accommodate non-evm chains. */ function _setPeer(uint32 _eid, bytes32 _peer) internal virtual { peers[_eid] = _peer; emit PeerSet(_eid, _peer); } /** * @notice Internal function to get the peer address associated with a specific endpoint; reverts if NOT set. * ie. the peer is set to bytes32(0). * @param _eid The endpoint ID. * @return peer The address of the peer associated with the specified endpoint. */ function _getPeerOrRevert(uint32 _eid) internal view virtual returns (bytes32) { bytes32 peer = peers[_eid]; if (peer == bytes32(0)) revert NoPeer(_eid); return peer; } /** * @notice Sets the delegate address for the OApp. * @param _delegate The address of the delegate to be set. * * @dev Only the owner/admin of the OApp can call this function. * @dev Provides the ability for a delegate to set configs, on behalf of the OApp, directly on the Endpoint contract. */ function setDelegate(address _delegate) public onlyOwner { endpoint.setDelegate(_delegate); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { AddressCast } from "@layerzerolabs/lz-evm-protocol-v2/contracts/libs/AddressCast.sol"; import { OApp } from "./OApp.sol"; abstract contract OAppRead is OApp { constructor(address _endpoint, address _delegate) OApp(_endpoint, _delegate) {} // ------------------------------- // Only Owner function setReadChannel(uint32 _channelId, bool _active) public virtual onlyOwner { _setPeer(_channelId, _active ? AddressCast.toBytes32(address(this)) : bytes32(0)); } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { IOAppReceiver, Origin } from "./interfaces/IOAppReceiver.sol"; import { OAppCore } from "./OAppCore.sol"; /** * @title OAppReceiver * @dev Abstract contract implementing the ILayerZeroReceiver interface and extending OAppCore for OApp receivers. */ abstract contract OAppReceiver is IOAppReceiver, OAppCore { // Custom error message for when the caller is not the registered endpoint/ error OnlyEndpoint(address addr); // @dev The version of the OAppReceiver implementation. // @dev Version is bumped when changes are made to this contract. uint64 internal constant RECEIVER_VERSION = 2; /** * @notice Retrieves the OApp version information. * @return senderVersion The version of the OAppSender.sol contract. * @return receiverVersion The version of the OAppReceiver.sol contract. * * @dev Providing 0 as the default for OAppSender version. Indicates that the OAppSender is not implemented. * ie. this is a RECEIVE only OApp. * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions. */ function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) { return (0, RECEIVER_VERSION); } /** * @notice Indicates whether an address is an approved composeMsg sender to the Endpoint. * @dev _origin The origin information containing the source endpoint and sender address. * - srcEid: The source chain endpoint ID. * - sender: The sender address on the src chain. * - nonce: The nonce of the message. * @dev _message The lzReceive payload. * @param _sender The sender address. * @return isSender Is a valid sender. * * @dev Applications can optionally choose to implement separate composeMsg senders that are NOT the bridging layer. * @dev The default sender IS the OAppReceiver implementer. */ function isComposeMsgSender( Origin calldata /*_origin*/, bytes calldata /*_message*/, address _sender ) public view virtual returns (bool) { return _sender == address(this); } /** * @notice Checks if the path initialization is allowed based on the provided origin. * @param origin The origin information containing the source endpoint and sender address. * @return Whether the path has been initialized. * * @dev This indicates to the endpoint that the OApp has enabled msgs for this particular path to be received. * @dev This defaults to assuming if a peer has been set, its initialized. * Can be overridden by the OApp if there is other logic to determine this. */ function allowInitializePath(Origin calldata origin) public view virtual returns (bool) { return peers[origin.srcEid] == origin.sender; } /** * @notice Retrieves the next nonce for a given source endpoint and sender address. * @dev _srcEid The source endpoint ID. * @dev _sender The sender address. * @return nonce The next nonce. * * @dev The path nonce starts from 1. If 0 is returned it means that there is NO nonce ordered enforcement. * @dev Is required by the off-chain executor to determine the OApp expects msg execution is ordered. * @dev This is also enforced by the OApp. * @dev By default this is NOT enabled. ie. nextNonce is hardcoded to return 0. */ function nextNonce(uint32 /*_srcEid*/, bytes32 /*_sender*/) public view virtual returns (uint64 nonce) { return 0; } /** * @dev Entry point for receiving messages or packets from the endpoint. * @param _origin The origin information containing the source endpoint and sender address. * - srcEid: The source chain endpoint ID. * - sender: The sender address on the src chain. * - nonce: The nonce of the message. * @param _guid The unique identifier for the received LayerZero message. * @param _message The payload of the received message. * @param _executor The address of the executor for the received message. * @param _extraData Additional arbitrary data provided by the corresponding executor. * * @dev Entry point for receiving msg/packet from the LayerZero endpoint. */ function lzReceive( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) public payable virtual { // Ensures that only the endpoint can attempt to lzReceive() messages to this OApp. if (address(endpoint) != msg.sender) revert OnlyEndpoint(msg.sender); // Ensure that the sender matches the expected peer for the source endpoint. if (_getPeerOrRevert(_origin.srcEid) != _origin.sender) revert OnlyPeer(_origin.srcEid, _origin.sender); // Call the internal OApp implementation of lzReceive. _lzReceive(_origin, _guid, _message, _executor, _extraData); } /** * @dev Internal function to implement lzReceive logic without needing to copy the basic parameter validation. */ function _lzReceive( Origin calldata _origin, bytes32 _guid, bytes calldata _message, address _executor, bytes calldata _extraData ) internal virtual; }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.20; import { SafeERC20, IERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { MessagingParams, MessagingFee, MessagingReceipt } from "@layerzerolabs/lz-evm-protocol-v2/contracts/interfaces/ILayerZeroEndpointV2.sol"; import { OAppCore } from "./OAppCore.sol"; /** * @title OAppSender * @dev Abstract contract implementing the OAppSender functionality for sending messages to a LayerZero endpoint. */ abstract contract OAppSender is OAppCore { using SafeERC20 for IERC20; // Custom error messages error NotEnoughNative(uint256 msgValue); error LzTokenUnavailable(); // @dev The version of the OAppSender implementation. // @dev Version is bumped when changes are made to this contract. uint64 internal constant SENDER_VERSION = 1; /** * @notice Retrieves the OApp version information. * @return senderVersion The version of the OAppSender.sol contract. * @return receiverVersion The version of the OAppReceiver.sol contract. * * @dev Providing 0 as the default for OAppReceiver version. Indicates that the OAppReceiver is not implemented. * ie. this is a SEND only OApp. * @dev If the OApp uses both OAppSender and OAppReceiver, then this needs to be override returning the correct versions */ function oAppVersion() public view virtual returns (uint64 senderVersion, uint64 receiverVersion) { return (SENDER_VERSION, 0); } /** * @dev Internal function to interact with the LayerZero EndpointV2.quote() for fee calculation. * @param _dstEid The destination endpoint ID. * @param _message The message payload. * @param _options Additional options for the message. * @param _payInLzToken Flag indicating whether to pay the fee in LZ tokens. * @return fee The calculated MessagingFee for the message. * - nativeFee: The native fee for the message. * - lzTokenFee: The LZ token fee for the message. */ function _quote( uint32 _dstEid, bytes memory _message, bytes memory _options, bool _payInLzToken ) internal view virtual returns (MessagingFee memory fee) { return endpoint.quote( MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _payInLzToken), address(this) ); } /** * @dev Internal function to interact with the LayerZero EndpointV2.send() for sending a message. * @param _dstEid The destination endpoint ID. * @param _message The message payload. * @param _options Additional options for the message. * @param _fee The calculated LayerZero fee for the message. * - nativeFee: The native fee. * - lzTokenFee: The lzToken fee. * @param _refundAddress The address to receive any excess fee values sent to the endpoint. * @return receipt The receipt for the sent message. * - guid: The unique identifier for the sent message. * - nonce: The nonce of the sent message. * - fee: The LayerZero fee incurred for the message. */ function _lzSend( uint32 _dstEid, bytes memory _message, bytes memory _options, MessagingFee memory _fee, address _refundAddress ) internal virtual returns (MessagingReceipt memory receipt) { // @dev Push corresponding fees to the endpoint, any excess is sent back to the _refundAddress from the endpoint. uint256 messageValue = _payNative(_fee.nativeFee); if (_fee.lzTokenFee > 0) _payLzToken(_fee.lzTokenFee); return // solhint-disable-next-line check-send-result endpoint.send{ value: messageValue }( MessagingParams(_dstEid, _getPeerOrRevert(_dstEid), _message, _options, _fee.lzTokenFee > 0), _refundAddress ); } /** * @dev Internal function to pay the native fee associated with the message. * @param _nativeFee The native fee to be paid. * @return nativeFee The amount of native currency paid. * * @dev If the OApp needs to initiate MULTIPLE LayerZero messages in a single transaction, * this will need to be overridden because msg.value would contain multiple lzFees. * @dev Should be overridden in the event the LayerZero endpoint requires a different native currency. * @dev Some EVMs use an ERC20 as a method for paying transactions/gasFees. * @dev The endpoint is EITHER/OR, ie. it will NOT support both types of native payment at a time. */ function _payNative(uint256 _nativeFee) internal virtual returns (uint256 nativeFee) { if (msg.value != _nativeFee) revert NotEnoughNative(msg.value); return _nativeFee; } /** * @dev Internal function to pay the LZ token fee associated with the message. * @param _lzTokenFee The LZ token fee to be paid. * * @dev If the caller is trying to pay in the specified lzToken, then the lzTokenFee is passed to the endpoint. * @dev Any excess sent, is passed back to the specified _refundAddress in the _lzSend(). */ function _payLzToken(uint256 _lzTokenFee) internal virtual { // @dev Cannot cache the token because it is not immutable in the endpoint. address lzToken = endpoint.lzToken(); if (lzToken == address(0)) revert LzTokenUnavailable(); // Pay LZ token fee by sending tokens to the endpoint. IERC20(lzToken).safeTransferFrom(msg.sender, address(endpoint), _lzTokenFee); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol) pragma solidity ^0.8.20; import {Context} from "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * The initial owner is set to the address provided by the deployer. This can * later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; /** * @dev The caller account is not authorized to perform an operation. */ error OwnableUnauthorizedAccount(address account); /** * @dev The owner is not a valid owner account. (eg. `address(0)`) */ error OwnableInvalidOwner(address owner); event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the address provided by the deployer as the initial owner. */ constructor(address initialOwner) { if (initialOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(initialOwner); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { if (owner() != _msgSender()) { revert OwnableUnauthorizedAccount(_msgSender()); } } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby disabling any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { if (newOwner == address(0)) { revert OwnableInvalidOwner(address(0)); } _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol) pragma solidity ^0.8.20; import {IERC20} from "./IERC20.sol"; import {IERC165} from "./IERC165.sol"; /** * @title IERC1363 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363]. * * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction. */ interface IERC1363 is IERC20, IERC165 { /* * Note: the ERC-165 identifier for this interface is 0xb0202a11. * 0xb0202a11 === * bytes4(keccak256('transferAndCall(address,uint256)')) ^ * bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^ * bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^ * bytes4(keccak256('approveAndCall(address,uint256)')) ^ * bytes4(keccak256('approveAndCall(address,uint256,bytes)')) */ /** * @dev Moves a `value` amount of tokens from the caller's account to `to` * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferAndCall(address to, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from the caller's account to `to` * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @param data Additional data with no specified format, sent in call to `to`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param from The address which you want to send tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferFromAndCall(address from, address to, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism * and then calls {IERC1363Receiver-onTransferReceived} on `to`. * @param from The address which you want to send tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @param data Additional data with no specified format, sent in call to `to`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function approveAndCall(address spender, uint256 value) external returns (bool); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`. * @param spender The address which will spend the funds. * @param value The amount of tokens to be spent. * @param data Additional data with no specified format, sent in call to `spender`. * @return A boolean value indicating whether the operation succeeded unless throwing. */ function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol) pragma solidity ^0.8.20; import {IERC165} from "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../token/ERC20/IERC20.sol";
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-20 standard as defined in the ERC. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the value of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the value of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves a `value` amount of tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 value) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets a `value` amount of tokens as the allowance of `spender` over the * caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 value) external returns (bool); /** * @dev Moves a `value` amount of tokens from `from` to `to` using the * allowance mechanism. `value` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 value) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.20; import {IERC20} from "../IERC20.sol"; import {IERC1363} from "../../../interfaces/IERC1363.sol"; import {Address} from "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC-20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { /** * @dev An operation with an ERC-20 token failed. */ error SafeERC20FailedOperation(address token); /** * @dev Indicates a failed `decreaseAllowance` request. */ error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease); /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value))); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value))); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. * * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); forceApprove(token, spender, oldAllowance + value); } /** * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no * value, non-reverting calls are assumed to be successful. * * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client" * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal { unchecked { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance < requestedDecrease) { revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease); } forceApprove(token, spender, currentAllowance - requestedDecrease); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval * to be set to zero before setting it to a non-zero value, such as USDT. * * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being * set here. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value)); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0))); _callOptionalReturn(token, approvalCall); } } /** * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * Reverts if the returned value is other than `true`. */ function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { if (to.code.length == 0) { safeTransfer(token, to, value); } else if (!token.transferAndCall(to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * Reverts if the returned value is other than `true`. */ function transferFromAndCallRelaxed( IERC1363 token, address from, address to, uint256 value, bytes memory data ) internal { if (to.code.length == 0) { safeTransferFrom(token, from, to, value); } else if (!token.transferFromAndCall(from, to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when * targeting contracts. * * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}. * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall} * once without retrying, and relies on the returned value to be true. * * Reverts if the returned value is other than `true`. */ function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal { if (to.code.length == 0) { forceApprove(token, to, value); } else if (!token.approveAndCall(to, value, data)) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements. */ function _callOptionalReturn(IERC20 token, bytes memory data) private { uint256 returnSize; uint256 returnValue; assembly ("memory-safe") { let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20) // bubble errors if iszero(success) { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize()) revert(ptr, returndatasize()) } returnSize := returndatasize() returnValue := mload(0) } if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) { revert SafeERC20FailedOperation(address(token)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { bool success; uint256 returnSize; uint256 returnValue; assembly ("memory-safe") { success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20) returnSize := returndatasize() returnValue := mload(0) } return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.20; import {IERC165} from "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC-721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon * a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external; /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC-721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or * {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon * a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom(address from, address to, uint256 tokenId) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721 * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must * understand this adds an external call which potentially creates a reentrancy vulnerability. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 tokenId) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the address zero. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Address.sol) pragma solidity ^0.8.20; import {Errors} from "./Errors.sol"; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev There's no code at `target` (it is not a contract). */ error AddressEmptyCode(address target); /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { if (address(this).balance < amount) { revert Errors.InsufficientBalance(address(this).balance, amount); } (bool success, ) = recipient.call{value: amount}(""); if (!success) { revert Errors.FailedCall(); } } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason or custom error, it is bubbled * up by this function (like regular Solidity function calls). However, if * the call reverted with no returned reason, this function reverts with a * {Errors.FailedCall} error. * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCallWithValue(target, data, 0); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { if (address(this).balance < value) { revert Errors.InsufficientBalance(address(this).balance, value); } (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target * was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case * of an unsuccessful call. */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata ) internal view returns (bytes memory) { if (!success) { _revert(returndata); } else { // only check if target is a contract if the call was successful and the return data is empty // otherwise we already know that it was a contract if (returndata.length == 0 && target.code.length == 0) { revert AddressEmptyCode(target); } return returndata; } } /** * @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the * revert reason or with a default {Errors.FailedCall} error. */ function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) { if (!success) { _revert(returndata); } else { return returndata; } } /** * @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}. */ function _revert(bytes memory returndata) private pure { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly ("memory-safe") { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert Errors.FailedCall(); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol) pragma solidity ^0.8.20; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } function _contextSuffixLength() internal view virtual returns (uint256) { return 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol) pragma solidity ^0.8.20; /** * @dev Collection of common custom errors used in multiple contracts * * IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library. * It is recommended to avoid relying on the error API for critical functionality. * * _Available since v5.1._ */ library Errors { /** * @dev The ETH balance of the account is not enough to perform the operation. */ error InsufficientBalance(uint256 balance, uint256 needed); /** * @dev A call to an address target failed. The target may have reverted. */ error FailedCall(); /** * @dev The deployment failed. */ error FailedDeployment(); /** * @dev A necessary precompile is missing. */ error MissingPrecompile(address); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol) pragma solidity ^0.8.20; /** * @dev Interface of the ERC-165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[ERC]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol) // This file was procedurally generated from scripts/generate/templates/SafeCast.js. pragma solidity ^0.8.20; /** * @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow * checks. * * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeCast { /** * @dev Value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value); /** * @dev An int value doesn't fit in an uint of `bits` size. */ error SafeCastOverflowedIntToUint(int256 value); /** * @dev Value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedIntDowncast(uint8 bits, int256 value); /** * @dev An uint value doesn't fit in an int of `bits` size. */ error SafeCastOverflowedUintToInt(uint256 value); /** * @dev Returns the downcasted uint248 from uint256, reverting on * overflow (when the input is greater than largest uint248). * * Counterpart to Solidity's `uint248` operator. * * Requirements: * * - input must fit into 248 bits */ function toUint248(uint256 value) internal pure returns (uint248) { if (value > type(uint248).max) { revert SafeCastOverflowedUintDowncast(248, value); } return uint248(value); } /** * @dev Returns the downcasted uint240 from uint256, reverting on * overflow (when the input is greater than largest uint240). * * Counterpart to Solidity's `uint240` operator. * * Requirements: * * - input must fit into 240 bits */ function toUint240(uint256 value) internal pure returns (uint240) { if (value > type(uint240).max) { revert SafeCastOverflowedUintDowncast(240, value); } return uint240(value); } /** * @dev Returns the downcasted uint232 from uint256, reverting on * overflow (when the input is greater than largest uint232). * * Counterpart to Solidity's `uint232` operator. * * Requirements: * * - input must fit into 232 bits */ function toUint232(uint256 value) internal pure returns (uint232) { if (value > type(uint232).max) { revert SafeCastOverflowedUintDowncast(232, value); } return uint232(value); } /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { if (value > type(uint224).max) { revert SafeCastOverflowedUintDowncast(224, value); } return uint224(value); } /** * @dev Returns the downcasted uint216 from uint256, reverting on * overflow (when the input is greater than largest uint216). * * Counterpart to Solidity's `uint216` operator. * * Requirements: * * - input must fit into 216 bits */ function toUint216(uint256 value) internal pure returns (uint216) { if (value > type(uint216).max) { revert SafeCastOverflowedUintDowncast(216, value); } return uint216(value); } /** * @dev Returns the downcasted uint208 from uint256, reverting on * overflow (when the input is greater than largest uint208). * * Counterpart to Solidity's `uint208` operator. * * Requirements: * * - input must fit into 208 bits */ function toUint208(uint256 value) internal pure returns (uint208) { if (value > type(uint208).max) { revert SafeCastOverflowedUintDowncast(208, value); } return uint208(value); } /** * @dev Returns the downcasted uint200 from uint256, reverting on * overflow (when the input is greater than largest uint200). * * Counterpart to Solidity's `uint200` operator. * * Requirements: * * - input must fit into 200 bits */ function toUint200(uint256 value) internal pure returns (uint200) { if (value > type(uint200).max) { revert SafeCastOverflowedUintDowncast(200, value); } return uint200(value); } /** * @dev Returns the downcasted uint192 from uint256, reverting on * overflow (when the input is greater than largest uint192). * * Counterpart to Solidity's `uint192` operator. * * Requirements: * * - input must fit into 192 bits */ function toUint192(uint256 value) internal pure returns (uint192) { if (value > type(uint192).max) { revert SafeCastOverflowedUintDowncast(192, value); } return uint192(value); } /** * @dev Returns the downcasted uint184 from uint256, reverting on * overflow (when the input is greater than largest uint184). * * Counterpart to Solidity's `uint184` operator. * * Requirements: * * - input must fit into 184 bits */ function toUint184(uint256 value) internal pure returns (uint184) { if (value > type(uint184).max) { revert SafeCastOverflowedUintDowncast(184, value); } return uint184(value); } /** * @dev Returns the downcasted uint176 from uint256, reverting on * overflow (when the input is greater than largest uint176). * * Counterpart to Solidity's `uint176` operator. * * Requirements: * * - input must fit into 176 bits */ function toUint176(uint256 value) internal pure returns (uint176) { if (value > type(uint176).max) { revert SafeCastOverflowedUintDowncast(176, value); } return uint176(value); } /** * @dev Returns the downcasted uint168 from uint256, reverting on * overflow (when the input is greater than largest uint168). * * Counterpart to Solidity's `uint168` operator. * * Requirements: * * - input must fit into 168 bits */ function toUint168(uint256 value) internal pure returns (uint168) { if (value > type(uint168).max) { revert SafeCastOverflowedUintDowncast(168, value); } return uint168(value); } /** * @dev Returns the downcasted uint160 from uint256, reverting on * overflow (when the input is greater than largest uint160). * * Counterpart to Solidity's `uint160` operator. * * Requirements: * * - input must fit into 160 bits */ function toUint160(uint256 value) internal pure returns (uint160) { if (value > type(uint160).max) { revert SafeCastOverflowedUintDowncast(160, value); } return uint160(value); } /** * @dev Returns the downcasted uint152 from uint256, reverting on * overflow (when the input is greater than largest uint152). * * Counterpart to Solidity's `uint152` operator. * * Requirements: * * - input must fit into 152 bits */ function toUint152(uint256 value) internal pure returns (uint152) { if (value > type(uint152).max) { revert SafeCastOverflowedUintDowncast(152, value); } return uint152(value); } /** * @dev Returns the downcasted uint144 from uint256, reverting on * overflow (when the input is greater than largest uint144). * * Counterpart to Solidity's `uint144` operator. * * Requirements: * * - input must fit into 144 bits */ function toUint144(uint256 value) internal pure returns (uint144) { if (value > type(uint144).max) { revert SafeCastOverflowedUintDowncast(144, value); } return uint144(value); } /** * @dev Returns the downcasted uint136 from uint256, reverting on * overflow (when the input is greater than largest uint136). * * Counterpart to Solidity's `uint136` operator. * * Requirements: * * - input must fit into 136 bits */ function toUint136(uint256 value) internal pure returns (uint136) { if (value > type(uint136).max) { revert SafeCastOverflowedUintDowncast(136, value); } return uint136(value); } /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { if (value > type(uint128).max) { revert SafeCastOverflowedUintDowncast(128, value); } return uint128(value); } /** * @dev Returns the downcasted uint120 from uint256, reverting on * overflow (when the input is greater than largest uint120). * * Counterpart to Solidity's `uint120` operator. * * Requirements: * * - input must fit into 120 bits */ function toUint120(uint256 value) internal pure returns (uint120) { if (value > type(uint120).max) { revert SafeCastOverflowedUintDowncast(120, value); } return uint120(value); } /** * @dev Returns the downcasted uint112 from uint256, reverting on * overflow (when the input is greater than largest uint112). * * Counterpart to Solidity's `uint112` operator. * * Requirements: * * - input must fit into 112 bits */ function toUint112(uint256 value) internal pure returns (uint112) { if (value > type(uint112).max) { revert SafeCastOverflowedUintDowncast(112, value); } return uint112(value); } /** * @dev Returns the downcasted uint104 from uint256, reverting on * overflow (when the input is greater than largest uint104). * * Counterpart to Solidity's `uint104` operator. * * Requirements: * * - input must fit into 104 bits */ function toUint104(uint256 value) internal pure returns (uint104) { if (value > type(uint104).max) { revert SafeCastOverflowedUintDowncast(104, value); } return uint104(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { if (value > type(uint96).max) { revert SafeCastOverflowedUintDowncast(96, value); } return uint96(value); } /** * @dev Returns the downcasted uint88 from uint256, reverting on * overflow (when the input is greater than largest uint88). * * Counterpart to Solidity's `uint88` operator. * * Requirements: * * - input must fit into 88 bits */ function toUint88(uint256 value) internal pure returns (uint88) { if (value > type(uint88).max) { revert SafeCastOverflowedUintDowncast(88, value); } return uint88(value); } /** * @dev Returns the downcasted uint80 from uint256, reverting on * overflow (when the input is greater than largest uint80). * * Counterpart to Solidity's `uint80` operator. * * Requirements: * * - input must fit into 80 bits */ function toUint80(uint256 value) internal pure returns (uint80) { if (value > type(uint80).max) { revert SafeCastOverflowedUintDowncast(80, value); } return uint80(value); } /** * @dev Returns the downcasted uint72 from uint256, reverting on * overflow (when the input is greater than largest uint72). * * Counterpart to Solidity's `uint72` operator. * * Requirements: * * - input must fit into 72 bits */ function toUint72(uint256 value) internal pure returns (uint72) { if (value > type(uint72).max) { revert SafeCastOverflowedUintDowncast(72, value); } return uint72(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { if (value > type(uint64).max) { revert SafeCastOverflowedUintDowncast(64, value); } return uint64(value); } /** * @dev Returns the downcasted uint56 from uint256, reverting on * overflow (when the input is greater than largest uint56). * * Counterpart to Solidity's `uint56` operator. * * Requirements: * * - input must fit into 56 bits */ function toUint56(uint256 value) internal pure returns (uint56) { if (value > type(uint56).max) { revert SafeCastOverflowedUintDowncast(56, value); } return uint56(value); } /** * @dev Returns the downcasted uint48 from uint256, reverting on * overflow (when the input is greater than largest uint48). * * Counterpart to Solidity's `uint48` operator. * * Requirements: * * - input must fit into 48 bits */ function toUint48(uint256 value) internal pure returns (uint48) { if (value > type(uint48).max) { revert SafeCastOverflowedUintDowncast(48, value); } return uint48(value); } /** * @dev Returns the downcasted uint40 from uint256, reverting on * overflow (when the input is greater than largest uint40). * * Counterpart to Solidity's `uint40` operator. * * Requirements: * * - input must fit into 40 bits */ function toUint40(uint256 value) internal pure returns (uint40) { if (value > type(uint40).max) { revert SafeCastOverflowedUintDowncast(40, value); } return uint40(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { if (value > type(uint32).max) { revert SafeCastOverflowedUintDowncast(32, value); } return uint32(value); } /** * @dev Returns the downcasted uint24 from uint256, reverting on * overflow (when the input is greater than largest uint24). * * Counterpart to Solidity's `uint24` operator. * * Requirements: * * - input must fit into 24 bits */ function toUint24(uint256 value) internal pure returns (uint24) { if (value > type(uint24).max) { revert SafeCastOverflowedUintDowncast(24, value); } return uint24(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { if (value > type(uint16).max) { revert SafeCastOverflowedUintDowncast(16, value); } return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits */ function toUint8(uint256 value) internal pure returns (uint8) { if (value > type(uint8).max) { revert SafeCastOverflowedUintDowncast(8, value); } return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { if (value < 0) { revert SafeCastOverflowedIntToUint(value); } return uint256(value); } /** * @dev Returns the downcasted int248 from int256, reverting on * overflow (when the input is less than smallest int248 or * greater than largest int248). * * Counterpart to Solidity's `int248` operator. * * Requirements: * * - input must fit into 248 bits */ function toInt248(int256 value) internal pure returns (int248 downcasted) { downcasted = int248(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(248, value); } } /** * @dev Returns the downcasted int240 from int256, reverting on * overflow (when the input is less than smallest int240 or * greater than largest int240). * * Counterpart to Solidity's `int240` operator. * * Requirements: * * - input must fit into 240 bits */ function toInt240(int256 value) internal pure returns (int240 downcasted) { downcasted = int240(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(240, value); } } /** * @dev Returns the downcasted int232 from int256, reverting on * overflow (when the input is less than smallest int232 or * greater than largest int232). * * Counterpart to Solidity's `int232` operator. * * Requirements: * * - input must fit into 232 bits */ function toInt232(int256 value) internal pure returns (int232 downcasted) { downcasted = int232(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(232, value); } } /** * @dev Returns the downcasted int224 from int256, reverting on * overflow (when the input is less than smallest int224 or * greater than largest int224). * * Counterpart to Solidity's `int224` operator. * * Requirements: * * - input must fit into 224 bits */ function toInt224(int256 value) internal pure returns (int224 downcasted) { downcasted = int224(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(224, value); } } /** * @dev Returns the downcasted int216 from int256, reverting on * overflow (when the input is less than smallest int216 or * greater than largest int216). * * Counterpart to Solidity's `int216` operator. * * Requirements: * * - input must fit into 216 bits */ function toInt216(int256 value) internal pure returns (int216 downcasted) { downcasted = int216(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(216, value); } } /** * @dev Returns the downcasted int208 from int256, reverting on * overflow (when the input is less than smallest int208 or * greater than largest int208). * * Counterpart to Solidity's `int208` operator. * * Requirements: * * - input must fit into 208 bits */ function toInt208(int256 value) internal pure returns (int208 downcasted) { downcasted = int208(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(208, value); } } /** * @dev Returns the downcasted int200 from int256, reverting on * overflow (when the input is less than smallest int200 or * greater than largest int200). * * Counterpart to Solidity's `int200` operator. * * Requirements: * * - input must fit into 200 bits */ function toInt200(int256 value) internal pure returns (int200 downcasted) { downcasted = int200(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(200, value); } } /** * @dev Returns the downcasted int192 from int256, reverting on * overflow (when the input is less than smallest int192 or * greater than largest int192). * * Counterpart to Solidity's `int192` operator. * * Requirements: * * - input must fit into 192 bits */ function toInt192(int256 value) internal pure returns (int192 downcasted) { downcasted = int192(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(192, value); } } /** * @dev Returns the downcasted int184 from int256, reverting on * overflow (when the input is less than smallest int184 or * greater than largest int184). * * Counterpart to Solidity's `int184` operator. * * Requirements: * * - input must fit into 184 bits */ function toInt184(int256 value) internal pure returns (int184 downcasted) { downcasted = int184(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(184, value); } } /** * @dev Returns the downcasted int176 from int256, reverting on * overflow (when the input is less than smallest int176 or * greater than largest int176). * * Counterpart to Solidity's `int176` operator. * * Requirements: * * - input must fit into 176 bits */ function toInt176(int256 value) internal pure returns (int176 downcasted) { downcasted = int176(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(176, value); } } /** * @dev Returns the downcasted int168 from int256, reverting on * overflow (when the input is less than smallest int168 or * greater than largest int168). * * Counterpart to Solidity's `int168` operator. * * Requirements: * * - input must fit into 168 bits */ function toInt168(int256 value) internal pure returns (int168 downcasted) { downcasted = int168(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(168, value); } } /** * @dev Returns the downcasted int160 from int256, reverting on * overflow (when the input is less than smallest int160 or * greater than largest int160). * * Counterpart to Solidity's `int160` operator. * * Requirements: * * - input must fit into 160 bits */ function toInt160(int256 value) internal pure returns (int160 downcasted) { downcasted = int160(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(160, value); } } /** * @dev Returns the downcasted int152 from int256, reverting on * overflow (when the input is less than smallest int152 or * greater than largest int152). * * Counterpart to Solidity's `int152` operator. * * Requirements: * * - input must fit into 152 bits */ function toInt152(int256 value) internal pure returns (int152 downcasted) { downcasted = int152(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(152, value); } } /** * @dev Returns the downcasted int144 from int256, reverting on * overflow (when the input is less than smallest int144 or * greater than largest int144). * * Counterpart to Solidity's `int144` operator. * * Requirements: * * - input must fit into 144 bits */ function toInt144(int256 value) internal pure returns (int144 downcasted) { downcasted = int144(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(144, value); } } /** * @dev Returns the downcasted int136 from int256, reverting on * overflow (when the input is less than smallest int136 or * greater than largest int136). * * Counterpart to Solidity's `int136` operator. * * Requirements: * * - input must fit into 136 bits */ function toInt136(int256 value) internal pure returns (int136 downcasted) { downcasted = int136(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(136, value); } } /** * @dev Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits */ function toInt128(int256 value) internal pure returns (int128 downcasted) { downcasted = int128(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(128, value); } } /** * @dev Returns the downcasted int120 from int256, reverting on * overflow (when the input is less than smallest int120 or * greater than largest int120). * * Counterpart to Solidity's `int120` operator. * * Requirements: * * - input must fit into 120 bits */ function toInt120(int256 value) internal pure returns (int120 downcasted) { downcasted = int120(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(120, value); } } /** * @dev Returns the downcasted int112 from int256, reverting on * overflow (when the input is less than smallest int112 or * greater than largest int112). * * Counterpart to Solidity's `int112` operator. * * Requirements: * * - input must fit into 112 bits */ function toInt112(int256 value) internal pure returns (int112 downcasted) { downcasted = int112(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(112, value); } } /** * @dev Returns the downcasted int104 from int256, reverting on * overflow (when the input is less than smallest int104 or * greater than largest int104). * * Counterpart to Solidity's `int104` operator. * * Requirements: * * - input must fit into 104 bits */ function toInt104(int256 value) internal pure returns (int104 downcasted) { downcasted = int104(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(104, value); } } /** * @dev Returns the downcasted int96 from int256, reverting on * overflow (when the input is less than smallest int96 or * greater than largest int96). * * Counterpart to Solidity's `int96` operator. * * Requirements: * * - input must fit into 96 bits */ function toInt96(int256 value) internal pure returns (int96 downcasted) { downcasted = int96(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(96, value); } } /** * @dev Returns the downcasted int88 from int256, reverting on * overflow (when the input is less than smallest int88 or * greater than largest int88). * * Counterpart to Solidity's `int88` operator. * * Requirements: * * - input must fit into 88 bits */ function toInt88(int256 value) internal pure returns (int88 downcasted) { downcasted = int88(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(88, value); } } /** * @dev Returns the downcasted int80 from int256, reverting on * overflow (when the input is less than smallest int80 or * greater than largest int80). * * Counterpart to Solidity's `int80` operator. * * Requirements: * * - input must fit into 80 bits */ function toInt80(int256 value) internal pure returns (int80 downcasted) { downcasted = int80(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(80, value); } } /** * @dev Returns the downcasted int72 from int256, reverting on * overflow (when the input is less than smallest int72 or * greater than largest int72). * * Counterpart to Solidity's `int72` operator. * * Requirements: * * - input must fit into 72 bits */ function toInt72(int256 value) internal pure returns (int72 downcasted) { downcasted = int72(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(72, value); } } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits */ function toInt64(int256 value) internal pure returns (int64 downcasted) { downcasted = int64(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(64, value); } } /** * @dev Returns the downcasted int56 from int256, reverting on * overflow (when the input is less than smallest int56 or * greater than largest int56). * * Counterpart to Solidity's `int56` operator. * * Requirements: * * - input must fit into 56 bits */ function toInt56(int256 value) internal pure returns (int56 downcasted) { downcasted = int56(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(56, value); } } /** * @dev Returns the downcasted int48 from int256, reverting on * overflow (when the input is less than smallest int48 or * greater than largest int48). * * Counterpart to Solidity's `int48` operator. * * Requirements: * * - input must fit into 48 bits */ function toInt48(int256 value) internal pure returns (int48 downcasted) { downcasted = int48(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(48, value); } } /** * @dev Returns the downcasted int40 from int256, reverting on * overflow (when the input is less than smallest int40 or * greater than largest int40). * * Counterpart to Solidity's `int40` operator. * * Requirements: * * - input must fit into 40 bits */ function toInt40(int256 value) internal pure returns (int40 downcasted) { downcasted = int40(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(40, value); } } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits */ function toInt32(int256 value) internal pure returns (int32 downcasted) { downcasted = int32(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(32, value); } } /** * @dev Returns the downcasted int24 from int256, reverting on * overflow (when the input is less than smallest int24 or * greater than largest int24). * * Counterpart to Solidity's `int24` operator. * * Requirements: * * - input must fit into 24 bits */ function toInt24(int256 value) internal pure returns (int24 downcasted) { downcasted = int24(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(24, value); } } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits */ function toInt16(int256 value) internal pure returns (int16 downcasted) { downcasted = int16(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(16, value); } } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits */ function toInt8(int256 value) internal pure returns (int8 downcasted) { downcasted = int8(value); if (downcasted != value) { revert SafeCastOverflowedIntDowncast(8, value); } } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive if (value > uint256(type(int256).max)) { revert SafeCastOverflowedUintToInt(value); } return int256(value); } /** * @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump. */ function toUint(bool b) internal pure returns (uint256 u) { assembly ("memory-safe") { u := iszero(iszero(b)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; import {DelegateCheckerLib} from "solady/src/utils/ext/delegatexyz/DelegateCheckerLib.sol"; import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import {ReentrancyGuardTransient} from "solady/src/utils/ReentrancyGuardTransient.sol"; interface SanctionsList { function isSanctioned(address addr) external view returns (bool); } contract ClaimChecker is ReentrancyGuardTransient { /// @dev Chainalysis sanctions contract. SanctionsList internal constant _SANCTIONS_LIST = SanctionsList(0x40C57923924B5c5c5455c48D93317139ADDaC8fb); /// @dev See: https://chainlist.org/chain/1 uint256 internal constant _CHAIN_ID_ETHEREUM = 1; /// @dev Key for subdelegation rights. bytes32 constant SUBDELEGATION_RIGHTS_KEY = bytes32(keccak256("AN_CLAIMER_PERMS")); /// @dev Maps an explicit contract to a claimer. mapping(address => address) public explicitContractClaimers; /// @dev Sets an explicit contract as a claimer for sender. function setExplicitContractAsClaimer(address claimerContractAddress) external { explicitContractClaimers[msg.sender] = claimerContractAddress; } /// @dev Checks if the claimer is authorized to claim for a set of NFTs and collectors. function checkClaims( uint256 claimNonce, address claimer, uint256[] calldata packedNFTIds, address[] calldata collectors, bool isClaimerContractOnL2 ) external nonReentrant returns (uint256, bool) { if (isSanctioned(claimer)) return (claimNonce, false); for (uint256 i; i < packedNFTIds.length; i++) { uint256 packed = packedNFTIds[i]; address nft = address(uint160(packed)); uint256 id = packed >> 160; if (!_checkNFTClaim(claimer, nft, id, isClaimerContractOnL2)) { return (claimNonce, false); } } for (uint256 i; i < collectors.length; i++) { if (!_checkCollectorClaim(claimer, collectors[i], isClaimerContractOnL2)) { return (claimNonce, false); } } return (claimNonce, true); } /// @dev Checks if the claimer is sanctioned on ethereum mainnet. function isSanctioned(address claimer) public view returns (bool) { if (block.chainid == _CHAIN_ID_ETHEREUM) { return _SANCTIONS_LIST.isSanctioned(claimer); } return false; } /// @dev Imperfect check on whether address is a smart contract. function _isContract(address addr) internal view returns (bool) { uint256 codeSize; assembly { codeSize := extcodesize(addr) } return codeSize > 0; } function _checkNFTClaim(address claimer, address nftContractAddress, uint256 tokenId, bool isClaimerContractOnL2) internal view returns (bool) { // Try to get the NFT owner, return false if the call fails try IERC721(nftContractAddress).ownerOf(tokenId) returns (address nftOwner) { // If claimer is a smart contract on either L2 or L1, it must have explicitly been delegated for this claim. if (_isContract(claimer) || isClaimerContractOnL2) { address explicitClaimer = explicitContractClaimers[nftOwner]; return !isSanctioned(nftOwner) && explicitClaimer != address(0) && explicitClaimer == claimer; } // forgefmt: disable-next-item if (nftOwner != claimer) { if (isSanctioned(nftOwner)) return false; // If a delegate all was made, this check will still pass. Same for delegate to nft with default all rights. // Subdelegation rights allows the option to delegate a specific nft for a specific right (e.g. claim). return DelegateCheckerLib.checkDelegateForERC721(claimer, nftOwner, nftContractAddress, tokenId, SUBDELEGATION_RIGHTS_KEY) || DelegateCheckerLib.checkDelegateForERC721(claimer, nftOwner, nftContractAddress, tokenId); } return true; } catch { return false; } } function _checkCollectorClaim(address claimer, address collector, bool isClaimerContractOnL2) internal view returns (bool) { // If claimer is a smart contract on either L2 or L1, it must have explicitly been delegated for this claim. if (_isContract(claimer) || isClaimerContractOnL2) { address explicitClaimer = explicitContractClaimers[collector]; return !isSanctioned(collector) && explicitClaimer != address(0) && explicitClaimer == claimer; } if (collector != claimer) { if (isSanctioned(collector)) return false; // If a delegate all with default all rights was made, this check will still pass. // Subdelegation rights allows the option to delegate for a specific right (e.g. claim). return DelegateCheckerLib.checkDelegateForAll(claimer, collector, SUBDELEGATION_RIGHTS_KEY) || DelegateCheckerLib.checkDelegateForAll(claimer, collector); } return true; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Gas optimized ECDSA wrapper. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ECDSA.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/ECDSA.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/ECDSA.sol) /// /// @dev Note: /// - The recovery functions use the ecrecover precompile (0x1). /// - As of Solady version 0.0.68, the `recover` variants will revert upon recovery failure. /// This is for more safety by default. /// Use the `tryRecover` variants if you need to get the zero address back /// upon recovery failure instead. /// - As of Solady version 0.0.134, all `bytes signature` variants accept both /// regular 65-byte `(r, s, v)` and EIP-2098 `(r, vs)` short form signatures. /// See: https://eips.ethereum.org/EIPS/eip-2098 /// This is for calldata efficiency on smart accounts prevalent on L2s. /// /// WARNING! Do NOT directly use signatures as unique identifiers: /// - The recovery operations do NOT check if a signature is non-malleable. /// - Use a nonce in the digest to prevent replay attacks on the same contract. /// - Use EIP-712 for the digest to prevent replay attacks across different chains and contracts. /// EIP-712 also enables readable signing of typed data for better user safety. /// - If you need a unique hash from a signature, please use the `canonicalHash` functions. library ECDSA { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The order of the secp256k1 elliptic curve. uint256 internal constant N = 0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141; /// @dev `N/2 + 1`. Used for checking the malleability of the signature. uint256 private constant _HALF_N_PLUS_1 = 0x7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a1; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The signature is invalid. error InvalidSignature(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* RECOVERY OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Recovers the signer's address from a message digest `hash`, and the `signature`. function recover(bytes32 hash, bytes memory signature) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { for { let m := mload(0x40) } 1 { mstore(0x00, 0x8baa579f) // `InvalidSignature()`. revert(0x1c, 0x04) } { switch mload(signature) case 64 { let vs := mload(add(signature, 0x40)) mstore(0x20, add(shr(255, vs), 27)) // `v`. mstore(0x60, shr(1, shl(1, vs))) // `s`. } case 65 { mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`. mstore(0x60, mload(add(signature, 0x40))) // `s`. } default { continue } mstore(0x00, hash) mstore(0x40, mload(add(signature, 0x20))) // `r`. result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20)) mstore(0x60, 0) // Restore the zero slot. mstore(0x40, m) // Restore the free memory pointer. // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. if returndatasize() { break } } } } /// @dev Recovers the signer's address from a message digest `hash`, and the `signature`. function recoverCalldata(bytes32 hash, bytes calldata signature) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { for { let m := mload(0x40) } 1 { mstore(0x00, 0x8baa579f) // `InvalidSignature()`. revert(0x1c, 0x04) } { switch signature.length case 64 { let vs := calldataload(add(signature.offset, 0x20)) mstore(0x20, add(shr(255, vs), 27)) // `v`. mstore(0x40, calldataload(signature.offset)) // `r`. mstore(0x60, shr(1, shl(1, vs))) // `s`. } case 65 { mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`. calldatacopy(0x40, signature.offset, 0x40) // Copy `r` and `s`. } default { continue } mstore(0x00, hash) result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20)) mstore(0x60, 0) // Restore the zero slot. mstore(0x40, m) // Restore the free memory pointer. // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. if returndatasize() { break } } } } /// @dev Recovers the signer's address from a message digest `hash`, /// and the EIP-2098 short form signature defined by `r` and `vs`. function recover(bytes32 hash, bytes32 r, bytes32 vs) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x00, hash) mstore(0x20, add(shr(255, vs), 27)) // `v`. mstore(0x40, r) mstore(0x60, shr(1, shl(1, vs))) // `s`. result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20)) // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. if iszero(returndatasize()) { mstore(0x00, 0x8baa579f) // `InvalidSignature()`. revert(0x1c, 0x04) } mstore(0x60, 0) // Restore the zero slot. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Recovers the signer's address from a message digest `hash`, /// and the signature defined by `v`, `r`, `s`. function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x00, hash) mstore(0x20, and(v, 0xff)) mstore(0x40, r) mstore(0x60, s) result := mload(staticcall(gas(), 1, 0x00, 0x80, 0x01, 0x20)) // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. if iszero(returndatasize()) { mstore(0x00, 0x8baa579f) // `InvalidSignature()`. revert(0x1c, 0x04) } mstore(0x60, 0) // Restore the zero slot. mstore(0x40, m) // Restore the free memory pointer. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* TRY-RECOVER OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // WARNING! // These functions will NOT revert upon recovery failure. // Instead, they will return the zero address upon recovery failure. // It is critical that the returned address is NEVER compared against // a zero address (e.g. an uninitialized address variable). /// @dev Recovers the signer's address from a message digest `hash`, and the `signature`. function tryRecover(bytes32 hash, bytes memory signature) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { for { let m := mload(0x40) } 1 {} { switch mload(signature) case 64 { let vs := mload(add(signature, 0x40)) mstore(0x20, add(shr(255, vs), 27)) // `v`. mstore(0x60, shr(1, shl(1, vs))) // `s`. } case 65 { mstore(0x20, byte(0, mload(add(signature, 0x60)))) // `v`. mstore(0x60, mload(add(signature, 0x40))) // `s`. } default { break } mstore(0x00, hash) mstore(0x40, mload(add(signature, 0x20))) // `r`. pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20)) mstore(0x60, 0) // Restore the zero slot. // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. result := mload(xor(0x60, returndatasize())) mstore(0x40, m) // Restore the free memory pointer. break } } } /// @dev Recovers the signer's address from a message digest `hash`, and the `signature`. function tryRecoverCalldata(bytes32 hash, bytes calldata signature) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { for { let m := mload(0x40) } 1 {} { switch signature.length case 64 { let vs := calldataload(add(signature.offset, 0x20)) mstore(0x20, add(shr(255, vs), 27)) // `v`. mstore(0x40, calldataload(signature.offset)) // `r`. mstore(0x60, shr(1, shl(1, vs))) // `s`. } case 65 { mstore(0x20, byte(0, calldataload(add(signature.offset, 0x40)))) // `v`. calldatacopy(0x40, signature.offset, 0x40) // Copy `r` and `s`. } default { break } mstore(0x00, hash) pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20)) mstore(0x60, 0) // Restore the zero slot. // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. result := mload(xor(0x60, returndatasize())) mstore(0x40, m) // Restore the free memory pointer. break } } } /// @dev Recovers the signer's address from a message digest `hash`, /// and the EIP-2098 short form signature defined by `r` and `vs`. function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x00, hash) mstore(0x20, add(shr(255, vs), 27)) // `v`. mstore(0x40, r) mstore(0x60, shr(1, shl(1, vs))) // `s`. pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20)) mstore(0x60, 0) // Restore the zero slot. // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. result := mload(xor(0x60, returndatasize())) mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Recovers the signer's address from a message digest `hash`, /// and the signature defined by `v`, `r`, `s`. function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns (address result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x00, hash) mstore(0x20, and(v, 0xff)) mstore(0x40, r) mstore(0x60, s) pop(staticcall(gas(), 1, 0x00, 0x80, 0x40, 0x20)) mstore(0x60, 0) // Restore the zero slot. // `returndatasize()` will be `0x20` upon success, and `0x00` otherwise. result := mload(xor(0x60, returndatasize())) mstore(0x40, m) // Restore the free memory pointer. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* HASHING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns an Ethereum Signed Message, created from a `hash`. /// This produces a hash corresponding to the one signed with the /// [`eth_sign`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign) /// JSON-RPC method as part of EIP-191. function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { mstore(0x20, hash) // Store into scratch space for keccak256. mstore(0x00, "\x00\x00\x00\x00\x19Ethereum Signed Message:\n32") // 28 bytes. result := keccak256(0x04, 0x3c) // `32 * 2 - (32 - 28) = 60 = 0x3c`. } } /// @dev Returns an Ethereum Signed Message, created from `s`. /// This produces a hash corresponding to the one signed with the /// [`eth_sign`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign) /// JSON-RPC method as part of EIP-191. /// Note: Supports lengths of `s` up to 999999 bytes. function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let sLength := mload(s) let o := 0x20 mstore(o, "\x19Ethereum Signed Message:\n") // 26 bytes, zero-right-padded. mstore(0x00, 0x00) // Convert the `s.length` to ASCII decimal representation: `base10(s.length)`. for { let temp := sLength } 1 {} { o := sub(o, 1) mstore8(o, add(48, mod(temp, 10))) temp := div(temp, 10) if iszero(temp) { break } } let n := sub(0x3a, o) // Header length: `26 + 32 - o`. // Throw an out-of-offset error (consumes all gas) if the header exceeds 32 bytes. returndatacopy(returndatasize(), returndatasize(), gt(n, 0x20)) mstore(s, or(mload(0x00), mload(n))) // Temporarily store the header. result := keccak256(add(s, sub(0x20, n)), add(n, sLength)) mstore(s, sLength) // Restore the length. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CANONICAL HASH FUNCTIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // The following functions returns the hash of the signature in it's canonicalized format, // which is the 65-byte `abi.encodePacked(r, s, uint8(v))`, where `v` is either 27 or 28. // If `s` is greater than `N / 2` then it will be converted to `N - s` // and the `v` value will be flipped. // If the signature has an invalid length, or if `v` is invalid, // a uniquely corrupt hash will be returned. // These functions are useful for "poor-mans-VRF". /// @dev Returns the canonical hash of `signature`. function canonicalHash(bytes memory signature) internal pure returns (bytes32 result) { // @solidity memory-safe-assembly assembly { let l := mload(signature) for {} 1 {} { mstore(0x00, mload(add(signature, 0x20))) // `r`. let s := mload(add(signature, 0x40)) let v := mload(add(signature, 0x41)) if eq(l, 64) { v := add(shr(255, s), 27) s := shr(1, shl(1, s)) } if iszero(lt(s, _HALF_N_PLUS_1)) { v := xor(v, 7) s := sub(N, s) } mstore(0x21, v) mstore(0x20, s) result := keccak256(0x00, 0x41) mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. break } // If the length is neither 64 nor 65, return a uniquely corrupted hash. if iszero(lt(sub(l, 64), 2)) { // `bytes4(keccak256("InvalidSignatureLength"))`. result := xor(keccak256(add(signature, 0x20), l), 0xd62f1ab2) } } } /// @dev Returns the canonical hash of `signature`. function canonicalHashCalldata(bytes calldata signature) internal pure returns (bytes32 result) { // @solidity memory-safe-assembly assembly { for {} 1 {} { mstore(0x00, calldataload(signature.offset)) // `r`. let s := calldataload(add(signature.offset, 0x20)) let v := calldataload(add(signature.offset, 0x21)) if eq(signature.length, 64) { v := add(shr(255, s), 27) s := shr(1, shl(1, s)) } if iszero(lt(s, _HALF_N_PLUS_1)) { v := xor(v, 7) s := sub(N, s) } mstore(0x21, v) mstore(0x20, s) result := keccak256(0x00, 0x41) mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. break } // If the length is neither 64 nor 65, return a uniquely corrupted hash. if iszero(lt(sub(signature.length, 64), 2)) { calldatacopy(mload(0x40), signature.offset, signature.length) // `bytes4(keccak256("InvalidSignatureLength"))`. result := xor(keccak256(mload(0x40), signature.length), 0xd62f1ab2) } } } /// @dev Returns the canonical hash of `signature`. function canonicalHash(bytes32 r, bytes32 vs) internal pure returns (bytes32 result) { // @solidity memory-safe-assembly assembly { mstore(0x00, r) // `r`. let v := add(shr(255, vs), 27) let s := shr(1, shl(1, vs)) mstore(0x21, v) mstore(0x20, s) result := keccak256(0x00, 0x41) mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. } } /// @dev Returns the canonical hash of `signature`. function canonicalHash(uint8 v, bytes32 r, bytes32 s) internal pure returns (bytes32 result) { // @solidity memory-safe-assembly assembly { mstore(0x00, r) // `r`. if iszero(lt(s, _HALF_N_PLUS_1)) { v := xor(v, 7) s := sub(N, s) } mstore(0x21, v) mstore(0x20, s) result := keccak256(0x00, 0x41) mstore(0x21, 0) // Restore the overwritten part of the free memory pointer. } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EMPTY CALLDATA HELPERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns an empty calldata bytes. function emptySignature() internal pure returns (bytes calldata signature) { /// @solidity memory-safe-assembly assembly { signature.length := 0 } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Library for efficiently performing keccak256 hashes. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/EfficientHashLib.sol) /// @dev To avoid stack-too-deep, you can use: /// ``` /// bytes32[] memory buffer = EfficientHashLib.malloc(10); /// EfficientHashLib.set(buffer, 0, value0); /// .. /// EfficientHashLib.set(buffer, 9, value9); /// bytes32 finalHash = EfficientHashLib.hash(buffer); /// ``` library EfficientHashLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MALLOC-LESS HASHING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `keccak256(abi.encode(v0))`. function hash(bytes32 v0) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { mstore(0x00, v0) result := keccak256(0x00, 0x20) } } /// @dev Returns `keccak256(abi.encode(v0))`. function hash(uint256 v0) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { mstore(0x00, v0) result := keccak256(0x00, 0x20) } } /// @dev Returns `keccak256(abi.encode(v0, v1))`. function hash(bytes32 v0, bytes32 v1) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { mstore(0x00, v0) mstore(0x20, v1) result := keccak256(0x00, 0x40) } } /// @dev Returns `keccak256(abi.encode(v0, v1))`. function hash(uint256 v0, uint256 v1) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { mstore(0x00, v0) mstore(0x20, v1) result := keccak256(0x00, 0x40) } } /// @dev Returns `keccak256(abi.encode(v0, v1, v2))`. function hash(bytes32 v0, bytes32 v1, bytes32 v2) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) result := keccak256(m, 0x60) } } /// @dev Returns `keccak256(abi.encode(v0, v1, v2))`. function hash(uint256 v0, uint256 v1, uint256 v2) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) result := keccak256(m, 0x60) } } /// @dev Returns `keccak256(abi.encode(v0, v1, v2, v3))`. function hash(bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) result := keccak256(m, 0x80) } } /// @dev Returns `keccak256(abi.encode(v0, v1, v2, v3))`. function hash(uint256 v0, uint256 v1, uint256 v2, uint256 v3) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) result := keccak256(m, 0x80) } } /// @dev Returns `keccak256(abi.encode(v0, .., v4))`. function hash(bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) result := keccak256(m, 0xa0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v4))`. function hash(uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) result := keccak256(m, 0xa0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v5))`. function hash(bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) result := keccak256(m, 0xc0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v5))`. function hash(uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) result := keccak256(m, 0xc0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v6))`. function hash( bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5, bytes32 v6 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) result := keccak256(m, 0xe0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v6))`. function hash( uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5, uint256 v6 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) result := keccak256(m, 0xe0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v7))`. function hash( bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5, bytes32 v6, bytes32 v7 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) result := keccak256(m, 0x100) } } /// @dev Returns `keccak256(abi.encode(v0, .., v7))`. function hash( uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5, uint256 v6, uint256 v7 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) result := keccak256(m, 0x100) } } /// @dev Returns `keccak256(abi.encode(v0, .., v8))`. function hash( bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5, bytes32 v6, bytes32 v7, bytes32 v8 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) result := keccak256(m, 0x120) } } /// @dev Returns `keccak256(abi.encode(v0, .., v8))`. function hash( uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5, uint256 v6, uint256 v7, uint256 v8 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) result := keccak256(m, 0x120) } } /// @dev Returns `keccak256(abi.encode(v0, .., v9))`. function hash( bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5, bytes32 v6, bytes32 v7, bytes32 v8, bytes32 v9 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) result := keccak256(m, 0x140) } } /// @dev Returns `keccak256(abi.encode(v0, .., v9))`. function hash( uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5, uint256 v6, uint256 v7, uint256 v8, uint256 v9 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) result := keccak256(m, 0x140) } } /// @dev Returns `keccak256(abi.encode(v0, .., v10))`. function hash( bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5, bytes32 v6, bytes32 v7, bytes32 v8, bytes32 v9, bytes32 v10 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) mstore(add(m, 0x140), v10) result := keccak256(m, 0x160) } } /// @dev Returns `keccak256(abi.encode(v0, .., v10))`. function hash( uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5, uint256 v6, uint256 v7, uint256 v8, uint256 v9, uint256 v10 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) mstore(add(m, 0x140), v10) result := keccak256(m, 0x160) } } /// @dev Returns `keccak256(abi.encode(v0, .., v11))`. function hash( bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5, bytes32 v6, bytes32 v7, bytes32 v8, bytes32 v9, bytes32 v10, bytes32 v11 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) mstore(add(m, 0x140), v10) mstore(add(m, 0x160), v11) result := keccak256(m, 0x180) } } /// @dev Returns `keccak256(abi.encode(v0, .., v11))`. function hash( uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5, uint256 v6, uint256 v7, uint256 v8, uint256 v9, uint256 v10, uint256 v11 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) mstore(add(m, 0x140), v10) mstore(add(m, 0x160), v11) result := keccak256(m, 0x180) } } /// @dev Returns `keccak256(abi.encode(v0, .., v12))`. function hash( bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5, bytes32 v6, bytes32 v7, bytes32 v8, bytes32 v9, bytes32 v10, bytes32 v11, bytes32 v12 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) mstore(add(m, 0x140), v10) mstore(add(m, 0x160), v11) mstore(add(m, 0x180), v12) result := keccak256(m, 0x1a0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v12))`. function hash( uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5, uint256 v6, uint256 v7, uint256 v8, uint256 v9, uint256 v10, uint256 v11, uint256 v12 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) mstore(add(m, 0x140), v10) mstore(add(m, 0x160), v11) mstore(add(m, 0x180), v12) result := keccak256(m, 0x1a0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v13))`. function hash( bytes32 v0, bytes32 v1, bytes32 v2, bytes32 v3, bytes32 v4, bytes32 v5, bytes32 v6, bytes32 v7, bytes32 v8, bytes32 v9, bytes32 v10, bytes32 v11, bytes32 v12, bytes32 v13 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) mstore(add(m, 0x140), v10) mstore(add(m, 0x160), v11) mstore(add(m, 0x180), v12) mstore(add(m, 0x1a0), v13) result := keccak256(m, 0x1c0) } } /// @dev Returns `keccak256(abi.encode(v0, .., v13))`. function hash( uint256 v0, uint256 v1, uint256 v2, uint256 v3, uint256 v4, uint256 v5, uint256 v6, uint256 v7, uint256 v8, uint256 v9, uint256 v10, uint256 v11, uint256 v12, uint256 v13 ) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, v0) mstore(add(m, 0x20), v1) mstore(add(m, 0x40), v2) mstore(add(m, 0x60), v3) mstore(add(m, 0x80), v4) mstore(add(m, 0xa0), v5) mstore(add(m, 0xc0), v6) mstore(add(m, 0xe0), v7) mstore(add(m, 0x100), v8) mstore(add(m, 0x120), v9) mstore(add(m, 0x140), v10) mstore(add(m, 0x160), v11) mstore(add(m, 0x180), v12) mstore(add(m, 0x1a0), v13) result := keccak256(m, 0x1c0) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* BYTES32 BUFFER HASHING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `keccak256(abi.encode(buffer[0], .., buffer[buffer.length - 1]))`. function hash(bytes32[] memory buffer) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { result := keccak256(add(buffer, 0x20), shl(5, mload(buffer))) } } /// @dev Sets `buffer[i]` to `value`, without a bounds check. /// Returns the `buffer` for function chaining. function set(bytes32[] memory buffer, uint256 i, bytes32 value) internal pure returns (bytes32[] memory) { /// @solidity memory-safe-assembly assembly { mstore(add(buffer, shl(5, add(1, i))), value) } return buffer; } /// @dev Sets `buffer[i]` to `value`, without a bounds check. /// Returns the `buffer` for function chaining. function set(bytes32[] memory buffer, uint256 i, uint256 value) internal pure returns (bytes32[] memory) { /// @solidity memory-safe-assembly assembly { mstore(add(buffer, shl(5, add(1, i))), value) } return buffer; } /// @dev Returns `new bytes32[](n)`, without zeroing out the memory. function malloc(uint256 n) internal pure returns (bytes32[] memory buffer) { /// @solidity memory-safe-assembly assembly { buffer := mload(0x40) mstore(buffer, n) mstore(0x40, add(shl(5, add(1, n)), buffer)) } } /// @dev Frees memory that has been allocated for `buffer`. /// No-op if `buffer.length` is zero, or if new memory has been allocated after `buffer`. function free(bytes32[] memory buffer) internal pure { /// @solidity memory-safe-assembly assembly { let n := mload(buffer) mstore(shl(6, lt(iszero(n), eq(add(shl(5, add(1, n)), buffer), mload(0x40)))), buffer) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EQUALITY CHECKS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `a == abi.decode(b, (bytes32))`. function eq(bytes32 a, bytes memory b) internal pure returns (bool result) { /// @solidity memory-safe-assembly assembly { result := and(eq(0x20, mload(b)), eq(a, mload(add(b, 0x20)))) } } /// @dev Returns `abi.decode(a, (bytes32)) == a`. function eq(bytes memory a, bytes32 b) internal pure returns (bool result) { /// @solidity memory-safe-assembly assembly { result := and(eq(0x20, mload(a)), eq(b, mload(add(a, 0x20)))) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* BYTE SLICE HASHING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the keccak256 of the slice from `start` to `end` (exclusive). /// `start` and `end` are byte offsets. function hash(bytes memory b, uint256 start, uint256 end) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let n := mload(b) end := xor(end, mul(xor(end, n), lt(n, end))) start := xor(start, mul(xor(start, n), lt(n, start))) result := keccak256(add(add(b, 0x20), start), mul(gt(end, start), sub(end, start))) } } /// @dev Returns the keccak256 of the slice from `start` to the end of the bytes. function hash(bytes memory b, uint256 start) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let n := mload(b) start := xor(start, mul(xor(start, n), lt(n, start))) result := keccak256(add(add(b, 0x20), start), mul(gt(n, start), sub(n, start))) } } /// @dev Returns the keccak256 of the bytes. function hash(bytes memory b) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { result := keccak256(add(b, 0x20), mload(b)) } } /// @dev Returns the keccak256 of the slice from `start` to `end` (exclusive). /// `start` and `end` are byte offsets. function hashCalldata(bytes calldata b, uint256 start, uint256 end) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { end := xor(end, mul(xor(end, b.length), lt(b.length, end))) start := xor(start, mul(xor(start, b.length), lt(b.length, start))) let n := mul(gt(end, start), sub(end, start)) calldatacopy(mload(0x40), add(b.offset, start), n) result := keccak256(mload(0x40), n) } } /// @dev Returns the keccak256 of the slice from `start` to the end of the bytes. function hashCalldata(bytes calldata b, uint256 start) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { start := xor(start, mul(xor(start, b.length), lt(b.length, start))) let n := mul(gt(b.length, start), sub(b.length, start)) calldatacopy(mload(0x40), add(b.offset, start), n) result := keccak256(mload(0x40), n) } } /// @dev Returns the keccak256 of the bytes. function hashCalldata(bytes calldata b) internal pure returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { calldatacopy(mload(0x40), b.offset, b.length) result := keccak256(mload(0x40), b.length) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* SHA2-256 HELPERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `sha256(abi.encode(b))`. Yes, it's more efficient. function sha2(bytes32 b) internal view returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { mstore(0x00, b) result := mload(staticcall(gas(), 2, 0x00, 0x20, 0x01, 0x20)) if iszero(returndatasize()) { invalid() } } } /// @dev Returns the sha256 of the slice from `start` to `end` (exclusive). /// `start` and `end` are byte offsets. function sha2(bytes memory b, uint256 start, uint256 end) internal view returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let n := mload(b) end := xor(end, mul(xor(end, n), lt(n, end))) start := xor(start, mul(xor(start, n), lt(n, start))) // forgefmt: disable-next-item result := mload(staticcall(gas(), 2, add(add(b, 0x20), start), mul(gt(end, start), sub(end, start)), 0x01, 0x20)) if iszero(returndatasize()) { invalid() } } } /// @dev Returns the sha256 of the slice from `start` to the end of the bytes. function sha2(bytes memory b, uint256 start) internal view returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { let n := mload(b) start := xor(start, mul(xor(start, n), lt(n, start))) // forgefmt: disable-next-item result := mload(staticcall(gas(), 2, add(add(b, 0x20), start), mul(gt(n, start), sub(n, start)), 0x01, 0x20)) if iszero(returndatasize()) { invalid() } } } /// @dev Returns the sha256 of the bytes. function sha2(bytes memory b) internal view returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { result := mload(staticcall(gas(), 2, add(b, 0x20), mload(b), 0x01, 0x20)) if iszero(returndatasize()) { invalid() } } } /// @dev Returns the sha256 of the slice from `start` to `end` (exclusive). /// `start` and `end` are byte offsets. function sha2Calldata(bytes calldata b, uint256 start, uint256 end) internal view returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { end := xor(end, mul(xor(end, b.length), lt(b.length, end))) start := xor(start, mul(xor(start, b.length), lt(b.length, start))) let n := mul(gt(end, start), sub(end, start)) calldatacopy(mload(0x40), add(b.offset, start), n) result := mload(staticcall(gas(), 2, mload(0x40), n, 0x01, 0x20)) if iszero(returndatasize()) { invalid() } } } /// @dev Returns the sha256 of the slice from `start` to the end of the bytes. function sha2Calldata(bytes calldata b, uint256 start) internal view returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { start := xor(start, mul(xor(start, b.length), lt(b.length, start))) let n := mul(gt(b.length, start), sub(b.length, start)) calldatacopy(mload(0x40), add(b.offset, start), n) result := mload(staticcall(gas(), 2, mload(0x40), n, 0x01, 0x20)) if iszero(returndatasize()) { invalid() } } } /// @dev Returns the sha256 of the bytes. function sha2Calldata(bytes calldata b) internal view returns (bytes32 result) { /// @solidity memory-safe-assembly assembly { calldatacopy(mload(0x40), b.offset, b.length) result := mload(staticcall(gas(), 2, mload(0x40), b.length, 0x01, 0x20)) if iszero(returndatasize()) { invalid() } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Library for efficient querying of the delegate registries. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ext/delegate/DelegateCheckerLib.sol) library DelegateCheckerLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The canonical delegate registry V1. /// See: https://etherscan.io/address/0x00000000000076a84fef008cdabe6409d2fe638b address internal constant DELEGATE_REGISTRY_V1 = 0x00000000000076A84feF008CDAbe6409d2FE638B; /// @dev The canonical delegate registry V2. /// See: https://etherscan.io/address/0x00000000000000447e69651d841bD8D104Bed493 address internal constant DELEGATE_REGISTRY_V2 = 0x00000000000000447e69651d841bD8D104Bed493; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* DELEGATE CHECKING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // Note: // - `to` is the delegate. Typically called the "hot wallet". // - `from` is the grantor of the delegate rights. Typically called the "cold vault". /// @dev Returns if `to` is a delegate of `from`. /// ``` /// v2.checkDelegateForAll(to, from, "") || /// v1.checkDelegateForAll(to, from) /// ``` function checkDelegateForAll(address to, address from) internal view returns (bool isValid) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // `0x60` is already 0. mstore(0x40, from) mstore(0x2c, shl(96, to)) mstore(0x0c, 0xe839bd53000000000000000000000000) // `checkDelegateForAll(address,address,bytes32)`. isValid := eq(mload(staticcall(gas(), DELEGATE_REGISTRY_V2, 0x1c, 0x64, 0x01, 0x20)), 1) if iszero(isValid) { mstore(0x01, 0x9c395bc200) // `checkDelegateForAll(address,address)`. isValid := eq(mload(staticcall(gas(), DELEGATE_REGISTRY_V1, 0x1c, 0x44, 0x01, 0x20)), 1) } mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Returns if `to` is a delegate of `from`. /// ``` /// v2.checkDelegateForAll(to, from, rights) || /// (rights == "" && v1.checkDelegateForAll(to, from)) /// ``` function checkDelegateForAll(address to, address from, bytes32 rights) internal view returns (bool isValid) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(0x60, rights) mstore(0x40, from) mstore(0x2c, shl(96, to)) mstore(0x0c, 0xe839bd53000000000000000000000000) // `checkDelegateForAll(address,address,bytes32)`. isValid := eq(mload(staticcall(gas(), DELEGATE_REGISTRY_V2, 0x1c, 0x64, 0x01, 0x20)), 1) if iszero(or(rights, isValid)) { mstore(0x01, 0x9c395bc200) // `checkDelegateForAll(address,address)`. isValid := eq(mload(staticcall(gas(), DELEGATE_REGISTRY_V1, 0x1c, 0x44, 0x01, 0x20)), 1) } mstore(0x40, m) // Restore the free memory pointer. mstore(0x60, 0) // Restore the zero pointer. } } /// @dev Returns if `to` is a delegate of `from` for the specified `contract_`. /// ``` /// v2.checkDelegateForContract(to, from, contract_, "") || /// v1.checkDelegateForContract(to, from, contract_) /// ``` /// Returns true if `checkDelegateForAll(to, from)` returns true. function checkDelegateForContract(address to, address from, address contract_) internal view returns (bool isValid) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(add(0x80, m), 0) mstore(add(0x60, m), contract_) mstore(add(0x4c, m), shl(96, from)) mstore(add(0x2c, m), shl(96, to)) // `checkDelegateForContract(address,address,address,bytes32)`. mstore(add(0x0c, m), 0x8988eea9000000000000000000000000) isValid := staticcall(gas(), DELEGATE_REGISTRY_V2, add(m, 0x1c), 0x84, m, 0x20) isValid := and(eq(mload(m), 1), isValid) if iszero(isValid) { mstore(m, 0x90c9a2d0) // `checkDelegateForContract(address,address,address)`. isValid := staticcall(gas(), DELEGATE_REGISTRY_V1, add(m, 0x1c), 0x64, m, 0x20) isValid := and(eq(mload(m), 1), isValid) } } } /// @dev Returns if `to` is a delegate of `from` for the specified `contract_`. /// ``` /// v2.checkDelegateForContract(to, from, contract_, rights) || /// (rights == "" && v1.checkDelegateForContract(to, from, contract_)) /// ``` /// Returns true if `checkDelegateForAll(to, from, rights)` returns true. function checkDelegateForContract(address to, address from, address contract_, bytes32 rights) internal view returns (bool isValid) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(add(0x80, m), rights) mstore(add(0x60, m), contract_) mstore(add(0x4c, m), shl(96, from)) mstore(add(0x2c, m), shl(96, to)) // `checkDelegateForContract(address,address,address,bytes32)`. mstore(add(0x0c, m), 0x8988eea9000000000000000000000000) isValid := staticcall(gas(), DELEGATE_REGISTRY_V2, add(m, 0x1c), 0x84, m, 0x20) isValid := and(eq(mload(m), 1), isValid) if iszero(or(rights, isValid)) { mstore(m, 0x90c9a2d0) // `checkDelegateForContract(address,address,address)`. isValid := staticcall(gas(), DELEGATE_REGISTRY_V1, add(m, 0x1c), 0x64, m, 0x20) isValid := and(eq(mload(m), 1), isValid) } } } /// @dev Returns if `to` is a delegate of `from` for the specified `contract_` and token `id`. /// ``` /// v2.checkDelegateForERC721(to, from, contract_, id, "") || /// v1.checkDelegateForToken(to, from, contract_, id) /// ``` /// Returns true if `checkDelegateForContract(to, from, contract_)` returns true. function checkDelegateForERC721(address to, address from, address contract_, uint256 id) internal view returns (bool isValid) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(add(0xa0, m), 0) mstore(add(0x80, m), id) mstore(add(0x60, m), contract_) mstore(add(0x4c, m), shl(96, from)) mstore(add(0x2c, m), shl(96, to)) // `checkDelegateForERC721(address,address,address,uint256,bytes32)`. mstore(add(0x0c, m), 0xb9f36874000000000000000000000000) isValid := staticcall(gas(), DELEGATE_REGISTRY_V2, add(m, 0x1c), 0xa4, m, 0x20) isValid := and(eq(mload(m), 1), isValid) if iszero(isValid) { mstore(m, 0xaba69cf8) // `checkDelegateForToken(address,address,address,uint256)`. isValid := staticcall(gas(), DELEGATE_REGISTRY_V1, add(m, 0x1c), 0x84, m, 0x20) isValid := and(eq(mload(m), 1), isValid) } } } /// @dev Returns if `to` is a delegate of `from` for the specified `contract_` and token `id`. /// ``` /// v2.checkDelegateForERC721(to, from, contract_, id, rights) || /// (rights == "" && v1.checkDelegateForToken(to, from, contract_, id)) /// ``` /// Returns true if `checkDelegateForContract(to, from, contract_, rights)` returns true. function checkDelegateForERC721( address to, address from, address contract_, uint256 id, bytes32 rights ) internal view returns (bool isValid) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(add(0xa0, m), rights) mstore(add(0x80, m), id) mstore(add(0x60, m), contract_) mstore(add(0x4c, m), shl(96, from)) mstore(add(0x2c, m), shl(96, to)) // `checkDelegateForERC721(address,address,address,uint256,bytes32)`. mstore(add(0x0c, m), 0xb9f36874000000000000000000000000) isValid := staticcall(gas(), DELEGATE_REGISTRY_V2, add(m, 0x1c), 0xa4, m, 0x20) isValid := and(eq(mload(m), 1), isValid) if iszero(or(rights, isValid)) { mstore(m, 0xaba69cf8) // `checkDelegateForToken(address,address,address,uint256)`. isValid := staticcall(gas(), DELEGATE_REGISTRY_V1, add(m, 0x1c), 0x84, m, 0x20) isValid := and(eq(mload(m), 1), isValid) } } } /// @dev Returns the amount of an ERC20 token for `contract_` /// that `to` is granted rights to act on the behalf of `from`. /// ``` /// max( /// v2.checkDelegateForERC20(to, from, contract_, ""), /// v1.checkDelegateForContract(to, from, contract_) ? type(uint256).max : 0 /// ) /// ``` /// Returns `type(uint256).max` if `checkDelegateForContract(to, from, contract_)` returns true. function checkDelegateForERC20(address to, address from, address contract_) internal view returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let o := add(0x80, m) mstore(o, 0) mstore(add(0x60, m), contract_) mstore(add(0x4c, m), shl(96, from)) mstore(add(0x2c, m), shl(96, to)) // `checkDelegateForERC20(address,address,address,bytes32)`. mstore(add(0x0c, m), 0xba63c817000000000000000000000000) amount := staticcall(gas(), DELEGATE_REGISTRY_V2, add(m, 0x1c), 0x84, o, 0x20) amount := mul(mload(o), amount) if not(amount) { mstore(m, 0x90c9a2d0) // `checkDelegateForContract(address,address,address)`. let t := staticcall(gas(), DELEGATE_REGISTRY_V1, add(m, 0x1c), 0x64, m, 0x20) amount := or(sub(0, and(eq(mload(m), 1), t)), amount) } } } /// @dev Returns the amount of an ERC20 token for `contract_` /// that `to` is granted rights to act on the behalf of `from`. /// ``` /// max( /// v2.checkDelegateForERC20(to, from, contract_, rights), /// (rights == "" && v1.checkDelegateForContract(to, from, contract_)) ? type(uint256).max : 0 /// ) /// ``` /// Returns `type(uint256).max` if `checkDelegateForContract(to, from, contract_, rights)` returns true. function checkDelegateForERC20(address to, address from, address contract_, bytes32 rights) internal view returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(0x00, 0) mstore(add(0x80, m), rights) mstore(add(0x60, m), contract_) mstore(add(0x4c, m), shl(96, from)) mstore(add(0x2c, m), shl(96, to)) // `checkDelegateForERC20(address,address,address,bytes32)`. mstore(add(0x0c, m), 0xba63c817000000000000000000000000) amount := staticcall(gas(), DELEGATE_REGISTRY_V2, add(m, 0x1c), 0x84, 0x00, 0x20) amount := mul(mload(0x00), amount) if iszero(or(rights, iszero(not(amount)))) { mstore(m, 0x90c9a2d0) // `checkDelegateForContract(address,address,address)`. let t := staticcall(gas(), DELEGATE_REGISTRY_V1, add(m, 0x1c), 0x64, m, 0x20) amount := or(sub(0, and(eq(mload(m), 1), t)), amount) } } } /// @dev Returns the amount of an ERC1155 token `id` for `contract_` /// that `to` is granted rights to act on the behalf of `from`. /// ``` /// max( /// v2.checkDelegateForERC1155(to, from, contract_, id, rights), /// v1.checkDelegateForContract(to, from, contract_, id) ? type(uint256).max : 0 /// ) /// ``` /// Returns `type(uint256).max` if `checkDelegateForContract(to, from, contract_)` returns true. function checkDelegateForERC1155(address to, address from, address contract_, uint256 id) internal view returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) let o := add(0xa0, m) mstore(o, 0) mstore(add(0x80, m), id) mstore(add(0x60, m), contract_) mstore(add(0x4c, m), shl(96, from)) mstore(add(0x2c, m), shl(96, to)) // `checkDelegateForERC1155(address,address,address,uint256,bytes32)`. mstore(add(0x0c, m), 0xb8705875000000000000000000000000) amount := staticcall(gas(), DELEGATE_REGISTRY_V2, add(m, 0x1c), 0xa4, o, 0x20) amount := mul(mload(o), amount) if not(amount) { mstore(m, 0x90c9a2d0) // `checkDelegateForContract(address,address,address)`. let t := staticcall(gas(), DELEGATE_REGISTRY_V1, add(m, 0x1c), 0x64, m, 0x20) amount := or(sub(0, and(eq(mload(m), 1), t)), amount) } } } /// @dev Returns the amount of an ERC1155 token `id` for `contract_` /// that `to` is granted rights to act on the behalf of `from`. /// ``` /// max( /// v2.checkDelegateForERC1155(to, from, contract_, id, rights), /// (rights == "" && v1.checkDelegateForContract(to, from, contract_, id)) ? type(uint256).max : 0 /// ) /// ``` /// Returns `type(uint256).max` if `checkDelegateForContract(to, from, contract_, rights)` returns true. function checkDelegateForERC1155( address to, address from, address contract_, uint256 id, bytes32 rights ) internal view returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(0x00, 0) mstore(add(0xa0, m), rights) mstore(add(0x80, m), id) mstore(add(0x60, m), contract_) mstore(add(0x4c, m), shl(96, from)) mstore(add(0x2c, m), shl(96, to)) // `checkDelegateForERC1155(address,address,address,uint256,bytes32)`. mstore(add(0x0c, m), 0xb8705875000000000000000000000000) amount := staticcall(gas(), DELEGATE_REGISTRY_V2, add(m, 0x1c), 0xa4, 0x00, 0x20) amount := mul(mload(0x00), amount) if iszero(or(rights, iszero(not(amount)))) { mstore(m, 0x90c9a2d0) // `checkDelegateForContract(address,address,address)`. let t := staticcall(gas(), DELEGATE_REGISTRY_V1, add(m, 0x1c), 0x64, m, 0x20) amount := or(sub(0, and(eq(mload(m), 1), t)), amount) } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Arithmetic library with operations for fixed-point numbers. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/FixedPointMathLib.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol) library FixedPointMathLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The operation failed, as the output exceeds the maximum value of uint256. error ExpOverflow(); /// @dev The operation failed, as the output exceeds the maximum value of uint256. error FactorialOverflow(); /// @dev The operation failed, due to an overflow. error RPowOverflow(); /// @dev The mantissa is too big to fit. error MantissaOverflow(); /// @dev The operation failed, due to an multiplication overflow. error MulWadFailed(); /// @dev The operation failed, due to an multiplication overflow. error SMulWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error DivWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error SDivWadFailed(); /// @dev The operation failed, either due to a multiplication overflow, or a division by a zero. error MulDivFailed(); /// @dev The division failed, as the denominator is zero. error DivFailed(); /// @dev The full precision multiply-divide operation failed, either due /// to the result being larger than 256 bits, or a division by a zero. error FullMulDivFailed(); /// @dev The output is undefined, as the input is less-than-or-equal to zero. error LnWadUndefined(); /// @dev The input outside the acceptable domain. error OutOfDomain(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The scalar of ETH and most ERC20s. uint256 internal constant WAD = 1e18; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* SIMPLIFIED FIXED POINT OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Equivalent to `(x * y) / WAD` rounded down. function mulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. if gt(x, div(not(0), y)) { if y { mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. revert(0x1c, 0x04) } } z := div(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down. function sMulWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require((x == 0 || z / x == y) && !(x == -1 && y == type(int256).min))`. if iszero(gt(or(iszero(x), eq(sdiv(z, x), y)), lt(not(x), eq(y, shl(255, 1))))) { mstore(0x00, 0xedcd4dd4) // `SMulWadFailed()`. revert(0x1c, 0x04) } z := sdiv(z, WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. function rawMulWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded down, but without overflow checks. function rawSMulWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(mul(x, y), WAD) } } /// @dev Equivalent to `(x * y) / WAD` rounded up. function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require(y == 0 || x <= type(uint256).max / y)`. if iszero(eq(div(z, y), x)) { if y { mstore(0x00, 0xbac65e5b) // `MulWadFailed()`. revert(0x1c, 0x04) } } z := add(iszero(iszero(mod(z, WAD))), div(z, WAD)) } } /// @dev Equivalent to `(x * y) / WAD` rounded up, but without overflow checks. function rawMulWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(iszero(iszero(mod(mul(x, y), WAD))), div(mul(x, y), WAD)) } } /// @dev Equivalent to `(x * WAD) / y` rounded down. function divWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`. if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) { mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. revert(0x1c, 0x04) } z := div(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down. function sDivWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, WAD) // Equivalent to `require(y != 0 && ((x * WAD) / WAD == x))`. if iszero(mul(y, eq(sdiv(z, WAD), x))) { mstore(0x00, 0x5c43740d) // `SDivWadFailed()`. revert(0x1c, 0x04) } z := sdiv(z, y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. function rawDivWad(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded down, but without overflow and divide by zero checks. function rawSDivWad(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(mul(x, WAD), y) } } /// @dev Equivalent to `(x * WAD) / y` rounded up. function divWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Equivalent to `require(y != 0 && x <= type(uint256).max / WAD)`. if iszero(mul(y, lt(x, add(1, div(not(0), WAD))))) { mstore(0x00, 0x7c5f487d) // `DivWadFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) } } /// @dev Equivalent to `(x * WAD) / y` rounded up, but without overflow and divide by zero checks. function rawDivWadUp(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(iszero(iszero(mod(mul(x, WAD), y))), div(mul(x, WAD), y)) } } /// @dev Equivalent to `x` to the power of `y`. /// because `x ** y = (e ** ln(x)) ** y = e ** (ln(x) * y)`. /// Note: This function is an approximation. function powWad(int256 x, int256 y) internal pure returns (int256) { // Using `ln(x)` means `x` must be greater than 0. return expWad((lnWad(x) * y) / int256(WAD)); } /// @dev Returns `exp(x)`, denominated in `WAD`. /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln /// Note: This function is an approximation. Monotonically increasing. function expWad(int256 x) internal pure returns (int256 r) { unchecked { // When the result is less than 0.5 we return zero. // This happens when `x <= (log(1e-18) * 1e18) ~ -4.15e19`. if (x <= -41446531673892822313) return r; /// @solidity memory-safe-assembly assembly { // When the result is greater than `(2**255 - 1) / 1e18` we can not represent it as // an int. This happens when `x >= floor(log((2**255 - 1) / 1e18) * 1e18) ≈ 135`. if iszero(slt(x, 135305999368893231589)) { mstore(0x00, 0xa37bfec9) // `ExpOverflow()`. revert(0x1c, 0x04) } } // `x` is now in the range `(-42, 136) * 1e18`. Convert to `(-42, 136) * 2**96` // for more intermediate precision and a binary basis. This base conversion // is a multiplication by 1e18 / 2**96 = 5**18 / 2**78. x = (x << 78) / 5 ** 18; // Reduce range of x to (-½ ln 2, ½ ln 2) * 2**96 by factoring out powers // of two such that exp(x) = exp(x') * 2**k, where k is an integer. // Solving this gives k = round(x / log(2)) and x' = x - k * log(2). int256 k = ((x << 96) / 54916777467707473351141471128 + 2 ** 95) >> 96; x = x - k * 54916777467707473351141471128; // `k` is in the range `[-61, 195]`. // Evaluate using a (6, 7)-term rational approximation. // `p` is made monic, we'll multiply by a scale factor later. int256 y = x + 1346386616545796478920950773328; y = ((y * x) >> 96) + 57155421227552351082224309758442; int256 p = y + x - 94201549194550492254356042504812; p = ((p * y) >> 96) + 28719021644029726153956944680412240; p = p * x + (4385272521454847904659076985693276 << 96); // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. int256 q = x - 2855989394907223263936484059900; q = ((q * x) >> 96) + 50020603652535783019961831881945; q = ((q * x) >> 96) - 533845033583426703283633433725380; q = ((q * x) >> 96) + 3604857256930695427073651918091429; q = ((q * x) >> 96) - 14423608567350463180887372962807573; q = ((q * x) >> 96) + 26449188498355588339934803723976023; /// @solidity memory-safe-assembly assembly { // Div in assembly because solidity adds a zero check despite the unchecked. // The q polynomial won't have zeros in the domain as all its roots are complex. // No scaling is necessary because p is already `2**96` too large. r := sdiv(p, q) } // r should be in the range `(0.09, 0.25) * 2**96`. // We now need to multiply r by: // - The scale factor `s ≈ 6.031367120`. // - The `2**k` factor from the range reduction. // - The `1e18 / 2**96` factor for base conversion. // We do this all at once, with an intermediate result in `2**213` // basis, so the final right shift is always by a positive amount. r = int256( (uint256(r) * 3822833074963236453042738258902158003155416615667) >> uint256(195 - k) ); } } /// @dev Returns `ln(x)`, denominated in `WAD`. /// Credit to Remco Bloemen under MIT license: https://2π.com/22/exp-ln /// Note: This function is an approximation. Monotonically increasing. function lnWad(int256 x) internal pure returns (int256 r) { /// @solidity memory-safe-assembly assembly { // We want to convert `x` from `10**18` fixed point to `2**96` fixed point. // We do this by multiplying by `2**96 / 10**18`. But since // `ln(x * C) = ln(x) + ln(C)`, we can simply do nothing here // and add `ln(2**96 / 10**18)` at the end. // Compute `k = log2(x) - 96`, `r = 159 - k = 255 - log2(x) = 255 ^ log2(x)`. r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // We place the check here for more optimal stack operations. if iszero(sgt(x, 0)) { mstore(0x00, 0x1615e638) // `LnWadUndefined()`. revert(0x1c, 0x04) } // forgefmt: disable-next-item r := xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)) // Reduce range of x to (1, 2) * 2**96 // ln(2^k * x) = k * ln(2) + ln(x) x := shr(159, shl(r, x)) // Evaluate using a (8, 8)-term rational approximation. // `p` is made monic, we will multiply by a scale factor later. // forgefmt: disable-next-item let p := sub( // This heavily nested expression is to avoid stack-too-deep for via-ir. sar(96, mul(add(43456485725739037958740375743393, sar(96, mul(add(24828157081833163892658089445524, sar(96, mul(add(3273285459638523848632254066296, x), x))), x))), x)), 11111509109440967052023855526967) p := sub(sar(96, mul(p, x)), 45023709667254063763336534515857) p := sub(sar(96, mul(p, x)), 14706773417378608786704636184526) p := sub(mul(p, x), shl(96, 795164235651350426258249787498)) // We leave `p` in `2**192` basis so we don't need to scale it back up for the division. // `q` is monic by convention. let q := add(5573035233440673466300451813936, x) q := add(71694874799317883764090561454958, sar(96, mul(x, q))) q := add(283447036172924575727196451306956, sar(96, mul(x, q))) q := add(401686690394027663651624208769553, sar(96, mul(x, q))) q := add(204048457590392012362485061816622, sar(96, mul(x, q))) q := add(31853899698501571402653359427138, sar(96, mul(x, q))) q := add(909429971244387300277376558375, sar(96, mul(x, q))) // `p / q` is in the range `(0, 0.125) * 2**96`. // Finalization, we need to: // - Multiply by the scale factor `s = 5.549…`. // - Add `ln(2**96 / 10**18)`. // - Add `k * ln(2)`. // - Multiply by `10**18 / 2**96 = 5**18 >> 78`. // The q polynomial is known not to have zeros in the domain. // No scaling required because p is already `2**96` too large. p := sdiv(p, q) // Multiply by the scaling factor: `s * 5**18 * 2**96`, base is now `5**18 * 2**192`. p := mul(1677202110996718588342820967067443963516166, p) // Add `ln(2) * k * 5**18 * 2**192`. // forgefmt: disable-next-item p := add(mul(16597577552685614221487285958193947469193820559219878177908093499208371, sub(159, r)), p) // Add `ln(2**96 / 10**18) * 5**18 * 2**192`. p := add(600920179829731861736702779321621459595472258049074101567377883020018308, p) // Base conversion: mul `2**18 / 2**192`. r := sar(174, p) } } /// @dev Returns `W_0(x)`, denominated in `WAD`. /// See: https://en.wikipedia.org/wiki/Lambert_W_function /// a.k.a. Product log function. This is an approximation of the principal branch. /// Note: This function is an approximation. Monotonically increasing. function lambertW0Wad(int256 x) internal pure returns (int256 w) { // forgefmt: disable-next-item unchecked { if ((w = x) <= -367879441171442322) revert OutOfDomain(); // `x` less than `-1/e`. (int256 wad, int256 p) = (int256(WAD), x); uint256 c; // Whether we need to avoid catastrophic cancellation. uint256 i = 4; // Number of iterations. if (w <= 0x1ffffffffffff) { if (-0x4000000000000 <= w) { i = 1; // Inputs near zero only take one step to converge. } else if (w <= -0x3ffffffffffffff) { i = 32; // Inputs near `-1/e` take very long to converge. } } else if (uint256(w >> 63) == uint256(0)) { /// @solidity memory-safe-assembly assembly { // Inline log2 for more performance, since the range is small. let v := shr(49, w) let l := shl(3, lt(0xff, v)) l := add(or(l, byte(and(0x1f, shr(shr(l, v), 0x8421084210842108cc6318c6db6d54be)), 0x0706060506020504060203020504030106050205030304010505030400000000)), 49) w := sdiv(shl(l, 7), byte(sub(l, 31), 0x0303030303030303040506080c13)) c := gt(l, 60) i := add(2, add(gt(l, 53), c)) } } else { int256 ll = lnWad(w = lnWad(w)); /// @solidity memory-safe-assembly assembly { // `w = ln(x) - ln(ln(x)) + b * ln(ln(x)) / ln(x)`. w := add(sdiv(mul(ll, 1023715080943847266), w), sub(w, ll)) i := add(3, iszero(shr(68, x))) c := iszero(shr(143, x)) } if (c == uint256(0)) { do { // If `x` is big, use Newton's so that intermediate values won't overflow. int256 e = expWad(w); /// @solidity memory-safe-assembly assembly { let t := mul(w, div(e, wad)) w := sub(w, sdiv(sub(t, x), div(add(e, t), wad))) } if (p <= w) break; p = w; } while (--i != uint256(0)); /// @solidity memory-safe-assembly assembly { w := sub(w, sgt(w, 2)) } return w; } } do { // Otherwise, use Halley's for faster convergence. int256 e = expWad(w); /// @solidity memory-safe-assembly assembly { let t := add(w, wad) let s := sub(mul(w, e), mul(x, wad)) w := sub(w, sdiv(mul(s, wad), sub(mul(e, t), sdiv(mul(add(t, wad), s), add(t, t))))) } if (p <= w) break; p = w; } while (--i != c); /// @solidity memory-safe-assembly assembly { w := sub(w, sgt(w, 2)) } // For certain ranges of `x`, we'll use the quadratic-rate recursive formula of // R. Iacono and J.P. Boyd for the last iteration, to avoid catastrophic cancellation. if (c == uint256(0)) return w; int256 t = w | 1; /// @solidity memory-safe-assembly assembly { x := sdiv(mul(x, wad), t) } x = (t * (wad + lnWad(x))); /// @solidity memory-safe-assembly assembly { w := sdiv(x, add(wad, t)) } } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* GENERAL NUMBER UTILITIES */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `a * b == x * y`, with full precision. function fullMulEq(uint256 a, uint256 b, uint256 x, uint256 y) internal pure returns (bool result) { /// @solidity memory-safe-assembly assembly { result := and(eq(mul(a, b), mul(x, y)), eq(mulmod(x, y, not(0)), mulmod(a, b, not(0)))) } } /// @dev Calculates `floor(x * y / d)` with full precision. /// Throws if result overflows a uint256 or when `d` is zero. /// Credit to Remco Bloemen under MIT license: https://2π.com/21/muldiv function fullMulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // 512-bit multiply `[p1 p0] = x * y`. // Compute the product mod `2**256` and mod `2**256 - 1` // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that `product = p1 * 2**256 + p0`. // Temporarily use `z` as `p0` to save gas. z := mul(x, y) // Lower 256 bits of `x * y`. for {} 1 {} { // If overflows. if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { let mm := mulmod(x, y, not(0)) let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`. /*------------------- 512 by 256 division --------------------*/ // Make division exact by subtracting the remainder from `[p1 p0]`. let r := mulmod(x, y, d) // Compute remainder using mulmod. let t := and(d, sub(0, d)) // The least significant bit of `d`. `t >= 1`. // Make sure `z` is less than `2**256`. Also prevents `d == 0`. // Placing the check here seems to give more optimal stack operations. if iszero(gt(d, p1)) { mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } d := div(d, t) // Divide `d` by `t`, which is a power of two. // Invert `d mod 2**256` // Now that `d` is an odd number, it has an inverse // modulo `2**256` such that `d * inv = 1 mod 2**256`. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, `d * inv = 1 mod 2**4`. let inv := xor(2, mul(3, d)) // Now use 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. inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**8 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**16 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**32 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**64 inv := mul(inv, sub(2, mul(d, inv))) // inverse mod 2**128 z := mul( // Divide [p1 p0] by the factors of two. // Shift in bits from `p1` into `p0`. For this we need // to flip `t` such that it is `2**256 / t`. or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)), mul(sub(2, mul(d, inv)), inv) // inverse mod 2**256 ) break } z := div(z, d) break } } } /// @dev Calculates `floor(x * y / d)` with full precision. /// Behavior is undefined if `d` is zero or the final result cannot fit in 256 bits. /// Performs the full 512 bit calculation regardless. function fullMulDivUnchecked(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) let mm := mulmod(x, y, not(0)) let p1 := sub(mm, add(z, lt(mm, z))) let t := and(d, sub(0, d)) let r := mulmod(x, y, d) d := div(d, t) let inv := xor(2, mul(3, d)) inv := mul(inv, sub(2, mul(d, inv))) inv := mul(inv, sub(2, mul(d, inv))) inv := mul(inv, sub(2, mul(d, inv))) inv := mul(inv, sub(2, mul(d, inv))) inv := mul(inv, sub(2, mul(d, inv))) z := mul( or(mul(sub(p1, gt(r, z)), add(div(sub(0, t), t), 1)), div(sub(z, r), t)), mul(sub(2, mul(d, inv)), inv) ) } } /// @dev Calculates `floor(x * y / d)` with full precision, rounded up. /// Throws if result overflows a uint256 or when `d` is zero. /// Credit to Uniswap-v3-core under MIT license: /// https://github.com/Uniswap/v3-core/blob/main/contracts/libraries/FullMath.sol function fullMulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { z = fullMulDiv(x, y, d); /// @solidity memory-safe-assembly assembly { if mulmod(x, y, d) { z := add(z, 1) if iszero(z) { mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } } } } /// @dev Calculates `floor(x * y / 2 ** n)` with full precision. /// Throws if result overflows a uint256. /// Credit to Philogy under MIT license: /// https://github.com/SorellaLabs/angstrom/blob/main/contracts/src/libraries/X128MathLib.sol function fullMulDivN(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // Temporarily use `z` as `p0` to save gas. z := mul(x, y) // Lower 256 bits of `x * y`. We'll call this `z`. for {} 1 {} { if iszero(or(iszero(x), eq(div(z, x), y))) { let k := and(n, 0xff) // `n`, cleaned. let mm := mulmod(x, y, not(0)) let p1 := sub(mm, add(z, lt(mm, z))) // Upper 256 bits of `x * y`. // | p1 | z | // Before: | p1_0 ¦ p1_1 | z_0 ¦ z_1 | // Final: | 0 ¦ p1_0 | p1_1 ¦ z_0 | // Check that final `z` doesn't overflow by checking that p1_0 = 0. if iszero(shr(k, p1)) { z := add(shl(sub(256, k), p1), shr(k, z)) break } mstore(0x00, 0xae47f702) // `FullMulDivFailed()`. revert(0x1c, 0x04) } z := shr(and(n, 0xff), z) break } } } /// @dev Returns `floor(x * y / d)`. /// Reverts if `x * y` overflows, or `d` is zero. function mulDiv(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`. if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { mstore(0x00, 0xad251c27) // `MulDivFailed()`. revert(0x1c, 0x04) } z := div(z, d) } } /// @dev Returns `ceil(x * y / d)`. /// Reverts if `x * y` overflows, or `d` is zero. function mulDivUp(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(x, y) // Equivalent to `require(d != 0 && (y == 0 || x <= type(uint256).max / y))`. if iszero(mul(or(iszero(x), eq(div(z, x), y)), d)) { mstore(0x00, 0xad251c27) // `MulDivFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(z, d))), div(z, d)) } } /// @dev Returns `x`, the modular multiplicative inverse of `a`, such that `(a * x) % n == 1`. function invMod(uint256 a, uint256 n) internal pure returns (uint256 x) { /// @solidity memory-safe-assembly assembly { let g := n let r := mod(a, n) for { let y := 1 } 1 {} { let q := div(g, r) let t := g g := r r := sub(t, mul(r, q)) let u := x x := y y := sub(u, mul(y, q)) if iszero(r) { break } } x := mul(eq(g, 1), add(x, mul(slt(x, 0), n))) } } /// @dev Returns `ceil(x / d)`. /// Reverts if `d` is zero. function divUp(uint256 x, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { if iszero(d) { mstore(0x00, 0x65244e4e) // `DivFailed()`. revert(0x1c, 0x04) } z := add(iszero(iszero(mod(x, d))), div(x, d)) } } /// @dev Returns `max(0, x - y)`. function zeroFloorSub(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(gt(x, y), sub(x, y)) } } /// @dev Returns `condition ? x : y`, without branching. function ternary(bool condition, uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), iszero(condition))) } } /// @dev Exponentiate `x` to `y` by squaring, denominated in base `b`. /// Reverts if the computation overflows. function rpow(uint256 x, uint256 y, uint256 b) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mul(b, iszero(y)) // `0 ** 0 = 1`. Otherwise, `0 ** n = 0`. if x { z := xor(b, mul(xor(b, x), and(y, 1))) // `z = isEven(y) ? scale : x` let half := shr(1, b) // Divide `b` by 2. // Divide `y` by 2 every iteration. for { y := shr(1, y) } y { y := shr(1, y) } { let xx := mul(x, x) // Store x squared. let xxRound := add(xx, half) // Round to the nearest number. // Revert if `xx + half` overflowed, or if `x ** 2` overflows. if or(lt(xxRound, xx), shr(128, x)) { mstore(0x00, 0x49f7642b) // `RPowOverflow()`. revert(0x1c, 0x04) } x := div(xxRound, b) // Set `x` to scaled `xxRound`. // If `y` is odd: if and(y, 1) { let zx := mul(z, x) // Compute `z * x`. let zxRound := add(zx, half) // Round to the nearest number. // If `z * x` overflowed or `zx + half` overflowed: if or(xor(div(zx, x), z), lt(zxRound, zx)) { // Revert if `x` is non-zero. if x { mstore(0x00, 0x49f7642b) // `RPowOverflow()`. revert(0x1c, 0x04) } } z := div(zxRound, b) // Return properly scaled `zxRound`. } } } } } /// @dev Returns the square root of `x`, rounded down. function sqrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { // `floor(sqrt(2**15)) = 181`. `sqrt(2**15) - 181 = 2.84`. z := 181 // The "correct" value is 1, but this saves a multiplication later. // This segment is to get a reasonable initial estimate for the Babylonian method. With a bad // start, the correct # of bits increases ~linearly each iteration instead of ~quadratically. // Let `y = x / 2**r`. We check `y >= 2**(k + 8)` // but shift right by `k` bits to ensure that if `x >= 256`, then `y >= 256`. let r := shl(7, lt(0xffffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffffff, shr(r, x)))) z := shl(shr(1, r), z) // Goal was to get `z*z*y` within a small factor of `x`. More iterations could // get y in a tighter range. Currently, we will have y in `[256, 256*(2**16))`. // We ensured `y >= 256` so that the relative difference between `y` and `y+1` is small. // That's not possible if `x < 256` but we can just verify those cases exhaustively. // Now, `z*z*y <= x < z*z*(y+1)`, and `y <= 2**(16+8)`, and either `y >= 256`, or `x < 256`. // Correctness can be checked exhaustively for `x < 256`, so we assume `y >= 256`. // Then `z*sqrt(y)` is within `sqrt(257)/sqrt(256)` of `sqrt(x)`, or about 20bps. // For `s` in the range `[1/256, 256]`, the estimate `f(s) = (181/1024) * (s+1)` // is in the range `(1/2.84 * sqrt(s), 2.84 * sqrt(s))`, // with largest error when `s = 1` and when `s = 256` or `1/256`. // Since `y` is in `[256, 256*(2**16))`, let `a = y/65536`, so that `a` is in `[1/256, 256)`. // Then we can estimate `sqrt(y)` using // `sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2**18`. // There is no overflow risk here since `y < 2**136` after the first branch above. z := shr(18, mul(z, add(shr(r, x), 65536))) // A `mul()` is saved from starting `z` at 181. // Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough. z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) z := shr(1, add(z, div(x, z))) // If `x+1` is a perfect square, the Babylonian method cycles between // `floor(sqrt(x))` and `ceil(sqrt(x))`. This statement ensures we return floor. // See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division z := sub(z, lt(div(x, z), z)) } } /// @dev Returns the cube root of `x`, rounded down. /// Credit to bout3fiddy and pcaversaccio under AGPLv3 license: /// https://github.com/pcaversaccio/snekmate/blob/main/src/utils/Math.vy /// Formally verified by xuwinnie: /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf function cbrt(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { let r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // Makeshift lookup table to nudge the approximate log2 result. z := div(shl(div(r, 3), shl(lt(0xf, shr(r, x)), 0xf)), xor(7, mod(r, 3))) // Newton-Raphson's. z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) z := div(add(add(div(x, mul(z, z)), z), z), 3) // Round down. z := sub(z, lt(div(x, mul(z, z)), z)) } } /// @dev Returns the square root of `x`, denominated in `WAD`, rounded down. function sqrtWad(uint256 x) internal pure returns (uint256 z) { unchecked { if (x <= type(uint256).max / 10 ** 18) return sqrt(x * 10 ** 18); z = (1 + sqrt(x)) * 10 ** 9; z = (fullMulDivUnchecked(x, 10 ** 18, z) + z) >> 1; } /// @solidity memory-safe-assembly assembly { z := sub(z, gt(999999999999999999, sub(mulmod(z, z, x), 1))) // Round down. } } /// @dev Returns the cube root of `x`, denominated in `WAD`, rounded down. /// Formally verified by xuwinnie: /// https://github.com/vectorized/solady/blob/main/audits/xuwinnie-solady-cbrt-proof.pdf function cbrtWad(uint256 x) internal pure returns (uint256 z) { unchecked { if (x <= type(uint256).max / 10 ** 36) return cbrt(x * 10 ** 36); z = (1 + cbrt(x)) * 10 ** 12; z = (fullMulDivUnchecked(x, 10 ** 36, z * z) + z + z) / 3; } /// @solidity memory-safe-assembly assembly { let p := x for {} 1 {} { if iszero(shr(229, p)) { if iszero(shr(199, p)) { p := mul(p, 100000000000000000) // 10 ** 17. break } p := mul(p, 100000000) // 10 ** 8. break } if iszero(shr(249, p)) { p := mul(p, 100) } break } let t := mulmod(mul(z, z), z, p) z := sub(z, gt(lt(t, shr(1, p)), iszero(t))) // Round down. } } /// @dev Returns the factorial of `x`. function factorial(uint256 x) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := 1 if iszero(lt(x, 58)) { mstore(0x00, 0xaba0f2a2) // `FactorialOverflow()`. revert(0x1c, 0x04) } for {} x { x := sub(x, 1) } { z := mul(z, x) } } } /// @dev Returns the log2 of `x`. /// Equivalent to computing the index of the most significant bit (MSB) of `x`. /// Returns 0 if `x` is zero. function log2(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // forgefmt: disable-next-item r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0x0706060506020504060203020504030106050205030304010505030400000000)) } } /// @dev Returns the log2 of `x`, rounded up. /// Returns 0 if `x` is zero. function log2Up(uint256 x) internal pure returns (uint256 r) { r = log2(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(shl(r, 1), x)) } } /// @dev Returns the log10 of `x`. /// Returns 0 if `x` is zero. function log10(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { if iszero(lt(x, 100000000000000000000000000000000000000)) { x := div(x, 100000000000000000000000000000000000000) r := 38 } if iszero(lt(x, 100000000000000000000)) { x := div(x, 100000000000000000000) r := add(r, 20) } if iszero(lt(x, 10000000000)) { x := div(x, 10000000000) r := add(r, 10) } if iszero(lt(x, 100000)) { x := div(x, 100000) r := add(r, 5) } r := add(r, add(gt(x, 9), add(gt(x, 99), add(gt(x, 999), gt(x, 9999))))) } } /// @dev Returns the log10 of `x`, rounded up. /// Returns 0 if `x` is zero. function log10Up(uint256 x) internal pure returns (uint256 r) { r = log10(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(exp(10, r), x)) } } /// @dev Returns the log256 of `x`. /// Returns 0 if `x` is zero. function log256(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(shr(3, r), lt(0xff, shr(r, x))) } } /// @dev Returns the log256 of `x`, rounded up. /// Returns 0 if `x` is zero. function log256Up(uint256 x) internal pure returns (uint256 r) { r = log256(x); /// @solidity memory-safe-assembly assembly { r := add(r, lt(shl(shl(3, r), 1), x)) } } /// @dev Returns the scientific notation format `mantissa * 10 ** exponent` of `x`. /// Useful for compressing prices (e.g. using 25 bit mantissa and 7 bit exponent). function sci(uint256 x) internal pure returns (uint256 mantissa, uint256 exponent) { /// @solidity memory-safe-assembly assembly { mantissa := x if mantissa { if iszero(mod(mantissa, 1000000000000000000000000000000000)) { mantissa := div(mantissa, 1000000000000000000000000000000000) exponent := 33 } if iszero(mod(mantissa, 10000000000000000000)) { mantissa := div(mantissa, 10000000000000000000) exponent := add(exponent, 19) } if iszero(mod(mantissa, 1000000000000)) { mantissa := div(mantissa, 1000000000000) exponent := add(exponent, 12) } if iszero(mod(mantissa, 1000000)) { mantissa := div(mantissa, 1000000) exponent := add(exponent, 6) } if iszero(mod(mantissa, 10000)) { mantissa := div(mantissa, 10000) exponent := add(exponent, 4) } if iszero(mod(mantissa, 100)) { mantissa := div(mantissa, 100) exponent := add(exponent, 2) } if iszero(mod(mantissa, 10)) { mantissa := div(mantissa, 10) exponent := add(exponent, 1) } } } } /// @dev Convenience function for packing `x` into a smaller number using `sci`. /// The `mantissa` will be in bits [7..255] (the upper 249 bits). /// The `exponent` will be in bits [0..6] (the lower 7 bits). /// Use `SafeCastLib` to safely ensure that the `packed` number is small /// enough to fit in the desired unsigned integer type: /// ``` /// uint32 packed = SafeCastLib.toUint32(FixedPointMathLib.packSci(777 ether)); /// ``` function packSci(uint256 x) internal pure returns (uint256 packed) { (x, packed) = sci(x); // Reuse for `mantissa` and `exponent`. /// @solidity memory-safe-assembly assembly { if shr(249, x) { mstore(0x00, 0xce30380c) // `MantissaOverflow()`. revert(0x1c, 0x04) } packed := or(shl(7, x), packed) } } /// @dev Convenience function for unpacking a packed number from `packSci`. function unpackSci(uint256 packed) internal pure returns (uint256 unpacked) { unchecked { unpacked = (packed >> 7) * 10 ** (packed & 0x7f); } } /// @dev Returns the average of `x` and `y`. Rounds towards zero. function avg(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = (x & y) + ((x ^ y) >> 1); } } /// @dev Returns the average of `x` and `y`. Rounds towards negative infinity. function avg(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = (x >> 1) + (y >> 1) + (x & y & 1); } } /// @dev Returns the absolute value of `x`. function abs(int256 x) internal pure returns (uint256 z) { unchecked { z = (uint256(x) + uint256(x >> 255)) ^ uint256(x >> 255); } } /// @dev Returns the absolute distance between `x` and `y`. function dist(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(xor(sub(0, gt(x, y)), sub(y, x)), gt(x, y)) } } /// @dev Returns the absolute distance between `x` and `y`. function dist(int256 x, int256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := add(xor(sub(0, sgt(x, y)), sub(y, x)), sgt(x, y)) } } /// @dev Returns the minimum of `x` and `y`. function min(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), lt(y, x))) } } /// @dev Returns the minimum of `x` and `y`. function min(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), slt(y, x))) } } /// @dev Returns the maximum of `x` and `y`. function max(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), gt(y, x))) } } /// @dev Returns the maximum of `x` and `y`. function max(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, y), sgt(y, x))) } } /// @dev Returns `x`, bounded to `minValue` and `maxValue`. function clamp(uint256 x, uint256 minValue, uint256 maxValue) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, minValue), gt(minValue, x))) z := xor(z, mul(xor(z, maxValue), lt(maxValue, z))) } } /// @dev Returns `x`, bounded to `minValue` and `maxValue`. function clamp(int256 x, int256 minValue, int256 maxValue) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := xor(x, mul(xor(x, minValue), sgt(minValue, x))) z := xor(z, mul(xor(z, maxValue), slt(maxValue, z))) } } /// @dev Returns greatest common divisor of `x` and `y`. function gcd(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { for { z := x } y {} { let t := y y := mod(z, y) z := t } } } /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`, /// with `t` clamped between `begin` and `end` (inclusive). /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`). /// If `begins == end`, returns `t <= begin ? a : b`. function lerp(uint256 a, uint256 b, uint256 t, uint256 begin, uint256 end) internal pure returns (uint256) { if (begin > end) (t, begin, end) = (~t, ~begin, ~end); if (t <= begin) return a; if (t >= end) return b; unchecked { if (b >= a) return a + fullMulDiv(b - a, t - begin, end - begin); return a - fullMulDiv(a - b, t - begin, end - begin); } } /// @dev Returns `a + (b - a) * (t - begin) / (end - begin)`. /// with `t` clamped between `begin` and `end` (inclusive). /// Agnostic to the order of (`a`, `b`) and (`end`, `begin`). /// If `begins == end`, returns `t <= begin ? a : b`. function lerp(int256 a, int256 b, int256 t, int256 begin, int256 end) internal pure returns (int256) { if (begin > end) (t, begin, end) = (~t, ~begin, ~end); if (t <= begin) return a; if (t >= end) return b; // forgefmt: disable-next-item unchecked { if (b >= a) return int256(uint256(a) + fullMulDiv(uint256(b - a), uint256(t - begin), uint256(end - begin))); return int256(uint256(a) - fullMulDiv(uint256(a - b), uint256(t - begin), uint256(end - begin))); } } /// @dev Returns if `x` is an even number. Some people may need this. function isEven(uint256 x) internal pure returns (bool) { return x & uint256(1) == uint256(0); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* RAW NUMBER OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns `x + y`, without checking for overflow. function rawAdd(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x + y; } } /// @dev Returns `x + y`, without checking for overflow. function rawAdd(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x + y; } } /// @dev Returns `x - y`, without checking for underflow. function rawSub(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x - y; } } /// @dev Returns `x - y`, without checking for underflow. function rawSub(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x - y; } } /// @dev Returns `x * y`, without checking for overflow. function rawMul(uint256 x, uint256 y) internal pure returns (uint256 z) { unchecked { z = x * y; } } /// @dev Returns `x * y`, without checking for overflow. function rawMul(int256 x, int256 y) internal pure returns (int256 z) { unchecked { z = x * y; } } /// @dev Returns `x / y`, returning 0 if `y` is zero. function rawDiv(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := div(x, y) } } /// @dev Returns `x / y`, returning 0 if `y` is zero. function rawSDiv(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := sdiv(x, y) } } /// @dev Returns `x % y`, returning 0 if `y` is zero. function rawMod(uint256 x, uint256 y) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mod(x, y) } } /// @dev Returns `x % y`, returning 0 if `y` is zero. function rawSMod(int256 x, int256 y) internal pure returns (int256 z) { /// @solidity memory-safe-assembly assembly { z := smod(x, y) } } /// @dev Returns `(x + y) % d`, return 0 if `d` if zero. function rawAddMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := addmod(x, y, d) } } /// @dev Returns `(x * y) % d`, return 0 if `d` if zero. function rawMulMod(uint256 x, uint256 y, uint256 d) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := mulmod(x, y, d) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; // This file is auto-generated. /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STRUCTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev A bitmap in storage. struct Bitmap { mapping(uint256 => uint256) map; } using LibBitmap for Bitmap global; import {LibBit} from "../LibBit.sol"; /// @notice Library for storage of packed unsigned booleans. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/g/LibBitmap.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/LibBitmap.sol) /// @author Modified from Solidity-Bits (https://github.com/estarriolvetch/solidity-bits/blob/main/contracts/BitMaps.sol) library LibBitmap { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The constant returned when a bitmap scan does not find a result. uint256 internal constant NOT_FOUND = type(uint256).max; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns the boolean value of the bit at `index` in `bitmap`. function get(Bitmap storage bitmap, uint256 index) internal view returns (bool isSet) { // It is better to set `isSet` to either 0 or 1, than zero vs non-zero. // Both cost the same amount of gas, but the former allows the returned value // to be reused without cleaning the upper bits. uint256 b = (bitmap.map[index >> 8] >> (index & 0xff)) & 1; /// @solidity memory-safe-assembly assembly { isSet := b } } /// @dev Updates the bit at `index` in `bitmap` to true. function set(Bitmap storage bitmap, uint256 index) internal { bitmap.map[index >> 8] |= (1 << (index & 0xff)); } /// @dev Updates the bit at `index` in `bitmap` to false. function unset(Bitmap storage bitmap, uint256 index) internal { bitmap.map[index >> 8] &= ~(1 << (index & 0xff)); } /// @dev Flips the bit at `index` in `bitmap`. /// Returns the boolean result of the flipped bit. function toggle(Bitmap storage bitmap, uint256 index) internal returns (bool newIsSet) { /// @solidity memory-safe-assembly assembly { mstore(0x20, bitmap.slot) mstore(0x00, shr(8, index)) let storageSlot := keccak256(0x00, 0x40) let shift := and(index, 0xff) let storageValue := xor(sload(storageSlot), shl(shift, 1)) // It makes sense to return the `newIsSet`, // as it allow us to skip an additional warm `sload`, // and it costs minimal gas (about 15), // which may be optimized away if the returned value is unused. newIsSet := and(1, shr(shift, storageValue)) sstore(storageSlot, storageValue) } } /// @dev Updates the bit at `index` in `bitmap` to `shouldSet`. function setTo(Bitmap storage bitmap, uint256 index, bool shouldSet) internal { /// @solidity memory-safe-assembly assembly { mstore(0x20, bitmap.slot) mstore(0x00, shr(8, index)) let storageSlot := keccak256(0x00, 0x40) let storageValue := sload(storageSlot) let shift := and(index, 0xff) sstore( storageSlot, // Unsets the bit at `shift` via `and`, then sets its new value via `or`. or(and(storageValue, not(shl(shift, 1))), shl(shift, iszero(iszero(shouldSet)))) ) } } /// @dev Consecutively sets `amount` of bits starting from the bit at `start`. function setBatch(Bitmap storage bitmap, uint256 start, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { let max := not(0) let shift := and(start, 0xff) mstore(0x20, bitmap.slot) mstore(0x00, shr(8, start)) if iszero(lt(add(shift, amount), 257)) { let storageSlot := keccak256(0x00, 0x40) sstore(storageSlot, or(sload(storageSlot), shl(shift, max))) let bucket := add(mload(0x00), 1) let bucketEnd := add(mload(0x00), shr(8, add(amount, shift))) amount := and(add(amount, shift), 0xff) shift := 0 for {} iszero(eq(bucket, bucketEnd)) { bucket := add(bucket, 1) } { mstore(0x00, bucket) sstore(keccak256(0x00, 0x40), max) } mstore(0x00, bucket) } let storageSlot := keccak256(0x00, 0x40) sstore(storageSlot, or(sload(storageSlot), shl(shift, shr(sub(256, amount), max)))) } } /// @dev Consecutively unsets `amount` of bits starting from the bit at `start`. function unsetBatch(Bitmap storage bitmap, uint256 start, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { let shift := and(start, 0xff) mstore(0x20, bitmap.slot) mstore(0x00, shr(8, start)) if iszero(lt(add(shift, amount), 257)) { let storageSlot := keccak256(0x00, 0x40) sstore(storageSlot, and(sload(storageSlot), not(shl(shift, not(0))))) let bucket := add(mload(0x00), 1) let bucketEnd := add(mload(0x00), shr(8, add(amount, shift))) amount := and(add(amount, shift), 0xff) shift := 0 for {} iszero(eq(bucket, bucketEnd)) { bucket := add(bucket, 1) } { mstore(0x00, bucket) sstore(keccak256(0x00, 0x40), 0) } mstore(0x00, bucket) } let storageSlot := keccak256(0x00, 0x40) sstore( storageSlot, and(sload(storageSlot), not(shl(shift, shr(sub(256, amount), not(0))))) ) } } /// @dev Returns number of set bits within a range by /// scanning `amount` of bits starting from the bit at `start`. function popCount(Bitmap storage bitmap, uint256 start, uint256 amount) internal view returns (uint256 count) { unchecked { uint256 bucket = start >> 8; uint256 shift = start & 0xff; if (!(amount + shift < 257)) { count = LibBit.popCount(bitmap.map[bucket] >> shift); uint256 bucketEnd = bucket + ((amount + shift) >> 8); amount = (amount + shift) & 0xff; shift = 0; for (++bucket; bucket != bucketEnd; ++bucket) { count += LibBit.popCount(bitmap.map[bucket]); } } count += LibBit.popCount((bitmap.map[bucket] >> shift) << (256 - amount)); } } /// @dev Returns the index of the most significant set bit in `[0..upTo]`. /// If no set bit is found, returns `NOT_FOUND`. function findLastSet(Bitmap storage bitmap, uint256 upTo) internal view returns (uint256 setBitIndex) { setBitIndex = NOT_FOUND; uint256 bucket = upTo >> 8; uint256 bits; /// @solidity memory-safe-assembly assembly { mstore(0x00, bucket) mstore(0x20, bitmap.slot) let offset := and(0xff, not(upTo)) // `256 - (255 & upTo) - 1`. bits := shr(offset, shl(offset, sload(keccak256(0x00, 0x40)))) if iszero(or(bits, iszero(bucket))) { for {} 1 {} { bucket := add(bucket, setBitIndex) // `sub(bucket, 1)`. mstore(0x00, bucket) bits := sload(keccak256(0x00, 0x40)) if or(bits, iszero(bucket)) { break } } } } if (bits != 0) { setBitIndex = (bucket << 8) | LibBit.fls(bits); /// @solidity memory-safe-assembly assembly { setBitIndex := or(setBitIndex, sub(0, gt(setBitIndex, upTo))) } } } /// @dev Returns the index of the least significant unset bit in `[begin..upTo]`. /// If no unset bit is found, returns `NOT_FOUND`. function findFirstUnset(Bitmap storage bitmap, uint256 begin, uint256 upTo) internal view returns (uint256 unsetBitIndex) { unsetBitIndex = NOT_FOUND; uint256 bucket = begin >> 8; uint256 negBits; /// @solidity memory-safe-assembly assembly { mstore(0x00, bucket) mstore(0x20, bitmap.slot) let offset := and(0xff, begin) negBits := shl(offset, shr(offset, not(sload(keccak256(0x00, 0x40))))) if iszero(negBits) { let lastBucket := shr(8, upTo) for {} 1 {} { bucket := add(bucket, 1) mstore(0x00, bucket) negBits := not(sload(keccak256(0x00, 0x40))) if or(negBits, gt(bucket, lastBucket)) { break } } if gt(bucket, lastBucket) { negBits := shl(and(0xff, not(upTo)), shr(and(0xff, not(upTo)), negBits)) } } } if (negBits != 0) { uint256 r = (bucket << 8) | LibBit.ffs(negBits); /// @solidity memory-safe-assembly assembly { unsetBitIndex := or(r, sub(0, or(gt(r, upTo), lt(r, begin)))) } } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Library for bit twiddling and boolean operations. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/LibBit.sol) /// @author Inspired by (https://graphics.stanford.edu/~seander/bithacks.html) library LibBit { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* BIT TWIDDLING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Find last set. /// Returns the index of the most significant bit of `x`, /// counting from the least significant bit position. /// If `x` is zero, returns 256. function fls(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { r := or(shl(8, iszero(x)), shl(7, lt(0xffffffffffffffffffffffffffffffff, x))) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // forgefmt: disable-next-item r := or(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0x0706060506020504060203020504030106050205030304010505030400000000)) } } /// @dev Count leading zeros. /// Returns the number of zeros preceding the most significant one bit. /// If `x` is zero, returns 256. function clz(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { r := shl(7, lt(0xffffffffffffffffffffffffffffffff, x)) r := or(r, shl(6, lt(0xffffffffffffffff, shr(r, x)))) r := or(r, shl(5, lt(0xffffffff, shr(r, x)))) r := or(r, shl(4, lt(0xffff, shr(r, x)))) r := or(r, shl(3, lt(0xff, shr(r, x)))) // forgefmt: disable-next-item r := add(xor(r, byte(and(0x1f, shr(shr(r, x), 0x8421084210842108cc6318c6db6d54be)), 0xf8f9f9faf9fdfafbf9fdfcfdfafbfcfef9fafdfafcfcfbfefafafcfbffffffff)), iszero(x)) } } /// @dev Find first set. /// Returns the index of the least significant bit of `x`, /// counting from the least significant bit position. /// If `x` is zero, returns 256. /// Equivalent to `ctz` (count trailing zeros), which gives /// the number of zeros following the least significant one bit. function ffs(uint256 x) internal pure returns (uint256 r) { /// @solidity memory-safe-assembly assembly { // Isolate the least significant bit. x := and(x, add(not(x), 1)) // For the upper 3 bits of the result, use a De Bruijn-like lookup. // Credit to adhusson: https://blog.adhusson.com/cheap-find-first-set-evm/ // forgefmt: disable-next-item r := shl(5, shr(252, shl(shl(2, shr(250, mul(x, 0xb6db6db6ddddddddd34d34d349249249210842108c6318c639ce739cffffffff))), 0x8040405543005266443200005020610674053026020000107506200176117077))) // For the lower 5 bits of the result, use a De Bruijn lookup. // forgefmt: disable-next-item r := or(r, byte(and(div(0xd76453e0, shr(r, x)), 0x1f), 0x001f0d1e100c1d070f090b19131c1706010e11080a1a141802121b1503160405)) } } /// @dev Returns the number of set bits in `x`. function popCount(uint256 x) internal pure returns (uint256 c) { /// @solidity memory-safe-assembly assembly { let max := not(0) let isMax := eq(x, max) x := sub(x, and(shr(1, x), div(max, 3))) x := add(and(x, div(max, 5)), and(shr(2, x), div(max, 5))) x := and(add(x, shr(4, x)), div(max, 17)) c := or(shl(8, isMax), shr(248, mul(x, div(max, 255)))) } } /// @dev Returns whether `x` is a power of 2. function isPo2(uint256 x) internal pure returns (bool result) { /// @solidity memory-safe-assembly assembly { // Equivalent to `x && !(x & (x - 1))`. result := iszero(add(and(x, sub(x, 1)), iszero(x))) } } /// @dev Returns `x` reversed at the bit level. function reverseBits(uint256 x) internal pure returns (uint256 r) { uint256 m0 = 0x0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f0f; uint256 m1 = m0 ^ (m0 << 2); uint256 m2 = m1 ^ (m1 << 1); r = reverseBytes(x); r = (m2 & (r >> 1)) | ((m2 & r) << 1); r = (m1 & (r >> 2)) | ((m1 & r) << 2); r = (m0 & (r >> 4)) | ((m0 & r) << 4); } /// @dev Returns `x` reversed at the byte level. function reverseBytes(uint256 x) internal pure returns (uint256 r) { unchecked { // Computing masks on-the-fly reduces bytecode size by about 200 bytes. uint256 m0 = 0x100000000000000000000000000000001 * (~toUint(x == uint256(0)) >> 192); uint256 m1 = m0 ^ (m0 << 32); uint256 m2 = m1 ^ (m1 << 16); uint256 m3 = m2 ^ (m2 << 8); r = (m3 & (x >> 8)) | ((m3 & x) << 8); r = (m2 & (r >> 16)) | ((m2 & r) << 16); r = (m1 & (r >> 32)) | ((m1 & r) << 32); r = (m0 & (r >> 64)) | ((m0 & r) << 64); r = (r >> 128) | (r << 128); } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* BOOLEAN OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // A Solidity bool on the stack or memory is represented as a 256-bit word. // Non-zero values are true, zero is false. // A clean bool is either 0 (false) or 1 (true) under the hood. // Usually, if not always, the bool result of a regular Solidity expression, // or the argument of a public/external function will be a clean bool. // You can usually use the raw variants for more performance. // If uncertain, test (best with exact compiler settings). // Or use the non-raw variants (compiler can sometimes optimize out the double `iszero`s). /// @dev Returns `x & y`. Inputs must be clean. function rawAnd(bool x, bool y) internal pure returns (bool z) { /// @solidity memory-safe-assembly assembly { z := and(x, y) } } /// @dev Returns `x & y`. function and(bool x, bool y) internal pure returns (bool z) { /// @solidity memory-safe-assembly assembly { z := and(iszero(iszero(x)), iszero(iszero(y))) } } /// @dev Returns `x | y`. Inputs must be clean. function rawOr(bool x, bool y) internal pure returns (bool z) { /// @solidity memory-safe-assembly assembly { z := or(x, y) } } /// @dev Returns `x | y`. function or(bool x, bool y) internal pure returns (bool z) { /// @solidity memory-safe-assembly assembly { z := or(iszero(iszero(x)), iszero(iszero(y))) } } /// @dev Returns 1 if `b` is true, else 0. Input must be clean. function rawToUint(bool b) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := b } } /// @dev Returns 1 if `b` is true, else 0. function toUint(bool b) internal pure returns (uint256 z) { /// @solidity memory-safe-assembly assembly { z := iszero(iszero(b)) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Gas optimized verification of proof of inclusion for a leaf in a Merkle tree. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/MerkleProofLib.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/MerkleProofLib.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/cryptography/MerkleProof.sol) library MerkleProofLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* MERKLE PROOF VERIFICATION OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`. function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool isValid) { /// @solidity memory-safe-assembly assembly { if mload(proof) { // Initialize `offset` to the offset of `proof` elements in memory. let offset := add(proof, 0x20) // Left shift by 5 is equivalent to multiplying by 0x20. let end := add(offset, shl(5, mload(proof))) // Iterate over proof elements to compute root hash. for {} 1 {} { // Slot of `leaf` in scratch space. // If the condition is true: 0x20, otherwise: 0x00. let scratch := shl(5, gt(leaf, mload(offset))) // Store elements to hash contiguously in scratch space. // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes. mstore(scratch, leaf) mstore(xor(scratch, 0x20), mload(offset)) // Reuse `leaf` to store the hash to reduce stack operations. leaf := keccak256(0x00, 0x40) offset := add(offset, 0x20) if iszero(lt(offset, end)) { break } } } isValid := eq(leaf, root) } } /// @dev Returns whether `leaf` exists in the Merkle tree with `root`, given `proof`. function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool isValid) { /// @solidity memory-safe-assembly assembly { if proof.length { // Left shift by 5 is equivalent to multiplying by 0x20. let end := add(proof.offset, shl(5, proof.length)) // Initialize `offset` to the offset of `proof` in the calldata. let offset := proof.offset // Iterate over proof elements to compute root hash. for {} 1 {} { // Slot of `leaf` in scratch space. // If the condition is true: 0x20, otherwise: 0x00. let scratch := shl(5, gt(leaf, calldataload(offset))) // Store elements to hash contiguously in scratch space. // Scratch space is 64 bytes (0x00 - 0x3f) and both elements are 32 bytes. mstore(scratch, leaf) mstore(xor(scratch, 0x20), calldataload(offset)) // Reuse `leaf` to store the hash to reduce stack operations. leaf := keccak256(0x00, 0x40) offset := add(offset, 0x20) if iszero(lt(offset, end)) { break } } } isValid := eq(leaf, root) } } /// @dev Returns whether all `leaves` exist in the Merkle tree with `root`, /// given `proof` and `flags`. /// /// Note: /// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length` /// will always return false. /// - The sum of the lengths of `proof` and `leaves` must never overflow. /// - Any non-zero word in the `flags` array is treated as true. /// - The memory offset of `proof` must be non-zero /// (i.e. `proof` is not pointing to the scratch space). function verifyMultiProof( bytes32[] memory proof, bytes32 root, bytes32[] memory leaves, bool[] memory flags ) internal pure returns (bool isValid) { // Rebuilds the root by consuming and producing values on a queue. // The queue starts with the `leaves` array, and goes into a `hashes` array. // After the process, the last element on the queue is verified // to be equal to the `root`. // // The `flags` array denotes whether the sibling // should be popped from the queue (`flag == true`), or // should be popped from the `proof` (`flag == false`). /// @solidity memory-safe-assembly assembly { // Cache the lengths of the arrays. let leavesLength := mload(leaves) let proofLength := mload(proof) let flagsLength := mload(flags) // Advance the pointers of the arrays to point to the data. leaves := add(0x20, leaves) proof := add(0x20, proof) flags := add(0x20, flags) // If the number of flags is correct. for {} eq(add(leavesLength, proofLength), add(flagsLength, 1)) {} { // For the case where `proof.length + leaves.length == 1`. if iszero(flagsLength) { // `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`. isValid := eq(mload(xor(leaves, mul(xor(proof, leaves), proofLength))), root) break } // The required final proof offset if `flagsLength` is not zero, otherwise zero. let proofEnd := add(proof, shl(5, proofLength)) // We can use the free memory space for the queue. // We don't need to allocate, since the queue is temporary. let hashesFront := mload(0x40) // Copy the leaves into the hashes. // Sometimes, a little memory expansion costs less than branching. // Should cost less, even with a high free memory offset of 0x7d00. leavesLength := shl(5, leavesLength) for { let i := 0 } iszero(eq(i, leavesLength)) { i := add(i, 0x20) } { mstore(add(hashesFront, i), mload(add(leaves, i))) } // Compute the back of the hashes. let hashesBack := add(hashesFront, leavesLength) // This is the end of the memory for the queue. // We recycle `flagsLength` to save on stack variables (sometimes save gas). flagsLength := add(hashesBack, shl(5, flagsLength)) for {} 1 {} { // Pop from `hashes`. let a := mload(hashesFront) // Pop from `hashes`. let b := mload(add(hashesFront, 0x20)) hashesFront := add(hashesFront, 0x40) // If the flag is false, load the next proof, // else, pops from the queue. if iszero(mload(flags)) { // Loads the next proof. b := mload(proof) proof := add(proof, 0x20) // Unpop from `hashes`. hashesFront := sub(hashesFront, 0x20) } // Advance to the next flag. flags := add(flags, 0x20) // Slot of `a` in scratch space. // If the condition is true: 0x20, otherwise: 0x00. let scratch := shl(5, gt(a, b)) // Hash the scratch space and push the result onto the queue. mstore(scratch, a) mstore(xor(scratch, 0x20), b) mstore(hashesBack, keccak256(0x00, 0x40)) hashesBack := add(hashesBack, 0x20) if iszero(lt(hashesBack, flagsLength)) { break } } isValid := and( // Checks if the last value in the queue is same as the root. eq(mload(sub(hashesBack, 0x20)), root), // And whether all the proofs are used, if required. eq(proofEnd, proof) ) break } } } /// @dev Returns whether all `leaves` exist in the Merkle tree with `root`, /// given `proof` and `flags`. /// /// Note: /// - Breaking the invariant `flags.length == (leaves.length - 1) + proof.length` /// will always return false. /// - Any non-zero word in the `flags` array is treated as true. /// - The calldata offset of `proof` must be non-zero /// (i.e. `proof` is from a regular Solidity function with a 4-byte selector). function verifyMultiProofCalldata( bytes32[] calldata proof, bytes32 root, bytes32[] calldata leaves, bool[] calldata flags ) internal pure returns (bool isValid) { // Rebuilds the root by consuming and producing values on a queue. // The queue starts with the `leaves` array, and goes into a `hashes` array. // After the process, the last element on the queue is verified // to be equal to the `root`. // // The `flags` array denotes whether the sibling // should be popped from the queue (`flag == true`), or // should be popped from the `proof` (`flag == false`). /// @solidity memory-safe-assembly assembly { // If the number of flags is correct. for {} eq(add(leaves.length, proof.length), add(flags.length, 1)) {} { // For the case where `proof.length + leaves.length == 1`. if iszero(flags.length) { // `isValid = (proof.length == 1 ? proof[0] : leaves[0]) == root`. // forgefmt: disable-next-item isValid := eq( calldataload( xor(leaves.offset, mul(xor(proof.offset, leaves.offset), proof.length)) ), root ) break } // The required final proof offset if `flagsLength` is not zero, otherwise zero. let proofEnd := add(proof.offset, shl(5, proof.length)) // We can use the free memory space for the queue. // We don't need to allocate, since the queue is temporary. let hashesFront := mload(0x40) // Copy the leaves into the hashes. // Sometimes, a little memory expansion costs less than branching. // Should cost less, even with a high free memory offset of 0x7d00. calldatacopy(hashesFront, leaves.offset, shl(5, leaves.length)) // Compute the back of the hashes. let hashesBack := add(hashesFront, shl(5, leaves.length)) // This is the end of the memory for the queue. // We recycle `flagsLength` to save on stack variables (sometimes save gas). flags.length := add(hashesBack, shl(5, flags.length)) // We don't need to make a copy of `proof.offset` or `flags.offset`, // as they are pass-by-value (this trick may not always save gas). for {} 1 {} { // Pop from `hashes`. let a := mload(hashesFront) // Pop from `hashes`. let b := mload(add(hashesFront, 0x20)) hashesFront := add(hashesFront, 0x40) // If the flag is false, load the next proof, // else, pops from the queue. if iszero(calldataload(flags.offset)) { // Loads the next proof. b := calldataload(proof.offset) proof.offset := add(proof.offset, 0x20) // Unpop from `hashes`. hashesFront := sub(hashesFront, 0x20) } // Advance to the next flag offset. flags.offset := add(flags.offset, 0x20) // Slot of `a` in scratch space. // If the condition is true: 0x20, otherwise: 0x00. let scratch := shl(5, gt(a, b)) // Hash the scratch space and push the result onto the queue. mstore(scratch, a) mstore(xor(scratch, 0x20), b) mstore(hashesBack, keccak256(0x00, 0x40)) hashesBack := add(hashesBack, 0x20) if iszero(lt(hashesBack, flags.length)) { break } } isValid := and( // Checks if the last value in the queue is same as the root. eq(mload(sub(hashesBack, 0x20)), root), // And whether all the proofs are used, if required. eq(proofEnd, proof.offset) ) break } } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* EMPTY CALLDATA HELPERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Returns an empty calldata bytes32 array. function emptyProof() internal pure returns (bytes32[] calldata proof) { /// @solidity memory-safe-assembly assembly { proof.length := 0 } } /// @dev Returns an empty calldata bytes32 array. function emptyLeaves() internal pure returns (bytes32[] calldata leaves) { /// @solidity memory-safe-assembly assembly { leaves.length := 0 } } /// @dev Returns an empty calldata bool array. function emptyFlags() internal pure returns (bool[] calldata flags) { /// @solidity memory-safe-assembly assembly { flags.length := 0 } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.24; /// @notice Reentrancy guard mixin (transient storage variant). /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/ReentrancyGuardTransient.sol) /// /// @dev Note: This implementation utilizes the `TSTORE` and `TLOAD` opcodes. /// Please ensure that the chain you are deploying on supports them. abstract contract ReentrancyGuardTransient { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Unauthorized reentrant call. error Reentrancy(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* STORAGE */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Equivalent to: `uint32(bytes4(keccak256("Reentrancy()"))) | 1 << 71`. /// 9 bytes is large enough to avoid collisions in practice, /// but not too large to result in excessive bytecode bloat. uint256 private constant _REENTRANCY_GUARD_SLOT = 0x8000000000ab143c06; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* REENTRANCY GUARD */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Guards a function from reentrancy. modifier nonReentrant() virtual { if (_useTransientReentrancyGuardOnlyOnMainnet()) { uint256 s = _REENTRANCY_GUARD_SLOT; if (block.chainid == 1) { /// @solidity memory-safe-assembly assembly { if tload(s) { mstore(0x00, s) // `Reentrancy()`. revert(0x1c, 0x04) } tstore(s, address()) } } else { /// @solidity memory-safe-assembly assembly { if eq(sload(s), address()) { mstore(0x00, s) // `Reentrancy()`. revert(0x1c, 0x04) } sstore(s, address()) } } } else { /// @solidity memory-safe-assembly assembly { if tload(_REENTRANCY_GUARD_SLOT) { mstore(0x00, 0xab143c06) // `Reentrancy()`. revert(0x1c, 0x04) } tstore(_REENTRANCY_GUARD_SLOT, address()) } } _; if (_useTransientReentrancyGuardOnlyOnMainnet()) { uint256 s = _REENTRANCY_GUARD_SLOT; if (block.chainid == 1) { /// @solidity memory-safe-assembly assembly { tstore(s, 0) } } else { /// @solidity memory-safe-assembly assembly { sstore(s, s) } } } else { /// @solidity memory-safe-assembly assembly { tstore(_REENTRANCY_GUARD_SLOT, 0) } } } /// @dev Guards a view function from read-only reentrancy. modifier nonReadReentrant() virtual { if (_useTransientReentrancyGuardOnlyOnMainnet()) { uint256 s = _REENTRANCY_GUARD_SLOT; if (block.chainid == 1) { /// @solidity memory-safe-assembly assembly { if tload(s) { mstore(0x00, s) // `Reentrancy()`. revert(0x1c, 0x04) } } } else { /// @solidity memory-safe-assembly assembly { if eq(sload(s), address()) { mstore(0x00, s) // `Reentrancy()`. revert(0x1c, 0x04) } } } } else { /// @solidity memory-safe-assembly assembly { if tload(_REENTRANCY_GUARD_SLOT) { mstore(0x00, 0xab143c06) // `Reentrancy()`. revert(0x1c, 0x04) } } } _; } /// @dev For widespread compatibility with L2s. /// Only Ethereum mainnet is expensive anyways. function _useTransientReentrancyGuardOnlyOnMainnet() internal view virtual returns (bool) { return true; } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Safe integer casting library that reverts on overflow. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeCastLib.sol) /// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeCast.sol) /// @dev Optimized for runtime gas for very high number of optimizer runs (i.e. >= 1000000). library SafeCastLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ error Overflow(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* UNSIGNED INTEGER SAFE CASTING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function toUint8(uint256 x) internal pure returns (uint8) { if (x >= 1 << 8) _revertOverflow(); return uint8(x); } function toUint16(uint256 x) internal pure returns (uint16) { if (x >= 1 << 16) _revertOverflow(); return uint16(x); } function toUint24(uint256 x) internal pure returns (uint24) { if (x >= 1 << 24) _revertOverflow(); return uint24(x); } function toUint32(uint256 x) internal pure returns (uint32) { if (x >= 1 << 32) _revertOverflow(); return uint32(x); } function toUint40(uint256 x) internal pure returns (uint40) { if (x >= 1 << 40) _revertOverflow(); return uint40(x); } function toUint48(uint256 x) internal pure returns (uint48) { if (x >= 1 << 48) _revertOverflow(); return uint48(x); } function toUint56(uint256 x) internal pure returns (uint56) { if (x >= 1 << 56) _revertOverflow(); return uint56(x); } function toUint64(uint256 x) internal pure returns (uint64) { if (x >= 1 << 64) _revertOverflow(); return uint64(x); } function toUint72(uint256 x) internal pure returns (uint72) { if (x >= 1 << 72) _revertOverflow(); return uint72(x); } function toUint80(uint256 x) internal pure returns (uint80) { if (x >= 1 << 80) _revertOverflow(); return uint80(x); } function toUint88(uint256 x) internal pure returns (uint88) { if (x >= 1 << 88) _revertOverflow(); return uint88(x); } function toUint96(uint256 x) internal pure returns (uint96) { if (x >= 1 << 96) _revertOverflow(); return uint96(x); } function toUint104(uint256 x) internal pure returns (uint104) { if (x >= 1 << 104) _revertOverflow(); return uint104(x); } function toUint112(uint256 x) internal pure returns (uint112) { if (x >= 1 << 112) _revertOverflow(); return uint112(x); } function toUint120(uint256 x) internal pure returns (uint120) { if (x >= 1 << 120) _revertOverflow(); return uint120(x); } function toUint128(uint256 x) internal pure returns (uint128) { if (x >= 1 << 128) _revertOverflow(); return uint128(x); } function toUint136(uint256 x) internal pure returns (uint136) { if (x >= 1 << 136) _revertOverflow(); return uint136(x); } function toUint144(uint256 x) internal pure returns (uint144) { if (x >= 1 << 144) _revertOverflow(); return uint144(x); } function toUint152(uint256 x) internal pure returns (uint152) { if (x >= 1 << 152) _revertOverflow(); return uint152(x); } function toUint160(uint256 x) internal pure returns (uint160) { if (x >= 1 << 160) _revertOverflow(); return uint160(x); } function toUint168(uint256 x) internal pure returns (uint168) { if (x >= 1 << 168) _revertOverflow(); return uint168(x); } function toUint176(uint256 x) internal pure returns (uint176) { if (x >= 1 << 176) _revertOverflow(); return uint176(x); } function toUint184(uint256 x) internal pure returns (uint184) { if (x >= 1 << 184) _revertOverflow(); return uint184(x); } function toUint192(uint256 x) internal pure returns (uint192) { if (x >= 1 << 192) _revertOverflow(); return uint192(x); } function toUint200(uint256 x) internal pure returns (uint200) { if (x >= 1 << 200) _revertOverflow(); return uint200(x); } function toUint208(uint256 x) internal pure returns (uint208) { if (x >= 1 << 208) _revertOverflow(); return uint208(x); } function toUint216(uint256 x) internal pure returns (uint216) { if (x >= 1 << 216) _revertOverflow(); return uint216(x); } function toUint224(uint256 x) internal pure returns (uint224) { if (x >= 1 << 224) _revertOverflow(); return uint224(x); } function toUint232(uint256 x) internal pure returns (uint232) { if (x >= 1 << 232) _revertOverflow(); return uint232(x); } function toUint240(uint256 x) internal pure returns (uint240) { if (x >= 1 << 240) _revertOverflow(); return uint240(x); } function toUint248(uint256 x) internal pure returns (uint248) { if (x >= 1 << 248) _revertOverflow(); return uint248(x); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* SIGNED INTEGER SAFE CASTING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function toInt8(int256 x) internal pure returns (int8) { unchecked { if (((1 << 7) + uint256(x)) >> 8 == uint256(0)) return int8(x); _revertOverflow(); } } function toInt16(int256 x) internal pure returns (int16) { unchecked { if (((1 << 15) + uint256(x)) >> 16 == uint256(0)) return int16(x); _revertOverflow(); } } function toInt24(int256 x) internal pure returns (int24) { unchecked { if (((1 << 23) + uint256(x)) >> 24 == uint256(0)) return int24(x); _revertOverflow(); } } function toInt32(int256 x) internal pure returns (int32) { unchecked { if (((1 << 31) + uint256(x)) >> 32 == uint256(0)) return int32(x); _revertOverflow(); } } function toInt40(int256 x) internal pure returns (int40) { unchecked { if (((1 << 39) + uint256(x)) >> 40 == uint256(0)) return int40(x); _revertOverflow(); } } function toInt48(int256 x) internal pure returns (int48) { unchecked { if (((1 << 47) + uint256(x)) >> 48 == uint256(0)) return int48(x); _revertOverflow(); } } function toInt56(int256 x) internal pure returns (int56) { unchecked { if (((1 << 55) + uint256(x)) >> 56 == uint256(0)) return int56(x); _revertOverflow(); } } function toInt64(int256 x) internal pure returns (int64) { unchecked { if (((1 << 63) + uint256(x)) >> 64 == uint256(0)) return int64(x); _revertOverflow(); } } function toInt72(int256 x) internal pure returns (int72) { unchecked { if (((1 << 71) + uint256(x)) >> 72 == uint256(0)) return int72(x); _revertOverflow(); } } function toInt80(int256 x) internal pure returns (int80) { unchecked { if (((1 << 79) + uint256(x)) >> 80 == uint256(0)) return int80(x); _revertOverflow(); } } function toInt88(int256 x) internal pure returns (int88) { unchecked { if (((1 << 87) + uint256(x)) >> 88 == uint256(0)) return int88(x); _revertOverflow(); } } function toInt96(int256 x) internal pure returns (int96) { unchecked { if (((1 << 95) + uint256(x)) >> 96 == uint256(0)) return int96(x); _revertOverflow(); } } function toInt104(int256 x) internal pure returns (int104) { unchecked { if (((1 << 103) + uint256(x)) >> 104 == uint256(0)) return int104(x); _revertOverflow(); } } function toInt112(int256 x) internal pure returns (int112) { unchecked { if (((1 << 111) + uint256(x)) >> 112 == uint256(0)) return int112(x); _revertOverflow(); } } function toInt120(int256 x) internal pure returns (int120) { unchecked { if (((1 << 119) + uint256(x)) >> 120 == uint256(0)) return int120(x); _revertOverflow(); } } function toInt128(int256 x) internal pure returns (int128) { unchecked { if (((1 << 127) + uint256(x)) >> 128 == uint256(0)) return int128(x); _revertOverflow(); } } function toInt136(int256 x) internal pure returns (int136) { unchecked { if (((1 << 135) + uint256(x)) >> 136 == uint256(0)) return int136(x); _revertOverflow(); } } function toInt144(int256 x) internal pure returns (int144) { unchecked { if (((1 << 143) + uint256(x)) >> 144 == uint256(0)) return int144(x); _revertOverflow(); } } function toInt152(int256 x) internal pure returns (int152) { unchecked { if (((1 << 151) + uint256(x)) >> 152 == uint256(0)) return int152(x); _revertOverflow(); } } function toInt160(int256 x) internal pure returns (int160) { unchecked { if (((1 << 159) + uint256(x)) >> 160 == uint256(0)) return int160(x); _revertOverflow(); } } function toInt168(int256 x) internal pure returns (int168) { unchecked { if (((1 << 167) + uint256(x)) >> 168 == uint256(0)) return int168(x); _revertOverflow(); } } function toInt176(int256 x) internal pure returns (int176) { unchecked { if (((1 << 175) + uint256(x)) >> 176 == uint256(0)) return int176(x); _revertOverflow(); } } function toInt184(int256 x) internal pure returns (int184) { unchecked { if (((1 << 183) + uint256(x)) >> 184 == uint256(0)) return int184(x); _revertOverflow(); } } function toInt192(int256 x) internal pure returns (int192) { unchecked { if (((1 << 191) + uint256(x)) >> 192 == uint256(0)) return int192(x); _revertOverflow(); } } function toInt200(int256 x) internal pure returns (int200) { unchecked { if (((1 << 199) + uint256(x)) >> 200 == uint256(0)) return int200(x); _revertOverflow(); } } function toInt208(int256 x) internal pure returns (int208) { unchecked { if (((1 << 207) + uint256(x)) >> 208 == uint256(0)) return int208(x); _revertOverflow(); } } function toInt216(int256 x) internal pure returns (int216) { unchecked { if (((1 << 215) + uint256(x)) >> 216 == uint256(0)) return int216(x); _revertOverflow(); } } function toInt224(int256 x) internal pure returns (int224) { unchecked { if (((1 << 223) + uint256(x)) >> 224 == uint256(0)) return int224(x); _revertOverflow(); } } function toInt232(int256 x) internal pure returns (int232) { unchecked { if (((1 << 231) + uint256(x)) >> 232 == uint256(0)) return int232(x); _revertOverflow(); } } function toInt240(int256 x) internal pure returns (int240) { unchecked { if (((1 << 239) + uint256(x)) >> 240 == uint256(0)) return int240(x); _revertOverflow(); } } function toInt248(int256 x) internal pure returns (int248) { unchecked { if (((1 << 247) + uint256(x)) >> 248 == uint256(0)) return int248(x); _revertOverflow(); } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* OTHER SAFE CASTING OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function toInt8(uint256 x) internal pure returns (int8) { if (x >= 1 << 7) _revertOverflow(); return int8(int256(x)); } function toInt16(uint256 x) internal pure returns (int16) { if (x >= 1 << 15) _revertOverflow(); return int16(int256(x)); } function toInt24(uint256 x) internal pure returns (int24) { if (x >= 1 << 23) _revertOverflow(); return int24(int256(x)); } function toInt32(uint256 x) internal pure returns (int32) { if (x >= 1 << 31) _revertOverflow(); return int32(int256(x)); } function toInt40(uint256 x) internal pure returns (int40) { if (x >= 1 << 39) _revertOverflow(); return int40(int256(x)); } function toInt48(uint256 x) internal pure returns (int48) { if (x >= 1 << 47) _revertOverflow(); return int48(int256(x)); } function toInt56(uint256 x) internal pure returns (int56) { if (x >= 1 << 55) _revertOverflow(); return int56(int256(x)); } function toInt64(uint256 x) internal pure returns (int64) { if (x >= 1 << 63) _revertOverflow(); return int64(int256(x)); } function toInt72(uint256 x) internal pure returns (int72) { if (x >= 1 << 71) _revertOverflow(); return int72(int256(x)); } function toInt80(uint256 x) internal pure returns (int80) { if (x >= 1 << 79) _revertOverflow(); return int80(int256(x)); } function toInt88(uint256 x) internal pure returns (int88) { if (x >= 1 << 87) _revertOverflow(); return int88(int256(x)); } function toInt96(uint256 x) internal pure returns (int96) { if (x >= 1 << 95) _revertOverflow(); return int96(int256(x)); } function toInt104(uint256 x) internal pure returns (int104) { if (x >= 1 << 103) _revertOverflow(); return int104(int256(x)); } function toInt112(uint256 x) internal pure returns (int112) { if (x >= 1 << 111) _revertOverflow(); return int112(int256(x)); } function toInt120(uint256 x) internal pure returns (int120) { if (x >= 1 << 119) _revertOverflow(); return int120(int256(x)); } function toInt128(uint256 x) internal pure returns (int128) { if (x >= 1 << 127) _revertOverflow(); return int128(int256(x)); } function toInt136(uint256 x) internal pure returns (int136) { if (x >= 1 << 135) _revertOverflow(); return int136(int256(x)); } function toInt144(uint256 x) internal pure returns (int144) { if (x >= 1 << 143) _revertOverflow(); return int144(int256(x)); } function toInt152(uint256 x) internal pure returns (int152) { if (x >= 1 << 151) _revertOverflow(); return int152(int256(x)); } function toInt160(uint256 x) internal pure returns (int160) { if (x >= 1 << 159) _revertOverflow(); return int160(int256(x)); } function toInt168(uint256 x) internal pure returns (int168) { if (x >= 1 << 167) _revertOverflow(); return int168(int256(x)); } function toInt176(uint256 x) internal pure returns (int176) { if (x >= 1 << 175) _revertOverflow(); return int176(int256(x)); } function toInt184(uint256 x) internal pure returns (int184) { if (x >= 1 << 183) _revertOverflow(); return int184(int256(x)); } function toInt192(uint256 x) internal pure returns (int192) { if (x >= 1 << 191) _revertOverflow(); return int192(int256(x)); } function toInt200(uint256 x) internal pure returns (int200) { if (x >= 1 << 199) _revertOverflow(); return int200(int256(x)); } function toInt208(uint256 x) internal pure returns (int208) { if (x >= 1 << 207) _revertOverflow(); return int208(int256(x)); } function toInt216(uint256 x) internal pure returns (int216) { if (x >= 1 << 215) _revertOverflow(); return int216(int256(x)); } function toInt224(uint256 x) internal pure returns (int224) { if (x >= 1 << 223) _revertOverflow(); return int224(int256(x)); } function toInt232(uint256 x) internal pure returns (int232) { if (x >= 1 << 231) _revertOverflow(); return int232(int256(x)); } function toInt240(uint256 x) internal pure returns (int240) { if (x >= 1 << 239) _revertOverflow(); return int240(int256(x)); } function toInt248(uint256 x) internal pure returns (int248) { if (x >= 1 << 247) _revertOverflow(); return int248(int256(x)); } function toInt256(uint256 x) internal pure returns (int256) { if (int256(x) >= 0) return int256(x); _revertOverflow(); } function toUint256(int256 x) internal pure returns (uint256) { if (x >= 0) return uint256(x); _revertOverflow(); } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* PRIVATE HELPERS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ function _revertOverflow() private pure { /// @solidity memory-safe-assembly assembly { // Store the function selector of `Overflow()`. mstore(0x00, 0x35278d12) // Revert with (offset, size). revert(0x1c, 0x04) } } }
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values. /// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol) /// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol) /// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol) /// /// @dev Note: /// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection. library SafeTransferLib { /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CUSTOM ERRORS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev The ETH transfer has failed. error ETHTransferFailed(); /// @dev The ERC20 `transferFrom` has failed. error TransferFromFailed(); /// @dev The ERC20 `transfer` has failed. error TransferFailed(); /// @dev The ERC20 `approve` has failed. error ApproveFailed(); /// @dev The ERC20 `totalSupply` query has failed. error TotalSupplyQueryFailed(); /// @dev The Permit2 operation has failed. error Permit2Failed(); /// @dev The Permit2 amount must be less than `2**160 - 1`. error Permit2AmountOverflow(); /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* CONSTANTS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes. uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300; /// @dev Suggested gas stipend for contract receiving ETH to perform a few /// storage reads and writes, but low enough to prevent griefing. uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000; /// @dev The unique EIP-712 domain domain separator for the DAI token contract. bytes32 internal constant DAI_DOMAIN_SEPARATOR = 0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7; /// @dev The address for the WETH9 contract on Ethereum mainnet. address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; /// @dev The canonical Permit2 address. /// [Github](https://github.com/Uniswap/permit2) /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3) address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3; /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ETH OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants. // // The regular variants: // - Forwards all remaining gas to the target. // - Reverts if the target reverts. // - Reverts if the current contract has insufficient balance. // // The force variants: // - Forwards with an optional gas stipend // (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases). // - If the target reverts, or if the gas stipend is exhausted, // creates a temporary contract to force send the ETH via `SELFDESTRUCT`. // Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758. // - Reverts if the current contract has insufficient balance. // // The try variants: // - Forwards with a mandatory gas stipend. // - Instead of reverting, returns whether the transfer succeeded. /// @dev Sends `amount` (in wei) ETH to `to`. function safeTransferETH(address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } } } /// @dev Sends all the ETH in the current contract to `to`. function safeTransferAllETH(address to) internal { /// @solidity memory-safe-assembly assembly { // Transfer all the ETH and check if it succeeded or not. if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } } } /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`. function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal { /// @solidity memory-safe-assembly assembly { if lt(selfbalance(), amount) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`. function forceSafeTransferAllETH(address to, uint256 gasStipend) internal { /// @solidity memory-safe-assembly assembly { if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`. function forceSafeTransferETH(address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { if lt(selfbalance(), amount) { mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`. revert(0x1c, 0x04) } if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`. function forceSafeTransferAllETH(address to) internal { /// @solidity memory-safe-assembly assembly { // forgefmt: disable-next-item if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) { mstore(0x00, to) // Store the address in scratch space. mstore8(0x0b, 0x73) // Opcode `PUSH20`. mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`. if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation. } } } /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`. function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00) } } /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`. function trySafeTransferAllETH(address to, uint256 gasStipend) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00) } } /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/ /* ERC20 OPERATIONS */ /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/ /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// Reverts upon failure. /// /// The `from` account must have at least `amount` approved for /// the current contract to manage. function safeTransferFrom(address token, address from, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, amount) // Store the `amount` argument. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`. let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// /// The `from` account must have at least `amount` approved for the current contract to manage. function trySafeTransferFrom(address token, address from, address to, uint256 amount) internal returns (bool success) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x60, amount) // Store the `amount` argument. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`. success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { success := lt(or(iszero(extcodesize(token)), returndatasize()), success) } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends all of ERC20 `token` from `from` to `to`. /// Reverts upon failure. /// /// The `from` account must have their entire balance approved for the current contract to manage. function safeTransferAllFrom(address token, address from, address to) internal returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) // Cache the free memory pointer. mstore(0x40, to) // Store the `to` argument. mstore(0x2c, shl(96, from)) // Store the `from` argument. mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`. // Read the balance, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20) ) ) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`. amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x7939f424) // `TransferFromFailed()`. revert(0x1c, 0x04) } } mstore(0x60, 0) // Restore the zero slot to zero. mstore(0x40, m) // Restore the free memory pointer. } } /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`. /// Reverts upon failure. function safeTransfer(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sends all of ERC20 `token` from the current contract to `to`. /// Reverts upon failure. function safeTransferAll(address token, address to) internal returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`. mstore(0x20, address()) // Store the address of the current contract. // Read the balance, reverting upon failure. if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20) ) ) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } mstore(0x14, to) // Store the `to` argument. amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it. mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`. // Perform the transfer, reverting upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x90b8ec18) // `TransferFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract. /// Reverts upon failure. function safeApprove(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`. revert(0x1c, 0x04) } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract. /// If the initial attempt to approve fails, attempts to reset the approved amount to zero, /// then retries the approval again (some tokens, e.g. USDT, requires this). /// Reverts upon failure. function safeApproveWithRetry(address token, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { mstore(0x14, to) // Store the `to` argument. mstore(0x34, amount) // Store the `amount` argument. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. // Perform the approval, retrying upon failure. let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x34, 0) // Store 0 for the `amount`. mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`. pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval. mstore(0x34, amount) // Store back the original `amount`. // Retry the approval, reverting upon failure. success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20) if iszero(and(eq(mload(0x00), 1), success)) { // Check the `extcodesize` again just in case the token selfdestructs lol. if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) { mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`. revert(0x1c, 0x04) } } } } mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten. } } /// @dev Returns the amount of ERC20 `token` owned by `account`. /// Returns zero if the `token` does not exist. function balanceOf(address token, address account) internal view returns (uint256 amount) { /// @solidity memory-safe-assembly assembly { mstore(0x14, account) // Store the `account` argument. mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`. amount := mul( // The arguments of `mul` are evaluated from right to left. mload(0x20), and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x1f), // At least 32 bytes returned. staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20) ) ) } } /// @dev Returns the total supply of the `token`. /// Reverts if the token does not exist or does not implement `totalSupply()`. function totalSupply(address token) internal view returns (uint256 result) { /// @solidity memory-safe-assembly assembly { mstore(0x00, 0x18160ddd) // `totalSupply()`. if iszero( and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20)) ) { mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`. revert(0x1c, 0x04) } result := mload(0x00) } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to`. /// If the initial attempt fails, try to use Permit2 to transfer the token. /// Reverts upon failure. /// /// The `from` account must have at least `amount` approved for the current contract to manage. function safeTransferFrom2(address token, address from, address to, uint256 amount) internal { if (!trySafeTransferFrom(token, from, to, amount)) { permit2TransferFrom(token, from, to, amount); } } /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2. /// Reverts upon failure. function permit2TransferFrom(address token, address from, address to, uint256 amount) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(add(m, 0x74), shr(96, shl(96, token))) mstore(add(m, 0x54), amount) mstore(add(m, 0x34), to) mstore(add(m, 0x20), shl(96, from)) // `transferFrom(address,address,uint160,address)`. mstore(m, 0x36c78516000000000000000000000000) let p := PERMIT2 let exists := eq(chainid(), 1) if iszero(exists) { exists := iszero(iszero(extcodesize(p))) } if iszero( and( call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00), lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists. ) ) { mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`. revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04) } } } /// @dev Permit a user to spend a given amount of /// another user's tokens via native EIP-2612 permit if possible, falling /// back to Permit2 if native permit fails or is not implemented on the token. function permit2( address token, address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { bool success; /// @solidity memory-safe-assembly assembly { for {} shl(96, xor(token, WETH9)) {} { mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`. if iszero( and( // The arguments of `and` are evaluated from right to left. lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word. // Gas stipend to limit gas burn for tokens that don't refund gas when // an non-existing function is called. 5K should be enough for a SLOAD. staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20) ) ) { break } // After here, we can be sure that token is a contract. let m := mload(0x40) mstore(add(m, 0x34), spender) mstore(add(m, 0x20), shl(96, owner)) mstore(add(m, 0x74), deadline) if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) { mstore(0x14, owner) mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`. mstore(add(m, 0x94), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20)) mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`. // `nonces` is already at `add(m, 0x54)`. // `1` is already stored at `add(m, 0x94)`. mstore(add(m, 0xb4), and(0xff, v)) mstore(add(m, 0xd4), r) mstore(add(m, 0xf4), s) success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00) break } mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`. mstore(add(m, 0x54), amount) mstore(add(m, 0x94), and(0xff, v)) mstore(add(m, 0xb4), r) mstore(add(m, 0xd4), s) success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00) break } } if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s); } /// @dev Simple permit on the Permit2 contract. function simplePermit2( address token, address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { /// @solidity memory-safe-assembly assembly { let m := mload(0x40) mstore(m, 0x927da105) // `allowance(address,address,address)`. { let addressMask := shr(96, not(0)) mstore(add(m, 0x20), and(addressMask, owner)) mstore(add(m, 0x40), and(addressMask, token)) mstore(add(m, 0x60), and(addressMask, spender)) mstore(add(m, 0xc0), and(addressMask, spender)) } let p := mul(PERMIT2, iszero(shr(160, amount))) if iszero( and( // The arguments of `and` are evaluated from right to left. gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`. staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60) ) ) { mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`. revert(add(0x18, shl(2, iszero(p))), 0x04) } mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant). // `owner` is already `add(m, 0x20)`. // `token` is already at `add(m, 0x40)`. mstore(add(m, 0x60), amount) mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`. // `nonce` is already at `add(m, 0xa0)`. // `spender` is already at `add(m, 0xc0)`. mstore(add(m, 0xe0), deadline) mstore(add(m, 0x100), 0x100) // `signature` offset. mstore(add(m, 0x120), 0x41) // `signature` length. mstore(add(m, 0x140), r) mstore(add(m, 0x160), s) mstore(add(m, 0x180), shl(248, v)) if iszero( // Revert if token does not have code, or if the call fails. mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) { mstore(0x00, 0x6b836e6b) // `Permit2Failed()`. revert(0x1c, 0x04) } } } }
// SPDX-License-Identifier: Unlicense /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.8.0 <0.9.0; library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes.slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes.slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes.slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes.slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) { require(_bytes.length >= _start + 2, "toUint16_outOfBounds"); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) { require(_bytes.length >= _start + 4, "toUint32_outOfBounds"); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) { require(_bytes.length >= _start + 8, "toUint64_outOfBounds"); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) { require(_bytes.length >= _start + 12, "toUint96_outOfBounds"); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) { require(_bytes.length >= _start + 16, "toUint128_outOfBounds"); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) { require(_bytes.length >= _start + 32, "toUint256_outOfBounds"); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) { require(_bytes.length >= _start + 32, "toBytes32_outOfBounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equal_nonAligned(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let endMinusWord := add(_preBytes, length) let mc := add(_preBytes, 0x20) let cc := add(_postBytes, 0x20) for { // the next line is the loop condition: // while(uint256(mc < endWord) + cb == 2) } eq(add(lt(mc, endMinusWord), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } // Only if still successful // For <1 word tail bytes if gt(success, 0) { // Get the remainder of length/32 // length % 32 = AND(length, 32 - 1) let numTailBytes := and(length, 0x1f) let mcRem := mload(mc) let ccRem := mload(cc) for { let i := 0 // the next line is the loop condition: // while(uint256(i < numTailBytes) + cb == 2) } eq(add(lt(i, numTailBytes), cb), 2) { i := add(i, 1) } { if iszero(eq(byte(i, mcRem), byte(i, ccRem))) { // unsuccess: success := 0 cb := 0 } } } } default { // unsuccess: success := 0 } } return success; } function equalStorage( bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes.slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } }
{ "optimizer": { "enabled": true, "runs": 200 }, "evmVersion": "cancun", "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true }, "libraries": {} }
Contract Security Audit
- No Contract Security Audit Submitted- Submit Audit Here
Contract ABI
API[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"inputs":[],"name":"ClaimRequestTooOld","type":"error"},{"inputs":[],"name":"ExceedDailyTotalWithdrawnLimit","type":"error"},{"inputs":[],"name":"InvalidDelegate","type":"error"},{"inputs":[],"name":"InvalidEndpointCall","type":"error"},{"inputs":[],"name":"InvalidNftTokenIdUuidLink","type":"error"},{"inputs":[{"internalType":"uint16","name":"optionType","type":"uint16"}],"name":"InvalidOptionType","type":"error"},{"inputs":[{"internalType":"bytes","name":"options","type":"bytes"}],"name":"InvalidOptions","type":"error"},{"inputs":[],"name":"InvalidProof","type":"error"},{"inputs":[],"name":"InvalidSignature","type":"error"},{"inputs":[],"name":"InvalidVestingConfig","type":"error"},{"inputs":[],"name":"LzTokenUnavailable","type":"error"},{"inputs":[],"name":"MaxConfigsPerRequestExceeded","type":"error"},{"inputs":[{"internalType":"uint32","name":"eid","type":"uint32"}],"name":"NoPeer","type":"error"},{"inputs":[],"name":"NonceAlreadyUsed","type":"error"},{"inputs":[{"internalType":"uint256","name":"msgValue","type":"uint256"}],"name":"NotEnoughNative","type":"error"},{"inputs":[],"name":"NotReadyForClaim","type":"error"},{"inputs":[{"internalType":"address","name":"addr","type":"address"}],"name":"OnlyEndpoint","type":"error"},{"inputs":[{"internalType":"uint32","name":"eid","type":"uint32"},{"internalType":"bytes32","name":"sender","type":"bytes32"}],"name":"OnlyPeer","type":"error"},{"inputs":[{"internalType":"address","name":"owner","type":"address"}],"name":"OwnableInvalidOwner","type":"error"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"OwnableUnauthorizedAccount","type":"error"},{"inputs":[],"name":"Paused","type":"error"},{"inputs":[],"name":"Reentrancy","type":"error"},{"inputs":[{"internalType":"uint8","name":"bits","type":"uint8"},{"internalType":"uint256","name":"value","type":"uint256"}],"name":"SafeCastOverflowedUintDowncast","type":"error"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"SafeERC20FailedOperation","type":"error"},{"inputs":[],"name":"ToIsZeroAddress","type":"error"},{"inputs":[],"name":"UUIDSignerZeroAddress","type":"error"},{"inputs":[],"name":"Unauthorized","type":"error"},{"inputs":[],"name":"UnsupportedChainId","type":"error"},{"inputs":[],"name":"ZeroConfigs","type":"error"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"caller","type":"address"},{"indexed":false,"internalType":"bytes","name":"msgData","type":"bytes"}],"name":"AdminAccessed","type":"event"},{"anonymous":false,"inputs":[],"name":"DailyTotalWithdrawnLimitReached","type":"event"},{"anonymous":false,"inputs":[{"components":[{"internalType":"uint32","name":"eid","type":"uint32"},{"internalType":"uint16","name":"msgType","type":"uint16"},{"internalType":"bytes","name":"options","type":"bytes"}],"indexed":false,"internalType":"struct EnforcedOptionParam[]","name":"_enforcedOptions","type":"tuple[]"}],"name":"EnforcedOptionSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"previousOwner","type":"address"},{"indexed":true,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnershipTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint32","name":"eid","type":"uint32"},{"indexed":false,"internalType":"bytes32","name":"peer","type":"bytes32"}],"name":"PeerSet","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"claimNonce","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"Released","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"nft","type":"address"},{"indexed":true,"internalType":"uint256","name":"tokenId","type":"uint256"},{"indexed":true,"internalType":"address","name":"collector","type":"address"},{"indexed":false,"internalType":"uint256","name":"streamId","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount","type":"uint256"}],"name":"VestWithdrawn","type":"event"},{"inputs":[{"components":[{"internalType":"uint32","name":"srcEid","type":"uint32"},{"internalType":"bytes32","name":"sender","type":"bytes32"},{"internalType":"uint64","name":"nonce","type":"uint64"}],"internalType":"struct Origin","name":"origin","type":"tuple"}],"name":"allowInitializePath","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"animeToken","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"claimChecker","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"_eid","type":"uint32"},{"internalType":"uint16","name":"_msgType","type":"uint16"},{"internalType":"bytes","name":"_extraOptions","type":"bytes"}],"name":"combineOptions","outputs":[{"internalType":"bytes","name":"","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentClaimNonce","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"currentTimestamp","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dailyTotalWithdrawn","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"dailyTotalWithdrawnLimit","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"endpoint","outputs":[{"internalType":"contract ILayerZeroEndpointV2","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"eid","type":"uint32"},{"internalType":"uint16","name":"msgType","type":"uint16"}],"name":"enforcedOptions","outputs":[{"internalType":"bytes","name":"enforcedOption","type":"bytes"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"expectedBaseGasRequired","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"expectedCalldataSize","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"expectedUnitGasRequired","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint32","name":"srcEid","type":"uint32"},{"internalType":"bytes32","name":"sender","type":"bytes32"},{"internalType":"uint64","name":"nonce","type":"uint64"}],"internalType":"struct Origin","name":"","type":"tuple"},{"internalType":"bytes","name":"","type":"bytes"},{"internalType":"address","name":"_sender","type":"address"}],"name":"isComposeMsgSender","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"isPaused","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lzReadChannel","outputs":[{"internalType":"uint32","name":"","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"lzReadConfirmations","outputs":[{"internalType":"uint16","name":"","type":"uint16"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"uint32","name":"srcEid","type":"uint32"},{"internalType":"bytes32","name":"sender","type":"bytes32"},{"internalType":"uint64","name":"nonce","type":"uint64"}],"internalType":"struct Origin","name":"_origin","type":"tuple"},{"internalType":"bytes32","name":"_guid","type":"bytes32"},{"internalType":"bytes","name":"_message","type":"bytes"},{"internalType":"address","name":"_executor","type":"address"},{"internalType":"bytes","name":"_extraData","type":"bytes"}],"name":"lzReceive","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[],"name":"manager","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"maxConfigsPerRequest","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"","type":"uint32"},{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"nextNonce","outputs":[{"internalType":"uint64","name":"nonce","type":"uint64"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"claimNonce","type":"uint256"}],"name":"nonceIsUsed","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"oAppVersion","outputs":[{"internalType":"uint64","name":"senderVersion","type":"uint64"},{"internalType":"uint64","name":"receiverVersion","type":"uint64"}],"stateMutability":"pure","type":"function"},{"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint32","name":"eid","type":"uint32"}],"name":"peers","outputs":[{"internalType":"bytes32","name":"peer","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"numNFTAllos","type":"uint256"},{"internalType":"uint256","name":"numCollectorAllos","type":"uint256"}],"name":"quoteForClaim","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"nft","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes32","name":"uuid","type":"bytes32"},{"internalType":"address","name":"collector","type":"address"},{"internalType":"uint8","name":"streamId","type":"uint8"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"uint256","name":"allocation","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"},{"internalType":"bytes","name":"signature","type":"bytes"}],"internalType":"struct AnimeClaimer.VestingConfig[]","name":"configs","type":"tuple[]"}],"name":"quoteForClaim","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"readyForClaim","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"renounceOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"nft","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes32","name":"uuid","type":"bytes32"},{"internalType":"address","name":"collector","type":"address"},{"internalType":"uint8","name":"streamId","type":"uint8"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"uint256","name":"allocation","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"},{"internalType":"bytes","name":"signature","type":"bytes"}],"internalType":"struct AnimeClaimer.VestingConfig[]","name":"configs","type":"tuple[]"}],"name":"requestClaim","outputs":[{"components":[{"internalType":"bytes32","name":"guid","type":"bytes32"},{"internalType":"uint64","name":"nonce","type":"uint64"},{"components":[{"internalType":"uint256","name":"nativeFee","type":"uint256"},{"internalType":"uint256","name":"lzTokenFee","type":"uint256"}],"internalType":"struct MessagingFee","name":"fee","type":"tuple"}],"internalType":"struct MessagingReceipt","name":"","type":"tuple"}],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"setAnimeToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newClaimChecker","type":"address"}],"name":"setClaimChecker","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"window","type":"uint32"}],"name":"setClaimRequestExecutionWindow","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"limit","type":"uint256"}],"name":"setDailyTotalWithdrawnLimit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_delegate","type":"address"}],"name":"setDelegate","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint32","name":"eid","type":"uint32"},{"internalType":"uint16","name":"msgType","type":"uint16"},{"internalType":"bytes","name":"options","type":"bytes"}],"internalType":"struct EnforcedOptionParam[]","name":"_enforcedOptions","type":"tuple[]"}],"name":"setEnforcedOptions","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"required","type":"uint256"}],"name":"setExpectedBaseGasRequired","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"size","type":"uint256"}],"name":"setExpectedCalldataSize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"required","type":"uint256"}],"name":"setExpectedUnitGasRequired","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_manager","type":"address"}],"name":"setManager","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint8","name":"_maxConfigsPerRequest","type":"uint8"}],"name":"setMaxConfigsPerRequest","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"nft","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes32","name":"uuid","type":"bytes32"}],"name":"setNFTToUUID","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bool","name":"paused","type":"bool"}],"name":"setPaused","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"_eid","type":"uint32"},{"internalType":"bytes32","name":"_peer","type":"bytes32"}],"name":"setPeer","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint32","name":"channelId","type":"uint32"},{"internalType":"bool","name":"active","type":"bool"}],"name":"setReadChannel","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint16","name":"confirmations","type":"uint16"}],"name":"setReadConfirmations","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"signer","type":"address"}],"name":"setUUIDSigner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"uuid","type":"bytes32"},{"internalType":"address","name":"nft","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"}],"name":"setUUIDToPackedNftID","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"root","type":"bytes32"}],"name":"setVestingRoot","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"newOwner","type":"address"}],"name":"transferOwnership","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"uuidSigner","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"nft","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes32","name":"uuid","type":"bytes32"},{"internalType":"address","name":"collector","type":"address"},{"internalType":"uint8","name":"streamId","type":"uint8"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"uint256","name":"allocation","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"},{"internalType":"bytes","name":"signature","type":"bytes"}],"internalType":"struct AnimeClaimer.VestingConfig","name":"c","type":"tuple"},{"internalType":"bytes32","name":"root","type":"bytes32"}],"name":"validateVestingConfig","outputs":[],"stateMutability":"pure","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"nft","type":"address"},{"internalType":"uint256","name":"tokenId","type":"uint256"},{"internalType":"bytes32","name":"uuid","type":"bytes32"},{"internalType":"address","name":"collector","type":"address"},{"internalType":"uint8","name":"streamId","type":"uint8"},{"internalType":"uint256","name":"start","type":"uint256"},{"internalType":"uint256","name":"end","type":"uint256"},{"internalType":"uint256","name":"allocation","type":"uint256"},{"internalType":"bytes32[]","name":"proof","type":"bytes32[]"},{"internalType":"bytes","name":"signature","type":"bytes"}],"internalType":"struct AnimeClaimer.VestingConfig[]","name":"configs","type":"tuple[]"}],"name":"vestingInfos","outputs":[{"components":[{"internalType":"uint256","name":"withdrawn","type":"uint256"},{"internalType":"uint256","name":"vested","type":"uint256"}],"internalType":"struct AnimeClaimer.VestingInfo[]","name":"infos","type":"tuple[]"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"vestingRoot","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawERC20","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"withdrawETH","outputs":[],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
60a060405234801562000010575f80fd5b506200001b6200016c565b338181818180806200004657604051631e4fbdf760e01b81525f600482015260240160405180910390fd5b6200005181620001cd565b506001600160a01b0380831660805281166200008057604051632d618d8160e21b815260040160405180910390fd5b60805160405163ca5eb5e160e01b81526001600160a01b0383811660048301529091169063ca5eb5e1906024015f604051808303815f87803b158015620000c5575f80fd5b505af1158015620000d8573d5f803e3d5ffd5b505050505050505050505f620000f36200021c60201b60201c565b6001810180546001600160881b0319166d80000186a000061a8000000e1001179055600a8101805466ffffffffffffff60a01b191666320003ffffffff60a01b1790819055909150620001659063ffffffff600160a01b909104166200015f306001600160a01b031690565b62000229565b506200027d565b5f61a4b14603620001905750731a44076050125825900e736c501f859c50fe728c90565b62066eee4603620001b45750736edce65403992e310a62460808c4b910d972f10f90565b60405163c08c729760e01b815260040160405180910390fd5b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b6862dc72c6d15e6284df90565b63ffffffff82165f81815260016020908152604091829020849055815192835282018390527f238399d427b947898edb290f5ff0f9109849b1c3ba196a42e35f00c50a54b98b910160405180910390a15050565b608051614925620002c05f395f818161061701528181610d22015281816118100152818161265d01528181612e0301528181612eba015261324101526149255ff3fe60806040526004361061035b575f3560e01c806382413eac116101bd578063c21be51e116100f2578063d8333ac811610092578063f0a9e4811161006d578063f0a9e48114610a99578063f2fde38b14610ab8578063f79fd08514610ad7578063ff7bd03d14610b03575f80fd5b8063d8333ac814610a3c578063ddeedcc314610a5b578063def55d1c14610a7a575f80fd5b8063ca5eb5e1116100cd578063ca5eb5e1146109ac578063ce271616146109cb578063d0ebdbe7146109ea578063d3bebea614610a09575f80fd5b8063c21be51e1461093f578063c460af0a1461095e578063c7fc466514610983575f80fd5b8063a25798751161015d578063b187bd2611610138578063b187bd26146108b7578063b98bd070146108d6578063bb0b6a53146108f5578063bc70b35414610920575f80fd5b8063a25798751461084e578063a761821f14610879578063b097aeb814610898575f80fd5b806398385a3b1161019857806398385a3b146107ca578063983a2122146107ff5780639a08fe3d1461081b5780639b894b0c1461082f575f80fd5b806382413eac1461077057806386e326031461078f5780638da5cb5b146107ae575f80fd5b80634782f77911610293578063715018a61161023357806379a2c8dc1161020e57806379a2c8dc146106c75780637d25a05e146106ec5780637ec133081461072557806381b5d66114610744575f80fd5b8063715018a61461066257806375216e651461067657806378858ee3146106a2575f80fd5b80635535d4611161026e5780635535d461146105bb57806359b87bf4146105e75780635e280f111461060657806362a1a94d14610639575f80fd5b80634782f77914610544578063481c6a751461056357806352f7f3f61461059c575f80fd5b806327570d90116102fe5780633400288b116102d95780633400288b146104b857806344004cc1146104d75780634693e7a8146104f65780634763666c14610525575f80fd5b806327570d9014610441578063278e024c14610460578063282a915614610499575f80fd5b806317442b701161033957806317442b70146103bc578063176c41d7146103dd5780631e2ff94f146103fc57806321c210d814610418575f80fd5b80630f601f5f1461035f57806313137d651461038857806316c38b3c1461039d575b5f80fd5b61037261036d36600461391e565b610b22565b60405161037f919061395c565b60405180910390f35b61039b610396366004613a0d565b610d20565b005b3480156103a8575f80fd5b5061039b6103b7366004613ab4565b610de0565b3480156103c7575f80fd5b506040805160018152600260208201520161037f565b3480156103e8575f80fd5b5061039b6103f7366004613ad4565b610e70565b348015610407575f80fd5b50425b60405190815260200161037f565b348015610423575f80fd5b506862dc72c6d15e6284e054600160281b900463ffffffff1661040a565b34801561044c575f80fd5b5061040a61045b366004613aeb565b610e8d565b34801561046b575f80fd5b506862dc72c6d15e6284e954600160a01b900463ffffffff1660405163ffffffff909116815260200161037f565b3480156104a4575f80fd5b5061039b6104b3366004613b1e565b610f2c565b3480156104c3575f80fd5b5061039b6104d2366004613b37565b610f66565b3480156104e2575f80fd5b5061039b6104f1366004613b5f565b610f7c565b348015610501575f80fd5b50610515610510366004613ad4565b610fc3565b604051901515815260200161037f565b348015610530575f80fd5b5061039b61053f366004613b9d565b610feb565b34801561054f575f80fd5b5061039b61055e366004613bc1565b611028565b34801561056e575f80fd5b506862dc72c6d15e6284df546001600160a01b03165b6040516001600160a01b03909116815260200161037f565b3480156105a7575f80fd5b5061039b6105b6366004613bee565b611069565b3480156105c6575f80fd5b506105da6105d5366004613c07565b6110a4565b60405161037f9190613c85565b3480156105f2575f80fd5b5061039b610601366004613ad4565b611146565b348015610611575f80fd5b506105847f000000000000000000000000000000000000000000000000000000000000000081565b348015610644575f80fd5b506862dc72c6d15e6284e054600160681b900463ffffffff1661040a565b34801561066d575f80fd5b5061039b6111ca565b348015610681575f80fd5b506862dc72c6d15e6284df54600160a01b90046001600160601b031661040a565b3480156106ad575f80fd5b506862dc72c6d15e6284e9546001600160a01b0316610584565b3480156106d2575f80fd5b506862dc72c6d15e6284e1546001600160601b031661040a565b3480156106f7575f80fd5b5061070d610706366004613b37565b5f92915050565b6040516001600160401b03909116815260200161037f565b348015610730575f80fd5b5061039b61073f366004613ad4565b6111dd565b34801561074f575f80fd5b506862dc72c6d15e6284e154600160601b90046001600160a01b0316610584565b34801561077b575f80fd5b5061051561078a366004613c97565b611228565b34801561079a575f80fd5b5061039b6107a9366004613d09565b61123d565b3480156107b9575f80fd5b505f546001600160a01b0316610584565b3480156107d5575f80fd5b506862dc72c6d15e6284e954600160c01b900461ffff1660405161ffff909116815260200161037f565b34801561080a575f80fd5b506862dc72c6d15e6284e55461040a565b348015610826575f80fd5b506105156112b1565b34801561083a575f80fd5b5061039b610849366004613d22565b61142f565b348015610859575f80fd5b506862dc72c6d15e6284e054600160881b900465ffffffffffff1661040a565b348015610884575f80fd5b5061040a61089336600461391e565b6114a4565b3480156108a3575f80fd5b5061039b6108b2366004613ad4565b6114c4565b3480156108c2575f80fd5b506862dc72c6d15e6284e05460ff16610515565b3480156108e1575f80fd5b5061039b6108f036600461391e565b61154e565b348015610900575f80fd5b5061040a61090f366004613b1e565b60016020525f908152604090205481565b34801561092b575f80fd5b506105da61093a366004613d3d565b611568565b34801561094a575f80fd5b5061039b610959366004613d99565b611709565b348015610969575f80fd5b506862dc72c6d15e6284e6546001600160a01b0316610584565b34801561098e575f80fd5b506862dc72c6d15e6284e054600160481b900463ffffffff1661040a565b3480156109b7575f80fd5b5061039b6109c6366004613d22565b6117e9565b3480156109d6575f80fd5b5061039b6109e5366004613d22565b61186a565b3480156109f5575f80fd5b5061039b610a04366004613d22565b6118d1565b348015610a14575f80fd5b506862dc72c6d15e6284e954600160d01b900460ff1660405160ff909116815260200161037f565b348015610a47575f80fd5b5061039b610a56366004613d22565b611946565b348015610a66575f80fd5b5061039b610a75366004613dd1565b611980565b348015610a85575f80fd5b5061039b610a94366004613ad4565b6119be565b348015610aa4575f80fd5b5061039b610ab3366004613e03565b611a44565b348015610ac3575f80fd5b5061039b610ad2366004613d22565b611aa0565b348015610ae2575f80fd5b50610af6610af136600461391e565b611add565b60405161037f9190613e2b565b348015610b0e575f80fd5b50610515610b1d366004613e81565b611c16565b610b2a613894565b688000000000ab143c0646600103610b5457805c15610b4c57805f526004601cfd5b30815d610b69565b30815403610b6557805f526004601cfd5b3081555b506862dc72c6d15e6284df610b7c6112b1565b610b9957604051630a075a0560e41b815260040160405180910390fd5b600181015460ff1615610bbf576040516313d0ff5960e31b815260040160405180910390fd5b600a810154600160d01b900460ff16831115610bee576040516353da2aa560e01b815260040160405180910390fd5b5f839003610c0f57604051636910abcb60e11b815260040160405180910390fd5b610c198484611c4a565b5f610c248585611f53565b6001830180549192505f91600160881b900465ffffffffffff16906011610c4a83613eaf565b91906101000a81548165ffffffffffff021916908365ffffffffffff16021790555065ffffffffffff169050610c81818787612236565b600a83015482516020840151610cd79263ffffffff600160a01b82041692610cb39286926001600160a01b0316612447565b610cbc88612592565b60405180604001604052803481526020015f8152503361262c565b9350505050610ce4600190565b15610d0d57688000000000ab143c0646600103610d03575f815d610d07565b8081555b50610d1a565b5f688000000000ab143c065d5b92915050565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03163314610d70576040516391ac5e4f60e01b81523360048201526024015b60405180910390fd5b60208701803590610d8a90610d85908a613b1e565b612732565b14610dc857610d9c6020880188613b1e565b60405163309afaf360e21b815263ffffffff909116600482015260208801356024820152604401610d67565b610dd78787878787878761276d565b50505050505050565b5f546001600160a01b03163314610e23576862dc72c6d15e6284df546001600160a01b03163314610e23576040516282b42960e81b815260040160405180910390fd5b80610e4d57610e306112b1565b610e4d57604051630a075a0560e41b815260040160405180910390fd5b610e556127b0565b6862dc72c6d15e6284e0805460ff1916911515919091179055565b610e786127f5565b610e806127b0565b6862dc72c6d15e6284e555565b5f80836001600160401b03811115610ea757610ea7613ed3565b604051908082528060200260200182016040528015610ed0578160200160208202803683370190505b5090505f836001600160401b03811115610eec57610eec613ed3565b604051908082528060200260200182016040528015610f15578160200160208202803683370190505b509050610f23308383612821565b95945050505050565b610f346127f5565b610f3c6127b0565b6862dc72c6d15e6284e0805463ffffffff9092166101000264ffffffff0019909216919091179055565b610f6e6127f5565b610f78828261289b565b5050565b610f846127f5565b610f8c6127b0565b6001600160a01b038216610fb35760405163391bbb4160e01b815260040160405180910390fd5b610fbe8383836128ef565b505050565b600881901c5f9081526862dc72c6d15e6284e8602052604081205460ff83161c600116610d1a565b610ff36127f5565b610ffb6127b0565b5f9283526862dc72c6d15e6284e4602052604090922060a09290921b6001600160a01b0391909116179055565b6110306127f5565b6110386127b0565b6001600160a01b03821661105f5760405163391bbb4160e01b815260040160405180910390fd5b610f788282612939565b6110716127f5565b6110796127b0565b6862dc72c6d15e6284e9805461ffff92909216600160c01b0261ffff60c01b19909216919091179055565b600260209081525f9283526040808420909152908252902080546110c790613ee7565b80601f01602080910402602001604051908101604052809291908181526020018280546110f390613ee7565b801561113e5780601f106111155761010080835404028352916020019161113e565b820191905f5260205f20905b81548152906001019060200180831161112157829003601f168201915b505050505081565b5f546001600160a01b03163314611189576862dc72c6d15e6284df546001600160a01b03163314611189576040516282b42960e81b815260040160405180910390fd5b6111916127b0565b61119a81612952565b6862dc72c6d15e6284e0805463ffffffff92909216600160681b0263ffffffff60681b1990921691909117905550565b6111d26127f5565b6111db5f61296b565b565b6111e56127f5565b6111ed6127b0565b6111f6816129ba565b6862dc72c6d15e6284df80546001600160601b0392909216600160a01b026001600160a01b0390921691909117905550565b6001600160a01b03811630145b949350505050565b5f546001600160a01b03163314611280576862dc72c6d15e6284df546001600160a01b03163314611280576040516282b42960e81b815260040160405180910390fd5b6112886127b0565b6862dc72c6d15e6284e9805460ff92909216600160d01b0260ff60d01b19909216919091179055565b6862dc72c6d15e6284df80545f91906001600160a01b03166112d4575f91505090565b6001810154610100900463ffffffff165f036112f1575f91505090565b8054600160a01b90046001600160601b03165f03611310575f91505090565b6001810154600160281b900463ffffffff165f0361132f575f91505090565b6001810154600160481b900463ffffffff165f0361134e575f91505090565b6001810154600160681b900463ffffffff165f0361136d575f91505090565b600681015461137d575f91505090565b60078101546001600160a01b0316611396575f91505090565b600a8101546001600160a01b03166113af575f91505090565b6002810154600160601b90046001600160a01b03166113cf575f91505090565b600a810154600160a01b900463ffffffff165f036113ee575f91505090565b600a810154600160c01b900461ffff165f0361140b575f91505090565b600a810154600160d01b900460ff165f03611427575f91505090565b600191505090565b5f546001600160a01b03163314611472576862dc72c6d15e6284df546001600160a01b03163314611472576040516282b42960e81b815260040160405180910390fd5b61147a6127b0565b6862dc72c6d15e6284e680546001600160a01b0319166001600160a01b0392909216919091179055565b5f806114b08484611f53565b905061123581604001518260600151610e8d565b5f546001600160a01b03163314611507576862dc72c6d15e6284df546001600160a01b03163314611507576040516282b42960e81b815260040160405180910390fd5b61150f6127b0565b61151881612952565b6862dc72c6d15e6284e0805463ffffffff92909216600160481b026cffffffff0000000000000000001990921691909117905550565b6115566127f5565b610f786115638284614021565b6129ce565b63ffffffff84165f90815260026020908152604080832061ffff8716845290915281208054606092919061159b90613ee7565b80601f01602080910402602001604051908101604052809291908181526020018280546115c790613ee7565b80156116125780601f106115e957610100808354040283529160200191611612565b820191905f5260205f20905b8154815290600101906020018083116115f557829003601f168201915b5050505050905080515f036116605783838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152509294506112359350505050565b5f83900361166f579050611235565b600283106116ec576116b584848080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250612ada92505050565b806116c384600281886140e7565b6040516020016116d59392919061410e565b604051602081830303815290604052915050611235565b8383604051639a6d49cd60e01b8152600401610d67929190614134565b5f6117b261171a6020850185613d22565b6001600160a01b03166040850135611736578460200135611738565b5f5b604086013561174d6080880160608901613d22565b6001600160a01b031661176660a0890160808a01613d09565b60ff168860a001358960c001358a60e00135604080519889526020890197909752958701949094526060860192909252608085015260a084015260c083015260e0820152610100902090565b90506117cc6117c5610100850185614162565b8484612b06565b610fbe576040516309bde33960e01b815260040160405180910390fd5b6117f16127f5565b60405163ca5eb5e160e01b81526001600160a01b0382811660048301527f0000000000000000000000000000000000000000000000000000000000000000169063ca5eb5e1906024015f604051808303815f87803b158015611851575f80fd5b505af1158015611863573d5f803e3d5ffd5b5050505050565b6118726127f5565b6001600160a01b038116611899576040516371c46ce160e01b815260040160405180910390fd5b6118a16127b0565b6862dc72c6d15e6284e180546001600160a01b03909216600160601b026001600160601b03909216919091179055565b5f546001600160a01b03163314611914576862dc72c6d15e6284df546001600160a01b03163314611914576040516282b42960e81b815260040160405180910390fd5b61191c6127b0565b6862dc72c6d15e6284df80546001600160a01b0319166001600160a01b0392909216919091179055565b61194e6127f5565b6119566127b0565b6862dc72c6d15e6284e980546001600160a01b0319166001600160a01b0392909216919091179055565b6119886127f5565b6119906127b0565b6001600160a01b03929092165f9081526862dc72c6d15e6284e3602090815260408083209383529290522055565b5f546001600160a01b03163314611a01576862dc72c6d15e6284df546001600160a01b03163314611a01576040516282b42960e81b815260040160405180910390fd5b611a096127b0565b611a1281612952565b6862dc72c6d15e6284e0805463ffffffff92909216600160281b0268ffffffff00000000001990921691909117905550565b611a4c6127f5565b611a546127b0565b6862dc72c6d15e6284df611a738383611a6d575f61289b565b3061289b565b8115610fbe57600a8101805463ffffffff8516600160a01b0263ffffffff60a01b19909116179055505050565b611aa86127f5565b6001600160a01b038116611ad157604051631e4fbdf760e01b81525f6004820152602401610d67565b611ada8161296b565b50565b6060816001600160401b03811115611af757611af7613ed3565b604051908082528060200260200182016040528015611b3b57816020015b604080518082019091525f8082526020820152815260200190600190039081611b155790505b5090505f5b82811015611c0f5736848483818110611b5b57611b5b6141a7565b9050602002810190611b6d91906141bb565b90505f611bad611b806020840184613d22565b6020840135611b956080860160608701613d22565b611ba560a0870160808801613d09565b60ff16612b3e565b9050611bc1611bbb83614241565b42612b97565b848481518110611bd357611bd36141a7565b60200260200101516020018181525050805f0154848481518110611bf957611bf96141a7565b6020908102919091010151525050600101611b40565b5092915050565b5f602082018035906001908390611c2d9086613b1e565b63ffffffff16815260208101919091526040015f20541492915050565b6862dc72c6d15e6284e5546862dc72c6d15e6284df905f5b838110156118635736858583818110611c7d57611c7d6141a7565b9050602002810190611c8f91906141bb565b9050611c9b8184611709565b5f80611caa6020840184613d22565b6001600160a01b031614159050604082013515611e345780611cdf57604051632e4a826160e11b815260040160405180910390fd5b5f611d1d6040840135611cf56020860186613d22565b6001600160a01b03168560200135604080519384526020840192909252908201526060902090565b9050611d4d816020527b19457468657265756d205369676e6564204d6573736167653a0a33325f52603c60042090565b6002870154909150600160601b90046001600160a01b0316611d7c82611d77610120870187614316565b612bfb565b6001600160a01b031614611da357604051638baa579f60e01b815260040160405180910390fd5b5f611dc9611db46020860186613d22565b6001600160a01b0316602086013560a01b1790565b6040808601355f90815260058a01602052205490915015611e1b576040808501355f9081526005890160205220548114611e165760405163533c430760e01b815260040160405180910390fd5b611e31565b6040808501355f90815260058901602052208190555b50505b8015611f49575f6040830135611e4e57600160801b611e54565b82604001355b90505f6004870181611e696020870187613d22565b6001600160a01b03166001600160a01b031681526020019081526020015f205f856020013581526020019081526020015f205414611f0a5780600487015f611eb46020870187613d22565b6001600160a01b03166001600160a01b031681526020019081526020015f205f856020013581526020019081526020015f205414611f055760405163533c430760e01b815260040160405180910390fd5b611f47565b80600487015f611f1d6020870187613d22565b6001600160a01b0316815260208082019290925260409081015f9081208784013582529092529020555b505b5050600101611c62565b611f7c604051806080016040528060608152602001606081526020015f81526020015f81525090565b5f805f5b848110156120435736868683818110611f9b57611f9b6141a7565b9050602002810190611fad91906141bb565b90505f80611fc16080840160608501613d22565b6001600160a01b0316141590505f80611fdd6020850185613d22565b6001600160a01b03161415905081151581900361200d57604051632e4a826160e11b815260040160405180910390fd5b8115612021578461201d81614358565b9550505b8015612035578561203181614358565b9650505b505050806001019050611f80565b5061206d604051806080016040528060608152602001606081526020015f81526020015f81525090565b826001600160401b0381111561208557612085613ed3565b6040519080825280602002602001820160405280156120ae578160200160208202803683370190505b508152816001600160401b038111156120c9576120c9613ed3565b6040519080825280602002602001820160405280156120f2578160200160208202803683370190505b5060208201525f5b8581101561222c5736878783818110612115576121156141a7565b905060200281019061212791906141bb565b90505f8061213b6080840160608501613d22565b6001600160a01b0316141590505f806121576020850185613d22565b6001600160a01b03161415905081156121c25761217a6080840160608501613d22565b60208601516060870180519061218f82614358565b9052815181106121a1576121a16141a7565b60200260200101906001600160a01b031690816001600160a01b0316815250505b801561221e576121ed6121d86020850185613d22565b6001600160a01b0316602085013560a01b1790565b8551604087018051906121ff82614358565b905281518110612211576122116141a7565b6020026020010181815250505b5050508060010190506120fa565b5095945050505050565b5f8381526862dc72c6d15e6284e76020526040902080546001600160a01b031916331781556862dc72c6d15e6284df9061226f83612952565b81546001600160a01b0316600160e01b63ffffffff929092169190910267ffffffffffffffff60a01b191617600160a01b426001600160401b0316021781555f5b8381101561243f575f8181526001830160205260409020368686848181106122da576122da6141a7565b90506020028101906122ec91906141bb565b90506122fb6020820182613d22565b82546001600160a01b0319166001600160a01b03919091161782556123236020820135612c83565b825462ffffff91909116600160a01b0262ffffff60a01b1990911617825561235c61235460a0830160808401613d09565b60ff16612c97565b825460ff91909116600160b81b0260ff60b81b1990911617825561238360a0820135612952565b825463ffffffff91909116600160c01b0263ffffffff60c01b199091161782556123b060c0820135612952565b825463ffffffff91909116600160e01b026001600160e01b039091161782556123df6080820160608301613d22565b6001830180546001600160a01b0319166001600160a01b039290921691909117905561240e60e08201356129ba565b600192830180546001600160601b0392909216600160a01b026001600160a01b0390921691909117905550016122b0565b505050505050565b6040805160018082528183019092526060915f9190816020015b6040805160e0810182525f808252602080830182905292820181905260608083018290526080830182905260a083019190915260c082015282525f199092019101816124615790505090506040518060e00160405280600161ffff1681526020016124ca612ca9565b63ffffffff1681525f6020820152426001600160401b031660408201526862dc72c6d15e6284e954600160c01b900461ffff1660608201526001600160a01b038516608082015260a0018733888861252183612ce4565b604051602401612535959493929190614370565b60408051601f198184030181529190526020810180516001600160e01b0316636df6dc3760e11b1790529052815182905f90612573576125736141a7565b60200260200101819052506125885f82612cfb565b9695505050505050565b6862dc72c6d15e6284e0546060906862dc72c6d15e6284df905f906125c490600160481b900463ffffffff168561440f565b60018301546125e09190600160281b900463ffffffff16614426565b60018301549091506112359063ffffffff80841691600160681b9004165f61262460408051600360f01b602082015281516002818303018152602290910190915290565b929190612d81565b612634613894565b5f612641845f0151612ddd565b60208501519091501561265b5761265b8460200151612e00565b7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b0316632637a450826040518060a001604052808b63ffffffff1681526020016126ab8c612732565b81526020018a81526020018981526020015f8960200151111515815250866040518463ffffffff1660e01b81526004016126e6929190614439565b60806040518083038185885af1158015612702573d5f803e3d5ffd5b50505050506040513d601f19601f8201168201806040525081019061272791906144fd565b979650505050505050565b63ffffffff81165f9081526001602052604081205480610d1a5760405163f6ff4fb760e01b815263ffffffff84166004820152602401610d67565b5f8061277b86880188614550565b915091508061279c576040516282b42960e81b815260040160405180910390fd5b6127a582612edf565b505050505050505050565b336001600160a01b03167f2218aada03516237ddb3d2451b4ccb7efc7c423d55815d064da80786312706b45f366040516127eb929190614134565b60405180910390a2565b5f546001600160a01b031633146111db5760405163118cdaa760e01b8152336004820152602401610d67565b6862dc72c6d15e6284e9545f906862dc72c6d15e6284df908290612853908790879087906001600160a01b0316612447565b90505f8061286d865188516128689190614426565b612592565b600a85015490915061288e90600160a01b900463ffffffff1684838561322c565b5198975050505050505050565b63ffffffff82165f81815260016020908152604091829020849055815192835282018390527f238399d427b947898edb290f5ff0f9109849b1c3ba196a42e35f00c50a54b98b910160405180910390a15050565b816014528060345263a9059cbb60601b5f5260205f604460105f875af18060015f51141661292f57803d853b15171061292f576390b8ec185f526004601cfd5b505f603452505050565b5f385f3884865af1610f785763b12d13eb5f526004601cfd5b5f640100000000821061296757612967613301565b5090565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f600160601b821061296757612967613301565b5f5b8151811015612a9f576129ff8282815181106129ee576129ee6141a7565b602002602001015160400151612ada565b818181518110612a1157612a116141a7565b60200260200101516040015160025f848481518110612a3257612a326141a7565b60200260200101515f015163ffffffff1663ffffffff1681526020019081526020015f205f848481518110612a6957612a696141a7565b60200260200101516020015161ffff1661ffff1681526020019081526020015f209081612a9691906145b5565b506001016129d0565b507fbe4864a8e820971c0247f5992e2da559595f7bf076a21cb5928d443d2a13b67481604051612acf9190614670565b60405180910390a150565b600281015161ffff8116600314610f785781604051639a6d49cd60e01b8152600401610d679190613c85565b5f8315612b36578360051b8501855b803580851160051b94855260209485185260405f209301818110612b155750505b501492915050565b5f80612b78866001600160a01b031686866001600160a01b0316866040805194855260208501939093529183015260608201526080902090565b5f9081526862dc72c6d15e6284e2602052604090209695505050505050565b60a082015160c08301515f919082612baf83836146f9565b60e0870151909150838611612bca575f945050505050610d1a565b828610612bdc579350610d1a92505050565b81612be785886146f9565b612bf1908361440f565b612727919061470c565b5f6040518260408114612c165760418114612c3d5750612c6e565b60208581013560ff81901c601b0190915285356040526001600160ff1b0316606052612c4e565b60408501355f1a6020526040856040375b50845f526020600160805f60015afa5191505f606052806040523d612c7b575b638baa579f5f526004601cfd5b509392505050565b5f6301000000821061296757612967613301565b5f610100821061296757612967613301565b5f61a4b14603612cba575061759590565b62066eee4603612ccb5750619ce190565b60405163c08c729760e01b815260040160405180910390fd5b5f323314612cf457506001919050565b503b151590565b60605f600184612d0b855161330e565b6040516001600160f01b031960f094851b8116602083015292841b83166022820152921b16602482015260260160405160208183030381529060405290505f5b8351811015612c7b57612d7782858381518110612d6a57612d6a6141a7565b602002602001015161333c565b9150600101612d4b565b6060846003612d90825f6133cc565b61ffff1614612dc357612da3815f6133cc565b604051633a51740d60e01b815261ffff9091166004820152602401610d67565b5f612dcf868686613428565b9050612727876005836134d3565b5f813414612967576040516304fb820960e51b8152346004820152602401610d67565b5f7f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663e4fe1d946040518163ffffffff1660e01b8152600401602060405180830381865afa158015612e5d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e81919061472b565b90506001600160a01b038116612eaa576040516329b99a9560e11b815260040160405180910390fd5b610f786001600160a01b038216337f00000000000000000000000000000000000000000000000000000000000000008561353c565b6862dc72c6d15e6284df5f8080612ef58561359c565b919450925090506001600160a01b038216612f235760405163391bbb4160e01b815260040160405180910390fd5b600184015460ff1615612f49576040516313d0ff5960e31b815260040160405180910390fd5b600885901c5f90815260098501602052604090205460ff86161c60011615612f8357604051623f613760e71b815260040160405180910390fd5b6001840154612f9d90610100900463ffffffff16426146f9565b816001600160401b03161015612fc6576040516336c056a760e21b815260040160405180910390fd5b600885901c5f90815260098501602052604090208054600160ff88161b179055612fee61375e565b600284015484546001600160601b03918216600160a01b909104909116116130295760405163620eca6f60e11b815260040160405180910390fd5b600284015484545f918291613051916001600160601b0390811691600160a01b900416614746565b6001600160601b031690505f5b85518110156131b6575f86828151811061307a5761307a6141a7565b602002602001015190505f6130a3825f015183602001518460600151856080015160ff16612b3e565b90505f6130df825f01546130c0858a6001600160401b0316612b97565b6130ca91906146f9565b6130d488886146f9565b808218908211021890565b90506130eb8187614426565b955080825f015f8282546130ff9190614426565b9250508190555082606001516001600160a01b03168360200151845f01516001600160a01b03167f9fb8cf0df5a043b3003ee5402e773eca3296ff3e0af8aa116ac898a017bdb2e486608001518560405161316992919060ff929092168252602082015260400190565b60405180910390a48486036131a8576040517f0190970836bc5d65e97baf82f827186fccf05984b165b053a97e92d42eec02d1905f90a15050506131b6565b50505080600101905061305e565b508115610dd7576131c6826137c9565b60078601546131df906001600160a01b031685846128ef565b836001600160a01b0316877f3bfce8de0db7450cc169b94323c210e69a36c6a4a58c9f5d96bec4973adce3928460405161321b91815260200190565b60405180910390a350505050505050565b604080518082019091525f80825260208201527f00000000000000000000000000000000000000000000000000000000000000006001600160a01b031663ddc28c586040518060a001604052808863ffffffff16815260200161328e89612732565b8152602001878152602001868152602001851515815250306040518363ffffffff1660e01b81526004016132c3929190614439565b6040805180830381865afa1580156132dd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f239190614766565b6335278d125f526004601cfd5b5f61ffff821115612967576040516306dfcc6560e41b81526010600482015260248101839052604401610d67565b60605f836001845f015160016133628760c0015151602361335d9190614426565b61330e565b60208089015160405161337a97969594939201614780565b60408051601f19818403018152828252908501516060860151608087015160a088015160c08901519496506133b4958795906020016147f2565b60405160208183030381529060405291505092915050565b5f6133d8826002614426565b8351101561341f5760405162461bcd60e51b8152602060048201526014602482015273746f55696e7431365f6f75744f66426f756e647360601b6044820152606401610d67565b50016002015190565b60606fffffffffffffffffffffffffffffffff82161561348e576040516001600160801b0319608086811b821660208401526001600160e01b031960e087901b16603084015284901b166034820152604401604051602081830303815290604052611235565b6040516001600160801b0319608086901b1660208201526001600160e01b031960e085901b166030820152603401604051602081830303815290604052949350505050565b60608360036134e2825f6133cc565b61ffff16146134f557612da3815f6133cc565b846001613502855161330e565b61350d90600161486e565b8686604051602001613523959493929190614889565b6040516020818303038152906040529150509392505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b179052613596908590613828565b50505050565b60605f80806862dc72c6d15e6284df5f86815260088201602052604081208054929350916001600160a01b038116916001600160401b03600160a01b830481169263ffffffff600160e01b90910416908111156135fb576135fb613ed3565b60405190808252806020026020018201604052801561369257816020015b61367f6040518061014001604052805f6001600160a01b031681526020015f81526020015f80191681526020015f6001600160a01b031681526020015f60ff1681526020015f81526020015f81526020015f815260200160608152602001606081525090565b8152602001906001900390816136195790505b5090505f5b8151811015613750575f818152600186016020526040812083519091908490849081106136c6576136c66141a7565b60209081029190910181015183546001600160a01b038082168352600160a01b80830462ffffff1694840194909452600160b81b820460ff166080840152600160c01b820463ffffffff90811660a0850152600160e01b90920490911660c08301526001948501549081166060830152919091046001600160601b031660e0909101525001613697565b509891975095509350505050565b6862dc72c6d15e6284df5f613776620151804261470c565b6001830154909150600160b81b900463ffffffff168114610f785760018201805463ffffffff8316600160b81b0263ffffffff60b81b199091161790556002820180546001600160601b03191690555050565b6862dc72c6d15e6284e1546862dc72c6d15e6284df905f906137f59084906001600160601b0316614426565b9050613800816129ba565b60029290920180546001600160601b0319166001600160601b03909316929092179091555050565b5f8060205f8451602086015f885af180613847576040513d5f823e3d81fd5b50505f513d9150811561385e57806001141561386b565b6001600160a01b0384163b155b1561359657604051635274afe760e01b81526001600160a01b0385166004820152602401610d67565b60405180606001604052805f80191681526020015f6001600160401b031681526020016138d260405180604001604052805f81526020015f81525090565b905290565b5f8083601f8401126138e7575f80fd5b5081356001600160401b038111156138fd575f80fd5b6020830191508360208260051b8501011115613917575f80fd5b9250929050565b5f806020838503121561392f575f80fd5b82356001600160401b03811115613944575f80fd5b613950858286016138d7565b90969095509350505050565b5f608082019050825182526001600160401b0360208401511660208301526040830151611c0f604084018280518252602090810151910152565b5f606082840312156139a6575f80fd5b50919050565b5f8083601f8401126139bc575f80fd5b5081356001600160401b038111156139d2575f80fd5b602083019150836020828501011115613917575f80fd5b6001600160a01b0381168114611ada575f80fd5b8035613a08816139e9565b919050565b5f805f805f805f60e0888a031215613a23575f80fd5b613a2d8989613996565b96506060880135955060808801356001600160401b0380821115613a4f575f80fd5b613a5b8b838c016139ac565b909750955060a08a01359150613a70826139e9565b90935060c08901359080821115613a85575f80fd5b50613a928a828b016139ac565b989b979a50959850939692959293505050565b80358015158114613a08575f80fd5b5f60208284031215613ac4575f80fd5b613acd82613aa5565b9392505050565b5f60208284031215613ae4575f80fd5b5035919050565b5f8060408385031215613afc575f80fd5b50508035926020909101359150565b803563ffffffff81168114613a08575f80fd5b5f60208284031215613b2e575f80fd5b613acd82613b0b565b5f8060408385031215613b48575f80fd5b613b5183613b0b565b946020939093013593505050565b5f805f60608486031215613b71575f80fd5b8335613b7c816139e9565b92506020840135613b8c816139e9565b929592945050506040919091013590565b5f805f60608486031215613baf575f80fd5b833592506020840135613b8c816139e9565b5f8060408385031215613bd2575f80fd5b8235613b51816139e9565b803561ffff81168114613a08575f80fd5b5f60208284031215613bfe575f80fd5b613acd82613bdd565b5f8060408385031215613c18575f80fd5b613c2183613b0b565b9150613c2f60208401613bdd565b90509250929050565b5f5b83811015613c52578181015183820152602001613c3a565b50505f910152565b5f8151808452613c71816020860160208601613c38565b601f01601f19169290920160200192915050565b602081525f613acd6020830184613c5a565b5f805f8060a08587031215613caa575f80fd5b613cb48686613996565b935060608501356001600160401b03811115613cce575f80fd5b613cda878288016139ac565b9094509250506080850135613cee816139e9565b939692955090935050565b803560ff81168114613a08575f80fd5b5f60208284031215613d19575f80fd5b613acd82613cf9565b5f60208284031215613d32575f80fd5b8135613acd816139e9565b5f805f8060608587031215613d50575f80fd5b613d5985613b0b565b9350613d6760208601613bdd565b925060408501356001600160401b03811115613d81575f80fd5b613d8d878288016139ac565b95989497509550505050565b5f8060408385031215613daa575f80fd5b82356001600160401b03811115613dbf575f80fd5b83016101408186031215613b51575f80fd5b5f805f60608486031215613de3575f80fd5b8335613dee816139e9565b95602085013595506040909401359392505050565b5f8060408385031215613e14575f80fd5b613e1d83613b0b565b9150613c2f60208401613aa5565b602080825282518282018190525f919060409081850190868401855b82811015613e7457613e6484835180518252602090810151910152565b9284019290850190600101613e47565b5091979650505050505050565b5f60608284031215613e91575f80fd5b613acd8383613996565b634e487b7160e01b5f52601160045260245ffd5b5f65ffffffffffff808316818103613ec957613ec9613e9b565b6001019392505050565b634e487b7160e01b5f52604160045260245ffd5b600181811c90821680613efb57607f821691505b6020821081036139a657634e487b7160e01b5f52602260045260245ffd5b604051606081016001600160401b0381118282101715613f3b57613f3b613ed3565b60405290565b60405161014081016001600160401b0381118282101715613f3b57613f3b613ed3565b604051601f8201601f191681016001600160401b0381118282101715613f8c57613f8c613ed3565b604052919050565b5f6001600160401b03821115613fac57613fac613ed3565b5060051b60200190565b5f82601f830112613fc5575f80fd5b81356001600160401b03811115613fde57613fde613ed3565b613ff1601f8201601f1916602001613f64565b818152846020838601011115614005575f80fd5b816020850160208301375f918101602001919091529392505050565b5f61403361402e84613f94565b613f64565b80848252602080830192508560051b850136811115614050575f80fd5b855b818110156140db5780356001600160401b0380821115614070575f80fd5b818901915060608236031215614084575f80fd5b61408c613f19565b61409583613b0b565b81526140a2868401613bdd565b86820152604080840135838111156140b8575f80fd5b6140c436828701613fb6565b918301919091525087525050938201938201614052565b50919695505050505050565b5f80858511156140f5575f80fd5b83861115614101575f80fd5b5050820193919092039150565b5f845161411f818460208901613c38565b8201838582375f930192835250909392505050565b60208152816020820152818360408301375f818301604090810191909152601f909201601f19160101919050565b5f808335601e19843603018112614177575f80fd5b8301803591506001600160401b03821115614190575f80fd5b6020019150600581901b3603821315613917575f80fd5b634e487b7160e01b5f52603260045260245ffd5b5f823561013e198336030181126141d0575f80fd5b9190910192915050565b5f82601f8301126141e9575f80fd5b813560206141f961402e83613f94565b8083825260208201915060208460051b87010193508684111561421a575f80fd5b602086015b84811015614236578035835291830191830161421f565b509695505050505050565b5f6101408236031215614252575f80fd5b61425a613f41565b614263836139fd565b81526020830135602082015260408301356040820152614285606084016139fd565b606082015261429660808401613cf9565b608082015260a083013560a082015260c083013560c082015260e083013560e0820152610100808401356001600160401b03808211156142d4575f80fd5b6142e0368388016141da565b838501526101209250828601359150808211156142fb575f80fd5b5061430836828701613fb6565b918301919091525092915050565b5f808335601e1984360301811261432b575f80fd5b8301803591506001600160401b03821115614344575f80fd5b602001915036819003821315613917575f80fd5b5f6001820161436957614369613e9b565b5060010190565b5f60a08201878352602060018060a01b038089168286015260a0604086015282885180855260c087019150838a0194505f5b818110156143be578551835294840194918401916001016143a2565b5050858103606087015287518082529083019350828801905f5b818110156143f65782518416865294840194918401916001016143d8565b5050505084151560808501525090509695505050505050565b8082028115828204841417610d1a57610d1a613e9b565b80820180821115610d1a57610d1a613e9b565b6040815263ffffffff8351166040820152602083015160608201525f604084015160a0608084015261446e60e0840182613c5a565b90506060850151603f198483030160a085015261448b8282613c5a565b60809690960151151560c08501525050506001600160a01b039190911660209091015290565b5f604082840312156144c1575f80fd5b604051604081018181106001600160401b03821117156144e3576144e3613ed3565b604052825181526020928301519281019290925250919050565b5f6080828403121561450d575f80fd5b614515613f19565b8251815260208301516001600160401b0381168114614532575f80fd5b602082015261454484604085016144b1565b60408201529392505050565b5f8060408385031215614561575f80fd5b82359150613c2f60208401613aa5565b601f821115610fbe57805f5260205f20601f840160051c810160208510156145965750805b601f840160051c820191505b81811015611863575f81556001016145a2565b81516001600160401b038111156145ce576145ce613ed3565b6145e2816145dc8454613ee7565b84614571565b602080601f831160018114614615575f84156145fe5750858301515b5f19600386901b1c1916600185901b17855561243f565b5f85815260208120601f198616915b8281101561464357888601518255948401946001909101908401614624565b508582101561466057878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f60208083018184528085518083526040925060408601915060408160051b8701018488015f5b838110156146eb57888303603f190185528151805163ffffffff1684528781015161ffff168885015286015160608785018190526146d781860183613c5a565b968901969450505090860190600101614697565b509098975050505050505050565b81810381811115610d1a57610d1a613e9b565b5f8261472657634e487b7160e01b5f52601260045260245ffd5b500490565b5f6020828403121561473b575f80fd5b8151613acd816139e9565b6001600160601b03828116828216039080821115611c0f57611c0f613e9b565b5f60408284031215614776575f80fd5b613acd83836144b1565b5f8751614791818460208c01613c38565b60f89790971b6001600160f81b0319169190960190815260f094851b6001600160f01b0319908116600183015293851b841660038201529190931b909116600582015260e09190911b6001600160e01b0319166007820152600b0192915050565b5f8751614803818460208c01613c38565b87151560f81b90830190815260c087901b6001600160c01b031916600182015260f086901b6001600160f01b0319166009820152606085901b6001600160601b031916600b820152835161485e81601f840160208801613c38565b01601f0198975050505050505050565b61ffff818116838216019080821115611c0f57611c0f613e9b565b5f865161489a818460208b01613c38565b6001600160f81b031960f888811b82169285019283526001600160f01b031960f089901b16600184015286901b16600382015283516148e0816004840160208801613c38565b0160040197965050505050505056fea26469706673582212209a014b20aacdac2890236105c6d89246e72b61e08090dabac92398cd12cb2f3c64736f6c63430008180033
Deployed Bytecode
0x60806040526004361061035b575f3560e01c806382413eac116101bd578063c21be51e116100f2578063d8333ac811610092578063f0a9e4811161006d578063f0a9e48114610a99578063f2fde38b14610ab8578063f79fd08514610ad7578063ff7bd03d14610b03575f80fd5b8063d8333ac814610a3c578063ddeedcc314610a5b578063def55d1c14610a7a575f80fd5b8063ca5eb5e1116100cd578063ca5eb5e1146109ac578063ce271616146109cb578063d0ebdbe7146109ea578063d3bebea614610a09575f80fd5b8063c21be51e1461093f578063c460af0a1461095e578063c7fc466514610983575f80fd5b8063a25798751161015d578063b187bd2611610138578063b187bd26146108b7578063b98bd070146108d6578063bb0b6a53146108f5578063bc70b35414610920575f80fd5b8063a25798751461084e578063a761821f14610879578063b097aeb814610898575f80fd5b806398385a3b1161019857806398385a3b146107ca578063983a2122146107ff5780639a08fe3d1461081b5780639b894b0c1461082f575f80fd5b806382413eac1461077057806386e326031461078f5780638da5cb5b146107ae575f80fd5b80634782f77911610293578063715018a61161023357806379a2c8dc1161020e57806379a2c8dc146106c75780637d25a05e146106ec5780637ec133081461072557806381b5d66114610744575f80fd5b8063715018a61461066257806375216e651461067657806378858ee3146106a2575f80fd5b80635535d4611161026e5780635535d461146105bb57806359b87bf4146105e75780635e280f111461060657806362a1a94d14610639575f80fd5b80634782f77914610544578063481c6a751461056357806352f7f3f61461059c575f80fd5b806327570d90116102fe5780633400288b116102d95780633400288b146104b857806344004cc1146104d75780634693e7a8146104f65780634763666c14610525575f80fd5b806327570d9014610441578063278e024c14610460578063282a915614610499575f80fd5b806317442b701161033957806317442b70146103bc578063176c41d7146103dd5780631e2ff94f146103fc57806321c210d814610418575f80fd5b80630f601f5f1461035f57806313137d651461038857806316c38b3c1461039d575b5f80fd5b61037261036d36600461391e565b610b22565b60405161037f919061395c565b60405180910390f35b61039b610396366004613a0d565b610d20565b005b3480156103a8575f80fd5b5061039b6103b7366004613ab4565b610de0565b3480156103c7575f80fd5b506040805160018152600260208201520161037f565b3480156103e8575f80fd5b5061039b6103f7366004613ad4565b610e70565b348015610407575f80fd5b50425b60405190815260200161037f565b348015610423575f80fd5b506862dc72c6d15e6284e054600160281b900463ffffffff1661040a565b34801561044c575f80fd5b5061040a61045b366004613aeb565b610e8d565b34801561046b575f80fd5b506862dc72c6d15e6284e954600160a01b900463ffffffff1660405163ffffffff909116815260200161037f565b3480156104a4575f80fd5b5061039b6104b3366004613b1e565b610f2c565b3480156104c3575f80fd5b5061039b6104d2366004613b37565b610f66565b3480156104e2575f80fd5b5061039b6104f1366004613b5f565b610f7c565b348015610501575f80fd5b50610515610510366004613ad4565b610fc3565b604051901515815260200161037f565b348015610530575f80fd5b5061039b61053f366004613b9d565b610feb565b34801561054f575f80fd5b5061039b61055e366004613bc1565b611028565b34801561056e575f80fd5b506862dc72c6d15e6284df546001600160a01b03165b6040516001600160a01b03909116815260200161037f565b3480156105a7575f80fd5b5061039b6105b6366004613bee565b611069565b3480156105c6575f80fd5b506105da6105d5366004613c07565b6110a4565b60405161037f9190613c85565b3480156105f2575f80fd5b5061039b610601366004613ad4565b611146565b348015610611575f80fd5b506105847f0000000000000000000000001a44076050125825900e736c501f859c50fe728c81565b348015610644575f80fd5b506862dc72c6d15e6284e054600160681b900463ffffffff1661040a565b34801561066d575f80fd5b5061039b6111ca565b348015610681575f80fd5b506862dc72c6d15e6284df54600160a01b90046001600160601b031661040a565b3480156106ad575f80fd5b506862dc72c6d15e6284e9546001600160a01b0316610584565b3480156106d2575f80fd5b506862dc72c6d15e6284e1546001600160601b031661040a565b3480156106f7575f80fd5b5061070d610706366004613b37565b5f92915050565b6040516001600160401b03909116815260200161037f565b348015610730575f80fd5b5061039b61073f366004613ad4565b6111dd565b34801561074f575f80fd5b506862dc72c6d15e6284e154600160601b90046001600160a01b0316610584565b34801561077b575f80fd5b5061051561078a366004613c97565b611228565b34801561079a575f80fd5b5061039b6107a9366004613d09565b61123d565b3480156107b9575f80fd5b505f546001600160a01b0316610584565b3480156107d5575f80fd5b506862dc72c6d15e6284e954600160c01b900461ffff1660405161ffff909116815260200161037f565b34801561080a575f80fd5b506862dc72c6d15e6284e55461040a565b348015610826575f80fd5b506105156112b1565b34801561083a575f80fd5b5061039b610849366004613d22565b61142f565b348015610859575f80fd5b506862dc72c6d15e6284e054600160881b900465ffffffffffff1661040a565b348015610884575f80fd5b5061040a61089336600461391e565b6114a4565b3480156108a3575f80fd5b5061039b6108b2366004613ad4565b6114c4565b3480156108c2575f80fd5b506862dc72c6d15e6284e05460ff16610515565b3480156108e1575f80fd5b5061039b6108f036600461391e565b61154e565b348015610900575f80fd5b5061040a61090f366004613b1e565b60016020525f908152604090205481565b34801561092b575f80fd5b506105da61093a366004613d3d565b611568565b34801561094a575f80fd5b5061039b610959366004613d99565b611709565b348015610969575f80fd5b506862dc72c6d15e6284e6546001600160a01b0316610584565b34801561098e575f80fd5b506862dc72c6d15e6284e054600160481b900463ffffffff1661040a565b3480156109b7575f80fd5b5061039b6109c6366004613d22565b6117e9565b3480156109d6575f80fd5b5061039b6109e5366004613d22565b61186a565b3480156109f5575f80fd5b5061039b610a04366004613d22565b6118d1565b348015610a14575f80fd5b506862dc72c6d15e6284e954600160d01b900460ff1660405160ff909116815260200161037f565b348015610a47575f80fd5b5061039b610a56366004613d22565b611946565b348015610a66575f80fd5b5061039b610a75366004613dd1565b611980565b348015610a85575f80fd5b5061039b610a94366004613ad4565b6119be565b348015610aa4575f80fd5b5061039b610ab3366004613e03565b611a44565b348015610ac3575f80fd5b5061039b610ad2366004613d22565b611aa0565b348015610ae2575f80fd5b50610af6610af136600461391e565b611add565b60405161037f9190613e2b565b348015610b0e575f80fd5b50610515610b1d366004613e81565b611c16565b610b2a613894565b688000000000ab143c0646600103610b5457805c15610b4c57805f526004601cfd5b30815d610b69565b30815403610b6557805f526004601cfd5b3081555b506862dc72c6d15e6284df610b7c6112b1565b610b9957604051630a075a0560e41b815260040160405180910390fd5b600181015460ff1615610bbf576040516313d0ff5960e31b815260040160405180910390fd5b600a810154600160d01b900460ff16831115610bee576040516353da2aa560e01b815260040160405180910390fd5b5f839003610c0f57604051636910abcb60e11b815260040160405180910390fd5b610c198484611c4a565b5f610c248585611f53565b6001830180549192505f91600160881b900465ffffffffffff16906011610c4a83613eaf565b91906101000a81548165ffffffffffff021916908365ffffffffffff16021790555065ffffffffffff169050610c81818787612236565b600a83015482516020840151610cd79263ffffffff600160a01b82041692610cb39286926001600160a01b0316612447565b610cbc88612592565b60405180604001604052803481526020015f8152503361262c565b9350505050610ce4600190565b15610d0d57688000000000ab143c0646600103610d03575f815d610d07565b8081555b50610d1a565b5f688000000000ab143c065d5b92915050565b7f0000000000000000000000001a44076050125825900e736c501f859c50fe728c6001600160a01b03163314610d70576040516391ac5e4f60e01b81523360048201526024015b60405180910390fd5b60208701803590610d8a90610d85908a613b1e565b612732565b14610dc857610d9c6020880188613b1e565b60405163309afaf360e21b815263ffffffff909116600482015260208801356024820152604401610d67565b610dd78787878787878761276d565b50505050505050565b5f546001600160a01b03163314610e23576862dc72c6d15e6284df546001600160a01b03163314610e23576040516282b42960e81b815260040160405180910390fd5b80610e4d57610e306112b1565b610e4d57604051630a075a0560e41b815260040160405180910390fd5b610e556127b0565b6862dc72c6d15e6284e0805460ff1916911515919091179055565b610e786127f5565b610e806127b0565b6862dc72c6d15e6284e555565b5f80836001600160401b03811115610ea757610ea7613ed3565b604051908082528060200260200182016040528015610ed0578160200160208202803683370190505b5090505f836001600160401b03811115610eec57610eec613ed3565b604051908082528060200260200182016040528015610f15578160200160208202803683370190505b509050610f23308383612821565b95945050505050565b610f346127f5565b610f3c6127b0565b6862dc72c6d15e6284e0805463ffffffff9092166101000264ffffffff0019909216919091179055565b610f6e6127f5565b610f78828261289b565b5050565b610f846127f5565b610f8c6127b0565b6001600160a01b038216610fb35760405163391bbb4160e01b815260040160405180910390fd5b610fbe8383836128ef565b505050565b600881901c5f9081526862dc72c6d15e6284e8602052604081205460ff83161c600116610d1a565b610ff36127f5565b610ffb6127b0565b5f9283526862dc72c6d15e6284e4602052604090922060a09290921b6001600160a01b0391909116179055565b6110306127f5565b6110386127b0565b6001600160a01b03821661105f5760405163391bbb4160e01b815260040160405180910390fd5b610f788282612939565b6110716127f5565b6110796127b0565b6862dc72c6d15e6284e9805461ffff92909216600160c01b0261ffff60c01b19909216919091179055565b600260209081525f9283526040808420909152908252902080546110c790613ee7565b80601f01602080910402602001604051908101604052809291908181526020018280546110f390613ee7565b801561113e5780601f106111155761010080835404028352916020019161113e565b820191905f5260205f20905b81548152906001019060200180831161112157829003601f168201915b505050505081565b5f546001600160a01b03163314611189576862dc72c6d15e6284df546001600160a01b03163314611189576040516282b42960e81b815260040160405180910390fd5b6111916127b0565b61119a81612952565b6862dc72c6d15e6284e0805463ffffffff92909216600160681b0263ffffffff60681b1990921691909117905550565b6111d26127f5565b6111db5f61296b565b565b6111e56127f5565b6111ed6127b0565b6111f6816129ba565b6862dc72c6d15e6284df80546001600160601b0392909216600160a01b026001600160a01b0390921691909117905550565b6001600160a01b03811630145b949350505050565b5f546001600160a01b03163314611280576862dc72c6d15e6284df546001600160a01b03163314611280576040516282b42960e81b815260040160405180910390fd5b6112886127b0565b6862dc72c6d15e6284e9805460ff92909216600160d01b0260ff60d01b19909216919091179055565b6862dc72c6d15e6284df80545f91906001600160a01b03166112d4575f91505090565b6001810154610100900463ffffffff165f036112f1575f91505090565b8054600160a01b90046001600160601b03165f03611310575f91505090565b6001810154600160281b900463ffffffff165f0361132f575f91505090565b6001810154600160481b900463ffffffff165f0361134e575f91505090565b6001810154600160681b900463ffffffff165f0361136d575f91505090565b600681015461137d575f91505090565b60078101546001600160a01b0316611396575f91505090565b600a8101546001600160a01b03166113af575f91505090565b6002810154600160601b90046001600160a01b03166113cf575f91505090565b600a810154600160a01b900463ffffffff165f036113ee575f91505090565b600a810154600160c01b900461ffff165f0361140b575f91505090565b600a810154600160d01b900460ff165f03611427575f91505090565b600191505090565b5f546001600160a01b03163314611472576862dc72c6d15e6284df546001600160a01b03163314611472576040516282b42960e81b815260040160405180910390fd5b61147a6127b0565b6862dc72c6d15e6284e680546001600160a01b0319166001600160a01b0392909216919091179055565b5f806114b08484611f53565b905061123581604001518260600151610e8d565b5f546001600160a01b03163314611507576862dc72c6d15e6284df546001600160a01b03163314611507576040516282b42960e81b815260040160405180910390fd5b61150f6127b0565b61151881612952565b6862dc72c6d15e6284e0805463ffffffff92909216600160481b026cffffffff0000000000000000001990921691909117905550565b6115566127f5565b610f786115638284614021565b6129ce565b63ffffffff84165f90815260026020908152604080832061ffff8716845290915281208054606092919061159b90613ee7565b80601f01602080910402602001604051908101604052809291908181526020018280546115c790613ee7565b80156116125780601f106115e957610100808354040283529160200191611612565b820191905f5260205f20905b8154815290600101906020018083116115f557829003601f168201915b5050505050905080515f036116605783838080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152509294506112359350505050565b5f83900361166f579050611235565b600283106116ec576116b584848080601f0160208091040260200160405190810160405280939291908181526020018383808284375f92019190915250612ada92505050565b806116c384600281886140e7565b6040516020016116d59392919061410e565b604051602081830303815290604052915050611235565b8383604051639a6d49cd60e01b8152600401610d67929190614134565b5f6117b261171a6020850185613d22565b6001600160a01b03166040850135611736578460200135611738565b5f5b604086013561174d6080880160608901613d22565b6001600160a01b031661176660a0890160808a01613d09565b60ff168860a001358960c001358a60e00135604080519889526020890197909752958701949094526060860192909252608085015260a084015260c083015260e0820152610100902090565b90506117cc6117c5610100850185614162565b8484612b06565b610fbe576040516309bde33960e01b815260040160405180910390fd5b6117f16127f5565b60405163ca5eb5e160e01b81526001600160a01b0382811660048301527f0000000000000000000000001a44076050125825900e736c501f859c50fe728c169063ca5eb5e1906024015f604051808303815f87803b158015611851575f80fd5b505af1158015611863573d5f803e3d5ffd5b5050505050565b6118726127f5565b6001600160a01b038116611899576040516371c46ce160e01b815260040160405180910390fd5b6118a16127b0565b6862dc72c6d15e6284e180546001600160a01b03909216600160601b026001600160601b03909216919091179055565b5f546001600160a01b03163314611914576862dc72c6d15e6284df546001600160a01b03163314611914576040516282b42960e81b815260040160405180910390fd5b61191c6127b0565b6862dc72c6d15e6284df80546001600160a01b0319166001600160a01b0392909216919091179055565b61194e6127f5565b6119566127b0565b6862dc72c6d15e6284e980546001600160a01b0319166001600160a01b0392909216919091179055565b6119886127f5565b6119906127b0565b6001600160a01b03929092165f9081526862dc72c6d15e6284e3602090815260408083209383529290522055565b5f546001600160a01b03163314611a01576862dc72c6d15e6284df546001600160a01b03163314611a01576040516282b42960e81b815260040160405180910390fd5b611a096127b0565b611a1281612952565b6862dc72c6d15e6284e0805463ffffffff92909216600160281b0268ffffffff00000000001990921691909117905550565b611a4c6127f5565b611a546127b0565b6862dc72c6d15e6284df611a738383611a6d575f61289b565b3061289b565b8115610fbe57600a8101805463ffffffff8516600160a01b0263ffffffff60a01b19909116179055505050565b611aa86127f5565b6001600160a01b038116611ad157604051631e4fbdf760e01b81525f6004820152602401610d67565b611ada8161296b565b50565b6060816001600160401b03811115611af757611af7613ed3565b604051908082528060200260200182016040528015611b3b57816020015b604080518082019091525f8082526020820152815260200190600190039081611b155790505b5090505f5b82811015611c0f5736848483818110611b5b57611b5b6141a7565b9050602002810190611b6d91906141bb565b90505f611bad611b806020840184613d22565b6020840135611b956080860160608701613d22565b611ba560a0870160808801613d09565b60ff16612b3e565b9050611bc1611bbb83614241565b42612b97565b848481518110611bd357611bd36141a7565b60200260200101516020018181525050805f0154848481518110611bf957611bf96141a7565b6020908102919091010151525050600101611b40565b5092915050565b5f602082018035906001908390611c2d9086613b1e565b63ffffffff16815260208101919091526040015f20541492915050565b6862dc72c6d15e6284e5546862dc72c6d15e6284df905f5b838110156118635736858583818110611c7d57611c7d6141a7565b9050602002810190611c8f91906141bb565b9050611c9b8184611709565b5f80611caa6020840184613d22565b6001600160a01b031614159050604082013515611e345780611cdf57604051632e4a826160e11b815260040160405180910390fd5b5f611d1d6040840135611cf56020860186613d22565b6001600160a01b03168560200135604080519384526020840192909252908201526060902090565b9050611d4d816020527b19457468657265756d205369676e6564204d6573736167653a0a33325f52603c60042090565b6002870154909150600160601b90046001600160a01b0316611d7c82611d77610120870187614316565b612bfb565b6001600160a01b031614611da357604051638baa579f60e01b815260040160405180910390fd5b5f611dc9611db46020860186613d22565b6001600160a01b0316602086013560a01b1790565b6040808601355f90815260058a01602052205490915015611e1b576040808501355f9081526005890160205220548114611e165760405163533c430760e01b815260040160405180910390fd5b611e31565b6040808501355f90815260058901602052208190555b50505b8015611f49575f6040830135611e4e57600160801b611e54565b82604001355b90505f6004870181611e696020870187613d22565b6001600160a01b03166001600160a01b031681526020019081526020015f205f856020013581526020019081526020015f205414611f0a5780600487015f611eb46020870187613d22565b6001600160a01b03166001600160a01b031681526020019081526020015f205f856020013581526020019081526020015f205414611f055760405163533c430760e01b815260040160405180910390fd5b611f47565b80600487015f611f1d6020870187613d22565b6001600160a01b0316815260208082019290925260409081015f9081208784013582529092529020555b505b5050600101611c62565b611f7c604051806080016040528060608152602001606081526020015f81526020015f81525090565b5f805f5b848110156120435736868683818110611f9b57611f9b6141a7565b9050602002810190611fad91906141bb565b90505f80611fc16080840160608501613d22565b6001600160a01b0316141590505f80611fdd6020850185613d22565b6001600160a01b03161415905081151581900361200d57604051632e4a826160e11b815260040160405180910390fd5b8115612021578461201d81614358565b9550505b8015612035578561203181614358565b9650505b505050806001019050611f80565b5061206d604051806080016040528060608152602001606081526020015f81526020015f81525090565b826001600160401b0381111561208557612085613ed3565b6040519080825280602002602001820160405280156120ae578160200160208202803683370190505b508152816001600160401b038111156120c9576120c9613ed3565b6040519080825280602002602001820160405280156120f2578160200160208202803683370190505b5060208201525f5b8581101561222c5736878783818110612115576121156141a7565b905060200281019061212791906141bb565b90505f8061213b6080840160608501613d22565b6001600160a01b0316141590505f806121576020850185613d22565b6001600160a01b03161415905081156121c25761217a6080840160608501613d22565b60208601516060870180519061218f82614358565b9052815181106121a1576121a16141a7565b60200260200101906001600160a01b031690816001600160a01b0316815250505b801561221e576121ed6121d86020850185613d22565b6001600160a01b0316602085013560a01b1790565b8551604087018051906121ff82614358565b905281518110612211576122116141a7565b6020026020010181815250505b5050508060010190506120fa565b5095945050505050565b5f8381526862dc72c6d15e6284e76020526040902080546001600160a01b031916331781556862dc72c6d15e6284df9061226f83612952565b81546001600160a01b0316600160e01b63ffffffff929092169190910267ffffffffffffffff60a01b191617600160a01b426001600160401b0316021781555f5b8381101561243f575f8181526001830160205260409020368686848181106122da576122da6141a7565b90506020028101906122ec91906141bb565b90506122fb6020820182613d22565b82546001600160a01b0319166001600160a01b03919091161782556123236020820135612c83565b825462ffffff91909116600160a01b0262ffffff60a01b1990911617825561235c61235460a0830160808401613d09565b60ff16612c97565b825460ff91909116600160b81b0260ff60b81b1990911617825561238360a0820135612952565b825463ffffffff91909116600160c01b0263ffffffff60c01b199091161782556123b060c0820135612952565b825463ffffffff91909116600160e01b026001600160e01b039091161782556123df6080820160608301613d22565b6001830180546001600160a01b0319166001600160a01b039290921691909117905561240e60e08201356129ba565b600192830180546001600160601b0392909216600160a01b026001600160a01b0390921691909117905550016122b0565b505050505050565b6040805160018082528183019092526060915f9190816020015b6040805160e0810182525f808252602080830182905292820181905260608083018290526080830182905260a083019190915260c082015282525f199092019101816124615790505090506040518060e00160405280600161ffff1681526020016124ca612ca9565b63ffffffff1681525f6020820152426001600160401b031660408201526862dc72c6d15e6284e954600160c01b900461ffff1660608201526001600160a01b038516608082015260a0018733888861252183612ce4565b604051602401612535959493929190614370565b60408051601f198184030181529190526020810180516001600160e01b0316636df6dc3760e11b1790529052815182905f90612573576125736141a7565b60200260200101819052506125885f82612cfb565b9695505050505050565b6862dc72c6d15e6284e0546060906862dc72c6d15e6284df905f906125c490600160481b900463ffffffff168561440f565b60018301546125e09190600160281b900463ffffffff16614426565b60018301549091506112359063ffffffff80841691600160681b9004165f61262460408051600360f01b602082015281516002818303018152602290910190915290565b929190612d81565b612634613894565b5f612641845f0151612ddd565b60208501519091501561265b5761265b8460200151612e00565b7f0000000000000000000000001a44076050125825900e736c501f859c50fe728c6001600160a01b0316632637a450826040518060a001604052808b63ffffffff1681526020016126ab8c612732565b81526020018a81526020018981526020015f8960200151111515815250866040518463ffffffff1660e01b81526004016126e6929190614439565b60806040518083038185885af1158015612702573d5f803e3d5ffd5b50505050506040513d601f19601f8201168201806040525081019061272791906144fd565b979650505050505050565b63ffffffff81165f9081526001602052604081205480610d1a5760405163f6ff4fb760e01b815263ffffffff84166004820152602401610d67565b5f8061277b86880188614550565b915091508061279c576040516282b42960e81b815260040160405180910390fd5b6127a582612edf565b505050505050505050565b336001600160a01b03167f2218aada03516237ddb3d2451b4ccb7efc7c423d55815d064da80786312706b45f366040516127eb929190614134565b60405180910390a2565b5f546001600160a01b031633146111db5760405163118cdaa760e01b8152336004820152602401610d67565b6862dc72c6d15e6284e9545f906862dc72c6d15e6284df908290612853908790879087906001600160a01b0316612447565b90505f8061286d865188516128689190614426565b612592565b600a85015490915061288e90600160a01b900463ffffffff1684838561322c565b5198975050505050505050565b63ffffffff82165f81815260016020908152604091829020849055815192835282018390527f238399d427b947898edb290f5ff0f9109849b1c3ba196a42e35f00c50a54b98b910160405180910390a15050565b816014528060345263a9059cbb60601b5f5260205f604460105f875af18060015f51141661292f57803d853b15171061292f576390b8ec185f526004601cfd5b505f603452505050565b5f385f3884865af1610f785763b12d13eb5f526004601cfd5b5f640100000000821061296757612967613301565b5090565b5f80546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b5f600160601b821061296757612967613301565b5f5b8151811015612a9f576129ff8282815181106129ee576129ee6141a7565b602002602001015160400151612ada565b818181518110612a1157612a116141a7565b60200260200101516040015160025f848481518110612a3257612a326141a7565b60200260200101515f015163ffffffff1663ffffffff1681526020019081526020015f205f848481518110612a6957612a696141a7565b60200260200101516020015161ffff1661ffff1681526020019081526020015f209081612a9691906145b5565b506001016129d0565b507fbe4864a8e820971c0247f5992e2da559595f7bf076a21cb5928d443d2a13b67481604051612acf9190614670565b60405180910390a150565b600281015161ffff8116600314610f785781604051639a6d49cd60e01b8152600401610d679190613c85565b5f8315612b36578360051b8501855b803580851160051b94855260209485185260405f209301818110612b155750505b501492915050565b5f80612b78866001600160a01b031686866001600160a01b0316866040805194855260208501939093529183015260608201526080902090565b5f9081526862dc72c6d15e6284e2602052604090209695505050505050565b60a082015160c08301515f919082612baf83836146f9565b60e0870151909150838611612bca575f945050505050610d1a565b828610612bdc579350610d1a92505050565b81612be785886146f9565b612bf1908361440f565b612727919061470c565b5f6040518260408114612c165760418114612c3d5750612c6e565b60208581013560ff81901c601b0190915285356040526001600160ff1b0316606052612c4e565b60408501355f1a6020526040856040375b50845f526020600160805f60015afa5191505f606052806040523d612c7b575b638baa579f5f526004601cfd5b509392505050565b5f6301000000821061296757612967613301565b5f610100821061296757612967613301565b5f61a4b14603612cba575061759590565b62066eee4603612ccb5750619ce190565b60405163c08c729760e01b815260040160405180910390fd5b5f323314612cf457506001919050565b503b151590565b60605f600184612d0b855161330e565b6040516001600160f01b031960f094851b8116602083015292841b83166022820152921b16602482015260260160405160208183030381529060405290505f5b8351811015612c7b57612d7782858381518110612d6a57612d6a6141a7565b602002602001015161333c565b9150600101612d4b565b6060846003612d90825f6133cc565b61ffff1614612dc357612da3815f6133cc565b604051633a51740d60e01b815261ffff9091166004820152602401610d67565b5f612dcf868686613428565b9050612727876005836134d3565b5f813414612967576040516304fb820960e51b8152346004820152602401610d67565b5f7f0000000000000000000000001a44076050125825900e736c501f859c50fe728c6001600160a01b031663e4fe1d946040518163ffffffff1660e01b8152600401602060405180830381865afa158015612e5d573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190612e81919061472b565b90506001600160a01b038116612eaa576040516329b99a9560e11b815260040160405180910390fd5b610f786001600160a01b038216337f0000000000000000000000001a44076050125825900e736c501f859c50fe728c8561353c565b6862dc72c6d15e6284df5f8080612ef58561359c565b919450925090506001600160a01b038216612f235760405163391bbb4160e01b815260040160405180910390fd5b600184015460ff1615612f49576040516313d0ff5960e31b815260040160405180910390fd5b600885901c5f90815260098501602052604090205460ff86161c60011615612f8357604051623f613760e71b815260040160405180910390fd5b6001840154612f9d90610100900463ffffffff16426146f9565b816001600160401b03161015612fc6576040516336c056a760e21b815260040160405180910390fd5b600885901c5f90815260098501602052604090208054600160ff88161b179055612fee61375e565b600284015484546001600160601b03918216600160a01b909104909116116130295760405163620eca6f60e11b815260040160405180910390fd5b600284015484545f918291613051916001600160601b0390811691600160a01b900416614746565b6001600160601b031690505f5b85518110156131b6575f86828151811061307a5761307a6141a7565b602002602001015190505f6130a3825f015183602001518460600151856080015160ff16612b3e565b90505f6130df825f01546130c0858a6001600160401b0316612b97565b6130ca91906146f9565b6130d488886146f9565b808218908211021890565b90506130eb8187614426565b955080825f015f8282546130ff9190614426565b9250508190555082606001516001600160a01b03168360200151845f01516001600160a01b03167f9fb8cf0df5a043b3003ee5402e773eca3296ff3e0af8aa116ac898a017bdb2e486608001518560405161316992919060ff929092168252602082015260400190565b60405180910390a48486036131a8576040517f0190970836bc5d65e97baf82f827186fccf05984b165b053a97e92d42eec02d1905f90a15050506131b6565b50505080600101905061305e565b508115610dd7576131c6826137c9565b60078601546131df906001600160a01b031685846128ef565b836001600160a01b0316877f3bfce8de0db7450cc169b94323c210e69a36c6a4a58c9f5d96bec4973adce3928460405161321b91815260200190565b60405180910390a350505050505050565b604080518082019091525f80825260208201527f0000000000000000000000001a44076050125825900e736c501f859c50fe728c6001600160a01b031663ddc28c586040518060a001604052808863ffffffff16815260200161328e89612732565b8152602001878152602001868152602001851515815250306040518363ffffffff1660e01b81526004016132c3929190614439565b6040805180830381865afa1580156132dd573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190610f239190614766565b6335278d125f526004601cfd5b5f61ffff821115612967576040516306dfcc6560e41b81526010600482015260248101839052604401610d67565b60605f836001845f015160016133628760c0015151602361335d9190614426565b61330e565b60208089015160405161337a97969594939201614780565b60408051601f19818403018152828252908501516060860151608087015160a088015160c08901519496506133b4958795906020016147f2565b60405160208183030381529060405291505092915050565b5f6133d8826002614426565b8351101561341f5760405162461bcd60e51b8152602060048201526014602482015273746f55696e7431365f6f75744f66426f756e647360601b6044820152606401610d67565b50016002015190565b60606fffffffffffffffffffffffffffffffff82161561348e576040516001600160801b0319608086811b821660208401526001600160e01b031960e087901b16603084015284901b166034820152604401604051602081830303815290604052611235565b6040516001600160801b0319608086901b1660208201526001600160e01b031960e085901b166030820152603401604051602081830303815290604052949350505050565b60608360036134e2825f6133cc565b61ffff16146134f557612da3815f6133cc565b846001613502855161330e565b61350d90600161486e565b8686604051602001613523959493929190614889565b6040516020818303038152906040529150509392505050565b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b179052613596908590613828565b50505050565b60605f80806862dc72c6d15e6284df5f86815260088201602052604081208054929350916001600160a01b038116916001600160401b03600160a01b830481169263ffffffff600160e01b90910416908111156135fb576135fb613ed3565b60405190808252806020026020018201604052801561369257816020015b61367f6040518061014001604052805f6001600160a01b031681526020015f81526020015f80191681526020015f6001600160a01b031681526020015f60ff1681526020015f81526020015f81526020015f815260200160608152602001606081525090565b8152602001906001900390816136195790505b5090505f5b8151811015613750575f818152600186016020526040812083519091908490849081106136c6576136c66141a7565b60209081029190910181015183546001600160a01b038082168352600160a01b80830462ffffff1694840194909452600160b81b820460ff166080840152600160c01b820463ffffffff90811660a0850152600160e01b90920490911660c08301526001948501549081166060830152919091046001600160601b031660e0909101525001613697565b509891975095509350505050565b6862dc72c6d15e6284df5f613776620151804261470c565b6001830154909150600160b81b900463ffffffff168114610f785760018201805463ffffffff8316600160b81b0263ffffffff60b81b199091161790556002820180546001600160601b03191690555050565b6862dc72c6d15e6284e1546862dc72c6d15e6284df905f906137f59084906001600160601b0316614426565b9050613800816129ba565b60029290920180546001600160601b0319166001600160601b03909316929092179091555050565b5f8060205f8451602086015f885af180613847576040513d5f823e3d81fd5b50505f513d9150811561385e57806001141561386b565b6001600160a01b0384163b155b1561359657604051635274afe760e01b81526001600160a01b0385166004820152602401610d67565b60405180606001604052805f80191681526020015f6001600160401b031681526020016138d260405180604001604052805f81526020015f81525090565b905290565b5f8083601f8401126138e7575f80fd5b5081356001600160401b038111156138fd575f80fd5b6020830191508360208260051b8501011115613917575f80fd5b9250929050565b5f806020838503121561392f575f80fd5b82356001600160401b03811115613944575f80fd5b613950858286016138d7565b90969095509350505050565b5f608082019050825182526001600160401b0360208401511660208301526040830151611c0f604084018280518252602090810151910152565b5f606082840312156139a6575f80fd5b50919050565b5f8083601f8401126139bc575f80fd5b5081356001600160401b038111156139d2575f80fd5b602083019150836020828501011115613917575f80fd5b6001600160a01b0381168114611ada575f80fd5b8035613a08816139e9565b919050565b5f805f805f805f60e0888a031215613a23575f80fd5b613a2d8989613996565b96506060880135955060808801356001600160401b0380821115613a4f575f80fd5b613a5b8b838c016139ac565b909750955060a08a01359150613a70826139e9565b90935060c08901359080821115613a85575f80fd5b50613a928a828b016139ac565b989b979a50959850939692959293505050565b80358015158114613a08575f80fd5b5f60208284031215613ac4575f80fd5b613acd82613aa5565b9392505050565b5f60208284031215613ae4575f80fd5b5035919050565b5f8060408385031215613afc575f80fd5b50508035926020909101359150565b803563ffffffff81168114613a08575f80fd5b5f60208284031215613b2e575f80fd5b613acd82613b0b565b5f8060408385031215613b48575f80fd5b613b5183613b0b565b946020939093013593505050565b5f805f60608486031215613b71575f80fd5b8335613b7c816139e9565b92506020840135613b8c816139e9565b929592945050506040919091013590565b5f805f60608486031215613baf575f80fd5b833592506020840135613b8c816139e9565b5f8060408385031215613bd2575f80fd5b8235613b51816139e9565b803561ffff81168114613a08575f80fd5b5f60208284031215613bfe575f80fd5b613acd82613bdd565b5f8060408385031215613c18575f80fd5b613c2183613b0b565b9150613c2f60208401613bdd565b90509250929050565b5f5b83811015613c52578181015183820152602001613c3a565b50505f910152565b5f8151808452613c71816020860160208601613c38565b601f01601f19169290920160200192915050565b602081525f613acd6020830184613c5a565b5f805f8060a08587031215613caa575f80fd5b613cb48686613996565b935060608501356001600160401b03811115613cce575f80fd5b613cda878288016139ac565b9094509250506080850135613cee816139e9565b939692955090935050565b803560ff81168114613a08575f80fd5b5f60208284031215613d19575f80fd5b613acd82613cf9565b5f60208284031215613d32575f80fd5b8135613acd816139e9565b5f805f8060608587031215613d50575f80fd5b613d5985613b0b565b9350613d6760208601613bdd565b925060408501356001600160401b03811115613d81575f80fd5b613d8d878288016139ac565b95989497509550505050565b5f8060408385031215613daa575f80fd5b82356001600160401b03811115613dbf575f80fd5b83016101408186031215613b51575f80fd5b5f805f60608486031215613de3575f80fd5b8335613dee816139e9565b95602085013595506040909401359392505050565b5f8060408385031215613e14575f80fd5b613e1d83613b0b565b9150613c2f60208401613aa5565b602080825282518282018190525f919060409081850190868401855b82811015613e7457613e6484835180518252602090810151910152565b9284019290850190600101613e47565b5091979650505050505050565b5f60608284031215613e91575f80fd5b613acd8383613996565b634e487b7160e01b5f52601160045260245ffd5b5f65ffffffffffff808316818103613ec957613ec9613e9b565b6001019392505050565b634e487b7160e01b5f52604160045260245ffd5b600181811c90821680613efb57607f821691505b6020821081036139a657634e487b7160e01b5f52602260045260245ffd5b604051606081016001600160401b0381118282101715613f3b57613f3b613ed3565b60405290565b60405161014081016001600160401b0381118282101715613f3b57613f3b613ed3565b604051601f8201601f191681016001600160401b0381118282101715613f8c57613f8c613ed3565b604052919050565b5f6001600160401b03821115613fac57613fac613ed3565b5060051b60200190565b5f82601f830112613fc5575f80fd5b81356001600160401b03811115613fde57613fde613ed3565b613ff1601f8201601f1916602001613f64565b818152846020838601011115614005575f80fd5b816020850160208301375f918101602001919091529392505050565b5f61403361402e84613f94565b613f64565b80848252602080830192508560051b850136811115614050575f80fd5b855b818110156140db5780356001600160401b0380821115614070575f80fd5b818901915060608236031215614084575f80fd5b61408c613f19565b61409583613b0b565b81526140a2868401613bdd565b86820152604080840135838111156140b8575f80fd5b6140c436828701613fb6565b918301919091525087525050938201938201614052565b50919695505050505050565b5f80858511156140f5575f80fd5b83861115614101575f80fd5b5050820193919092039150565b5f845161411f818460208901613c38565b8201838582375f930192835250909392505050565b60208152816020820152818360408301375f818301604090810191909152601f909201601f19160101919050565b5f808335601e19843603018112614177575f80fd5b8301803591506001600160401b03821115614190575f80fd5b6020019150600581901b3603821315613917575f80fd5b634e487b7160e01b5f52603260045260245ffd5b5f823561013e198336030181126141d0575f80fd5b9190910192915050565b5f82601f8301126141e9575f80fd5b813560206141f961402e83613f94565b8083825260208201915060208460051b87010193508684111561421a575f80fd5b602086015b84811015614236578035835291830191830161421f565b509695505050505050565b5f6101408236031215614252575f80fd5b61425a613f41565b614263836139fd565b81526020830135602082015260408301356040820152614285606084016139fd565b606082015261429660808401613cf9565b608082015260a083013560a082015260c083013560c082015260e083013560e0820152610100808401356001600160401b03808211156142d4575f80fd5b6142e0368388016141da565b838501526101209250828601359150808211156142fb575f80fd5b5061430836828701613fb6565b918301919091525092915050565b5f808335601e1984360301811261432b575f80fd5b8301803591506001600160401b03821115614344575f80fd5b602001915036819003821315613917575f80fd5b5f6001820161436957614369613e9b565b5060010190565b5f60a08201878352602060018060a01b038089168286015260a0604086015282885180855260c087019150838a0194505f5b818110156143be578551835294840194918401916001016143a2565b5050858103606087015287518082529083019350828801905f5b818110156143f65782518416865294840194918401916001016143d8565b5050505084151560808501525090509695505050505050565b8082028115828204841417610d1a57610d1a613e9b565b80820180821115610d1a57610d1a613e9b565b6040815263ffffffff8351166040820152602083015160608201525f604084015160a0608084015261446e60e0840182613c5a565b90506060850151603f198483030160a085015261448b8282613c5a565b60809690960151151560c08501525050506001600160a01b039190911660209091015290565b5f604082840312156144c1575f80fd5b604051604081018181106001600160401b03821117156144e3576144e3613ed3565b604052825181526020928301519281019290925250919050565b5f6080828403121561450d575f80fd5b614515613f19565b8251815260208301516001600160401b0381168114614532575f80fd5b602082015261454484604085016144b1565b60408201529392505050565b5f8060408385031215614561575f80fd5b82359150613c2f60208401613aa5565b601f821115610fbe57805f5260205f20601f840160051c810160208510156145965750805b601f840160051c820191505b81811015611863575f81556001016145a2565b81516001600160401b038111156145ce576145ce613ed3565b6145e2816145dc8454613ee7565b84614571565b602080601f831160018114614615575f84156145fe5750858301515b5f19600386901b1c1916600185901b17855561243f565b5f85815260208120601f198616915b8281101561464357888601518255948401946001909101908401614624565b508582101561466057878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b5f60208083018184528085518083526040925060408601915060408160051b8701018488015f5b838110156146eb57888303603f190185528151805163ffffffff1684528781015161ffff168885015286015160608785018190526146d781860183613c5a565b968901969450505090860190600101614697565b509098975050505050505050565b81810381811115610d1a57610d1a613e9b565b5f8261472657634e487b7160e01b5f52601260045260245ffd5b500490565b5f6020828403121561473b575f80fd5b8151613acd816139e9565b6001600160601b03828116828216039080821115611c0f57611c0f613e9b565b5f60408284031215614776575f80fd5b613acd83836144b1565b5f8751614791818460208c01613c38565b60f89790971b6001600160f81b0319169190960190815260f094851b6001600160f01b0319908116600183015293851b841660038201529190931b909116600582015260e09190911b6001600160e01b0319166007820152600b0192915050565b5f8751614803818460208c01613c38565b87151560f81b90830190815260c087901b6001600160c01b031916600182015260f086901b6001600160f01b0319166009820152606085901b6001600160601b031916600b820152835161485e81601f840160208801613c38565b01601f0198975050505050505050565b61ffff818116838216019080821115611c0f57611c0f613e9b565b5f865161489a818460208b01613c38565b6001600160f81b031960f888811b82169285019283526001600160f01b031960f089901b16600184015286901b16600382015283516148e0816004840160208801613c38565b0160040197965050505050505056fea26469706673582212209a014b20aacdac2890236105c6d89246e72b61e08090dabac92398cd12cb2f3c64736f6c63430008180033
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 34 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
Loading...
Loading
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.