Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xbBF85df4007b922121a4D590029499Df66A29033
Balance 0 ETH
Nonce 1
Code Size 9196 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

9196 bytes
0x6080604052600436106101815760003560e01c8063ace6628c116100d1578063de250ace1161008a578063f4734b0c11610064578063f4734b0c146104ac578063f973a209146104cc578063ffa1ad74146104e1578063ffd4ba401461051257600080fd5b8063de250ace1461044c578063f2fde38b1461046c578063f3fef3a31461048c57600080fd5b8063ace6628c14610399578063c2585411146103b9578063c3388830146103cc578063d2ccacf3146103ec578063d547741f1461040c578063d84a9c991461042c57600080fd5b80636fe7266e1161013e57806384b0196e1161011857806384b0196e146102d85780638bb9c5bf146103005780638da5cb5b14610320578063a3f4df7e1461035257600080fd5b80636fe7266e14610276578063715018a61461029657806383fa2a7e146102ab57600080fd5b806307225b4d146101865780632346890e146101af5780632f2ff15d146101ef5780633456e014146102115780635e5571ac146102265780636c0f6c5214610246575b600080fd5b34801561019257600080fd5b5061019c60035481565b6040519081526020015b60405180910390f35b3480156101bb57600080fd5b506101df6101ca366004611b4c565b60076020526000908152604090205460ff1681565b60405190151581526020016101a6565b3480156101fb57600080fd5b5061020f61020a366004611b7c565b61053f565b005b34801561021d57600080fd5b5061019c61055d565b34801561023257600080fd5b5061020f610241366004611ba8565b610587565b34801561025257600080fd5b506101df610261366004611b4c565b60086020526000908152604090205460ff1681565b34801561028257600080fd5b5061020f610291366004611bf1565b6106ac565b3480156102a257600080fd5b5061020f6106fe565b3480156102b757600080fd5b506102cb6102c6366004611d07565b610712565b6040516101a69190611d49565b3480156102e457600080fd5b506102ed6107db565b6040516101a69796959493929190611dd5565b34801561030c57600080fd5b5061020f61031b366004611b4c565b610864565b34801561032c57600080fd5b506000546001600160a01b03165b6040516001600160a01b0390911681526020016101a6565b34801561035e57600080fd5b5061038c6040518060400160405280600e81526020016d084e4d2c8ceca8ae8d0a8dea0e8d60931b81525081565b6040516101a69190611e6b565b3480156103a557600080fd5b506101df6103b4366004611ec0565b610879565b61020f6103c7366004611f1a565b6108d9565b3480156103d857600080fd5b506101df6103e7366004611b7c565b610b04565b3480156103f857600080fd5b506101df610407366004611ec0565b610b42565b34801561041857600080fd5b5061020f610427366004611b7c565b610b66565b34801561043857600080fd5b5061020f610447366004611f75565b610b78565b34801561045857600080fd5b5061019c610467366004611b4c565b610d5f565b34801561047857600080fd5b5061020f61048736600461200f565b610d81565b34801561049857600080fd5b5061020f6104a736600461202a565b610d92565b3480156104b857600080fd5b5060095461033a906001600160a01b031681565b3480156104d857600080fd5b5061019c610e30565b3480156104ed57600080fd5b5061038c604051806040016040528060058152602001640322e302e360dc1b81525081565b34801561051e57600080fd5b5061053261052d366004611b4c565b610e58565b6040516101a69190612054565b610547610ebb565b6105518282610f15565b610559610fae565b5050565b604051806040016040528060058152602001642820aca2a960d91b81525061058490612095565b81565b61058f610ff9565b6105bf604051806040016040528060058152602001642820aca2a960d91b8152506105b990612095565b33610b04565b6105e45760405162461bcd60e51b81526004016105db906120bc565b60405180910390fd5b60008181526008602052604090205460ff16156106285760405162461bcd60e51b8152602060048201526002602482015261503160f01b60448201526064016105db565b6000818152600860205260409020805460ff1916600117905561064b8383611052565b610653610fae565b604080516001600160a01b0385168152602081018490529081018290527f1b174056799bea141540e324bb093eb297a02b564c15e75840a30cf0d0f483779060600160405180910390a16106a76001600455565b505050565b6106b4610ebb565b60005b81518110156106f5576106e3838383815181106106d6576106d66120d9565b6020026020010151610f15565b806106ed81612105565b9150506106b7565b50610559610fae565b610706610ebb565b61071060006110b5565b565b6060818067ffffffffffffffff81111561072e5761072e611bdb565b604051908082528060200260200182016040528015610757578160200160208202803683370190505b50915060005b818110156107d2576008600086868481811061077b5761077b6120d9565b90506020020135815260200190815260200160002060009054906101000a900460ff168382815181106107b0576107b06120d9565b91151560209283029190910190910152806107ca81612105565b91505061075d565b50505b92915050565b60006060808280808361080f7f427269646765457468546f50746800000000000000000000000000000000000e6005611105565b61083a7f322e302e300000000000000000000000000000000000000000000000000000056006611105565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b61086e81336111a9565b610876610fae565b50565b60006108bb8484848080601f01602080910402602001604051908101604052809392919081815260200183838082843760009201919091525061122f92505050565b6001600160a01b0316856001600160a01b0316149050949350505050565b6108e1610ff9565b60006108f0602085018561200f565b90506000610904604086016020870161200f565b905060408501356060860135608087013560a08801356001600160a01b03861633146109575760405162461bcd60e51b8152602060048201526002602482015261533160f01b60448201526064016105db565b6001600160a01b0385166109925760405162461bcd60e51b8152602060048201526002602482015261299960f11b60448201526064016105db565b4281116109c65760405162461bcd60e51b8152602060048201526002602482015261533360f01b60448201526064016105db565b600084116109fb5760405162461bcd60e51b815260206004820152600260248201526114cd60f21b60448201526064016105db565b6000610a0b878787878787611253565b60008181526007602052604090205490915060ff1615610a525760405162461bcd60e51b8152602060048201526002602482015261533560f01b60448201526064016105db565b610a5d818a8a6112d2565b610a8e5760405162461bcd60e51b8152602060048201526002602482015261299b60f11b60448201526064016105db565b6000818152600760205260409020805460ff19166001179055610ab285858561135e565b610aba610fae565b7f4d0d16336b0b189d3191cef8530b7f22e116fe90d5747703c2b035605166c49a8a82604051610aeb92919061211e565b60405180910390a1505050505050506106a76001600455565b600080546001600160a01b03166001600160a01b0316826001600160a01b031603610b31575060016107d5565b610b3b838361144e565b9392505050565b600080610b4e85611466565b9050610b5c86828686610879565b9695505050505050565b610b6e610ebb565b61055182826111a9565b610b80610ff9565b610baa604051806040016040528060058152602001642820aca2a960d91b8152506105b990612095565b610bc65760405162461bcd60e51b81526004016105db906120bc565b8483148015610bd457508281145b610c065760405162461bcd60e51b815260206004820152600360248201526250533160e81b60448201526064016105db565b60005b85811015610d44576000878783818110610c2557610c256120d9565b9050602002016020810190610c3a919061200f565b90506000868684818110610c5057610c506120d9565b9050602002013590506000858585818110610c6d57610c6d6120d9565b60209081029290920135600081815260089093526040909220549192505060ff1615610cc15760405162461bcd60e51b815260206004820152600360248201526250533160e81b60448201526064016105db565b6000818152600860205260409020805460ff19166001179055610ce48383611052565b604080516001600160a01b0385168152602081018490529081018290527f1b174056799bea141540e324bb093eb297a02b564c15e75840a30cf0d0f483779060600160405180910390a15050508080610d3c90612105565b915050610c09565b50610d4d610fae565b610d576001600455565b505050505050565b6000600354821015610d7c57506000818152600260205260409020545b919050565b610d89610ebb565b61086e81611493565b610dbc604051806040016040528060058152602001642820aca2a960d91b8152506105b990612095565b610dd85760405162461bcd60e51b81526004016105db906120bc565b610de28282611509565b610dea610fae565b604080516001600160a01b0384168152602081018390527f884edad9ce6fa2440d8a54cc123490eb96d2768479d49ff9c7366125a9424364910160405180910390a15050565b604051602001610e3f90612180565b6040516020818303038152906040528051906020012081565b60008181526001602052604090206060906107d590611542565b6000602083511015610e8e57610e878361154f565b90506107d5565b81610e9984826122a4565b5060ff90506107d5565b90565b6000610b3b836001600160a01b03841661158d565b6000546001600160a01b031633146107105760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016105db565b6001600160a01b03811615801590610f4057506000828152600160205260409020610f409082610ea6565b610f745760405162461bcd60e51b81526020600482015260056024820152645f4752303160d81b60448201526064016105db565b6040516001600160a01b0382169083907f5a06360d65acf95e98445dc834f205063424c636e65418d928cdfabc33a9539990600090a35050565b43600260006001600354610fc29190612364565b81526020019081526020016000205410610fd857565b61071060038054600090815260026020526040902043905580546001019055565b60026004540361104b5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016105db565b6002600455565b6009546040516340c10f1960e01b81526001600160a01b03848116600483015260248201849052909116906340c10f19906044015b600060405180830381600087803b1580156110a157600080fd5b505af1158015610d57573d6000803e3d6000fd5b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b606060ff831461111857610e87836115dc565b8180546111249061222a565b80601f01602080910402602001604051908101604052809291908181526020018280546111509061222a565b801561119d5780601f106111725761010080835404028352916020019161119d565b820191906000526020600020905b81548152906001019060200180831161118057829003601f168201915b505050505090506107d5565b60008281526001602052604090206111c1908261161b565b6111f55760405162461bcd60e51b81526020600482015260056024820152645f5252303160d81b60448201526064016105db565b6040516001600160a01b0382169083907f76e6093c136cd7faa5a6d92b2b633f3b4595abd4a529b7a13917398355fea69490600090a35050565b600080600061123e8585611630565b9150915061124b81611675565b509392505050565b600060405160200161126490612180565b60408051808303601f190181528282528051602091820120818401526001600160a01b03998a168383015297909816606082015260808101959095525060a084019290925260c083015260e08083019190915283518083039091018152610100909101909252815191012090565b6000806112ff604051806040016040528060058152602001642820aca2a960d91b81525061052d90612095565b805190915060005b8181101561135457611334838281518110611324576113246120d9565b6020026020010151888888610b42565b156113425760019350611354565b8061134c81612105565b915050611307565b5050509392505050565b6009546001600160a01b0316806323b872dd33308561137d888a612377565b6113879190612377565b6040516001600160e01b031960e086901b1681526001600160a01b0393841660048201529290911660248301526044820152606401600060405180830381600087803b1580156113d657600080fd5b505af11580156113ea573d6000803e3d6000fd5b5050604051630852cd8d60e31b8152600481018790526001600160a01b03841692506342966c689150602401600060405180830381600087803b15801561143057600080fd5b505af1158015611444573d6000803e3d6000fd5b5050505050505050565b6000828152600160205260408120610b3b90836117bf565b60006107d56114736117e1565b8360405161190160f01b8152600281019290925260228201526042902090565b61149b610ebb565b6001600160a01b0381166115005760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016105db565b610876816110b5565b60095460405163a9059cbb60e01b81526001600160a01b038481166004830152602482018490529091169063a9059cbb90604401611087565b60606000610b3b83611911565b600080829050601f8151111561157a578260405163305a27a960e01b81526004016105db9190611e6b565b805161158582612095565b179392505050565b60008181526001830160205260408120546115d4575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556107d5565b5060006107d5565b606060006115e98361196d565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b6000610b3b836001600160a01b038416611995565b60008082516041036116665760208301516040840151606085015160001a61165a87828585611a88565b9450945050505061166e565b506000905060025b9250929050565b60008160048111156116895761168961238a565b036116915750565b60018160048111156116a5576116a561238a565b036116f25760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e6174757265000000000000000060448201526064016105db565b60028160048111156117065761170661238a565b036117535760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e6774680060448201526064016105db565b60038160048111156117675761176761238a565b036108765760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b60648201526084016105db565b6001600160a01b03811660009081526001830160205260408120541515610b3b565b6000306001600160a01b037f000000000000000000000000bbf85df4007b922121a4d590029499df66a290331614801561183a57507f000000000000000000000000000000000000000000000000000000000000000146145b1561186457507f84a64df07dd1904e924c30d891c85a9e9a867a196d1b762466ebabf4e8ecb5fc90565b61190c604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f135e28eff983bec7ff85f09994a8d7b72b7a472d1c203fd5e9214aad9ee2772f918101919091527fb4bcb154e38601c389396fa918314da42d4626f13ef6d0ceb07e5f5d26b2fbc360608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b905090565b60608160000180548060200260200160405190810160405280929190818152602001828054801561196157602002820191906000526020600020905b81548152602001906001019080831161194d575b50505050509050919050565b600060ff8216601f8111156107d557604051632cd44ac360e21b815260040160405180910390fd5b60008181526001830160205260408120548015611a7e5760006119b9600183612364565b85549091506000906119cd90600190612364565b9050818114611a325760008660000182815481106119ed576119ed6120d9565b9060005260206000200154905080876000018481548110611a1057611a106120d9565b6000918252602080832090910192909255918252600188019052604090208390555b8554869080611a4357611a436123a0565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506107d5565b60009150506107d5565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0831115611abf5750600090506003611b43565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015611b13573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116611b3c57600060019250925050611b43565b9150600090505b94509492505050565b600060208284031215611b5e57600080fd5b5035919050565b80356001600160a01b0381168114610d7c57600080fd5b60008060408385031215611b8f57600080fd5b82359150611b9f60208401611b65565b90509250929050565b600080600060608486031215611bbd57600080fd5b611bc684611b65565b95602085013595506040909401359392505050565b634e487b7160e01b600052604160045260246000fd5b60008060408385031215611c0457600080fd5b8235915060208084013567ffffffffffffffff80821115611c2457600080fd5b818601915086601f830112611c3857600080fd5b813581811115611c4a57611c4a611bdb565b8060051b604051601f19603f83011681018181108582111715611c6f57611c6f611bdb565b604052918252848201925083810185019189831115611c8d57600080fd5b938501935b82851015611cb257611ca385611b65565b84529385019392850192611c92565b8096505050505050509250929050565b60008083601f840112611cd457600080fd5b50813567ffffffffffffffff811115611cec57600080fd5b6020830191508360208260051b850101111561166e57600080fd5b60008060208385031215611d1a57600080fd5b823567ffffffffffffffff811115611d3157600080fd5b611d3d85828601611cc2565b90969095509350505050565b6020808252825182820181905260009190848201906040850190845b81811015611d83578351151583529284019291840191600101611d65565b50909695505050505050565b6000815180845260005b81811015611db557602081850181015186830182015201611d99565b506000602082860101526020601f19601f83011685010191505092915050565b60ff60f81b881681526000602060e081840152611df560e084018a611d8f565b8381036040850152611e07818a611d8f565b606085018990526001600160a01b038816608086015260a0850187905284810360c0860152855180825283870192509083019060005b81811015611e5957835183529284019291840191600101611e3d565b50909c9b505050505050505050505050565b602081526000610b3b6020830184611d8f565b60008083601f840112611e9057600080fd5b50813567ffffffffffffffff811115611ea857600080fd5b60208301915083602082850101111561166e57600080fd5b60008060008060608587031215611ed657600080fd5b611edf85611b65565b935060208501359250604085013567ffffffffffffffff811115611f0257600080fd5b611f0e87828801611e7e565b95989497509550505050565b600080600083850360e0811215611f3057600080fd5b60c0811215611f3e57600080fd5b5083925060c084013567ffffffffffffffff811115611f5c57600080fd5b611f6886828701611e7e565b9497909650939450505050565b60008060008060008060608789031215611f8e57600080fd5b863567ffffffffffffffff80821115611fa657600080fd5b611fb28a838b01611cc2565b90985096506020890135915080821115611fcb57600080fd5b611fd78a838b01611cc2565b90965094506040890135915080821115611ff057600080fd5b50611ffd89828a01611cc2565b979a9699509497509295939492505050565b60006020828403121561202157600080fd5b610b3b82611b65565b6000806040838503121561203d57600080fd5b61204683611b65565b946020939093013593505050565b6020808252825182820181905260009190848201906040850190845b81811015611d835783516001600160a01b031683529284019291840191600101612070565b805160208083015191908110156120b6576000198160200360031b1b821691505b50919050565b6020808252600390820152624f503160e81b604082015260600190565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b600060018201612117576121176120ef565b5060010190565b60e081016001600160a01b038061213486611b65565b1683528061214460208701611b65565b1660208401525060408401356040830152606084013560608301526080840135608083015260a084013560a08301528260c08301529392505050565b6509ee4c8cae4560d31b81526c1859191c995cdcc8199c9bdb4b609a1b60068201526a1859191c995cdcc81d1bcb60aa1b60138201526e1d5a5b9d0c8d4d88185b5bdd5b9d0b608a1b601e8201526f1d5a5b9d0c8d4d8819d85cd7d999594b60821b602d820152721d5a5b9d0c8d4d88189c9a5919d957d999594b606a1b603d8201526d75696e743235362065787069726560901b6050820152602960f81b605e820152605f0190565b600181811c9082168061223e57607f821691505b6020821081036120b657634e487b7160e01b600052602260045260246000fd5b601f8211156106a757600081815260208120601f850160051c810160208610156122855750805b601f850160051c820191505b81811015610d5757828155600101612291565b815167ffffffffffffffff8111156122be576122be611bdb565b6122d2816122cc845461222a565b8461225e565b602080601f83116001811461230757600084156122ef5750858301515b600019600386901b1c1916600185901b178555610d57565b600085815260208120601f198616915b8281101561233657888601518255948401946001909101908401612317565b50858210156123545787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b818103818111156107d5576107d56120ef565b808201808211156107d5576107d56120ef565b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052603160045260246000fdfea26469706673582212205f464e5de54f78a6b1d036cc7f0d4226e23915dbffa42fe264985ab053f2df5964736f6c63430008120033

Verified Source Code Full Match

Compiler: v0.8.18+commit.87f61d96 EVM: london Optimization: Yes (200 runs)
Ownable.sol 83 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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);
    }
}
IERC5267.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)

pragma solidity ^0.8.0;

interface IERC5267 {
    /**
     * @dev MAY be emitted to signal that the domain could have changed.
     */
    event EIP712DomainChanged();

    /**
     * @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
     * signature.
     */
    function eip712Domain()
        external
        view
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        );
}
ReentrancyGuard.sol 77 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}
Context.sol 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @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;
    }
}
ECDSA.sol 217 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, "\x19Ethereum Signed Message:\n32")
            mstore(0x1c, hash)
            message := keccak256(0x00, 0x3c)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
        /// @solidity memory-safe-assembly
        assembly {
            let ptr := mload(0x40)
            mstore(ptr, "\x19\x01")
            mstore(add(ptr, 0x02), domainSeparator)
            mstore(add(ptr, 0x22), structHash)
            data := keccak256(ptr, 0x42)
        }
    }

    /**
     * @dev Returns an Ethereum Signed Data with intended validator, created from a
     * `validator` and `data` according to the version 0 of EIP-191.
     *
     * See {recover}.
     */
    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x00", validator, data));
    }
}
EIP712.sol 142 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.8;

import "./ECDSA.sol";
import "../ShortStrings.sol";
import "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * _Available since v3.4._
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant _TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {EIP-5267}.
     *
     * _Available since v4.9._
     */
    function eip712Domain()
        public
        view
        virtual
        override
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _name.toStringWithFallback(_nameFallback),
            _version.toStringWithFallback(_versionFallback),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }
}
Math.sol 339 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                // Solidity will revert if denominator == 0, unlike the div opcode on its own.
                // The surrounding unchecked block does not change this fact.
                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1, "Math: mulDiv overflow");

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10 ** 64) {
                value /= 10 ** 64;
                result += 64;
            }
            if (value >= 10 ** 32) {
                value /= 10 ** 32;
                result += 32;
            }
            if (value >= 10 ** 16) {
                value /= 10 ** 16;
                result += 16;
            }
            if (value >= 10 ** 8) {
                value /= 10 ** 8;
                result += 8;
            }
            if (value >= 10 ** 4) {
                value /= 10 ** 4;
                result += 4;
            }
            if (value >= 10 ** 2) {
                value /= 10 ** 2;
                result += 2;
            }
            if (value >= 10 ** 1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
        }
    }
}
SignedMath.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard signed math utilities missing in the Solidity language.
 */
library SignedMath {
    /**
     * @dev Returns the largest of two signed numbers.
     */
    function max(int256 a, int256 b) internal pure returns (int256) {
        return a > b ? a : b;
    }

    /**
     * @dev Returns the smallest of two signed numbers.
     */
    function min(int256 a, int256 b) internal pure returns (int256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two signed numbers without overflow.
     * The result is rounded towards zero.
     */
    function average(int256 a, int256 b) internal pure returns (int256) {
        // Formula from the book "Hacker's Delight"
        int256 x = (a & b) + ((a ^ b) >> 1);
        return x + (int256(uint256(x) >> 255) & (a ^ b));
    }

    /**
     * @dev Returns the absolute unsigned value of a signed value.
     */
    function abs(int256 n) internal pure returns (uint256) {
        unchecked {
            // must be unchecked in order to support `n = type(int256).min`
            return uint256(n >= 0 ? n : -n);
        }
    }
}
ShortStrings.sol 122 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)

pragma solidity ^0.8.8;

import "./StorageSlot.sol";

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        /// @solidity memory-safe-assembly
        assembly {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(_FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}
StorageSlot.sol 138 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for reading and writing primitive types to specific storage slots.
 *
 * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
 * This library helps with reading and writing to such slots without the need for inline assembly.
 *
 * The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
 *
 * Example usage to set ERC1967 implementation slot:
 * ```solidity
 * contract ERC1967 {
 *     bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
 *
 *     function _getImplementation() internal view returns (address) {
 *         return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
 *     }
 *
 *     function _setImplementation(address newImplementation) internal {
 *         require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
 *         StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
 *     }
 * }
 * ```
 *
 * _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
 * _Available since v4.9 for `string`, `bytes`._
 */
library StorageSlot {
    struct AddressSlot {
        address value;
    }

    struct BooleanSlot {
        bool value;
    }

    struct Bytes32Slot {
        bytes32 value;
    }

    struct Uint256Slot {
        uint256 value;
    }

    struct StringSlot {
        string value;
    }

    struct BytesSlot {
        bytes value;
    }

    /**
     * @dev Returns an `AddressSlot` with member `value` located at `slot`.
     */
    function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BooleanSlot` with member `value` located at `slot`.
     */
    function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
     */
    function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `Uint256Slot` with member `value` located at `slot`.
     */
    function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` with member `value` located at `slot`.
     */
    function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `StringSlot` representation of the string storage pointer `store`.
     */
    function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` with member `value` located at `slot`.
     */
    function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := slot
        }
    }

    /**
     * @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
     */
    function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
        /// @solidity memory-safe-assembly
        assembly {
            r.slot := store.slot
        }
    }
}
Strings.sol 85 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";
import "./math/SignedMath.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `int256` to its ASCII `string` decimal representation.
     */
    function toString(int256 value) internal pure returns (string memory) {
        return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }

    /**
     * @dev Returns true if the two strings are equal.
     */
    function equal(string memory a, string memory b) internal pure returns (bool) {
        return keccak256(bytes(a)) == keccak256(bytes(b));
    }
}
EnumerableSet.sol 378 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}
IBridgeERC20.sol 9 lines
// SPDX-License-Identifier: Apache-2.0
pragma solidity =0.8.18;

interface IBridgeERC20 {
    function mint(address recipient, uint256 amount) external;
    function burn(uint256 amount) external;
    function transferFrom(address sender, address recipient, uint256 amount) external;
    function transfer(address recipient, uint256 amount) external;
}
VerifySignature.sol 20 lines
// SPDX-License-Identifier: MIT
pragma solidity =0.8.18;

import {EIP712, ECDSA} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";

contract VerifySignature is EIP712 {
    constructor(string memory name, string memory version) EIP712(name, version) {}

    function verifyEIP712(
        address signer,
        bytes32 structHash,
        bytes calldata signature
    ) public view returns (bool result) {
        bytes32 digest = _hashTypedDataV4(structHash);
        result = _verifyEIP712(signer, digest, signature);
    }
    function _verifyEIP712(address signer, bytes32 digest, bytes calldata signature) public pure returns (bool result) {
        result = signer == ECDSA.recover(digest, signature);
    }
}
BridgeEthToPthV2.sol 11 lines
// SPDX-License-Identifier: MIT
pragma solidity =0.8.18;

import {ERC20BridgeV2} from "./v2/ERC20BridgeV2.sol";

contract BridgeEthToPthV2 is ERC20BridgeV2 {
    string public constant NAME = "BridgeEthToPth";
    string public constant VERSION = "2.0.0";

    constructor(address _bridgeToken, address[] memory payers) ERC20BridgeV2(_bridgeToken, NAME, VERSION, payers) {}
}
BaseBridgeV2.sol 134 lines
// SPDX-License-Identifier: MIT
pragma solidity =0.8.18;

import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {BaseRoleSystem} from "../../../utils/BaseRoleSystem.sol";
import {VerifySignature} from "../bridge/signature/VerifySignature.sol";
contract BaseBridgeV2 is BaseRoleSystem, ReentrancyGuard, VerifySignature {
    struct Order {
        address from;
        address to;
        uint256 amount;
        uint256 gas_fee;
        uint256 bridge_fee;
        uint256 expire;
    }

    bytes32 public constant ORDER_TYPEHASH =
        keccak256(
            abi.encodePacked(
                "Order(",
                "address from,",
                "address to,",
                "uint256 amount,",
                "uint256 gas_fee,",
                "uint256 bridge_fee,",
                "uint256 expire",
                ")"
            )
        );

    bytes32 public constant PAYER = bytes32(bytes("PAYER"));

    mapping(bytes32 => bool) public receiptSwap;
    mapping(bytes32 => bool) public receiptPay;

    event Swap(Order order, bytes32 orderHash);
    event Pay(address to, uint256 amount, bytes32 txHash);
    event Withdraw(address to, uint256 amount);

    modifier onlyPayer() {
        require(isRole(PAYER, _msgSender()), "OP1");
        _;
    }

    constructor(string memory name, string memory version, address[] memory payers) VerifySignature(name, version) {
        for (uint256 i = 0; i < payers.length; i++) {
            _grantRole(PAYER, payers[i]);
        }
    }

    function swap(Order calldata order, bytes calldata signature) external payable nonReentrant {
        address from = order.from;
        address to = order.to;
        uint256 amount = order.amount;
        uint256 gas_fee = order.gas_fee;
        uint256 bridge_fee = order.bridge_fee;
        uint256 expire = order.expire;
        require(from == msg.sender, "S1");
        require(to != address(0), "S2");
        require(expire > block.timestamp, "S3");
        require(amount > 0, "S4");
        bytes32 orderHash = _orderHash(from, to, amount, gas_fee, bridge_fee, expire);
        require(!receiptSwap[orderHash], "S5");
        require(_verifySigner(orderHash, signature), "S6");
        receiptSwap[orderHash] = true;
        _swap(amount, gas_fee, bridge_fee);
        _increaseBlock();
        emit Swap(order, orderHash);
    }
    function pay(address to, uint256 amount, bytes32 txHash) public nonReentrant onlyPayer {
        require(!receiptPay[txHash], "P1");
        receiptPay[txHash] = true;
        _pay(to, amount);
        _increaseBlock();
        emit Pay(to, amount, txHash);
    }
    function pays(
        address[] calldata tos,
        uint256[] calldata amounts,
        bytes32[] calldata txHashes
    ) external nonReentrant onlyPayer {
        require(tos.length == amounts.length && amounts.length == txHashes.length, "PS1");
        for (uint256 i = 0; i < tos.length; i++) {
            address to = tos[i];
            uint256 amount = amounts[i];
            bytes32 txHash = txHashes[i];
            require(!receiptPay[txHash], "PS1");
            receiptPay[txHash] = true;
            _pay(to, amount);
            emit Pay(to, amount, txHash);
        }
        _increaseBlock();
    }
    function withdraw(address to, uint256 amount) external onlyPayer {
        _withdraw(to, amount);
        _increaseBlock();
        emit Withdraw(to, amount);
    }

    function receiptPays(bytes32[] calldata txHashes) external view returns (bool[] memory pays) {
        uint256 length = txHashes.length;
        pays = new bool[](length);
        for (uint256 i = 0; i < length; i++) {
            pays[i] = receiptPay[txHashes[i]];
        }
        return pays;
    }

    function _swap(uint256 amount, uint256 gas_fee, uint256 bridge_fee) internal virtual {}

    function _pay(address to, uint256 amount) internal virtual {}
    function _withdraw(address to, uint256 amount) internal virtual {}

    function _verifySigner(bytes32 orderHash, bytes calldata signature) private view returns (bool isVerified) {
        address[] memory signers = roleArray(PAYER);
        uint256 sLen = signers.length;
        for (uint256 i = 0; i < sLen; i++) {
            if (verifyEIP712(signers[i], orderHash, signature)) {
                isVerified = true;
                break;
            }
        }
    }
    function _orderHash(
        address from,
        address to,
        uint256 amount,
        uint256 gas_fee,
        uint256 bridge_fee,
        uint256 expire
    ) internal pure returns (bytes32) {
        return keccak256(abi.encode(ORDER_TYPEHASH, from, to, amount, gas_fee, bridge_fee, expire));
    }
}
ERC20BridgeV2.sol 30 lines
// SPDX-License-Identifier: MIT
pragma solidity =0.8.18;

import {IBridgeERC20} from "../bridge/IBridgeERC20.sol";
import {BaseBridgeV2} from "./BaseBridgeV2.sol";
contract ERC20BridgeV2 is BaseBridgeV2 {
    address public bridgeToken;
    constructor(
        address _bridgeToken,
        string memory name,
        string memory version,
        address[] memory payers
    ) BaseBridgeV2(name, version, payers) {
        bridgeToken = _bridgeToken;
    }

    function _swap(uint256 amount, uint256 gas_fee, uint256 bridge_fee) internal virtual override {
        IBridgeERC20 token = IBridgeERC20(bridgeToken);
        token.transferFrom(_msgSender(), address(this), amount + gas_fee + bridge_fee);
        token.burn(amount);
    }

    function _pay(address to, uint256 amount) internal virtual override {
        IBridgeERC20(bridgeToken).mint(to, amount);
    }

    function _withdraw(address to, uint256 amount) internal virtual override {
        IBridgeERC20(bridgeToken).transfer(to, amount);
    }
}
BaseRoleSystem.sol 42 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {AccessRole} from "./role/AccessRole.sol";
import {BlockRecordLite} from "./block/BlockRecordLite.sol";

abstract contract BaseRoleSystem is Ownable, AccessRole, BlockRecordLite {
    function grantRole(bytes32 role, address addr) external onlyOwner {
        _grantRole(role, addr);
        _increaseBlock();
    }

    function revokeRole(bytes32 role, address addr) external onlyOwner {
        _revokeRole(role, addr);
        _increaseBlock();
    }

    function renounceRole(bytes32 role) external {
        _revokeRole(role, _msgSender());
        _increaseBlock();
    }
    function grantRoleArray(bytes32 role, address[] memory addrs) public onlyOwner {
        for (uint256 i = 0; i < addrs.length; i++) {
            _grantRole(role, addrs[i]);
        }
        _increaseBlock();
    }

    function transferOwnership(address newOwner) public virtual override onlyOwner {
        super.transferOwnership(newOwner);
        _increaseBlock();
    }

    function isRole(bytes32 role, address addr) public view virtual override returns (bool result) {
        if (addr == owner()) {
            result = true;
        } else {
            result = super.isRole(role, addr);
        }
    }
}
BlockRecordLite.sol 29 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

abstract contract BlockRecordLite {
    //index => blockNumber
    mapping(uint256 => uint256) private _blockNumber;
    uint256 public blockCount;

    constructor() {
        _writeBlock();
    }

    function blockHistory(uint256 idx) external view returns (uint256 number) {
        if (idx < blockCount) {
            number = _blockNumber[idx];
        }
    }

    function _increaseBlock() internal {
        if (_blockNumber[blockCount - 1] >= block.number) return;
        _writeBlock();
    }
    function _writeBlock() private {
        unchecked {
            _blockNumber[blockCount] = block.number;
            ++blockCount;
        }
    }
}
AccessRole.sol 33 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import {Context} from "@openzeppelin/contracts/utils/Context.sol";
import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {IAccessRole} from "./IAccessRole.sol";

abstract contract AccessRole is Context, IAccessRole {
    using EnumerableSet for EnumerableSet.AddressSet;

    mapping(bytes32 => EnumerableSet.AddressSet) private _role;

    event GrantRole(bytes32 indexed role, address indexed addr);
    event RevokeRole(bytes32 indexed role, address indexed addr);

    function isRole(bytes32 role, address addr) public view virtual returns (bool result) {
        result = _role[role].contains(addr);
    }

    function roleArray(bytes32 role) public view returns (address[] memory addrs) {
        addrs = _role[role].values();
    }

    function _grantRole(bytes32 role, address addr) internal {
        require(addr != address(0) && _role[role].add(addr), "_GR01");
        emit GrantRole(role, addr);
    }

    function _revokeRole(bytes32 role, address addr) internal {
        require(_role[role].remove(addr), "_RR01");
        emit RevokeRole(role, addr);
    }
}
IAccessRole.sol 8 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

interface IAccessRole {
    function isRole(bytes32 role, address addr) external view returns (bool result);

    function roleArray(bytes32 role) external view returns (address[] memory addrs);
}

Read Contract

NAME 0xa3f4df7e → string
ORDER_TYPEHASH 0xf973a209 → bytes32
PAYER 0x3456e014 → bytes32
VERSION 0xffa1ad74 → string
_verifyEIP712 0xace6628c → bool
blockCount 0x07225b4d → uint256
blockHistory 0xde250ace → uint256
bridgeToken 0xf4734b0c → address
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
isRole 0xc3388830 → bool
owner 0x8da5cb5b → address
receiptPay 0x6c0f6c52 → bool
receiptPays 0x83fa2a7e → bool[]
receiptSwap 0x2346890e → bool
roleArray 0xffd4ba40 → address[]
verifyEIP712 0xd2ccacf3 → bool

Write Contract 10 functions

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

grantRole 0x2f2ff15d
bytes32 role
address addr
grantRoleArray 0x6fe7266e
bytes32 role
address[] addrs
pay 0x5e5571ac
address to
uint256 amount
bytes32 txHash
pays 0xd84a9c99
address[] tos
uint256[] amounts
bytes32[] txHashes
renounceOwnership 0x715018a6
No parameters
renounceRole 0x8bb9c5bf
bytes32 role
revokeRole 0xd547741f
bytes32 role
address addr
swap 0xd52126e2
tuple order
bytes signature
transferOwnership 0xf2fde38b
address newOwner
withdraw 0xf3fef3a3
address to
uint256 amount

Recent Transactions

No transactions found for this address