Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x282b71A653e255cBe0D4896F965835c41F1Ee5c8
Balance 0 ETH
Nonce 4
Code Size 19335 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

19335 bytes
0x608060405234801561000f575f80fd5b5060043610610086575f3560e01c80636521d89e116100595780636521d89e146101265780637f7c47461461015657806396347c2514610174578063e7bbb8711461019257610086565b806318b02b371461008a5780632dd15992146100a857806352dfe571146100d8578063631c2bb814610108575b5f80fd5b6100926101c2565b60405161009f919061096d565b60405180910390f35b6100c260048036038101906100bd91906109c8565b61024c565b6040516100cf9190610a02565b60405180910390f35b6100f260048036038101906100ed91906109c8565b6102b1565b6040516100ff9190610a02565b60405180910390f35b610110610634565b60405161011d9190610a8b565b60405180910390f35b610140600480360381019061013b91906109c8565b61066d565b60405161014d9190610a02565b60405180910390f35b61015e61069d565b60405161016b9190610a8b565b60405180910390f35b61017c6106d6565b6040516101899190610ac3565b60405180910390f35b6101ac60048036038101906101a79190610b06565b6106e1565b6040516101b99190610a02565b60405180910390f35b60605f80548060200260200160405190810160405280929190818152602001828054801561024257602002820191905f5260205f20905b815f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190600101908083116101f9575b5050505050905090565b5f60015f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff169050919050565b5f8073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603610320576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161031790610b7b565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff1660015f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16146103ea576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016103e190610c09565b60405180910390fd5b5f6103f48361071b565b90505f6040518060400160405280601281526020017f446963652047616d6520546f6b656e202d2000000000000000000000000000008152508260405160200161043f929190610c61565b60405160208183030381529060405290505f6040518060400160405280600281526020017f445400000000000000000000000000000000000000000000000000000000000081525083604051602001610499929190610c61565b60405160208183030381529060405290505f8583836040516104ba90610879565b6104c693929190610c84565b604051809103905ff0801580156104df573d5f803e3d5ffd5b5090505f8190505f81908060018154018082558091505060019003905f5260205f20015f9091909190916101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508060015f8973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055508673ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff167fd154813d008d49adb3bd84182d83afe0ef63d7a0b7459363696088762a043bd6868660405161061f929190610cc7565b60405180910390a38095505050505050919050565b6040518060400160405280600281526020017f445400000000000000000000000000000000000000000000000000000000000081525081565b6001602052805f5260405f205f915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b6040518060400160405280601281526020017f446963652047616d6520546f6b656e202d20000000000000000000000000000081525081565b5f8080549050905090565b5f81815481106106ef575f80fd5b905f5260205f20015f915054906101000a900473ffffffffffffffffffffffffffffffffffffffff1681565b60605f808373ffffffffffffffffffffffffffffffffffffffff166040516024016040516020818303038152906040527f95d89b41000000000000000000000000000000000000000000000000000000007bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050506040516107c69190610d40565b5f60405180830381855afa9150503d805f81146107fe576040519150601f19603f3d011682016040523d82523d5f602084013e610803565b606091505b509150915081801561081757506020815110155b1561083957808060200190518101906108309190610e74565b92505050610874565b6040518060400160405280600781526020017f554e4b4e4f574e00000000000000000000000000000000000000000000000000815250925050505b919050565b613c9680610ebc83390190565b5f81519050919050565b5f82825260208201905092915050565b5f819050602082019050919050565b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6108d8826108af565b9050919050565b6108e8816108ce565b82525050565b5f6108f983836108df565b60208301905092915050565b5f602082019050919050565b5f61091b82610886565b6109258185610890565b9350610930836108a0565b805f5b8381101561096057815161094788826108ee565b975061095283610905565b925050600181019050610933565b5085935050505092915050565b5f6020820190508181035f8301526109858184610911565b905092915050565b5f604051905090565b5f80fd5b5f80fd5b6109a7816108ce565b81146109b1575f80fd5b50565b5f813590506109c28161099e565b92915050565b5f602082840312156109dd576109dc610996565b5b5f6109ea848285016109b4565b91505092915050565b6109fc816108ce565b82525050565b5f602082019050610a155f8301846109f3565b92915050565b5f81519050919050565b5f82825260208201905092915050565b8281835e5f83830152505050565b5f601f19601f8301169050919050565b5f610a5d82610a1b565b610a678185610a25565b9350610a77818560208601610a35565b610a8081610a43565b840191505092915050565b5f6020820190508181035f830152610aa38184610a53565b905092915050565b5f819050919050565b610abd81610aab565b82525050565b5f602082019050610ad65f830184610ab4565b92915050565b610ae581610aab565b8114610aef575f80fd5b50565b5f81359050610b0081610adc565b92915050565b5f60208284031215610b1b57610b1a610996565b5b5f610b2884828501610af2565b91505092915050565b7f496e76616c69642062657474696e6720746f6b656e20616464726573730000005f82015250565b5f610b65601d83610a25565b9150610b7082610b31565b602082019050919050565b5f6020820190508181035f830152610b9281610b59565b9050919050565b7f446963655461626c6520616c72656164792065786973747320666f72207468695f8201527f7320746f6b656e00000000000000000000000000000000000000000000000000602082015250565b5f610bf3602783610a25565b9150610bfe82610b99565b604082019050919050565b5f6020820190508181035f830152610c2081610be7565b9050919050565b5f81905092915050565b5f610c3b82610a1b565b610c458185610c27565b9350610c55818560208601610a35565b80840191505092915050565b5f610c6c8285610c31565b9150610c788284610c31565b91508190509392505050565b5f606082019050610c975f8301866109f3565b8181036020830152610ca98185610a53565b90508181036040830152610cbd8184610a53565b9050949350505050565b5f6040820190508181035f830152610cdf8185610a53565b90508181036020830152610cf38184610a53565b90509392505050565b5f81519050919050565b5f81905092915050565b5f610d1a82610cfc565b610d248185610d06565b9350610d34818560208601610a35565b80840191505092915050565b5f610d4b8284610d10565b915081905092915050565b5f80fd5b5f80fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b610d9482610a43565b810181811067ffffffffffffffff82111715610db357610db2610d5e565b5b80604052505050565b5f610dc561098d565b9050610dd18282610d8b565b919050565b5f67ffffffffffffffff821115610df057610def610d5e565b5b610df982610a43565b9050602081019050919050565b5f610e18610e1384610dd6565b610dbc565b905082815260208101848484011115610e3457610e33610d5a565b5b610e3f848285610a35565b509392505050565b5f82601f830112610e5b57610e5a610d56565b5b8151610e6b848260208601610e06565b91505092915050565b5f60208284031215610e8957610e88610996565b5b5f82015167ffffffffffffffff811115610ea657610ea561099a565b5b610eb284828501610e47565b9150509291505056fe60a060405234801561000f575f80fd5b50604051613c96380380613c96833981810160405281019061003191906102ae565b818181600390816100429190610543565b5080600490816100529190610543565b50505060016005819055505f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff16036100cb576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016100c29061066c565b60405180910390fd5b8273ffffffffffffffffffffffffffffffffffffffff1660808173ffffffffffffffffffffffffffffffffffffffff168152505050505061068a565b5f604051905090565b5f80fd5b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f61014182610118565b9050919050565b61015181610137565b811461015b575f80fd5b50565b5f8151905061016c81610148565b92915050565b5f80fd5b5f80fd5b5f601f19601f8301169050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b6101c08261017a565b810181811067ffffffffffffffff821117156101df576101de61018a565b5b80604052505050565b5f6101f1610107565b90506101fd82826101b7565b919050565b5f67ffffffffffffffff82111561021c5761021b61018a565b5b6102258261017a565b9050602081019050919050565b8281835e5f83830152505050565b5f61025261024d84610202565b6101e8565b90508281526020810184848401111561026e5761026d610176565b5b610279848285610232565b509392505050565b5f82601f83011261029557610294610172565b5b81516102a5848260208601610240565b91505092915050565b5f805f606084860312156102c5576102c4610110565b5b5f6102d28682870161015e565b935050602084015167ffffffffffffffff8111156102f3576102f2610114565b5b6102ff86828701610281565b925050604084015167ffffffffffffffff8111156103205761031f610114565b5b61032c86828701610281565b9150509250925092565b5f81519050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f600282049050600182168061038457607f821691505b60208210810361039757610396610340565b5b50919050565b5f819050815f5260205f209050919050565b5f6020601f8301049050919050565b5f82821b905092915050565b5f600883026103f97fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff826103be565b61040386836103be565b95508019841693508086168417925050509392505050565b5f819050919050565b5f819050919050565b5f61044761044261043d8461041b565b610424565b61041b565b9050919050565b5f819050919050565b6104608361042d565b61047461046c8261044e565b8484546103ca565b825550505050565b5f90565b61048861047c565b610493818484610457565b505050565b5b818110156104b6576104ab5f82610480565b600181019050610499565b5050565b601f8211156104fb576104cc8161039d565b6104d5846103af565b810160208510156104e4578190505b6104f86104f0856103af565b830182610498565b50505b505050565b5f82821c905092915050565b5f61051b5f1984600802610500565b1980831691505092915050565b5f610533838361050c565b9150826002028217905092915050565b61054c82610336565b67ffffffffffffffff8111156105655761056461018a565b5b61056f825461036d565b61057a8282856104ba565b5f60209050601f8311600181146105ab575f8415610599578287015190505b6105a38582610528565b86555061060a565b601f1984166105b98661039d565b5f5b828110156105e0578489015182556001820191506020850194506020810190506105bb565b868310156105fd57848901516105f9601f89168261050c565b8355505b6001600288020188555050505b505050505050565b5f82825260208201905092915050565b7f496e76616c69642062657474696e6720746f6b656e00000000000000000000005f82015250565b5f610656601583610612565b915061066182610622565b602082019050919050565b5f6020820190508181035f8301526106838161064a565b9050919050565b6080516135ae6106e85f395f8181610793015281816108330152818161087c01528181610a1101528181610ca601528181610f9d01528181611131015281816111d10152818161121a015281816119350152611bf201526135ae5ff3fe608060405234801561000f575f80fd5b50600436106101e3575f3560e01c806370a082311161010d578063a9059cbb116100a0578063e630b1a31161006f578063e630b1a31461060b578063e8b7422e14610627578063eba484bb14610645578063fea9b57214610675576101e3565b8063a9059cbb1461055d578063aaf5eb681461058d578063dd62ed3e146105ab578063e2926678146105db576101e3565b80638ecbdbed116100dc5780638ecbdbed146104d257806395d89b41146104f15780639aca27921461050f5780639dce5ff01461052d576101e3565b806370a0823114610448578063726b4f471461047857806377fc4a1a146104965780638daaaa2f146104b4576101e3565b806323b872dd11610185578063434b635e11610154578063434b635e1461039a5780634afe62b5146103ca5780635b21f3d4146103fa5780636a73c16314610418576101e3565b806323b872dd146102f5578063313ce567146103255780633df2967e1461034357806343425e881461037c576101e3565b806317a03db4116101c157806317a03db41461026557806317e4e25d1461028357806318160ddd1461029f57806322af00fa146102bd576101e3565b806306fdde03146101e7578063095ea7b3146102055780630f11035514610235575b5f80fd5b6101ef610693565b6040516101fc9190612771565b60405180910390f35b61021f600480360381019061021a9190612822565b610723565b60405161022c919061287a565b60405180910390f35b61024f600480360381019061024a9190612893565b610745565b60405161025c91906128cd565b60405180910390f35b61026d610a0e565b60405161027a91906128f5565b60405180910390f35b61029d60048036038101906102989190612893565b610a35565b005b6102a7610e3b565b6040516102b491906128cd565b60405180910390f35b6102d760048036038101906102d29190612893565b610e44565b6040516102ec99989796959493929190612999565b60405180910390f35b61030f600480360381019061030a9190612a24565b610eb9565b60405161031c919061287a565b60405180910390f35b61032d610ee7565b60405161033a9190612a8f565b60405180910390f35b61035d60048036038101906103589190612893565b610eef565b6040516103739a99989796959493929190612aa8565b60405180910390f35b610384610f9b565b6040516103919190612b9d565b60405180910390f35b6103b460048036038101906103af9190612893565b610fbf565b6040516103c191906128cd565b60405180910390f35b6103e460048036038101906103df9190612bb6565b611039565b6040516103f191906128cd565b60405180910390f35b6104026114e7565b60405161040f91906128cd565b60405180910390f35b610432600480360381019061042d9190612893565b6114ec565b60405161043f919061287a565b60405180910390f35b610462600480360381019061045d9190612bf4565b6115b7565b60405161046f91906128cd565b60405180910390f35b6104806115fc565b60405161048d91906128cd565b60405180910390f35b61049e611603565b6040516104ab91906128cd565b60405180910390f35b6104bc611609565b6040516104c991906128cd565b60405180910390f35b6104da61160f565b6040516104e8929190612c1f565b60405180910390f35b6104f961163d565b6040516105069190612771565b60405180910390f35b6105176116cd565b60405161052491906128cd565b60405180910390f35b61054760048036038101906105429190612bb6565b6116d3565b60405161055491906128cd565b60405180910390f35b61057760048036038101906105729190612822565b611765565b604051610584919061287a565b60405180910390f35b610595611787565b6040516105a291906128cd565b60405180910390f35b6105c560048036038101906105c09190612c46565b61178e565b6040516105d291906128cd565b60405180910390f35b6105f560048036038101906105f09190612893565b611810565b60405161060291906128cd565b60405180910390f35b61062560048036038101906106209190612893565b6119db565b005b61062f611c92565b60405161063c91906128cd565b60405180910390f35b61065f600480360381019061065a9190612893565b611c9b565b60405161066c919061287a565b60405180910390f35b61067d611d6a565b60405161068a91906128cd565b60405180910390f35b6060600380546106a290612cb1565b80601f01602080910402602001604051908101604052809291908181526020018280546106ce90612cb1565b80156107195780601f106106f057610100808354040283529160200191610719565b820191905f5260205f20905b8154815290600101906020018083116106fc57829003601f168201915b5050505050905090565b5f8061072d611d70565b905061073a818585611d77565b600191505092915050565b5f61074e611d89565b5f8211610790576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078790612d2b565b60405180910390fd5b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016107ea91906128f5565b602060405180830381865afa158015610805573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906108299190612d5d565b90506108783330857f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16611dd8909392919063ffffffff16565b5f817f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b81526004016108d391906128f5565b602060405180830381865afa1580156108ee573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906109129190612d5d565b61091c9190612db5565b90505f8111610960576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161095790612e32565b60405180910390fd5b5f806006540361097257819050610989565b6109868261097e610e3b565b600654611e5a565b90505b8160065f82825461099a9190612e50565b925050819055506109ab3382611f3f565b3373ffffffffffffffffffffffffffffffffffffffff167f92023dd282de3eea749a3a27a58271d70f04c1f7905fce2e1996ec9bdfccf33b83836040516109f3929190612c1f565b60405180910390a2809350505050610a09611fbe565b919050565b5f7f0000000000000000000000000000000000000000000000000000000000000000905090565b610a3d611d89565b5f60095f8381526020019081526020015f2090505f73ffffffffffffffffffffffffffffffffffffffff16815f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1603610ae1576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610ad890612ecd565b60405180910390fd5b5f6002811115610af457610af361290e565b5b816005015f9054906101000a900460ff166002811115610b1757610b1661290e565b5b14610b57576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b4e90612f35565b60405180910390fd5b80600401544311610b9d576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b9490612f9d565b60405180910390fd5b5f801b816006015403610be5576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610bdc90613005565b60405180910390fd5b5f600143610bf39190612db5565b4090505f8183600601541890505f62010000825f1c610c129190613050565b90508084600801819055506001846005015f6101000a81548160ff02191690836002811115610c4457610c4361290e565b5b0217905550836003015460085f828254610c5e9190612db5565b925050819055505f8460020154821090508015610d63575f85600301549050610cea865f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff16827f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16611fc89092919063ffffffff16565b86865f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f1ce690bab3f0797851d1673f462be38a6378af9c81188730b523525747eba55d8584604051610d55929190612c1f565b60405180910390a350610df1565b846001015460065f828254610d789190612e50565b9250508190555085855f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff167f3c230853746fa4dbbe7007b411fe7d1926ae5ff05c91fda309b02d714d848fb784604051610de891906128cd565b60405180910390a35b857f843f061d79853f6e1ad45db6025333a81d72ddf5e4cbce9caba1e0dc1c561d008383604051610e23929190613080565b60405180910390a25050505050610e38611fbe565b50565b5f600254905090565b6009602052805f5260405f205f91509050805f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1690806001015490806002015490806003015490806004015490806005015f9054906101000a900460ff16908060060154908060070154908060080154905089565b5f80610ec3611d70565b9050610ed0858285612047565b610edb8585856120da565b60019150509392505050565b5f6012905090565b5f805f805f805f805f805f60095f8d81526020019081526020015f209050805f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff168160010154826002015483600301548460040154856005015f9054906101000a900460ff16866006015487600701546276a7008960070154610f729190612e50565b421189600801549a509a509a509a509a509a509a509a509a509a50509193959799509193959799565b7f000000000000000000000000000000000000000000000000000000000000000081565b5f80610fc961160f565b5090505f8103610fdc575f915050611034565b5f6064603283610fec91906130a7565b610ff691906130e8565b905061102f81620f42408661100b91906130a7565b62010000614e20620f42406110209190612db5565b61102a91906130a7565b611e5a565b925050505b919050565b5f611042611d89565b60018310158015611055575061fae18311155b611094576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161108b90613162565b60405180910390fd5b5f82116110d6576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016110cd906131f0565b60405180910390fd5b5f6110e184846116d3565b90506110ec84610fbf565b83111561112e576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161112590613258565b60405180910390fd5b5f7f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161118891906128f5565b602060405180830381865afa1580156111a3573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906111c79190612d5d565b90506112163330867f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16611dd8909392919063ffffffff16565b5f817f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff166370a08231306040518263ffffffff1660e01b815260040161127191906128f5565b602060405180830381865afa15801561128c573d5f803e3d5ffd5b505050506040513d601f19601f820116820180604052508101906112b09190612d5d565b6112ba9190612db5565b90505f81116112fe576040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016112f590612e32565b60405180910390fd5b61130886826116d3565b92505f60075f8154809291906001019190505590505f4290506040518061012001604052803373ffffffffffffffffffffffffffffffffffffffff1681526020018481526020018981526020018681526020014381526020015f60028111156113745761137361290e565b5b81526020016001436113869190612db5565b4081526020018281526020015f81525060095f8481526020019081526020015f205f820151815f015f6101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506020820151816001015560408201518160020155606082015181600301556080820151816004015560a0820151816005015f6101000a81548160ff0219169083600281111561143d5761143c61290e565b5b021790555060c0820151816006015560e0820151816007015561010082015181600801559050508460085f8282546114759190612e50565b92505081905550813373ffffffffffffffffffffffffffffffffffffffff167fce4169502e4ec788f06e096a7c876ac9e3c1102bdc6cb2089a3b41e0a7f594508a8689866040516114c99493929190613276565b60405180910390a381955050505050506114e1611fbe565b92915050565b600581565b5f8060095f8481526020019081526020015f2090505f73ffffffffffffffffffffffffffffffffffffffff16815f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415801561159257505f600281111561156d5761156c61290e565b5b816005015f9054906101000a900460ff1660028111156115905761158f61290e565b5b145b80156115af57506276a70081600701546115ac9190612e50565b42115b915050919050565b5f805f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050919050565b6276a70081565b60085481565b614e2081565b5f806008549050806006541115611635578060065461162e9190612db5565b9150611639565b5f91505b9091565b60606004805461164c90612cb1565b80601f016020809104026020016040519081016040528092919081815260200182805461167890612cb1565b80156116c35780601f1061169a576101008083540402835291602001916116c3565b820191905f5260205f20905b8154815290600101906020018083116116a657829003601f168201915b5050505050905090565b60075481565b5f600183101580156116e7575061fae18311155b611726576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161171d90613303565b60405180910390fd5b61175d8262010000614e20620f424061173f9190612db5565b61174991906130a7565b620f42408661175891906130a7565b611e5a565b905092915050565b5f8061176f611d70565b905061177c8185856120da565b600191505092915050565b620f424081565b5f60015f8473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2054905092915050565b5f611819611d89565b5f821161185b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161185290612d2b565b60405180910390fd5b611864336115b7565b8211156118a6576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161189d9061336b565b60405180910390fd5b5f6118bb836006546118b6610e3b565b611e5a565b90505f6118c661160f565b5090508082111561190c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611903906133f9565b60405180910390fd5b8160065f82825461191d9190612db5565b9250508190555061192e33856121ca565b61197933837f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16611fc89092919063ffffffff16565b3373ffffffffffffffffffffffffffffffffffffffff167f5332f17e54d6548ba227c2597cdde808fa7184b0a1e8019eed07d9608d6b3a8383866040516119c1929190612c1f565b60405180910390a281925050506119d6611fbe565b919050565b6119e3611d89565b5f60095f8381526020019081526020015f2090505f73ffffffffffffffffffffffffffffffffffffffff16815f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1603611a87576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611a7e90612ecd565b60405180910390fd5b5f6002811115611a9a57611a9961290e565b5b816005015f9054906101000a900460ff166002811115611abd57611abc61290e565b5b14611afd576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611af490612f35565b60405180910390fd5b6276a7008160070154611b109190612e50565b4211611b51576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611b4890613461565b60405180910390fd5b806003015460085f828254611b669190612db5565b925050819055505f606460058360010154611b8191906130a7565b611b8b91906130e8565b9050808260010154611b9d9190612db5565b60065f828254611bad9190612e50565b925050819055506002826005015f6101000a81548160ff02191690836002811115611bdb57611bda61290e565b5b021790555061ffff8260080181905550611c3633827f000000000000000000000000000000000000000000000000000000000000000073ffffffffffffffffffffffffffffffffffffffff16611fc89092919063ffffffff16565b3373ffffffffffffffffffffffffffffffffffffffff16837f34ba5342815e3cb40082d66082fdd3b809740e0cb9646c2a1b6a0f60e73829dc83604051611c7d91906128cd565b60405180910390a35050611c8f611fbe565b50565b5f600654905090565b5f8060095f8481526020019081526020015f2090505f73ffffffffffffffffffffffffffffffffffffffff16815f015f9054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614158015611d4157505f6002811115611d1c57611d1b61290e565b5b816005015f9054906101000a900460ff166002811115611d3f57611d3e61290e565b5b145b8015611d505750806004015443115b8015611d6257505f801b816006015414155b915050919050565b61fae181565b5f33905090565b611d848383836001612249565b505050565b600260055403611dce576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401611dc5906134c9565b60405180910390fd5b6002600581905550565b611e54848573ffffffffffffffffffffffffffffffffffffffff166323b872dd868686604051602401611e0d939291906134e7565b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050612418565b50505050565b5f8083850290505f8019858709828110838203039150505f8103611e9257838281611e8857611e87613023565b5b0492505050611f38565b808411611eb157611eb0611eab5f8614601260116124b3565b6124cc565b5b5f8486880990508281118203915080830392505f855f038616905080860495508084049350600181825f0304019050808302841793505f600287600302189050808702600203810290508087026002038102905080870260020381029050808702600203810290508087026002038102905080870260020381029050808502955050505050505b9392505050565b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603611faf575f6040517fec442f05000000000000000000000000000000000000000000000000000000008152600401611fa691906128f5565b60405180910390fd5b611fba5f83836124dd565b5050565b6001600581905550565b612042838473ffffffffffffffffffffffffffffffffffffffff1663a9059cbb8585604051602401611ffb92919061351c565b604051602081830303815290604052915060e01b6020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050612418565b505050565b5f612052848461178e565b90507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff8110156120d457818110156120c5578281836040517ffb8f41b20000000000000000000000000000000000000000000000000000000081526004016120bc93929190613543565b60405180910390fd5b6120d384848484035f612249565b5b50505050565b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff160361214a575f6040517f96c6fd1e00000000000000000000000000000000000000000000000000000000815260040161214191906128f5565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff16036121ba575f6040517fec442f050000000000000000000000000000000000000000000000000000000081526004016121b191906128f5565b60405180910390fd5b6121c58383836124dd565b505050565b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff160361223a575f6040517f96c6fd1e00000000000000000000000000000000000000000000000000000000815260040161223191906128f5565b60405180910390fd5b612245825f836124dd565b5050565b5f73ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff16036122b9575f6040517fe602df050000000000000000000000000000000000000000000000000000000081526004016122b091906128f5565b60405180910390fd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff1603612329575f6040517f94280d6200000000000000000000000000000000000000000000000000000000815260040161232091906128f5565b60405180910390fd5b8160015f8673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20819055508015612412578273ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258460405161240991906128cd565b60405180910390a35b50505050565b5f8060205f8451602086015f885af180612437576040513d5f823e3d81fd5b3d92505f519150505f821461245057600181141561246b565b5f8473ffffffffffffffffffffffffffffffffffffffff163b145b156124ad57836040517f5274afe70000000000000000000000000000000000000000000000000000000081526004016124a491906128f5565b60405180910390fd5b50505050565b5f6124bd846126f6565b82841802821890509392505050565b634e487b715f52806020526024601cfd5b5f73ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff160361252d578060025f8282546125219190612e50565b925050819055506125fb565b5f805f8573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f20549050818110156125b6578381836040517fe450d38c0000000000000000000000000000000000000000000000000000000081526004016125ad93929190613543565b60405180910390fd5b8181035f808673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f2081905550505b5f73ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1603612642578060025f828254039250508190555061268c565b805f808473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020015f205f82825401925050819055505b8173ffffffffffffffffffffffffffffffffffffffff168373ffffffffffffffffffffffffffffffffffffffff167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516126e991906128cd565b60405180910390a3505050565b5f8115159050919050565b5f81519050919050565b5f82825260208201905092915050565b8281835e5f83830152505050565b5f601f19601f8301169050919050565b5f61274382612701565b61274d818561270b565b935061275d81856020860161271b565b61276681612729565b840191505092915050565b5f6020820190508181035f8301526127898184612739565b905092915050565b5f80fd5b5f73ffffffffffffffffffffffffffffffffffffffff82169050919050565b5f6127be82612795565b9050919050565b6127ce816127b4565b81146127d8575f80fd5b50565b5f813590506127e9816127c5565b92915050565b5f819050919050565b612801816127ef565b811461280b575f80fd5b50565b5f8135905061281c816127f8565b92915050565b5f806040838503121561283857612837612791565b5b5f612845858286016127db565b92505060206128568582860161280e565b9150509250929050565b5f8115159050919050565b61287481612860565b82525050565b5f60208201905061288d5f83018461286b565b92915050565b5f602082840312156128a8576128a7612791565b5b5f6128b58482850161280e565b91505092915050565b6128c7816127ef565b82525050565b5f6020820190506128e05f8301846128be565b92915050565b6128ef816127b4565b82525050565b5f6020820190506129085f8301846128e6565b92915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b6003811061294c5761294b61290e565b5b50565b5f81905061295c8261293b565b919050565b5f61296b8261294f565b9050919050565b61297b81612961565b82525050565b5f819050919050565b61299381612981565b82525050565b5f610120820190506129ad5f83018c6128e6565b6129ba602083018b6128be565b6129c7604083018a6128be565b6129d460608301896128be565b6129e160808301886128be565b6129ee60a0830187612972565b6129fb60c083018661298a565b612a0860e08301856128be565b612a166101008301846128be565b9a9950505050505050505050565b5f805f60608486031215612a3b57612a3a612791565b5b5f612a48868287016127db565b9350506020612a59868287016127db565b9250506040612a6a8682870161280e565b9150509250925092565b5f60ff82169050919050565b612a8981612a74565b82525050565b5f602082019050612aa25f830184612a80565b92915050565b5f61014082019050612abc5f83018d6128e6565b612ac9602083018c6128be565b612ad6604083018b6128be565b612ae3606083018a6128be565b612af060808301896128be565b612afd60a0830188612972565b612b0a60c083018761298a565b612b1760e08301866128be565b612b2561010083018561286b565b612b336101208301846128be565b9b9a5050505050505050505050565b5f819050919050565b5f612b65612b60612b5b84612795565b612b42565b612795565b9050919050565b5f612b7682612b4b565b9050919050565b5f612b8782612b6c565b9050919050565b612b9781612b7d565b82525050565b5f602082019050612bb05f830184612b8e565b92915050565b5f8060408385031215612bcc57612bcb612791565b5b5f612bd98582860161280e565b9250506020612bea8582860161280e565b9150509250929050565b5f60208284031215612c0957612c08612791565b5b5f612c16848285016127db565b91505092915050565b5f604082019050612c325f8301856128be565b612c3f60208301846128be565b9392505050565b5f8060408385031215612c5c57612c5b612791565b5b5f612c69858286016127db565b9250506020612c7a858286016127db565b9150509250929050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b5f6002820490506001821680612cc857607f821691505b602082108103612cdb57612cda612c84565b5b50919050565b7f416d6f756e74206d75737420626520706f7369746976650000000000000000005f82015250565b5f612d1560178361270b565b9150612d2082612ce1565b602082019050919050565b5f6020820190508181035f830152612d4281612d09565b9050919050565b5f81519050612d57816127f8565b92915050565b5f60208284031215612d7257612d71612791565b5b5f612d7f84828501612d49565b91505092915050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b5f612dbf826127ef565b9150612dca836127ef565b9250828203905081811115612de257612de1612d88565b5b92915050565b7f4e6f20746f6b656e73207472616e7366657272656400000000000000000000005f82015250565b5f612e1c60158361270b565b9150612e2782612de8565b602082019050919050565b5f6020820190508181035f830152612e4981612e10565b9050919050565b5f612e5a826127ef565b9150612e65836127ef565b9250828201905080821115612e7d57612e7c612d88565b5b92915050565b7f42657420646f6573206e6f7420657869737400000000000000000000000000005f82015250565b5f612eb760128361270b565b9150612ec282612e83565b602082019050919050565b5f6020820190508181035f830152612ee481612eab565b9050919050565b7f42657420616c72656164792072657665616c6564206f722065787069726564005f82015250565b5f612f1f601f8361270b565b9150612f2a82612eeb565b602082019050919050565b5f6020820190508181035f830152612f4c81612f13565b9050919050565b7f5761697420666f72206e65787420626c6f636b000000000000000000000000005f82015250565b5f612f8760138361270b565b9150612f9282612f53565b602082019050919050565b5f6020820190508181035f830152612fb481612f7b565b9050919050565b7f496e76616c69642062657420626c6f636b2068617368000000000000000000005f82015250565b5f612fef60168361270b565b9150612ffa82612fbb565b602082019050919050565b5f6020820190508181035f83015261301c81612fe3565b9050919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b5f61305a826127ef565b9150613065836127ef565b92508261307557613074613023565b5b828206905092915050565b5f6040820190506130935f8301856128be565b6130a0602083018461286b565b9392505050565b5f6130b1826127ef565b91506130bc836127ef565b92508282026130ca816127ef565b915082820484148315176130e1576130e0612d88565b5b5092915050565b5f6130f2826127ef565b91506130fd836127ef565b92508261310d5761310c613023565b5b828204905092915050565b7f4c75636b79206e756d626572206f7574206f662072616e6765000000000000005f82015250565b5f61314c60198361270b565b915061315782613118565b602082019050919050565b5f6020820190508181035f83015261317981613140565b9050919050565b7f42657420616d6f756e74206d7573742062652067726561746572207468616e205f8201527f7a65726f00000000000000000000000000000000000000000000000000000000602082015250565b5f6131da60248361270b565b91506131e582613180565b604082019050919050565b5f6020820190508181035f830152613207816131ce565b9050919050565b7f4265742065786365656473206d6178696d756d20616c6c6f77656400000000005f82015250565b5f613242601b8361270b565b915061324d8261320e565b602082019050919050565b5f6020820190508181035f83015261326f81613236565b9050919050565b5f6080820190506132895f8301876128be565b61329660208301866128be565b6132a360408301856128be565b6132b060608301846128be565b95945050505050565b7f496e76616c6964206c75636b79206e756d6265720000000000000000000000005f82015250565b5f6132ed60148361270b565b91506132f8826132b9565b602082019050919050565b5f6020820190508181035f83015261331a816132e1565b9050919050565b7f496e73756666696369656e742044542062616c616e63650000000000000000005f82015250565b5f61335560178361270b565b915061336082613321565b602082019050919050565b5f6020820190508181035f83015261338281613349565b9050919050565b7f4578636565647320617661696c61626c652066756e64732064756520746f206f5f8201527f70656e2062657473000000000000000000000000000000000000000000000000602082015250565b5f6133e360288361270b565b91506133ee82613389565b604082019050919050565b5f6020820190508181035f830152613410816133d7565b9050919050565b7f426574206e6f74206578706972656420796574000000000000000000000000005f82015250565b5f61344b60138361270b565b915061345682613417565b602082019050919050565b5f6020820190508181035f8301526134788161343f565b9050919050565b7f5265656e7472616e637947756172643a207265656e7472616e742063616c6c005f82015250565b5f6134b3601f8361270b565b91506134be8261347f565b602082019050919050565b5f6020820190508181035f8301526134e0816134a7565b9050919050565b5f6060820190506134fa5f8301866128e6565b61350760208301856128e6565b61351460408301846128be565b949350505050565b5f60408201905061352f5f8301856128e6565b61353c60208301846128be565b9392505050565b5f6060820190506135565f8301866128e6565b61356360208301856128be565b61357060408301846128be565b94935050505056fea2646970667358221220a233f80700356dcd8ffda630ce4b28f81a7e3268e05b47c87a66e2cb2788e8fc64736f6c634300081a0033a2646970667358221220e1c367df840a0296b01a678308daa115d2bfedc618042940294418f5b59cce9f64736f6c634300081a0033

Verified Source Code Full Match

Compiler: v0.8.26+commit.8a97fa7a EVM: cancun Optimization: No
IERC1363.sol 86 lines
// 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);
}
IERC165.sol 6 lines
// 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";
IERC20.sol 6 lines
// 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";
draft-IERC6093.sol 161 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;

/**
 * @dev Standard ERC-20 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
 */
interface IERC20Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC20InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC20InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     * @param allowance Amount of tokens a `spender` is allowed to operate with.
     * @param needed Minimum amount required to perform a transfer.
     */
    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC20InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.
     * @param spender Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC20InvalidSpender(address spender);
}

/**
 * @dev Standard ERC-721 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
 */
interface IERC721Errors {
    /**
     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
     * Used in balance queries.
     * @param owner Address of the current owner of a token.
     */
    error ERC721InvalidOwner(address owner);

    /**
     * @dev Indicates a `tokenId` whose `owner` is the zero address.
     * @param tokenId Identifier number of a token.
     */
    error ERC721NonexistentToken(uint256 tokenId);

    /**
     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param tokenId Identifier number of a token.
     * @param owner Address of the current owner of a token.
     */
    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC721InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC721InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param tokenId Identifier number of a token.
     */
    error ERC721InsufficientApproval(address operator, uint256 tokenId);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC721InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC721InvalidOperator(address operator);
}

/**
 * @dev Standard ERC-1155 Errors
 * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
 */
interface IERC1155Errors {
    /**
     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     * @param balance Current balance for the interacting account.
     * @param needed Minimum amount required to perform a transfer.
     * @param tokenId Identifier number of a token.
     */
    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);

    /**
     * @dev Indicates a failure with the token `sender`. Used in transfers.
     * @param sender Address whose tokens are being transferred.
     */
    error ERC1155InvalidSender(address sender);

    /**
     * @dev Indicates a failure with the token `receiver`. Used in transfers.
     * @param receiver Address to which tokens are being transferred.
     */
    error ERC1155InvalidReceiver(address receiver);

    /**
     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     * @param owner Address of the current owner of a token.
     */
    error ERC1155MissingApprovalForAll(address operator, address owner);

    /**
     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
     * @param approver Address initiating an approval operation.
     */
    error ERC1155InvalidApprover(address approver);

    /**
     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.
     * @param operator Address that may be allowed to operate on tokens without being their owner.
     */
    error ERC1155InvalidOperator(address operator);

    /**
     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
     * Used in batch transfers.
     * @param idsLength Length of the array of token identifiers
     * @param valuesLength Length of the array of token amounts
     */
    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
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;
    }
}
ERC20.sol 312 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * The default value of {decimals} is 18. To change this, you should override
 * this function so it returns a different value.
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC-20
 * applications.
 */
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
    mapping(address account => uint256) private _balances;

    mapping(address account => mapping(address spender => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the default value returned by this function, unless
     * it's overridden.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `value`.
     */
    function transfer(address to, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, value);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
     * `transferFrom`. This is semantically equivalent to an infinite approval.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 value) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, value);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Skips emitting an {Approval} event indicating an allowance update. This is not
     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
     *
     * NOTE: Does not update the allowance if the current allowance
     * is the maximum `uint256`.
     *
     * Requirements:
     *
     * - `from` and `to` cannot be the zero address.
     * - `from` must have a balance of at least `value`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `value`.
     */
    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, value);
        _transfer(from, to, value);
        return true;
    }

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _transfer(address from, address to, uint256 value) internal {
        if (from == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        if (to == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(from, to, value);
    }

    /**
     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
     * this function.
     *
     * Emits a {Transfer} event.
     */
    function _update(address from, address to, uint256 value) internal virtual {
        if (from == address(0)) {
            // Overflow check required: The rest of the code assumes that totalSupply never overflows
            _totalSupply += value;
        } else {
            uint256 fromBalance = _balances[from];
            if (fromBalance < value) {
                revert ERC20InsufficientBalance(from, fromBalance, value);
            }
            unchecked {
                // Overflow not possible: value <= fromBalance <= totalSupply.
                _balances[from] = fromBalance - value;
            }
        }

        if (to == address(0)) {
            unchecked {
                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
                _totalSupply -= value;
            }
        } else {
            unchecked {
                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
                _balances[to] += value;
            }
        }

        emit Transfer(from, to, value);
    }

    /**
     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
     * Relies on the `_update` mechanism
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead.
     */
    function _mint(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidReceiver(address(0));
        }
        _update(address(0), account, value);
    }

    /**
     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
     * Relies on the `_update` mechanism.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * NOTE: This function is not virtual, {_update} should be overridden instead
     */
    function _burn(address account, uint256 value) internal {
        if (account == address(0)) {
            revert ERC20InvalidSender(address(0));
        }
        _update(account, address(0), value);
    }

    /**
     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     *
     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
     */
    function _approve(address owner, address spender, uint256 value) internal {
        _approve(owner, spender, value, true);
    }

    /**
     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
     *
     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
     * `Approval` event during `transferFrom` operations.
     *
     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
     * true using the following override:
     *
     * ```solidity
     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
     *     super._approve(owner, spender, value, true);
     * }
     * ```
     *
     * Requirements are the same as {_approve}.
     */
    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
        if (owner == address(0)) {
            revert ERC20InvalidApprover(address(0));
        }
        if (spender == address(0)) {
            revert ERC20InvalidSpender(address(0));
        }
        _allowances[owner][spender] = value;
        if (emitEvent) {
            emit Approval(owner, spender, value);
        }
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `value`.
     *
     * Does not update the allowance value in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Does not emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance < type(uint256).max) {
            if (currentAllowance < value) {
                revert ERC20InsufficientAllowance(spender, currentAllowance, value);
            }
            unchecked {
                _approve(owner, spender, currentAllowance - value, false);
            }
        }
    }
}
IERC20.sol 79 lines
// 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);
}
IERC20Metadata.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC-20 standard.
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
SafeERC20.sol 198 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.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);
    }
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract Context {
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
Panic.sol 57 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)

pragma solidity ^0.8.20;

/**
 * @dev Helper library for emitting standardized panic codes.
 *
 * ```solidity
 * contract Example {
 *      using Panic for uint256;
 *
 *      // Use any of the declared internal constants
 *      function foo() { Panic.GENERIC.panic(); }
 *
 *      // Alternatively
 *      function foo() { Panic.panic(Panic.GENERIC); }
 * }
 * ```
 *
 * Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
 *
 * _Available since v5.1._
 */
// slither-disable-next-line unused-state
library Panic {
    /// @dev generic / unspecified error
    uint256 internal constant GENERIC = 0x00;
    /// @dev used by the assert() builtin
    uint256 internal constant ASSERT = 0x01;
    /// @dev arithmetic underflow or overflow
    uint256 internal constant UNDER_OVERFLOW = 0x11;
    /// @dev division or modulo by zero
    uint256 internal constant DIVISION_BY_ZERO = 0x12;
    /// @dev enum conversion error
    uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
    /// @dev invalid encoding in storage
    uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
    /// @dev empty array pop
    uint256 internal constant EMPTY_ARRAY_POP = 0x31;
    /// @dev array out of bounds access
    uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
    /// @dev resource error (too large allocation or too large array)
    uint256 internal constant RESOURCE_ERROR = 0x41;
    /// @dev calling invalid internal function
    uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;

    /// @dev Reverts with a panic code. Recommended to use with
    /// the internal constants with predefined codes.
    function panic(uint256 code) internal pure {
        assembly ("memory-safe") {
            mstore(0x00, 0x4e487b71)
            mstore(0x20, code)
            revert(0x1c, 0x24)
        }
    }
}
IERC165.sol 25 lines
// 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);
}
Math.sol 685 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)

pragma solidity ^0.8.20;

import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Floor, // Toward negative infinity
        Ceil, // Toward positive infinity
        Trunc, // Toward zero
        Expand // Away from zero
    }

    /**
     * @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            uint256 c = a + b;
            if (c < a) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b > a) return (false, 0);
            return (true, a - b);
        }
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
            // benefit is lost if 'b' is also tested.
            // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
            if (a == 0) return (true, 0);
            uint256 c = a * b;
            if (c / a != b) return (false, 0);
            return (true, c);
        }
    }

    /**
     * @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a / b);
        }
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
        unchecked {
            if (b == 0) return (false, 0);
            return (true, a % b);
        }
    }

    /**
     * @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
     *
     * IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
     * However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
     * one branch when needed, making this function more expensive.
     */
    function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            // branchless ternary works because:
            // b ^ (a ^ b) == a
            // b ^ 0 == b
            return b ^ ((a ^ b) * SafeCast.toUint(condition));
        }
    }

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

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

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

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds towards infinity instead
     * of rounding towards zero.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        if (b == 0) {
            // Guarantee the same behavior as in a regular Solidity division.
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }

        // The following calculation ensures accurate ceiling division without overflow.
        // Since a is non-zero, (a - 1) / b will not overflow.
        // The largest possible result occurs when (a - 1) / b is type(uint256).max,
        // but the largest value we can obtain is type(uint256).max - 1, which happens
        // when a = type(uint256).max and b = 1.
        unchecked {
            return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
        }
    }

    /**
     * @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
     * denominator == 0.
     *
     * 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²⁵⁶ and mod 2²⁵⁶ - 1, then use
            // the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2²⁵⁶ + prod0.
            uint256 prod0 = x * y; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

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

            // Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
            if (denominator <= prod1) {
                Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_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.

            uint256 twos = denominator & (0 - denominator);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

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

                // Flip twos such that it is 2²⁵⁶ / 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²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
            // that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv ≡ 1 mod 2⁴.
            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⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
            inverse *= 2 - denominator * inverse; // inverse mod 2³²
            inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
            inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
            inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶

            // 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²⁵⁶. Since the preconditions guarantee that the outcome is
            // less than 2²⁵⁶, 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;
        }
    }

    /**
     * @dev 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) {
        return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
    }

    /**
     * @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
     *
     * If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
     * If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
     *
     * If the input value is not inversible, 0 is returned.
     *
     * NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
     * inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
     */
    function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
        unchecked {
            if (n == 0) return 0;

            // The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
            // Used to compute integers x and y such that: ax + ny = gcd(a, n).
            // When the gcd is 1, then the inverse of a modulo n exists and it's x.
            // ax + ny = 1
            // ax = 1 + (-y)n
            // ax ≡ 1 (mod n) # x is the inverse of a modulo n

            // If the remainder is 0 the gcd is n right away.
            uint256 remainder = a % n;
            uint256 gcd = n;

            // Therefore the initial coefficients are:
            // ax + ny = gcd(a, n) = n
            // 0a + 1n = n
            int256 x = 0;
            int256 y = 1;

            while (remainder != 0) {
                uint256 quotient = gcd / remainder;

                (gcd, remainder) = (
                    // The old remainder is the next gcd to try.
                    remainder,
                    // Compute the next remainder.
                    // Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
                    // where gcd is at most n (capped to type(uint256).max)
                    gcd - remainder * quotient
                );

                (x, y) = (
                    // Increment the coefficient of a.
                    y,
                    // Decrement the coefficient of n.
                    // Can overflow, but the result is casted to uint256 so that the
                    // next value of y is "wrapped around" to a value between 0 and n - 1.
                    x - y * int256(quotient)
                );
            }

            if (gcd != 1) return 0; // No inverse exists.
            return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
        }
    }

    /**
     * @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
     *
     * From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
     * prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
     * `a**(p-2)` is the modular multiplicative inverse of a in Fp.
     *
     * NOTE: this function does NOT check that `p` is a prime greater than `2`.
     */
    function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
        unchecked {
            return Math.modExp(a, p - 2, p);
        }
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
     *
     * Requirements:
     * - modulus can't be zero
     * - underlying staticcall to precompile must succeed
     *
     * IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
     * sure the chain you're using it on supports the precompiled contract for modular exponentiation
     * at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
     * the underlying function will succeed given the lack of a revert, but the result may be incorrectly
     * interpreted as 0.
     */
    function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
        (bool success, uint256 result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
     * It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
     * to operate modulo 0 or if the underlying precompile reverted.
     *
     * IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
     * you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
     * https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
     * of a revert, but the result may be incorrectly interpreted as 0.
     */
    function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
        if (m == 0) return (false, 0);
        assembly ("memory-safe") {
            let ptr := mload(0x40)
            // | Offset    | Content    | Content (Hex)                                                      |
            // |-----------|------------|--------------------------------------------------------------------|
            // | 0x00:0x1f | size of b  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x20:0x3f | size of e  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x40:0x5f | size of m  | 0x0000000000000000000000000000000000000000000000000000000000000020 |
            // | 0x60:0x7f | value of b | 0x<.............................................................b> |
            // | 0x80:0x9f | value of e | 0x<.............................................................e> |
            // | 0xa0:0xbf | value of m | 0x<.............................................................m> |
            mstore(ptr, 0x20)
            mstore(add(ptr, 0x20), 0x20)
            mstore(add(ptr, 0x40), 0x20)
            mstore(add(ptr, 0x60), b)
            mstore(add(ptr, 0x80), e)
            mstore(add(ptr, 0xa0), m)

            // Given the result < m, it's guaranteed to fit in 32 bytes,
            // so we can use the memory scratch space located at offset 0.
            success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
            result := mload(0x00)
        }
    }

    /**
     * @dev Variant of {modExp} that supports inputs of arbitrary length.
     */
    function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
        (bool success, bytes memory result) = tryModExp(b, e, m);
        if (!success) {
            Panic.panic(Panic.DIVISION_BY_ZERO);
        }
        return result;
    }

    /**
     * @dev Variant of {tryModExp} that supports inputs of arbitrary length.
     */
    function tryModExp(
        bytes memory b,
        bytes memory e,
        bytes memory m
    ) internal view returns (bool success, bytes memory result) {
        if (_zeroBytes(m)) return (false, new bytes(0));

        uint256 mLen = m.length;

        // Encode call args in result and move the free memory pointer
        result = abi.encodePacked(b.length, e.length, mLen, b, e, m);

        assembly ("memory-safe") {
            let dataPtr := add(result, 0x20)
            // Write result on top of args to avoid allocating extra memory.
            success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
            // Overwrite the length.
            // result.length > returndatasize() is guaranteed because returndatasize() == m.length
            mstore(result, mLen)
            // Set the memory pointer after the returned data.
            mstore(0x40, add(dataPtr, mLen))
        }
    }

    /**
     * @dev Returns whether the provided byte array is zero.
     */
    function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
        for (uint256 i = 0; i < byteArray.length; ++i) {
            if (byteArray[i] != 0) {
                return false;
            }
        }
        return true;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
     * towards zero.
     *
     * This method is based on Newton's method for computing square roots; the algorithm is restricted to only
     * using integer operations.
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        unchecked {
            // Take care of easy edge cases when a == 0 or a == 1
            if (a <= 1) {
                return a;
            }

            // In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
            // sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
            // the current value as `ε_n = | x_n - sqrt(a) |`.
            //
            // For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
            // of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
            // bigger than any uint256.
            //
            // By noticing that
            // `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
            // we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
            // to the msb function.
            uint256 aa = a;
            uint256 xn = 1;

            if (aa >= (1 << 128)) {
                aa >>= 128;
                xn <<= 64;
            }
            if (aa >= (1 << 64)) {
                aa >>= 64;
                xn <<= 32;
            }
            if (aa >= (1 << 32)) {
                aa >>= 32;
                xn <<= 16;
            }
            if (aa >= (1 << 16)) {
                aa >>= 16;
                xn <<= 8;
            }
            if (aa >= (1 << 8)) {
                aa >>= 8;
                xn <<= 4;
            }
            if (aa >= (1 << 4)) {
                aa >>= 4;
                xn <<= 2;
            }
            if (aa >= (1 << 2)) {
                xn <<= 1;
            }

            // We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
            //
            // We can refine our estimation by noticing that the middle of that interval minimizes the error.
            // If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
            // This is going to be our x_0 (and ε_0)
            xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)

            // From here, Newton's method give us:
            // x_{n+1} = (x_n + a / x_n) / 2
            //
            // One should note that:
            // x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
            //              = ((x_n² + a) / (2 * x_n))² - a
            //              = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
            //              = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
            //              = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
            //              = (x_n² - a)² / (2 * x_n)²
            //              = ((x_n² - a) / (2 * x_n))²
            //              ≥ 0
            // Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
            //
            // This gives us the proof of quadratic convergence of the sequence:
            // ε_{n+1} = | x_{n+1} - sqrt(a) |
            //         = | (x_n + a / x_n) / 2 - sqrt(a) |
            //         = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
            //         = | (x_n - sqrt(a))² / (2 * x_n) |
            //         = | ε_n² / (2 * x_n) |
            //         = ε_n² / | (2 * x_n) |
            //
            // For the first iteration, we have a special case where x_0 is known:
            // ε_1 = ε_0² / | (2 * x_0) |
            //     ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
            //     ≤ 2**(2*e-4) / (3 * 2**(e-1))
            //     ≤ 2**(e-3) / 3
            //     ≤ 2**(e-3-log2(3))
            //     ≤ 2**(e-4.5)
            //
            // For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
            // ε_{n+1} = ε_n² / | (2 * x_n) |
            //         ≤ (2**(e-k))² / (2 * 2**(e-1))
            //         ≤ 2**(2*e-2*k) / 2**e
            //         ≤ 2**(e-2*k)
            xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5)  -- special case, see above
            xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9)    -- general case with k = 4.5
            xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18)   -- general case with k = 9
            xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36)   -- general case with k = 18
            xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72)   -- general case with k = 36
            xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144)  -- general case with k = 72

            // Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
            // ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
            // sqrt(a) or sqrt(a) + 1.
            return xn - SafeCast.toUint(xn > a / xn);
        }
    }

    /**
     * @dev 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
        }
    }

    /**
     * @dev Return the log in base 2 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 exp;
        unchecked {
            exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
            value >>= exp;
            result += exp;

            exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
            value >>= exp;
            result += exp;

            exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
            value >>= exp;
            result += exp;

            exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
            value >>= exp;
            result += exp;

            exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
            value >>= exp;
            result += exp;

            exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
            value >>= exp;
            result += exp;

            exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
            value >>= exp;
            result += exp;

            result += SafeCast.toUint(value > 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
        }
    }

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

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

    /**
     * @dev Return the log in base 256 of a positive value rounded towards zero.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        uint256 isGt;
        unchecked {
            isGt = SafeCast.toUint(value > (1 << 128) - 1);
            value >>= isGt * 128;
            result += isGt * 16;

            isGt = SafeCast.toUint(value > (1 << 64) - 1);
            value >>= isGt * 64;
            result += isGt * 8;

            isGt = SafeCast.toUint(value > (1 << 32) - 1);
            value >>= isGt * 32;
            result += isGt * 4;

            isGt = SafeCast.toUint(value > (1 << 16) - 1);
            value >>= isGt * 16;
            result += isGt * 2;

            result += SafeCast.toUint(value > (1 << 8) - 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 + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
        }
    }

    /**
     * @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
     */
    function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
        return uint8(rounding) % 2 == 1;
    }
}
SafeCast.sol 1162 lines
// 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))
        }
    }
}
DiceFactory.sol 119 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "./DiceTable.sol";

/**
 * @title DiceTableFactory
 * @notice Factory contract for creating and tracking multiple DiceTable instances
 * for different underlying tokens (e.g., WETH, USDC, USDT)
 */
contract DiceTableFactory {
    // Constant name and symbol prefixes for all deployed DiceTable contracts
    string public constant NAME_PREFIX = "Dice Game Token - ";
    string public constant SYMBOL_PREFIX = "DT";
    
    // Array to store all deployed DiceTable contract addresses
    address[] public deployedDiceTables;
    
    // Mapping from betting token address to its corresponding DiceTable address
    mapping(address => address) public tokenToDiceContract;
    
    // Event emitted when a new DiceTable contract is deployed
    event DiceTableDeployed(
        address indexed diceTokenAddress,
        address indexed bettingTokenAddress,
        string tokenName,
        string tokenSymbol
    );
    
    /**
     * @notice Deploy a new DiceTable contract for a specific betting token
     * @param bettingToken Address of the ERC20 token to be used for betting
     * @return Address of the newly deployed DiceTable contract
     */
    function deployDiceTable(
        address bettingToken
    ) external returns (address) {
        // Ensure betting token address is valid
        require(bettingToken != address(0), "Invalid betting token address");
        
        // Check if a DiceTable contract already exists for this betting token
        require(tokenToDiceContract[bettingToken] == address(0), "DiceTable already exists for this token");
        
        // Get the betting token's symbol to incorporate in the new token's name and symbol
        string memory tokenSymbol = _getTokenSymbol(bettingToken);
        
        // Create the full name and symbol for the new DiceTable using the constant prefixes
        string memory diceTokenName = string(abi.encodePacked(NAME_PREFIX, tokenSymbol));
        string memory diceTokenSymbol = string(abi.encodePacked(SYMBOL_PREFIX, tokenSymbol));
        
        // Deploy a new DiceTable contract
        DiceTable newDiceTable = new DiceTable(
            bettingToken,
            diceTokenName,
            diceTokenSymbol
        );
        
        address diceTokenAddress = address(newDiceTable);
        
        // Update tracking data structures
        deployedDiceTables.push(diceTokenAddress);
        tokenToDiceContract[bettingToken] = diceTokenAddress;
        
        // Emit the deployment event
        emit DiceTableDeployed(
            diceTokenAddress,
            bettingToken,
            diceTokenName,
            diceTokenSymbol
        );
        
        return diceTokenAddress;
    }
    
    /**
     * @notice Get all deployed DiceTable contract addresses
     * @return Array of all deployed DiceTable addresses
     */
    function getAllDiceTables() external view returns (address[] memory) {
        return deployedDiceTables;
    }
    
    /**
     * @notice Get the total number of deployed DiceTable contracts
     * @return Count of deployed DiceTable contracts
     */
    function getDiceTableCount() external view returns (uint256) {
        return deployedDiceTables.length;
    }
    
    /**
     * @notice Get the DiceTable contract address for a specific betting token
     * @param bettingToken Address of the ERC20 betting token
     * @return Address of the corresponding DiceTable contract, or address(0) if none exists
     */
    function getDiceTableForBettingToken(address bettingToken) external view returns (address) {
        return tokenToDiceContract[bettingToken];
    }
    
    /**
     * @notice Helper function to get the symbol of an ERC20 token
     * @param tokenAddress Address of the ERC20 token
     * @return Symbol of the token as a string
     */
    function _getTokenSymbol(address tokenAddress) internal view returns (string memory) {
        // Try to get the symbol from the token contract
        (bool success, bytes memory data) = tokenAddress.staticcall(
            abi.encodeWithSignature("symbol()")
        );
        
        // If successful, decode and return the symbol
        if (success && data.length >= 32) {
            return abi.decode(data, (string));
        }
        
        // Return a generic name if symbol retrieval fails
        return "UNKNOWN";
    }
}
DiceTable.sol 387 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

/**
 * @title DiceTable - On-chain Bitcoin-style Dice Gambling with Open House Participation
 * 
 * @notice This contract implements a decentralized gambling game inspired
 * by SatoshiDice.  It functions as both an ERC20 token representing house
 * ownership shares and a betting platform.  Anyone can participate as "the
 * house" by depositing the betting token and receiving DT tokens
 * representing their proportional share of the house funds. House
 * participants earn profits when players lose bets and bear losses when
 * players win. The game uses a provably fair random number generation
 * mechanism based on blockchain hash values with a 2% house edge. Each bet
 * requires two transactions - one to place the bet and another to reveal
 * the outcome. The contract maintains solvency by tracking open
 * liabilities and limiting withdrawals accordingly. Abandoned bets can be
 * cleaned up after 3 months, treating them as house wins to reclaim funds.
 */

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/math/Math.sol";

contract DiceTable is ERC20, ReentrancyGuard {
    // Library usage
    using SafeERC20 for IERC20;
    
    // Constants
    uint256 public constant MAX_NUMBER = 64225;
    uint256 public constant PRECISION = 1e6;
    uint256 public constant HOUSE_EDGE = 20000; // 2% (20000/1000000)
    uint256 public constant BET_EXPIRATION = 90 days; // 3 months
    uint256 public constant CLEANUP_REWARD_PERCENT = 5; // 5% of bet amount
    
    // Token reference
    IERC20 public immutable bettingToken;
    
    // Pool state
    uint256 private _totalFunds;
    
    // Game state
    uint256 public nextBetId;
    uint256 public totalOpenLiability; // Total potential payout of all open bets
    
    // Bet status enum for better clarity
    enum BetStatus { Pending, Revealed, Expired }
    
    // Bet tracking
    struct Bet {
        address bettor;          // User address
        uint256 amount;          // Bet amount
        uint256 luckyNumber;     // User's chosen number (1-64,225)
        uint256 maxPayout;       // Maximum possible payout
        uint256 betBlock;        // Block when bet was placed
        BetStatus status;        // Status of the bet
        bytes32 betBlockHash;    // Hash of the block when bet was placed
        uint256 timestamp;       // Timestamp when bet was created
        uint256 resultNumber;    // Generated random number (0 if not revealed yet)
    }
    
    mapping(uint256 => Bet) public bets;
    
    // Events
    event FundsAdded(address indexed provider, uint256 amount, uint256 tokensIssued);
    event FundsRemoved(address indexed provider, uint256 amount, uint256 tokensBurned);
    event BetPlaced(address indexed bettor, uint256 indexed betId, uint256 luckyNumber, uint256 amount, uint256 maxPayout, uint256 timestamp);
    event BetWon(address indexed bettor, uint256 indexed betId, uint256 randomNumber, uint256 payoutAmount);
    event BetLost(address indexed bettor, uint256 indexed betId, uint256 randomNumber);
    event BetRevealed(uint256 indexed betId, uint256 randomNumber, bool isWin);
    event BetExpired(uint256 indexed betId, address indexed cleaner, uint256 rewardAmount);
    
    constructor(
        address _bettingToken,
        string memory _tokenName,
        string memory _tokenSymbol
    ) ERC20(_tokenName, _tokenSymbol) {
        require(_bettingToken != address(0), "Invalid betting token");
        bettingToken = IERC20(_bettingToken);
    }
    
    //--------------------------------------------------
    // House Funding Functions
    //--------------------------------------------------
    
    // Add funds to the house
    function addHouseFunds(uint256 amount) external nonReentrant returns (uint256) {
        require(amount > 0, "Amount must be positive");
        
        // Store initial balance to verify actual transferred amount
        uint256 initialBalance = bettingToken.balanceOf(address(this));
        
        // Transfer tokens from user to contract using SafeERC20
        bettingToken.safeTransferFrom(msg.sender, address(this), amount);
        
        // Verify actual transferred amount (handles fee-on-transfer tokens)
        uint256 actualAmount = bettingToken.balanceOf(address(this)) - initialBalance;
        require(actualAmount > 0, "No tokens transferred");
        
        uint256 tokensToIssue;
        
        // First depositor gets tokens 1:1
        if (_totalFunds == 0) {
            tokensToIssue = actualAmount;
        } else {
            // Calculate tokens based on share of the pool using Math.mulDiv for precision
            tokensToIssue = Math.mulDiv(actualAmount, totalSupply(), _totalFunds);
        }
        
        // Update total funds
        _totalFunds += actualAmount;
        
        // Mint DT tokens
        _mint(msg.sender, tokensToIssue);
        
        emit FundsAdded(msg.sender, actualAmount, tokensToIssue);
        
        return tokensToIssue;
    }
    
    // Remove funds from the house
    function removeHouseFunds(uint256 diceTokenAmount) external nonReentrant returns (uint256) {
        require(diceTokenAmount > 0, "Amount must be positive");
        require(diceTokenAmount <= balanceOf(msg.sender), "Insufficient DT balance");
        
        // Calculate assets to return using Math.mulDiv for precision
        uint256 amountToReturn = Math.mulDiv(diceTokenAmount, _totalFunds, totalSupply());
        
        // Get available funds (taking open liabilities into account)
        (uint256 availableFunds,) = getHouseLiquidityInfo();
        require(amountToReturn <= availableFunds, "Exceeds available funds due to open bets");
        
        // Update total funds
        _totalFunds -= amountToReturn;
        
        // Burn DT tokens
        _burn(msg.sender, diceTokenAmount);
        
        // Transfer assets to user using SafeERC20
        bettingToken.safeTransfer(msg.sender, amountToReturn);
        
        emit FundsRemoved(msg.sender, amountToReturn, diceTokenAmount);
        
        return amountToReturn;
    }
    
    // Get total funds in the house
    function totalHouseFunds() external view returns (uint256) {
        return _totalFunds;
    }
    
    //--------------------------------------------------
    // Betting Functions
    //--------------------------------------------------
    
    // Calculate payout for a given bet
    function calculatePayout(uint256 luckyNumber, uint256 betAmount) public pure returns (uint256) {
        require(luckyNumber >= 1 && luckyNumber <= MAX_NUMBER, "Invalid lucky number");
        
        // Calculate multiplier with ~2% house edge
        // payout = betAmount * ((1 - house edge) * 65536 / luckyNumber)
        return Math.mulDiv(
            betAmount,
            (PRECISION - HOUSE_EDGE) * 65536,
            luckyNumber * PRECISION
        );
    }
    
    // Get maximum allowed bet size based on house liquidity
    function getMaxBetAmount(uint256 luckyNumber) public view returns (uint256) {
        // Get available house funds (taking open liabilities into account)
        (uint256 availableFunds,) = getHouseLiquidityInfo();
        if (availableFunds == 0) return 0;
        
        // Maximum payout should not exceed 50% of available house funds
        uint256 maxPayoutAllowed = (availableFunds * 50) / 100;
        
        // Solve for max bet such that: payout = calculatePayout(betAmount) <= maxPayoutAllowed
        // Therefore: maxBet = maxPayoutAllowed * luckyNumber / ((1 - house edge) * 65536)
        return Math.mulDiv(
            maxPayoutAllowed,
            luckyNumber * PRECISION,
            (PRECISION - HOUSE_EDGE) * 65536
        );
    }
    
    // Place a bet
    function placeBet(uint256 luckyNumber, uint256 amount) external nonReentrant returns (uint256) {
        require(luckyNumber >= 1 && luckyNumber <= MAX_NUMBER, "Lucky number out of range");
        require(amount > 0, "Bet amount must be greater than zero");
        
        // Calculate potential payout
        uint256 maxPayout = calculatePayout(luckyNumber, amount);
        
        // Check if bet is within max allowed size
        require(amount <= getMaxBetAmount(luckyNumber), "Bet exceeds maximum allowed");
        
        // Store initial balance
        uint256 initialBalance = bettingToken.balanceOf(address(this));
        
        // Transfer betting tokens from bettor to this contract using SafeERC20
        bettingToken.safeTransferFrom(msg.sender, address(this), amount);
        
        // Verify actual transferred amount
        uint256 actualAmount = bettingToken.balanceOf(address(this)) - initialBalance;
        require(actualAmount > 0, "No tokens transferred");
        
        // Recalculate payout with actual amount
        maxPayout = calculatePayout(luckyNumber, actualAmount);
        
        // Store bet details
        uint256 betId;
        unchecked {
            betId = nextBetId++;
        }
        uint256 timestamp = block.timestamp;
        
        bets[betId] = Bet({
            bettor: msg.sender,
            amount: actualAmount,
            luckyNumber: luckyNumber,
            maxPayout: maxPayout,
            betBlock: block.number,
            status: BetStatus.Pending,
            betBlockHash: blockhash(block.number - 1),
            timestamp: timestamp,
            resultNumber: 0 // Initialize result number as 0
        });
        
        // Update total open liability
        totalOpenLiability += maxPayout;
        
        emit BetPlaced(msg.sender, betId, luckyNumber, actualAmount, maxPayout, timestamp);
        
        return betId;
    }
    
    // Reveal a bet outcome
    function revealBet(uint256 betId) external nonReentrant {
        Bet storage bet = bets[betId];
        
        // Validation checks
        require(bet.bettor != address(0), "Bet does not exist");
        require(bet.status == BetStatus.Pending, "Bet already revealed or expired");
        require(block.number > bet.betBlock, "Wait for next block");
        require(bet.betBlockHash != bytes32(0), "Invalid bet block hash");
        
        // Generate random number using XOR of bet block hash and current block hash
        bytes32 revealBlockHash = blockhash(block.number - 1);
        bytes32 combinedHash = bet.betBlockHash ^ revealBlockHash;
        uint256 randomNumber = uint256(combinedHash) % 65536; // Results in number between 0-65535
        
        // Store the random number
        bet.resultNumber = randomNumber;
        
        // Update bet status
        bet.status = BetStatus.Revealed;
        
        // Update total open liability
        totalOpenLiability -= bet.maxPayout;
        
        bool isWin = randomNumber < bet.luckyNumber;
        
        if (isWin) {
            // Bet won - use payout calculation for consistency
            // No need for separate calculateWinnings function
            uint256 payout = bet.maxPayout;
            
            // Send payout to bettor using SafeERC20
            bettingToken.safeTransfer(bet.bettor, payout);
            
            emit BetWon(bet.bettor, betId, randomNumber, payout);
        } else {
            // Bet lost - add to house funds
            _totalFunds += bet.amount;
            
            emit BetLost(bet.bettor, betId, randomNumber);
        }
        
        // Emit the BetRevealed event
        emit BetRevealed(betId, randomNumber, isWin);
    }
    
    // Clean up expired bets (after 3 months)
    function cleanupExpiredBet(uint256 betId) external nonReentrant {
        Bet storage bet = bets[betId];
        
        // Validation checks
        require(bet.bettor != address(0), "Bet does not exist");
        require(bet.status == BetStatus.Pending, "Bet already revealed or expired");
        require(block.timestamp > bet.timestamp + BET_EXPIRATION, "Bet not expired yet");
        
        // Update total open liability
        totalOpenLiability -= bet.maxPayout;
        
        // Calculate reward for cleaner (5% of bet amount)
        uint256 rewardAmount = (bet.amount * CLEANUP_REWARD_PERCENT) / 100;
        
        // Add the rest to house funds
        _totalFunds += (bet.amount - rewardAmount);
        
        // Mark as expired
        bet.status = BetStatus.Expired;
        
        // Set resultNumber to max to clearly indicate it was expired
        bet.resultNumber = 65535;
        
        // Transfer reward to cleaner using SafeERC20
        bettingToken.safeTransfer(msg.sender, rewardAmount);
        
        emit BetExpired(betId, msg.sender, rewardAmount);
    }
    
    //--------------------------------------------------
    // View Functions
    //--------------------------------------------------
    
    // Get house liquidity information
    function getHouseLiquidityInfo() public view returns (uint256 availableFunds, uint256 openLiability) {
        openLiability = totalOpenLiability;
        
        // Available funds is total funds minus open liabilities
        // If open liabilities exceed total funds (should never happen), return 0
        if (_totalFunds > openLiability) {
            availableFunds = _totalFunds - openLiability;
        } else {
            availableFunds = 0;
        }
        
        return (availableFunds, openLiability);
    }
    
    // Get bet details
    function getBetDetails(uint256 betId) external view returns (
        address bettor,
        uint256 amount,
        uint256 luckyNumber,
        uint256 maxPayout,
        uint256 betBlock,
        BetStatus status,
        bytes32 betBlockHash,
        uint256 timestamp,
        bool isExpired,
        uint256 resultNumber
    ) {
        Bet storage bet = bets[betId];
        return (
            bet.bettor,
            bet.amount,
            bet.luckyNumber,
            bet.maxPayout,
            bet.betBlock,
            bet.status,
            bet.betBlockHash,
            bet.timestamp,
            block.timestamp > bet.timestamp + BET_EXPIRATION,
            bet.resultNumber
        );
    }
    
    // Check if a bet can be revealed
    function canReveal(uint256 betId) external view returns (bool) {
        Bet storage bet = bets[betId];
        return (
            bet.bettor != address(0) &&
            bet.status == BetStatus.Pending &&
            block.number > bet.betBlock &&
            bet.betBlockHash != bytes32(0)
        );
    }
    
    // Check if a bet is expired
    function isBetExpired(uint256 betId) external view returns (bool) {
        Bet storage bet = bets[betId];
        return (
            bet.bettor != address(0) &&
            bet.status == BetStatus.Pending &&
            block.timestamp > bet.timestamp + BET_EXPIRATION
        );
    }
    
    // Get betting token address
    function getBettingTokenAddress() external view returns (address) {
        return address(bettingToken);
    }
}

Read Contract

NAME_PREFIX 0x7f7c4746 → string
SYMBOL_PREFIX 0x631c2bb8 → string
deployedDiceTables 0xe7bbb871 → address
getAllDiceTables 0x18b02b37 → address[]
getDiceTableCount 0x96347c25 → uint256
getDiceTableForBettingToken 0x2dd15992 → address
tokenToDiceContract 0x6521d89e → address

Write Contract 1 functions

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

deployDiceTable 0x52dfe571
address bettingToken
returns: address

Recent Transactions

No transactions found for this address