Address Contract Verified
Address
0xF15E150a8d4685B6466B2d07b644635cCFcA8b11
Balance
0 ETH
Nonce
1
Code Size
17872 bytes
Creator
0xD783CA0c...3279 at tx 0xef260fbd...4742fa
Indexed Transactions
0
Contract Bytecode
17872 bytes
0x608060405234801561000f575f5ffd5b506004361061029d575f3560e01c806375151b6311610171578063aed1d403116100d2578063f0d2d5a811610088578063f45346dc1161006e578063f45346dc14610721578063f4f54e3714610734578063feafed8414610747575f5ffd5b8063f0d2d5a8146106fb578063f2fde38b1461070e575f5ffd5b8063cf331250116100b8578063cf331250146106c0578063cf79c989146106d5578063d353d024146106e8575f5ffd5b8063aed1d40314610690578063c47ecab014610699575f5ffd5b80638da5cb5b1161012757806396a9a2851161010d57806396a9a2851461064d5780639dbf5eca14610674578063a5bbe22b14610687575f5ffd5b80638da5cb5b1461061c5780639688cc241461063a575f5ffd5b80637c1ced04116101575780637c1ced04146105b85780637d98ce0f146105da57806384b0196e14610601575f5ffd5b806375151b631461055957806379d5817f14610591575f5ffd5b806335fc92661161021b5780635a125c29116101d157806361b786a1116101b757806361b786a11461052b578063688ca81f1461053e578063715018a614610551575f5ffd5b80635a125c29146104e95780635c975abb14610521575f5ffd5b80634e6fd6c4116102015780634e6fd6c41461046b57806351858e2714610499578063541d5548146104a1575f5ffd5b806335fc926614610450578063449d3dd914610458575f5ffd5b806313d5e886116102705780631f79a60e116102565780631f79a60e146103ef57806323479d7c14610416578063261cfe6d14610429575f5ffd5b806313d5e886146103165780631a85d0a1146103dc575f5ffd5b806306dd6ff3146102a15780630928d152146102b65780630958022b146102c95780630d5ee32014610303575b5f5ffd5b6102b46102af366004613814565b61076e565b005b6102b46102c436600461386a565b610980565b6102f07f1939a259fb96616fa125012981232fcc8799d907fbe8fbafffd5472478c09c0d81565b6040519081526020015b60405180910390f35b6102b4610311366004613881565b610bc4565b6103cf61032436600461386a565b6040805160c0810182525f80825260208201819052918101829052606081018290526080810182905260a0810191909152505f908152600d6020908152604091829020825160c081018452815473ffffffffffffffffffffffffffffffffffffffff90811682526001830154811693820193909352600282015490921692820192909252600382015460608201526004820154608082015260059091015460ff16151560a082015290565b6040516102fa91906138a1565b6102b46103ea366004613937565b610caa565b6102f07f66c1e7aae58e4f07326ef663360514595ee08bd1274194d92d8d84907a09e0ea81565b6102b461042436600461399b565b610e39565b6102f07f0f0a80b21a2e8a336c42bc767d11e4a03e6e257eba375073bee7662765b3842681565b6007546102f0565b6102b46104663660046139d3565b61136b565b61047461dead81565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016102fa565b6102b4611457565b6104d96104af366004613881565b73ffffffffffffffffffffffffffffffffffffffff165f908152600a602052604090205460ff1690565b60405190151581526020016102fa565b6104d96104f7366004613881565b73ffffffffffffffffffffffffffffffffffffffff165f908152600b602052604090205460ff1690565b5f5460ff166104d9565b6102b46105393660046139ec565b6114ea565b6102b461054c366004613a84565b6119e0565b6102b4611b46565b6104d9610567366004613881565b73ffffffffffffffffffffffffffffffffffffffff165f908152600c602052604090205460ff1690565b6102f07f5e84e691fcc0b919f64f7295e0668206df31dace73b2d1969eb23366f165ed8281565b6104d96105c636600461386a565b5f908152600e602052604090205460ff1690565b6102f07f6dfa30102af85922f83a0f4c9d698992cfaef9ad65036e728bf90be0f82d21c481565b610609611b59565b6040516102fa9796959493929190613b18565b60045473ffffffffffffffffffffffffffffffffffffffff16610474565b6102b461064836600461386a565b611bb7565b6102f07fe907aac968608fb9b634130b5cb04473644489b158d9ab6f235523d5bfc2c18981565b6102b4610682366004613bd7565b611eec565b6102f061038481565b6102f060055481565b6102f07fd76f420c9e59ec76d3acf37d5e755af76c8d25e863d94627ca40d02335e6de5681565b6106c8611f81565b6040516102fa9190613c8a565b6102b46106e3366004613c9c565b612013565b6102b46106f6366004613cd3565b6123e8565b6102b4610709366004613881565b612428565b6102b461071c366004613881565b6124b9565b6102b461072f366004613d12565b612519565b6102b4610742366004613cd3565b612637565b6102f07f6d17e0a0373d74d607de53ea434e95402ca032e126fe5314754d766b469d775a81565b61077661266b565b5f818152600e602052604090205460ff16156107be576040517f68b1b0ae00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f818152600e6020908152604080832080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016600117905573ffffffffffffffffffffffffffffffffffffffff87168352600c90915290205460ff16610874576040517fe35d9dd500000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff851660048201524660248201526044015b60405180910390fd5b604080517fd76f420c9e59ec76d3acf37d5e755af76c8d25e863d94627ca40d02335e6de56602082015273ffffffffffffffffffffffffffffffffffffffff861691810191909152606081018290525f906108e8906080015b604051602081830303815290604052805190602001206126be565b90506108f68185855f61270b565b73ffffffffffffffffffffffffffffffffffffffff85165f818152600c602090815260409182902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00169055815192835246908301527f12c7466676da8453fdc8fb091f1a24d31919043a79a50ebe022867a5f5c1ed34910160405180910390a15050505050565b610988612a4d565b335f908152600a602052604090205460ff166109d0576040517f9e96785e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6109d8612a89565b5f818152600d60209081526040808320815160c081018352815473ffffffffffffffffffffffffffffffffffffffff908116825260018301548116948201949094526002820154909316918301919091526003810154606083015260048101546080830181905260059091015460ff16151560a0830152909103610a8b576040517feec377ad0000000000000000000000000000000000000000000000000000000081526004810183905260240161086b565b8060a0015115610aca576040517fba06041f0000000000000000000000000000000000000000000000000000000081526004810183905260240161086b565b610384816080015142610add9190613d78565b1015610b375781816080015142610af49190613d78565b6040517fbe3c1a8c00000000000000000000000000000000000000000000000000000000815260048101929092526024820152610384604482015260640161086b565b5f828152600d6020908152604080832060040192909255820151606083015191830151610b7d9273ffffffffffffffffffffffffffffffffffffffff9091169190612acc565b817fa8e281f4e5673285dc43009bf03659cf78f9b649a03b3d00a6fc6a7a913806d046604051610baf91815260200190565b60405180910390a250610bc160018055565b50565b610bcc61266b565b73ffffffffffffffffffffffffffffffffffffffff8116610c19576040517fef24cd7000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6008805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681179093556040805191909216808252602082019390935246918101919091527f94ffa6f841cb34599ad17e17526f2227277350e0260433fb3af63e7ec70a1bd4906060015b60405180910390a15050565b610cb261266b565b5f818152600e602052604090205460ff1615610cfa576040517fef0cae5f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f818152600e6020908152604080832080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016600117905580517f5e84e691fcc0b919f64f7295e0668206df31dace73b2d1969eb23366f165ed829281019290925273ffffffffffffffffffffffffffffffffffffffff881690820152851515606082015260808101839052610d939060a0016108cd565b9050610da18185855f61270b565b73ffffffffffffffffffffffffffffffffffffffff86165f818152600b602090815260409182902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001689151590811790915582519384529083015246908201527f3c01378166fbf18a93aa15165684eff707b2cb84722c884553127705e87cd6609060600160405180910390a1505050505050565b335f908152600a602052604090205460ff16610e81576040517f9e96785e00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b610e89612a89565b610e97610140820182613d8b565b15905080610eb55750600554610eb1610140830183613d8b565b9050115b15610eec576040517f50cc7e8100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b8060a00135421115610f2a576040517f885addea00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60c08101355f908152600e602052604090205460ff1615610f77576040517f95a399bc00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60c08101355f908152600e602052604080822080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00166001179055600c9190610fc79060608501908501613881565b73ffffffffffffffffffffffffffffffffffffffff16815260208101919091526040015f205460ff1661104f576110046060820160408301613881565b6040517f6c383f7200000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff909116600482015260240161086b565b5f6111197f0f0a80b21a2e8a336c42bc767d11e4a03e6e257eba375073bee7662765b384266110816020850185613881565b6110916040860160208701613881565b6110a16060870160408801613881565b866060013587608001358860a001358960c001356040516020016108cd98979695949392919097885273ffffffffffffffffffffffffffffffffffffffff96871660208901529486166040880152929094166060860152608085015260a084019290925260c083019190915260e08201526101000190565b90506111348161112d610140850185613d8b565b600161270b565b6008546111839073ffffffffffffffffffffffffffffffffffffffff1660608401356111666040860160208701613881565b73ffffffffffffffffffffffffffffffffffffffff169190612b27565b6008546040517f0c92d95300000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff90911690630c92d953906111d9908590600401613f78565b6020604051808303815f875af1925050508015611231575060408051601f3d9081017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016820190925261122e918101906140f6565b60015b6112cd576112426020830183613881565b73ffffffffffffffffffffffffffffffffffffffff166112686040840160208501613881565b604080515f815260016020820181905281830152466060820152905173ffffffffffffffffffffffffffffffffffffffff92909216917ffe8e2a21569ee647f381da2103c8f4826e7cc9be6bc4b23dbc69e837707b9b379181900360800190a3611361565b6112da6020840184613881565b73ffffffffffffffffffffffffffffffffffffffff166113006040850160208601613881565b60408051848152600160208201525f81830152466060820152905173ffffffffffffffffffffffffffffffffffffffff92909216917ffe8e2a21569ee647f381da2103c8f4826e7cc9be6bc4b23dbc69e837707b9b379181900360800190a3505b50610bc160018055565b611373612a89565b600c5f6113866040840160208501613881565b73ffffffffffffffffffffffffffffffffffffffff16815260208101919091526040015f205460ff1661140e576113c36040820160208301613881565b6040517f31ce22ff00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff909116600482015260240161086b565b61141781612b9f565b61144e6114276020830183613881565b6114346020840184613881565b6114446040850160208601613881565b8460400135612ca0565b610bc160018055565b61145f612a4d565b335f908152600b602052604090205460ff166114a7576040517f2fe2d31100000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6114af612d32565b604080513381524660208201527f2e31b3b12b9bb0e82c32f27df5f234fabc95a374f54fd287a7132878d5dc9fc391015b60405180910390a1565b6114f2612a4d565b6114fa61266b565b801580611508575060055481115b1561153f576040517fab4d203500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f61154c848601866141d5565b80515f908152600e602052604090205490915060ff1615611599576040517f71f77a5a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b80515f908152600e60209081526040822080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011790558201518251909190611629907fe907aac968608fb9b634130b5cb04473644489b158d9ab6f235523d5bfc2c1899061160a85612db1565b60408051602081019490945283019190915260608201526080016108cd565b90506116378186865f61270b565b6020830151515f90815b81811015611680578560200151818151811061165f5761165f614302565b60200260200101516040015183611676919061432f565b9250600101611641565b506005545f5b818110156117b7575f600b5f600984815481106116a5576116a5614302565b5f91825260208083206003929092029091015473ffffffffffffffffffffffffffffffffffffffff168352820192909252604001812080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00169215159290921790915560098054600f9183918590811061172257611722614302565b5f918252602080832060039092029091015473ffffffffffffffffffffffffffffffffffffffff16835282019290925260400181209190915560098054600f9183918590811061177457611774614302565b5f9182526020808320600160039093020182015473ffffffffffffffffffffffffffffffffffffffff168452830193909352604090910190209190915501611686565b506117c360095f61373d565b5f5b828110156119895760098682815181106117e1576117e1614302565b6020908102919091018101518254600180820185555f948552838520835160039093020180547fffffffffffffffffffffffff000000000000000000000000000000000000000090811673ffffffffffffffffffffffffffffffffffffffff94851617825594840151818301805490961693169290921790935560409091015160029091015587519091600b9189908590811061188057611880614302565b6020908102919091018101515173ffffffffffffffffffffffffffffffffffffffff1682528101919091526040015f2080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00169115159190911790556118e881600161432f565b600f5f8884815181106118fd576118fd614302565b6020908102919091018101515173ffffffffffffffffffffffffffffffffffffffff1682528101919091526040015f205561193981600161432f565b600f5f88848151811061194e5761194e614302565b60209081029190910181015181015173ffffffffffffffffffffffffffffffffffffffff1682528101919091526040015f20556001016117c5565b506005829055600783905585516040517f355d5bd99d5c02bfb078295b38190e74054fbefad96f1dd62d74469f3e41f0b8916119cc918890869088904690614342565b60405180910390a150505050505050505050565b6119e861266b565b6119f0612f29565b8115806119fe575060055482115b15611a35576040517fab4d203500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f818152600e602052604090205460ff1615611a7d576040517f71f77a5a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f818152600e6020908152604080832080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016600117905551611af2916108cd917f1939a259fb96616fa125012981232fcc8799d907fbe8fbafffd5472478c09c0d91869101918252602082015260400190565b9050611b008185855f61270b565b611b08612f64565b604080518381524660208201527f2182c29d99305e6939904665fd31aa9b3a026199483be33457f2b5d25470355e910160405180910390a150505050565b611b4e61266b565b611b575f612fba565b565b5f6060805f5f5f6060611b6a613030565b611b72613062565b604080515f808252602082019092527f0f000000000000000000000000000000000000000000000000000000000000009b939a50919850469750309650945092509050565b335f908152600b602052604090205460ff16611bff576040517f5bb12b5a00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5f818152600d60209081526040808320815160c081018352815473ffffffffffffffffffffffffffffffffffffffff908116825260018301548116948201949094526002820154909316918301919091526003810154606083015260048101546080830181905260059091015460ff16151560a0830152909103611cb8576040517fb2d18eb50000000000000000000000000000000000000000000000000000000081526004810183905246602482015260440161086b565b8060a0015115611cfd576040517f7104dcfb0000000000000000000000000000000000000000000000000000000081526004810183905246602482015260440161086b565b610384816080015142611d109190613d78565b10611d6f5781816080015142611d269190613d78565b6040517f87aa77ec00000000000000000000000000000000000000000000000000000000815260048101929092526024820152610384604482015246606482015260840161086b565b600160a082018181525f848152600d6020908152604091829020855181547fffffffffffffffffffffffff000000000000000000000000000000000000000090811673ffffffffffffffffffffffffffffffffffffffff92831617835592870151958201805484169682169690961790955582860151600282018054909316951694909417905560608401516003840155608084015160048401559051600590920180547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001692151592909217909155517f45d6486b1bf9f9155b061da2bd7ce37ed3fc2f9edb01dfde92bfda07dda723dd90611e7190849084904690614377565b60405180910390a1805160408083015160608085015183519081525f6020820181905293810193909352469083015273ffffffffffffffffffffffffffffffffffffffff9283169216907ffe8e2a21569ee647f381da2103c8f4826e7cc9be6bc4b23dbc69e837707b9b379060800160405180910390a35050565b611ef461266b565b73ffffffffffffffffffffffffffffffffffffffff82165f818152600a602090815260409182902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001685151590811790915582519384529083015246908201527fd14ff192ad92f9a8588f2a2d3ad652363466e2688bd2e66cb826ff40897219c390606001610c9e565b60606009805480602002602001604051908101604052809291908181526020015f905b8282101561200a575f8481526020908190206040805160608101825260038602909201805473ffffffffffffffffffffffffffffffffffffffff908116845260018083015490911684860152600290910154918301919091529083529092019101611fa4565b50505050905090565b61201b612a4d565b61202860a0820182613d8b565b15905080612045575060055461204160a0830183613d8b565b9050115b1561207c576040517fe3fd70dc00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60808101355f908152600e602052604090205460ff16156120c9576040517f12b70a4500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60808101355f908152600e60209081526040822080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011790556121b0907f66c1e7aae58e4f07326ef663360514595ee08bd1274194d92d8d84907a09e0ea9061213890850185613881565b6121486040860160208701613881565b6121586060870160408801613881565b60408051602081019590955273ffffffffffffffffffffffffffffffffffffffff9384169085015290821660608481019190915291166080838101919091529085013560a083015284013560c082015260e0016108cd565b90506121c38161112d60a0850185613d8b565b6040805160c08101909152806121dc6020850185613881565b73ffffffffffffffffffffffffffffffffffffffff16815260200183602001602081019061220a9190613881565b73ffffffffffffffffffffffffffffffffffffffff1681526020016122356060850160408601613881565b73ffffffffffffffffffffffffffffffffffffffff908116825260608581018035602080860191909152426040808701919091525f9584018690526080808a01358752600d835295819020875181547fffffffffffffffffffffffff00000000000000000000000000000000000000009081169188169190911782559288015160018201805485169188169190911790558782015160028201805490941696169590951790915591850151600384015592840151600483015560a090930151600590910180547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016911515919091179055612331918401613881565b73ffffffffffffffffffffffffffffffffffffffff166123576040840160208501613881565b73ffffffffffffffffffffffffffffffffffffffff1661237a6020850185613881565b73ffffffffffffffffffffffffffffffffffffffff167f6bf57e67a4a8059c7f18c1ef2f99a7e84a37c2201942818890c7328064411fd285606001358660800135466040516123dc939291909283526020830191909152604082015260600190565b60405180910390a45050565b805f5b818110156124225761241a84848381811061240857612408614302565b90506020028101906106e39190614413565b6001016123eb565b50505050565b61243061266b565b73ffffffffffffffffffffffffffffffffffffffff81165f818152600c602090815260409182902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00166001179055815192835246908301527f7dba1be544024070cd5eebfa8bdd80a8b198cea8058c7d3cc1f8dd36e41ab2f7910160405180910390a150565b6124c161266b565b73ffffffffffffffffffffffffffffffffffffffff8116612510576040517f1e4fbdf70000000000000000000000000000000000000000000000000000000081525f600482015260240161086b565b610bc181612fba565b612521612a89565b73ffffffffffffffffffffffffffffffffffffffff83165f908152600c602052604090205460ff16612597576040517f31ce22ff00000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8416600482015260240161086b565b815f036125d0576040517f4a4cfa8900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b73ffffffffffffffffffffffffffffffffffffffff811661261d576040517f05cf38da00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61262933828585612ca0565b61263260018055565b505050565b805f5b818110156124225761266384848381811061265757612657614302565b90506020020135610980565b60010161263a565b60045473ffffffffffffffffffffffffffffffffffffffff163314611b57576040517f118cdaa700000000000000000000000000000000000000000000000000000000815233600482015260240161086b565b5f6127056126ca61308f565b836040517f19010000000000000000000000000000000000000000000000000000000000008152600281019290925260228201526042902090565b92915050565b8180158061271a575060055481115b15612751576040517fb680ac4900000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6005545f90819067ffffffffffffffff8111156127705761277061410d565b604051908082528060200260200182016040528015612799578160200160208202803683370190505b5090505f5b83811015612a06578686828181106127b8576127b8614302565b90506020028101906127ca919061444f565b90506041146127db5760010161279e565b5f61283d898989858181106127f2576127f2614302565b9050602002810190612804919061444f565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f920191909152506131c592505050565b905073ffffffffffffffffffffffffffffffffffffffff8116612863575060010161279e565b73ffffffffffffffffffffffffffffffffffffffff81165f908152600f6020526040902054801580159061289957506005548111155b156129fc575f6128aa600183613d78565b90505f600982815481106128c0576128c0614302565b5f9182526020808320604080516060810182526003909402909101805473ffffffffffffffffffffffffffffffffffffffff9081168552600182015416928401929092526002909101549082015291508961294d57816020015173ffffffffffffffffffffffffffffffffffffffff168573ffffffffffffffffffffffffffffffffffffffff161461296b565b815173ffffffffffffffffffffffffffffffffffffffff8681169116145b9050808015612991575086838151811061298757612987614302565b6020026020010151155b156129f85760018784815181106129aa576129aa614302565b9115156020928302919091019091015260408201516129c9908961432f565b975060075460026129da91906144b0565b6129e58960036144b0565b106129f857505050505050505050612422565b5050505b505060010161279e565b506007546040517f6796134400000000000000000000000000000000000000000000000000000000815260048101849052602481019190915246604482015260640161086b565b5f5460ff1615611b57576040517fd93c066500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600260015403612ac5576040517f3ee5aeb500000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6002600155565b612ad983838360016131ed565b612632576040517f5274afe700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8416600482015260240161086b565b612b338383835f613275565b61263257612b4483835f6001613275565b612b92576040517f5274afe700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8416600482015260240161086b565b612ad98383836001613275565b612baf6040820160208301613881565b73ffffffffffffffffffffffffffffffffffffffff1663d505accf612bd76020840184613881565b3060408501356060860135612bf260a08801608089016144c7565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e088901b16815273ffffffffffffffffffffffffffffffffffffffff95861660048201529490931660248501526044840191909152606483015260ff16608482015260a084013560a482015260c084013560c482015260e4015f604051808303815f87803b158015612c87575f5ffd5b505af1925050508015612c98575060015b15610bc15750565b612ca8612a4d565b612cca73ffffffffffffffffffffffffffffffffffffffff83168530846132e5565b604080518281525f6020820181905281830152466060820152905173ffffffffffffffffffffffffffffffffffffffff85811692908516917ffe8e2a21569ee647f381da2103c8f4826e7cc9be6bc4b23dbc69e837707b9b379181900360800190a350505050565b612d3a612a4d565b5f80547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612d8c3390565b60405173ffffffffffffffffffffffffffffffffffffffff90911681526020016114e0565b5f5f825167ffffffffffffffff811115612dcd57612dcd61410d565b604051908082528060200260200182016040528015612df6578160200160208202803683370190505b5090505f5b8351811015612ef9577f6d17e0a0373d74d607de53ea434e95402ca032e126fe5314754d766b469d775a848281518110612e3757612e37614302565b60200260200101515f0151858381518110612e5457612e54614302565b602002602001015160200151868481518110612e7257612e72614302565b602002602001015160400151604051602001612ebe949392919093845273ffffffffffffffffffffffffffffffffffffffff928316602085015291166040830152606082015260800190565b60405160208183030381529060405280519060200120828281518110612ee657612ee6614302565b6020908102919091010152600101612dfb565b5080604051602001612f0b91906144e7565b60405160208183030381529060405280519060200120915050919050565b5f5460ff16611b57576040517f8dfc202b00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b612f6c612f29565b5f80547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff001690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa33612d8c565b6004805473ffffffffffffffffffffffffffffffffffffffff8381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b606061305d7f42726964676500000000000000000000000000000000000000000000000000066002613341565b905090565b606061305d7f31000000000000000000000000000000000000000000000000000000000000016003613341565b5f3073ffffffffffffffffffffffffffffffffffffffff7f000000000000000000000000f15e150a8d4685b6466b2d07b644635ccfca8b11161480156130f457507f000000000000000000000000000000000000000000000000000000000000000146145b1561311e57507f6ab38e421cc3ba3e736d127955c6088aa8f87b6b58e8e24d24743bc69a61bbc490565b61305d604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527f7aa5ae620294318af92bf4e2b2a729646c932a80312a5fa630da993a2ef5cc10918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b5f5f5f5f6131d386866133ea565b9250925092506131e38282613433565b5090949350505050565b6040517fa9059cbb000000000000000000000000000000000000000000000000000000005f81815273ffffffffffffffffffffffffffffffffffffffff8616600452602485905291602083604481808b5af1925060015f5114831661326957838315161561325d573d5f823e3d81fd5b5f873b113d1516831692505b60405250949350505050565b6040517f095ea7b3000000000000000000000000000000000000000000000000000000005f81815273ffffffffffffffffffffffffffffffffffffffff8616600452602485905291602083604481808b5af1925060015f5114831661326957838315161561325d573d5f823e3d81fd5b6132f384848484600161353a565b612422576040517f5274afe700000000000000000000000000000000000000000000000000000000815273ffffffffffffffffffffffffffffffffffffffff8516600482015260240161086b565b606060ff831461335b57613354836135cd565b9050612705565b8180546133679061451c565b80601f01602080910402602001604051908101604052809291908181526020018280546133939061451c565b80156133de5780601f106133b5576101008083540402835291602001916133de565b820191905f5260205f20905b8154815290600101906020018083116133c157829003601f168201915b50505050509050612705565b5f5f5f8351604103613421576020840151604085015160608601515f1a6134138882858561360a565b95509550955050505061342c565b505081515f91506002905b9250925092565b5f8260038111156134465761344661456d565b0361344f575050565b60018260038111156134635761346361456d565b0361349a576040517ff645eedf00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60028260038111156134ae576134ae61456d565b036134e8576040517ffce698f70000000000000000000000000000000000000000000000000000000081526004810182905260240161086b565b60038260038111156134fc576134fc61456d565b03613536576040517fd78bce0c0000000000000000000000000000000000000000000000000000000081526004810182905260240161086b565b5050565b6040517f23b872dd000000000000000000000000000000000000000000000000000000005f81815273ffffffffffffffffffffffffffffffffffffffff8781166004528616602452604485905291602083606481808c5af1925060015f511483166135bc5783831516156135b0573d5f823e3d81fd5b5f883b113d1516831692505b604052505f60605295945050505050565b60605f6135d9836136fd565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561364357505f915060039050826136f3565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa158015613694573d5f5f3e3d5ffd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015191505073ffffffffffffffffffffffffffffffffffffffff81166136ea57505f9250600191508290506136f3565b92505f91508190505b9450945094915050565b5f60ff8216601f811115612705576040517fb3512b0c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b5080545f8255600302905f5260205f2090810190610bc191905b808211156137a05780547fffffffffffffffffffffffff0000000000000000000000000000000000000000908116825560018201805490911690555f6002820155600301613757565b5090565b803573ffffffffffffffffffffffffffffffffffffffff811681146137c7575f5ffd5b919050565b5f5f83601f8401126137dc575f5ffd5b50813567ffffffffffffffff8111156137f3575f5ffd5b6020830191508360208260051b850101111561380d575f5ffd5b9250929050565b5f5f5f5f60608587031215613827575f5ffd5b613830856137a4565b9350602085013567ffffffffffffffff81111561384b575f5ffd5b613857878288016137cc565b9598909750949560400135949350505050565b5f6020828403121561387a575f5ffd5b5035919050565b5f60208284031215613891575f5ffd5b61389a826137a4565b9392505050565b60c08101612705828473ffffffffffffffffffffffffffffffffffffffff815116825273ffffffffffffffffffffffffffffffffffffffff602082015116602083015273ffffffffffffffffffffffffffffffffffffffff6040820151166040830152606081015160608301526080810151608083015260a0810151151560a08301525050565b803580151581146137c7575f5ffd5b5f5f5f5f5f6080868803121561394b575f5ffd5b613954866137a4565b945061396260208701613928565b9350604086013567ffffffffffffffff81111561397d575f5ffd5b613989888289016137cc565b96999598509660600135949350505050565b5f602082840312156139ab575f5ffd5b813567ffffffffffffffff8111156139c1575f5ffd5b8201610160818503121561389a575f5ffd5b5f60e08284031280156139e4575f5ffd5b509092915050565b5f5f5f5f604085870312156139ff575f5ffd5b843567ffffffffffffffff811115613a15575f5ffd5b8501601f81018713613a25575f5ffd5b803567ffffffffffffffff811115613a3b575f5ffd5b876020828401011115613a4c575f5ffd5b60209182019550935085013567ffffffffffffffff811115613a6c575f5ffd5b613a78878288016137cc565b95989497509550505050565b5f5f5f60408486031215613a96575f5ffd5b833567ffffffffffffffff811115613aac575f5ffd5b613ab8868287016137cc565b909790965060209590950135949350505050565b5f81518084528060208401602086015e5f6020828601015260207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f83011685010191505092915050565b7fff000000000000000000000000000000000000000000000000000000000000008816815260e060208201525f613b5260e0830189613acc565b8281036040840152613b648189613acc565b6060840188905273ffffffffffffffffffffffffffffffffffffffff8716608085015260a0840186905283810360c0850152845180825260208087019350909101905f5b81811015613bc6578351835260209384019390920191600101613ba8565b50909b9a5050505050505050505050565b5f5f60408385031215613be8575f5ffd5b613bf1836137a4565b9150613bff60208401613928565b90509250929050565b5f8151808452602084019350602083015f5b82811015613c8057815173ffffffffffffffffffffffffffffffffffffffff815116875273ffffffffffffffffffffffffffffffffffffffff60208201511660208801526040810151604088015250606086019550602082019150600181019050613c1a565b5093949350505050565b602081525f61389a6020830184613c08565b5f60208284031215613cac575f5ffd5b813567ffffffffffffffff811115613cc2575f5ffd5b820160c0818503121561389a575f5ffd5b5f5f60208385031215613ce4575f5ffd5b823567ffffffffffffffff811115613cfa575f5ffd5b613d06858286016137cc565b90969095509350505050565b5f5f5f60608486031215613d24575f5ffd5b613d2d846137a4565b925060208401359150613d42604085016137a4565b90509250925092565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b8181038181111561270557612705613d4b565b5f5f83357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1843603018112613dbe575f5ffd5b83018035915067ffffffffffffffff821115613dd8575f5ffd5b6020019150600581901b360382131561380d575f5ffd5b5f5f83357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1843603018112613e22575f5ffd5b830160208101925035905067ffffffffffffffff811115613e41575f5ffd5b80360382131561380d575f5ffd5b81835281816020850137505f602082840101525f60207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f840116840101905092915050565b5f5f83357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1843603018112613ec9575f5ffd5b830160208101925035905067ffffffffffffffff811115613ee8575f5ffd5b8060051b360382131561380d575f5ffd5b5f8383855260208501945060208460051b820101835f5b86811015613f6c577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0848403018852613f498287613def565b613f54858284613e4f565b60209a8b019a90955093909301925050600101613f10565b50909695505050505050565b60208152613fa660208201613f8c846137a4565b73ffffffffffffffffffffffffffffffffffffffff169052565b5f613fb3602084016137a4565b73ffffffffffffffffffffffffffffffffffffffff8116604084015250613fdc604084016137a4565b73ffffffffffffffffffffffffffffffffffffffff8116606084015250606083013560808381019190915283013560a08084019190915283013560c08084019190915283013560e0808401919091526140369084016137a4565b73ffffffffffffffffffffffffffffffffffffffff81166101008401525061406161010084016137a4565b73ffffffffffffffffffffffffffffffffffffffff81166101208401525061408d610120840184613def565b6101606101408501526140a561018085018284613e4f565b9150506140b6610140850185613e96565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0858403016101608601526140ec838284613ef9565b9695505050505050565b5f60208284031215614106575f5ffd5b5051919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b6040805190810167ffffffffffffffff8111828210171561415d5761415d61410d565b60405290565b6040516060810167ffffffffffffffff8111828210171561415d5761415d61410d565b604051601f82017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe016810167ffffffffffffffff811182821017156141cd576141cd61410d565b604052919050565b5f602082840312156141e5575f5ffd5b813567ffffffffffffffff8111156141fb575f5ffd5b82016040818503121561420c575f5ffd5b61421461413a565b81358152602082013567ffffffffffffffff811115614231575f5ffd5b80830192505084601f830112614245575f5ffd5b813567ffffffffffffffff81111561425f5761425f61410d565b61426e60208260051b01614186565b8082825260208201915060206060840286010192508783111561428f575f5ffd5b6020850194505b828510156142f257606085890312156142ad575f5ffd5b6142b5614163565b6142be866137a4565b81526142cc602087016137a4565b602082810191909152604087810135908301529083526060909501949190910190614296565b6020840152509095945050505050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b8082018082111561270557612705613d4b565b85815260a060208201525f61435a60a0830187613c08565b604083019590955250606081019290925260809091015292915050565b8381526101008101614405602083018573ffffffffffffffffffffffffffffffffffffffff815116825273ffffffffffffffffffffffffffffffffffffffff602082015116602083015273ffffffffffffffffffffffffffffffffffffffff6040820151166040830152606081015160608301526080810151608083015260a0810151151560a08301525050565b8260e0830152949350505050565b5f82357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff41833603018112614445575f5ffd5b9190910192915050565b5f5f83357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1843603018112614482575f5ffd5b83018035915067ffffffffffffffff82111561449c575f5ffd5b60200191503681900382131561380d575f5ffd5b808202811582820484141761270557612705613d4b565b5f602082840312156144d7575f5ffd5b813560ff8116811461389a575f5ffd5b81515f90829060208501835b828110156145115781518452602093840193909101906001016144f3565b509195945050505050565b600181811c9082168061453057607f821691505b602082108103614567577f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b50919050565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffdfea26469706673582212201d74f1c9ebaaf9d642d854dc670d86f9b8965b565f5a9de09cafac0d84a3220164736f6c634300081e0033
Verified Source Code Full Match
Compiler: v0.8.30+commit.73712a01
EVM: prague
Optimization: Yes (1000000000 runs)
Bridge.sol 931 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.30;
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";
import {ECDSA} from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import {EIP712} from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import {Ownable} from '@openzeppelin/contracts/access/Ownable.sol';
import {IBridge} from "./IBridge.sol";
import {ISpotSwap} from "./interfaces/ISpotSwap.sol";
/**
* @title Bridge
* @notice A cross-chain bridge contract that enables secure token deposits and withdrawals
* @dev This contract implements a multi-signature validation system with signer/hot and verifier/cold validator addresses,
* dispute mechanisms, emergency pause functionality, and EIP-712 compliant signature verification.
*
* Key Features:
* - Multi-signature validator system with weighted voting
* - Dispute period for withdrawal requests to allow challenge mechanisms
* - Emergency pause/unpause functionality for security incidents
* - Support for EIP-2612 permit functionality for gasless token approvals
* - Batch operations for gas efficiency
* - Segregated validator roles (signer/hot addresses for normal operations, verifier/cold for critical updates)
*/
contract Bridge is IBridge, Pausable, ReentrancyGuard, EIP712, Ownable {
using SafeERC20 for IERC20;
// ============ Constants ============
/// @notice Time period during which withdrawal requests can be disputed
uint256 public constant DISPUTE_PERIOD = 15 minutes;
address public constant DEAD_ADDRESS =
0x000000000000000000000000000000000000dEaD;
/// @notice EIP-712 type hash for withdrawal requests
bytes32 public constant WITHDRAWAL_TYPE_HASH =
keccak256(
"RequestWithdrawal(address user,address destination,address token,uint256 amount,uint256 nonce)"
);
/// @notice EIP-712 type hash for swap requests
bytes32 public constant SWAP_TYPE_HASH =
keccak256(
"Swap(address account,address tokenIn,address tokenOut,uint256 amountIn,uint256 amountOutMin,uint256 deadline,uint256 nonce)"
);
/// @notice EIP-712 type hash for validator set updates
bytes32 public constant VALIDATOR_UPDATE_TYPE_HASH =
keccak256(
"RequestValidatorUpdate(uint256 nonce,Validator[] validators)Validator(address hAddress,address cAddress,uint256 w)"
);
/// @notice EIP-712 type hash for individual validator struct
bytes32 public constant VALIDATOR_STRUCT_TYPE_HASH =
keccak256("Validator(address hAddress,address cAddress,uint256 w)");
/// @notice EIP-712 type hash for emergency pause requests
bytes32 public constant EMERGENCY_PAUSE_TYPE_HASH =
keccak256("EmergencyPause(uint256 nonce)");
/// @notice EIP-712 type hash for emergency unpause requests
bytes32 public constant EMERGENCY_UNPAUSE_TYPE_HASH =
keccak256("EmergencyUnpause(uint256 nonce)");
/// @notice EIP-712 type hash for collateral removal requests
bytes32 public constant REMOVE_COLLATERAL_TYPE_HASH =
keccak256("RemoveCollateral(address token,uint256 nonce)");
/// @notice EIP-712 type hash for adding new disputers
bytes32 public constant UPDATE_DISPUTER_TYPE_HASH =
keccak256("UpdateDisputer(address disputer,bool isDisputer,uint256 nonce)");
// ============ State Variables ============
/// @notice Current number of validators in the set
uint256 public validatorLength;
/// @notice Contract owner address (typically a multisig/mpc)
address private _owner;
/// @notice Total weight of all validators (used for quorum calculations)
uint256 private tw;
/// @notice Address of the spotSwap contract
address private spotSwap;
/// @notice Array of current validators
Validator[] private _validators;
/// @notice Mapping to track authorized relayers who can finalize withdrawals
mapping(address => bool) private _isRelayer;
/// @notice Mapping to track authorized disputers who can challenge withdrawals and emergency pause
mapping(address => bool) private _isDisputer;
/// @notice Mapping to track supported collateral tokens
mapping(address => bool) private _isSupported;
/// @notice Mapping from nonce to pending withdrawal requests
mapping(uint256 => PendingWithdrawal) private _pWithdrawal;
/// @notice Nonce for validator operations to prevent replay attacks.
/// @dev consume nonces are marked as used to prevent replay attacks. Nonce management is handled on the our hotstuff consensus L1 chain.
mapping(uint256 => bool) private _usedValidatorNonces;
/// @notice Mapping from validator addresses (both signer and verifier) to their indices (offset by 1 to avoid default 0)
mapping(address => uint256) private _validatorIndex;
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// █████████████████████████ MODIFIER FUNCTIONS ███████████████████████
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
/**
* @notice Restricts function access to authorized relayers only
*/
modifier onlyRelayer() {
if (!_isRelayer[msg.sender]) revert OnlyRelayer__NotRelayer();
_;
}
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ███████████████████████████ CONSTRUCTOR ████████████████████████████
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
/**
* @notice Initializes the bridge contract with initial configuration
* @dev Sets up the initial validator set, supported collaterals, relayers, and spotSwap address
* @param validators Array of initial validators with their hot/cold addresses and weights
* @param collaterals Array of initial supported collateral token addresses
* @param relayers Array of initial authorized relayer addresses
*/
// @audit-info: validators, collaterals, relayers, _solver are not checked for duplicates
constructor(
Validator[] memory validators,
address[] memory collaterals,
address[] memory relayers
) EIP712("Bridge", "1") Ownable(msg.sender) {
// Initialize validator set and calculate total weight
uint256 len = validators.length;
uint256 _totalWeight;
for (uint256 i = 0; i < len; ) {
_validators.push(validators[i]);
_totalWeight += validators[i].w;
// Grant disputer privileges to all validator hot addresses
_isDisputer[validators[i].hAddress] = true;
// Map both hot and cold addresses to their validator index (offset by 1)
_validatorIndex[validators[i].hAddress] = i + 1;
_validatorIndex[validators[i].cAddress] = i + 1;
unchecked {
++i;
}
}
tw = _totalWeight;
validatorLength = len;
// Set supported collateral tokens
len = collaterals.length;
for (uint256 i = 0; i < len; ) {
_isSupported[collaterals[i]] = true;
unchecked {
++i;
}
}
// Set authorized relayers
len = relayers.length;
for (uint256 i = 0; i < len; ) {
_isRelayer[relayers[i]] = true;
unchecked {
++i;
}
}
}
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// █████████████████████████ EXTERNAL FUNCTIONS ███████████████████████
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ============ Owner Access control Functions ============
/**
* @notice Updates relayer authorization status
* @dev Only owner can modify relayer permissions
* @param _relayer Address of the relayer to update
* @param update True to authorize, false to revoke authorization
*/
function updateRelayer(address _relayer, bool update) external onlyOwner {
_isRelayer[_relayer] = update;
emit RelayerUpdated(_relayer, update, block.chainid);
}
/**
* @notice Updates the spotSwap address
* @dev Only owner can update the spotSwap address
* @param newSpotSwap Address of the new spotSwap
*/
function updateSpotSwap(address newSpotSwap) external onlyOwner {
if (newSpotSwap == address(0)) revert UpdateSpotSwap__InvalidAddress();
address oldSpotSwap = spotSwap;
spotSwap = newSpotSwap;
emit SpotSwapUpdated(oldSpotSwap, newSpotSwap, block.chainid);
}
// ================ Access control Functions ============
/**
* @notice Updates the validator set with proper quorum verification
* @notice Requires validator quorum approval.
* @dev Critical security function that requires all current validators to sign with cold addresses
* @param signedData Encoded ValidatorUpdateRequest containing new validator set
* @param signatures Array of signatures from current validators (must equal current validator count)
*/
function updateValidatorSet(
bytes calldata signedData,
bytes[] calldata signatures
) external whenNotPaused onlyOwner {
// Ensure exactly all current validators have signed
if (signatures.length == 0 || signatures.length > validatorLength) {
revert ValidatorUpdate__InvalidInput();
}
ValidatorUpdateRequest memory updateRequest = abi.decode(
signedData,
(ValidatorUpdateRequest)
);
// Prevent replay attacks
if (_usedValidatorNonces[updateRequest.nonce]) {
revert ValidatorUpdate__InvalidNonce();
}
// consume validator nonce
_usedValidatorNonces[updateRequest.nonce] = true;
Validator[] memory newValidators = updateRequest.validators;
// Create EIP-712 message hash for verification
bytes32 digest = _hashTypedDataV4(
keccak256(
abi.encode(
VALIDATOR_UPDATE_TYPE_HASH,
updateRequest.nonce,
_hashValidators(newValidators)
)
)
);
// Verify quorum using cold addresses for maximum security
_checkForQuorum(digest, signatures, false);
// Calculate new total weight
uint256 _w;
uint256 _l = updateRequest.validators.length;
for (uint256 i = 0; i < _l; ) {
_w += updateRequest.validators[i].w;
unchecked {
++i;
}
}
// Remove disputer privileges from old validators
uint256 len = validatorLength;
for (uint256 i = 0; i < len; ) {
_isDisputer[_validators[i].hAddress] = false;
// Clear old validator mappings
_validatorIndex[_validators[i].hAddress] = 0;
_validatorIndex[_validators[i].cAddress] = 0;
unchecked {
++i;
}
}
// Clear old validator set
delete _validators;
// Set new validator set and grant disputer privileges
for (uint256 i = 0; i < _l; ) {
_validators.push(newValidators[i]);
_isDisputer[newValidators[i].hAddress] = true;
// Map both hot and cold addresses to their validator index (offset by 1)
_validatorIndex[newValidators[i].hAddress] = i + 1;
_validatorIndex[newValidators[i].cAddress] = i + 1;
unchecked {
++i;
}
}
// Update state variables
validatorLength = _l;
tw = _w;
emit ValidatorSetUpdated(
updateRequest.nonce,
newValidators,
_l,
_w,
block.chainid
);
}
/**
* @notice Updates the disputer status
* @notice Requires validator quorum approval.
* @dev Requires validator quorum approval using cold addresses for security
* @param disputer Address to grant disputer privileges
* @param isDisputer True to grant disputer privileges, false to revoke
* @param signatures Array of validator signatures approving the addition
*/
function updateDisputer(
address disputer,
bool isDisputer,
bytes[] calldata signatures,
uint256 validatorNonce
) external onlyOwner {
if (_usedValidatorNonces[validatorNonce]) {
revert UpdateDisputer__InvalidNonce();
}
// consume validator nonce
_usedValidatorNonces[validatorNonce] = true;
bytes32 digest = _hashTypedDataV4(
keccak256(
abi.encode(UPDATE_DISPUTER_TYPE_HASH, disputer, isDisputer, validatorNonce)
)
);
// Use verifier/cold addresses for this security-critical operation
_checkForQuorum(digest, signatures, false);
_isDisputer[disputer] = isDisputer;
emit DisputerUpdated(disputer, isDisputer, block.chainid);
}
// ============ Collateral Management Functions ============
/**
* @notice Adds a new supported collateral token to the bridge
* @dev Only the owner can add collaterals. This is an admin function that should be used carefully
* @param token Address of the token to add as supported collateral
*/
function addCollateral(address token) external onlyOwner {
_isSupported[token] = true;
emit CollateralAdded(token, block.chainid);
}
/**
* @notice Removes a supported collateral token from the bridge
* @notice Requires validator quorum approval.
* @dev Requires validator quorum approval. Prevents new deposits but allows existing withdrawals
* @param token Address of the token to remove from supported collaterals
* @param signatures Array of validator signatures approving the removal
*/
function removeCollateral(
address token,
bytes[] calldata signatures,
uint256 validatorNonce
) external onlyOwner {
if (_usedValidatorNonces[validatorNonce]) {
revert RemoveCollateral__InvalidNonce();
}
// consume validator nonce
_usedValidatorNonces[validatorNonce] = true;
if (!_isSupported[token]) {
revert RemoveCollateral__UnsupportedCollateral(
token,
block.chainid
);
}
// Create EIP-712 message hash for the removal request
bytes32 digest = _hashTypedDataV4(
keccak256(
abi.encode(REMOVE_COLLATERAL_TYPE_HASH, token, validatorNonce)
)
);
// Verify validator quorum using cold addresses (more secure for this critical operation)
_checkForQuorum(digest, signatures, false);
_isSupported[token] = false;
emit CollateralRemoved(token, block.chainid);
}
function getValidatorSet() external view returns (Validator[] memory) {
return _validators;
}
// =============== Pause Operations ===============
/**
* @notice Emergency pause function to halt all operations
* @dev Only authorized disputers can trigger emergency pause
*/
function emergencyPause() external whenNotPaused {
if (!_isDisputer[msg.sender]) revert EmergencyPause__NotDisputer();
_pause();
emit EmergencyPaused(msg.sender, block.chainid);
}
/**
* @notice Emergency unpause function to resume operations
* @notice Requires validator quorum approval.
* @dev Requires validator quorum approval using cold addresses for maximum security
* @param signatures Array of signatures from validators approving the unpause
* @param validatorNonce Nonce of the validator approving the unpause
*/
function emergencyUnpause(
bytes[] calldata signatures,
uint256 validatorNonce
) external onlyOwner whenPaused {
// Ensure all validators have provided signatures
if (signatures.length == 0 || signatures.length > validatorLength) {
revert ValidatorUpdate__InvalidInput();
}
if (_usedValidatorNonces[validatorNonce]) {
revert ValidatorUpdate__InvalidNonce();
}
// consume validator nonce
_usedValidatorNonces[validatorNonce] = true;
bytes32 digest = _hashTypedDataV4(
keccak256(abi.encode(EMERGENCY_UNPAUSE_TYPE_HASH, validatorNonce))
);
// Verify quorum using cold addresses for security
_checkForQuorum(digest, signatures, false);
_unpause();
emit EmergencyUnpaused(validatorNonce, block.chainid);
}
// ============ Deposit Operations ============
/**
* @notice Deposits tokens using EIP-2612 permit for gasless approvals
* @dev Handles permit signature and transfers tokens to the bridge
* @param request Deposit request containing permit signature and transfer details
*/
function depositWithPermit(
DepositRequest calldata request
) external nonReentrant {
if (!_isSupported[request.token]) {
revert Deposit__TokenNotSupported(request.token);
}
// Process permit signature (handles both success and failure gracefully)
_checkPermit(request);
_deposit(request.owner,request.owner, request.token, request.amount);
}
/**
* @notice Deposits tokens to the bridge with standard ERC20 approval
* @dev Requires prior token approval. Solver deposits are flagged differently
* @param token Address of the token to deposit
* @param amount Amount of tokens to deposit
* @param receiver Address to receive the deposited tokens (for tracking purposes)
*/
function deposit(
address token,
uint256 amount,
address receiver
) external nonReentrant {
if (!_isSupported[token]) revert Deposit__TokenNotSupported(token);
if (amount == 0) revert Deposit__ZeroAmount();
if (receiver == address(0)) revert Deposit__ZeroAddress();
_deposit(msg.sender, receiver, token, amount);
}
// ============ Withdraw Operations ============
/**
* @notice Finalizes multiple withdrawals in a single transaction
* @dev Gas-efficient batch processing for multiple withdrawal finalizations
* @param _nonces Array of withdrawal nonces to finalize
*/
function batchFinalizeWithdraw(uint256[] calldata _nonces) external {
uint256 len = _nonces.length;
for (uint256 i = 0; i < len; ) {
finalizeWithdraw(_nonces[i]);
unchecked {
++i;
}
}
}
/**
* @notice Processes multiple withdrawal requests in a single transaction
* @notice Each withdrawal request requires validator quorum approval.
* @dev Gas-efficient batch processing for multiple withdrawal requests
* @param requests Array of withdrawal requests to process
*/
function batchRequestWithdraw(
WithdrawalRequest[] calldata requests
) external {
uint256 len = requests.length;
for (uint256 i = 0; i < len; ) {
requestWithdraw(requests[i]);
unchecked {
++i;
}
}
}
// =============== Dispute Withdrawal Operations ===============
/**
* @notice Disputes a pending withdrawal during the dispute period
* @dev Only authorized disputers can challenge withdrawals
* @param _nonce Unique identifier for the withdrawal to dispute
*/
function disputeWithdrawal(uint256 _nonce) external {
if (!_isDisputer[msg.sender]) revert DisputeWithdrawal__NotDisputer();
PendingWithdrawal memory pWithdrawal = _pWithdrawal[_nonce];
// Verify withdrawal exists
if (pWithdrawal.requestedTime == 0) {
revert DisputeWithdrawal__NoPendingWithdrawal(
_nonce,
block.chainid
);
}
// Verify withdrawal is not already disputed
if (pWithdrawal.isDisputed) {
revert DisputeWithdrawal__AlreadyDisputed(_nonce, block.chainid);
}
// Verify dispute is within the allowed time window
if (block.timestamp - pWithdrawal.requestedTime >= DISPUTE_PERIOD) {
revert DisputeWithdrawal__DisputePeriodElapsed(
_nonce,
block.timestamp - pWithdrawal.requestedTime,
DISPUTE_PERIOD,
block.chainid
);
}
// Mark withdrawal as disputed
pWithdrawal.isDisputed = true;
_pWithdrawal[_nonce] = pWithdrawal;
emit DisputedWithdrawal(_nonce, pWithdrawal, block.chainid);
emit Deposit(
pWithdrawal.token,
pWithdrawal.account,
pWithdrawal.amount,
false,
false,
block.chainid
);
}
// ============ Spot Swap Operations ============
/**
* @notice Swaps tokens using the spotSwap contract
* @notice Requires validator quorum approval.
* @dev Requires validator quorum approval using signer/hot addresses for faster processing
* @param request Swap request containing token details and validator signatures
*/
function swap(
SwapRequest calldata request
) external onlyRelayer nonReentrant {
if (
request.signatures.length == 0 ||
request.signatures.length > validatorLength
) {
revert Swap__InvalidInput();
}
// check for deadline
if (block.timestamp > request.deadline) {
revert Swap__TransactionExpired();
}
if (_usedValidatorNonces[request.nonce]) {
revert Swap__InvalidNonce();
}
// consume validator nonce
_usedValidatorNonces[request.nonce] = true;
if (!_isSupported[request.tokenOut])
revert Swap__TokenOutNotSupported(request.tokenOut);
bytes32 digest = _hashTypedDataV4(
keccak256(
abi.encode(
SWAP_TYPE_HASH,
request.account,
request.tokenIn,
request.tokenOut,
request.amountIn,
request.amountOutMin,
request.deadline,
request.nonce
)
)
);
_checkForQuorum(digest, request.signatures, true);
IERC20(request.tokenIn).forceApprove(
address(spotSwap),
request.amountIn
);
try ISpotSwap(spotSwap).swapWithAdapter(request) returns (
uint256 amountOut
) {
emit Deposit(
request.tokenIn,
request.account,
amountOut,
true,
false,
block.chainid
);
} catch {
emit Deposit(
request.tokenIn,
request.account,
0,
true,
true,
block.chainid
);
}
}
// ============ External View Functions ============
/**
* @notice Checks if an address is an authorized relayer
* @param relayer Address to check
* @return True if address is an authorized relayer
*/
function isRelayer(address relayer) external view returns (bool) {
return _isRelayer[relayer];
}
/**
* @notice Checks if an address is an authorized disputer
* @param disputer Address to check
* @return True if address is an authorized disputer
*/
function isDisputer(address disputer) external view returns (bool) {
return _isDisputer[disputer];
}
/**
* @notice Returns the total weight of all validators
* @return Total validator weight used for quorum calculations
*/
function totalValidatorWeight() external view returns (uint256) {
return tw;
}
/**
* @notice Checks if a token is supported as collateral
* @param token Token address to check
* @return True if token is supported
*/
function isTokenSupported(address token) external view returns (bool) {
return _isSupported[token];
}
/**
* @notice Checks if a validator nonce has been used
* @dev Used to prevent replay attacks
* @param nonce The nonce to check
* @return True if the nonce has been used, false otherwise
*/
function checkValidatorNonce(uint256 nonce) external view returns (bool) {
return _usedValidatorNonces[nonce];
}
/**
* @notice Returns details of a pending withdrawal
* @param nonce Unique identifier for the withdrawal request
* @return PendingWithdrawal struct containing withdrawal details
*/
function pendingWithdrawal(
uint256 nonce
) external view returns (PendingWithdrawal memory) {
return _pWithdrawal[nonce];
}
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// █████████████████████████ PUBLIC FUNCTIONS █████████████████████████
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
/**
* @notice Initiates a withdrawal request that enters a dispute period
* @dev Requires validator quorum approval using signer/hot addresses for faster processing
* @param request Withdrawal request containing user details and validator signatures
*/
function requestWithdraw(
WithdrawalRequest calldata request
) public whenNotPaused {
// Ensure all validators have provided signatures
if (
request.signatures.length == 0 ||
request.signatures.length > validatorLength
) {
revert RequestWithdraw__InvalidInput();
}
// Ensure nonce is unique (prevents double-spending)
if (_usedValidatorNonces[request.nonce]) {
revert RequestWithdraw__InvalidNonce();
}
// consume validator nonce
_usedValidatorNonces[request.nonce] = true;
// Create EIP-712 message hash for verification
bytes32 digest = _hashTypedDataV4(
keccak256(
abi.encode(
WITHDRAWAL_TYPE_HASH,
request.user,
request.destination,
request.token,
request.amount,
request.nonce
)
)
);
// Verify validator quorum using hot addresses (faster for normal operations)
_checkForQuorum(digest, request.signatures, true);
// Store pending withdrawal with current timestamp
_pWithdrawal[request.nonce] = PendingWithdrawal({
account: request.user,
receiver: request.destination,
token: request.token,
amount: request.amount,
requestedTime: block.timestamp,
isDisputed: false
});
// Emit event for off-chain monitoring
emit RequestedWithdraw(
request.user,
request.destination,
request.token,
request.amount,
request.nonce,
block.chainid
);
}
/**
* @notice Finalizes a withdrawal after the dispute period has elapsed
* @dev Only authorized relayers can finalize withdrawals
* @param _nonce Unique identifier for the withdrawal to finalize
*/
function finalizeWithdraw(
uint256 _nonce
) public whenNotPaused onlyRelayer nonReentrant {
PendingWithdrawal memory pWithdrawal = _pWithdrawal[_nonce];
// Verify withdrawal exists
if (pWithdrawal.requestedTime == 0) {
revert FinalizeWithdraw__NoPendingWithdrawal(_nonce);
}
// Verify withdrawal is not disputed
if (pWithdrawal.isDisputed) revert FinalizeWithdraw__Disputed(_nonce);
// Verify dispute period has elapsed
if (block.timestamp - pWithdrawal.requestedTime < DISPUTE_PERIOD) {
revert FinalizeWithdraw__DisputePeriodNotElapsed(
_nonce,
block.timestamp - pWithdrawal.requestedTime,
DISPUTE_PERIOD
);
}
// Clear the withdrawal from storage (prevents re-finalization)
_pWithdrawal[_nonce].requestedTime = 0;
// Transfer tokens to the designated receiver
IERC20(pWithdrawal.token).safeTransfer(
pWithdrawal.receiver,
pWithdrawal.amount
);
emit FinalizedWithdraw(_nonce, block.chainid);
}
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
// ███████████████████████ INTERNAL FUNCTIONS █████████████████████████
// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
/**
* @notice Internal function to handle token deposits
* @dev Transfers tokens from depositor to bridge and emits deposit event
* @param owner_ Address of the token owner
* @param receiver_ Address of the receiver
* @param token Address of the token being deposited
* @param amount Amount of tokens to deposit
*/
function _deposit(
address owner_,
address receiver_,
address token,
uint256 amount
) internal whenNotPaused {
IERC20(token).safeTransferFrom(owner_, address(this), amount);
emit Deposit(token, receiver_, amount, false, false, block.chainid);
}
/**
* @notice Internal function to process EIP-2612 permit signatures
* @dev Gracefully handles both successful and failed permit calls
* @param request Deposit request containing permit signature data
*/
function _checkPermit(DepositRequest calldata request) internal {
// Attempt permit call, ignore failures (user may have pre-approved)
try
IERC20Permit(request.token).permit(
request.owner,
address(this),
request.amount,
request.deadline,
request.v,
request.r,
request.s
)
{} catch {}
}
/**
* @notice Creates a hash of the validator array for EIP-712 signature verification
* @dev Used in validator set update operations
* @param validators Array of validators to hash
* @return Hash of the validator array
*/
function _hashValidators(
Validator[] memory validators
) private pure returns (bytes32) {
bytes32[] memory hashes = new bytes32[](validators.length);
for (uint256 i = 0; i < validators.length; ) {
hashes[i] = keccak256(
abi.encode(
VALIDATOR_STRUCT_TYPE_HASH,
validators[i].hAddress,
validators[i].cAddress,
validators[i].w
)
);
unchecked {
++i;
}
}
return keccak256(abi.encodePacked(hashes));
}
/**
* @notice Verifies that a sufficient quorum of validators have signed a message
* @dev Implements weighted voting system requiring ≥67% (2/3) of total weight
* @param digest EIP-712 message hash to verify
* @param signatures Array of signatures to verify (can be in any order)
* @param isHot Whether to use signer/hot addresses (true) or verifier/cold addresses (false) for verification
*/
function _checkForQuorum(
bytes32 digest,
bytes[] calldata signatures,
bool isHot
) internal view {
uint256 sigLen = signatures.length;
if (sigLen == 0 || sigLen > validatorLength) {
revert Signature__InvalidInput();
}
uint256 cw = 0; // cumulative weight
// Track which validators have already signed to prevent signature reuse
bool[] memory hasValidatorSigned = new bool[](validatorLength);
// Iterate through signatures in any order
for (uint256 i = 0; i < sigLen; ) {
// Skip invalid signature lengths
if (signatures[i].length != 65) {
unchecked {
++i;
}
continue;
}
// Recover signer address from signature
address signer = ECDSA.recover(digest, signatures[i]);
if (signer == address(0)) {
unchecked {
++i;
}
continue;
}
// Find validator index from the unified mapping
uint256 validatorIndex = _validatorIndex[signer];
// Check if signer is a valid validator (index > 0 since we offset by 1)
if (validatorIndex > 0 && validatorIndex <= validatorLength) {
uint256 actualIndex = validatorIndex - 1; // Convert back to actual index
Validator memory validator = _validators[actualIndex];
// Verify signer is using the correct address type (hot or cold)
bool isValidSigner = isHot
? (signer == validator.hAddress)
: (signer == validator.cAddress);
if (isValidSigner && !hasValidatorSigned[actualIndex]) {
hasValidatorSigned[actualIndex] = true;
cw += validator.w;
// Check if we've reached the required threshold (≥67% of total weight)
if (3 * cw >= 2 * tw) {
return;
}
}
}
unchecked {
++i;
}
}
// Revert if insufficient weight was gathered
revert NotEnoughWeight(cw, tw, block.chainid);
}
}
Pausable.sol 112 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
ReentrancyGuard.sol 87 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
SafeERC20.sol 280 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 {
if (!_safeTransfer(token, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {
if (!_safeTransferFrom(token, from, to, value, true)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _safeTransfer(token, to, value, false);
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _safeTransferFrom(token, from, to, value, false);
}
/**
* @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 {
if (!_safeApprove(token, spender, value, false)) {
if (!_safeApprove(token, spender, 0, true)) revert SafeERC20FailedOperation(address(token));
if (!_safeApprove(token, spender, value, true)) revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 `token.transfer(to, value)` call, 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 to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransfer(IERC20 token, address to, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.transfer.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(to, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0, 0x44, 0, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
/**
* @dev Imitates a Solidity `token.transferFrom(from, to, value)` call, 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 from The sender of the tokens
* @param to The recipient of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value,
bool bubble
) private returns (bool success) {
bytes4 selector = IERC20.transferFrom.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(from, shr(96, not(0))))
mstore(0x24, and(to, shr(96, not(0))))
mstore(0x44, value)
success := call(gas(), token, 0, 0, 0x64, 0, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
mstore(0x60, 0)
}
}
/**
* @dev Imitates a Solidity `token.approve(spender, value)` call, 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 spender The spender of the tokens
* @param value The amount of token to transfer
* @param bubble Behavior switch if the transfer call reverts: bubble the revert reason or return a false boolean.
*/
function _safeApprove(IERC20 token, address spender, uint256 value, bool bubble) private returns (bool success) {
bytes4 selector = IERC20.approve.selector;
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(0x00, selector)
mstore(0x04, and(spender, shr(96, not(0))))
mstore(0x24, value)
success := call(gas(), token, 0, 0, 0x44, 0, 0x20)
// if call success and return is true, all is good.
// otherwise (not success or return is not true), we need to perform further checks
if iszero(and(success, eq(mload(0x00), 1))) {
// if the call was a failure and bubble is enabled, bubble the error
if and(iszero(success), bubble) {
returndatacopy(fmp, 0, returndatasize())
revert(fmp, returndatasize())
}
// if the return value is not true, then the call is only successful if:
// - the token address has code
// - the returndata is empty
success := and(success, and(iszero(returndatasize()), gt(extcodesize(token), 0)))
}
mstore(0x40, fmp)
}
}
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @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);
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[ERC-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC-20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
ECDSA.sol 213 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.20;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS
}
/**
* @dev The signature derives the `address(0)`.
*/
error ECDSAInvalidSignature();
/**
* @dev The signature has an invalid length.
*/
error ECDSAInvalidSignatureLength(uint256 length);
/**
* @dev The signature has an S value that is in the upper half order.
*/
error ECDSAInvalidSignatureS(bytes32 s);
/**
* @dev Returns the address that signed a hashed message (`hash`) with `signature` or an error. This will not
* return address(0) without also returning an error description. Errors are documented using an enum (error type)
* and a bytes32 providing additional information about the error.
*
* If no error is returned, then the address can be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*/
function tryRecover(
bytes32 hash,
bytes memory signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly ("memory-safe") {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Variant of {tryRecover} that takes a signature in calldata
*/
function tryRecoverCalldata(
bytes32 hash,
bytes calldata signature
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, calldata slices would work here, but are
// significantly more expensive (length check) than using calldataload in assembly.
assembly ("memory-safe") {
r := calldataload(signature.offset)
s := calldataload(add(signature.offset, 0x20))
v := byte(0, calldataload(add(signature.offset, 0x40)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength, bytes32(signature.length));
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Variant of {recover} that takes a signature in calldata
*/
function recoverCalldata(bytes32 hash, bytes calldata signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecoverCalldata(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[ERC-2098 short signatures]
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
unchecked {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
// We do not check for an overflow here since the shift operation results in 0 or 1.
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, r, vs);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address recovered, RecoverError err, bytes32 errArg) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS, s);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature, bytes32(0));
}
return (signer, RecoverError.NoError, bytes32(0));
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, v, r, s);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Optionally reverts with the corresponding custom error according to the `error` argument provided.
*/
function _throwError(RecoverError error, bytes32 errorArg) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert ECDSAInvalidSignature();
} else if (error == RecoverError.InvalidSignatureLength) {
revert ECDSAInvalidSignatureLength(uint256(errorArg));
} else if (error == RecoverError.InvalidSignatureS) {
revert ECDSAInvalidSignatureS(errorArg);
}
}
}
EIP712.sol 160 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.24;
import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
// slither-disable-next-line constable-states
string private _nameFallback;
// slither-disable-next-line constable-states
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/// @inheritdoc IERC5267
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: By default this function reads _name which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Name() internal view returns (string memory) {
return _name.toStringWithFallback(_nameFallback);
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: By default this function reads _version which is an immutable value.
* It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
*/
// solhint-disable-next-line func-name-mixedcase
function _EIP712Version() internal view returns (string memory) {
return _version.toStringWithFallback(_versionFallback);
}
}
Ownable.sol 100 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
IBridge.sol 168 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.30;
interface IBridge {
// Errors
error OnlyRelayer__NotRelayer();
error Deposit__TokenNotSupported(address token);
error Deposit__ZeroAmount();
error Deposit__ZeroAddress();
error ValidatorUpdate__InvalidInput();
error ValidatorUpdate__InvalidNonce();
error RequestWithdraw__InvalidInput();
error RequestWithdraw__InvalidNonce();
error FinalizeWithdraw__NoPendingWithdrawal(uint256 nonce);
error FinalizeWithdraw__Disputed(uint256 nonce);
error FinalizeWithdraw__DisputePeriodNotElapsed(uint256 nonce, uint256 elapsed, uint256 disputePeriod);
error DisputeWithdrawal__NoPendingWithdrawal(uint256 nonce, uint256 chainId);
error DisputeWithdrawal__AlreadyDisputed(uint256 nonce, uint256 chainId);
error DisputeWithdrawal__DisputePeriodElapsed(
uint256 nonce, uint256 elapsed, uint256 disputePeriod, uint256 chainId
);
error DisputeWithdrawal__NotDisputer();
error RemoveCollateral__UnsupportedCollateral(address token, uint256 chainId);
error EmergencyPause__NotDisputer();
error NotEnoughWeight(uint256 cumulativeWeight, uint256 totalWeight, uint256 chainId);
error RemoveCollateral__InvalidNonce();
error UpdateDisputer__InvalidNonce();
error Signature__InvalidInput();
error UpdateSpotSwap__InvalidAddress();
error Swap__InvalidInput();
error Swap__TransactionExpired();
error Swap__TokenOutNotSupported(address token);
error Swap__InvalidNonce();
// Events
event Deposit(
address indexed token,
address indexed receiver,
uint256 amount,
bool isSpotSwap,
bool isFailedSwap,
uint256 chainId
);
event RequestedWithdraw(
address indexed user,
address indexed destination,
address indexed token,
uint256 amount,
uint256 nonce,
uint256 chainId
);
event FinalizedWithdraw(uint256 indexed nonce, uint256 chainId);
event RelayerUpdated(address relayer, bool isRelayer, uint256 chainId);
event SolverUpdated(address oldSolver, address newSolver, uint256 chainId);
event DisputedWithdrawal(uint256 nonce, PendingWithdrawal pWithdrawal, uint256 chainId);
event EmergencyPaused(address disputer, uint256 chainId);
event EmergencyUnpaused(uint256 nonce, uint256 chainId);
event CollateralAdded(address token, uint256 chainId);
event CollateralRemoved(address token, uint256 chainId);
event DisputerUpdated(address disputer, bool isDisputer, uint256 chainId);
event ValidatorSetUpdated(
uint256 nonce, Validator[] newValidators, uint256 newValidatorLength, uint256 newTotalWeight, uint256 chainId
);
event SpotSwapUpdated(address oldSpotSwap, address newSpotSwap, uint256 chainId);
// Structs
struct DepositRequest {
address owner;
address token;
uint256 amount;
uint256 deadline;
uint8 v;
bytes32 r;
bytes32 s;
}
struct WithdrawalRequest {
address user;
address destination;
address token;
uint256 amount;
uint256 nonce;
bytes[] signatures;
}
struct SwapRequest {
address account;
address tokenIn;
address tokenOut;
uint256 amountIn;
uint256 amountOutMin;
uint256 deadline;
uint256 nonce;
address to;
address adapter;
bytes adapterData;
bytes[] signatures;
}
struct PendingWithdrawal {
address account;
address receiver;
address token;
uint256 amount;
uint256 requestedTime;
bool isDisputed;
}
struct ValidatorUpdateRequest {
uint256 nonce;
Validator[] validators;
}
struct Validator {
address hAddress; // signer address/hot address
address cAddress; // verifier address/cold address
uint256 w; // weight
}
struct PendingValidatorUpdate {
uint256 t; //timestamp
uint256 l; // number of validators after update
uint256 tw; // new total weight
bytes m; // signed message
}
// Constants
function DISPUTE_PERIOD() external view returns (uint256);
// State variables
function checkValidatorNonce(uint256 nonce) external view returns (bool);
function validatorLength() external view returns (uint256);
function totalValidatorWeight() external view returns (uint256);
function isRelayer(address relayer) external view returns (bool);
function isDisputer(address disputer) external view returns (bool);
function pendingWithdrawal(uint256 nonce) external view returns (PendingWithdrawal memory);
function isTokenSupported(address token) external view returns (bool);
// External functions
/**
* only owner(multisig) can add a new collateral. Owner is trusted which will research the token before adding it.
* @notice Add a new collateral to the bridge
* @param token The address of the collateral to add
*/
function addCollateral(address token) external;
/**
* Owner can remove the collateral only if validators reaches quorum for the removal. Removing the collateral revert the new deposits for the removed collateral
* but withdrawal will continue working if bridge holds collateral
* @notice Remove a collateral from the bridge
* @param token The address of the collateral to remove
* @param signatures The signatures of the validators to remove the collateral
*/
function removeCollateral(address token, bytes[] calldata signatures, uint256 validatorNonce) external;
function updateRelayer(address _relayer, bool update) external;
function updateSpotSwap(address newSpotSwap) external;
function updateDisputer(address disputer, bool isDisputer, bytes[] calldata signatures, uint256 validatorNonce) external;
function updateValidatorSet(bytes calldata signedData, bytes[] memory signatures) external;
function depositWithPermit(DepositRequest calldata request) external;
function deposit(address token, uint256 amount, address receiver) external;
function batchRequestWithdraw(WithdrawalRequest[] calldata requests) external;
function requestWithdraw(WithdrawalRequest calldata request) external;
function batchFinalizeWithdraw(uint256[] calldata _nonces) external;
function finalizeWithdraw(uint256 _nonce) external;
function disputeWithdrawal(uint256 _nonce) external;
function emergencyPause() external;
function emergencyUnpause(bytes[] calldata signatures, uint256 validatorNonce) external;
function getValidatorSet() external view returns (Validator[] memory);
}
ISpotSwap.sol 70 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.27;
import {IBridge} from "../IBridge.sol";
interface ISpotSwap {
// ============ Events ============
event AdapterAdded(address indexed adapter);
event AdapterRemoved(address indexed adapter);
event SwapExecuted( uint256 nonce,address adapter, address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut, address to);
event SwapFailed(uint256 nonce);
event SwapQueued(uint256 nonce);
event SwapRetried(uint256 nonce, address adapter);
event InvalidAdapter(uint256 nonce, address adapter);
event BridgeDeposit(uint256 nonce);
event OwnershipTransferred(address indexed newOwner);
event TokenAdapterAdded(address indexed token, address indexed adapter);
event TokenAdapterRemoved(address indexed token, address indexed adapter);
// ============ Errors ============
error OnlyOwner();
error InvalidBridge();
error AdapterNotFound();
error AdapterAlreadyExists();
error InvalidAmount();
error InvalidTokens();
error InsufficientOutput();
error SwapAlreadyQueued();
error SwapNotFound();
error InvalidOwner();
error InvalidAdapterForToken();
// ============ Core Functions ============
/**
* @dev Try swap with a specific adapter
* @param payload Swap parameters
* @return amountOut Amount of tokens received
*/
function swapWithAdapter(
IBridge.SwapRequest calldata payload
) external returns (uint256 amountOut);
// ============ Admin Functions ============
function addAdapter(
address adapter
) external;
function removeAdapter(address adapter) external;
function addAdapterForToken(
address token,
address adapter
) external;
function removeAdapterForToken(address token, address adapter) external;
// ============ View Functions ============
function isValidAdapter(address adapter) external view returns (bool);
function getAdapters() external view returns (address[] memory);
function getAdapterCount() external view returns (uint256);
function owner() external view returns (address);
function bridge() external view returns (address);
function transferOwnership(address newOwner) external;
}
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;
}
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
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);
}
MessageHashUtils.sol 99 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.24;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[ERC-191] and https://eips.ethereum.org/EIPS/eip-712[EIP 712]
* specifications.
*/
library MessageHashUtils {
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing a bytes32 `messageHash` with
* `"\x19Ethereum Signed Message:\n32"` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* NOTE: The `messageHash` parameter is intended to be the result of hashing a raw message with
* keccak256, although any bytes32 value can be safely used because the final digest will
* be re-hashed.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes32 messageHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, "\x19Ethereum Signed Message:\n32") // 32 is the bytes-length of messageHash
mstore(0x1c, messageHash) // 0x1c (28) is the length of the prefix
digest := keccak256(0x00, 0x3c) // 0x3c is the length of the prefix (0x1c) + messageHash (0x20)
}
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x45` (`personal_sign` messages).
*
* The digest is calculated by prefixing an arbitrary `message` with
* `"\x19Ethereum Signed Message:\n" + len(message)` and hashing the result. It corresponds with the
* hash signed when using the https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_sign[`eth_sign`] JSON-RPC method.
*
* See {ECDSA-recover}.
*/
function toEthSignedMessageHash(bytes memory message) internal pure returns (bytes32) {
return
keccak256(bytes.concat("\x19Ethereum Signed Message:\n", bytes(Strings.toString(message.length)), message));
}
/**
* @dev Returns the keccak256 digest of an ERC-191 signed data with version
* `0x00` (data with intended validator).
*
* The digest is calculated by prefixing an arbitrary `data` with `"\x19\x00"` and the intended
* `validator` address. Then hashing the result.
*
* See {ECDSA-recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(hex"19_00", validator, data));
}
/**
* @dev Variant of {toDataWithIntendedValidatorHash-address-bytes} optimized for cases where `data` is a bytes32.
*/
function toDataWithIntendedValidatorHash(
address validator,
bytes32 messageHash
) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
mstore(0x00, hex"19_00")
mstore(0x02, shl(96, validator))
mstore(0x16, messageHash)
digest := keccak256(0x00, 0x36)
}
}
/**
* @dev Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
ShortStrings.sol 122 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.20;
import {StorageSlot} from "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
assembly ("memory-safe") {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {toShortStringWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {toShortStringWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
IERC5267.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC5267.sol)
pragma solidity >=0.4.16;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
Strings.sol 508 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.sol";
import {Bytes} from "./Bytes.sol";
/**
* @dev String operations.
*/
library Strings {
using SafeCast for *;
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
uint256 private constant SPECIAL_CHARS_LOOKUP =
(1 << 0x08) | // backspace
(1 << 0x09) | // tab
(1 << 0x0a) | // newline
(1 << 0x0c) | // form feed
(1 << 0x0d) | // carriage return
(1 << 0x22) | // double quote
(1 << 0x5c); // backslash
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev The string being parsed contains characters that are not in scope of the given base.
*/
error StringsInvalidChar();
/**
* @dev The string being parsed is not a properly formatted address.
*/
error StringsInvalidAddressFormat();
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(add(buffer, 0x20), length)
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Converts a `bytes` buffer to its ASCII `string` hexadecimal representation.
*/
function toHexString(bytes memory input) internal pure returns (string memory) {
unchecked {
bytes memory buffer = new bytes(2 * input.length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 0; i < input.length; ++i) {
uint8 v = uint8(input[i]);
buffer[2 * i + 2] = HEX_DIGITS[v >> 4];
buffer[2 * i + 3] = HEX_DIGITS[v & 0xf];
}
return string(buffer);
}
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return Bytes.equal(bytes(a), bytes(b));
}
/**
* @dev Parse a decimal string and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input) internal pure returns (uint256) {
return parseUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[0-9]*`
* - The result must fit into an `uint256` type
*/
function parseUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseUint-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
uint256 result = 0;
for (uint256 i = begin; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 9) return (false, 0);
result *= 10;
result += chr;
}
return (true, result);
}
/**
* @dev Parse a decimal string and returns the value as a `int256`.
*
* Requirements:
* - The string must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input) internal pure returns (int256) {
return parseInt(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseInt-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `[-+]?[0-9]*`
* - The result must fit in an `int256` type.
*/
function parseInt(string memory input, uint256 begin, uint256 end) internal pure returns (int256) {
(bool success, int256 value) = tryParseInt(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseInt-string} that returns false if the parsing fails because of an invalid character or if
* the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(string memory input) internal pure returns (bool success, int256 value) {
return _tryParseIntUncheckedBounds(input, 0, bytes(input).length);
}
uint256 private constant ABS_MIN_INT256 = 2 ** 255;
/**
* @dev Variant of {parseInt-string-uint256-uint256} that returns false if the parsing fails because of an invalid
* character or if the result does not fit in a `int256`.
*
* NOTE: This function will revert if the absolute value of the result does not fit in a `uint256`.
*/
function tryParseInt(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, int256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseIntUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseInt-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseIntUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, int256 value) {
bytes memory buffer = bytes(input);
// Check presence of a negative sign.
bytes1 sign = begin == end ? bytes1(0) : bytes1(_unsafeReadBytesOffset(buffer, begin)); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
bool positiveSign = sign == bytes1("+");
bool negativeSign = sign == bytes1("-");
uint256 offset = (positiveSign || negativeSign).toUint();
(bool absSuccess, uint256 absValue) = tryParseUint(input, begin + offset, end);
if (absSuccess && absValue < ABS_MIN_INT256) {
return (true, negativeSign ? -int256(absValue) : int256(absValue));
} else if (absSuccess && negativeSign && absValue == ABS_MIN_INT256) {
return (true, type(int256).min);
} else return (false, 0);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as a `uint256`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input) internal pure returns (uint256) {
return parseHexUint(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]*`
* - The result must fit in an `uint256` type.
*/
function parseHexUint(string memory input, uint256 begin, uint256 end) internal pure returns (uint256) {
(bool success, uint256 value) = tryParseHexUint(input, begin, end);
if (!success) revert StringsInvalidChar();
return value;
}
/**
* @dev Variant of {parseHexUint-string} that returns false if the parsing fails because of an invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(string memory input) internal pure returns (bool success, uint256 value) {
return _tryParseHexUintUncheckedBounds(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseHexUint-string-uint256-uint256} that returns false if the parsing fails because of an
* invalid character.
*
* NOTE: This function will revert if the result does not fit in a `uint256`.
*/
function tryParseHexUint(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, uint256 value) {
if (end > bytes(input).length || begin > end) return (false, 0);
return _tryParseHexUintUncheckedBounds(input, begin, end);
}
/**
* @dev Implementation of {tryParseHexUint-string-uint256-uint256} that does not check bounds. Caller should make sure that
* `begin <= end <= input.length`. Other inputs would result in undefined behavior.
*/
function _tryParseHexUintUncheckedBounds(
string memory input,
uint256 begin,
uint256 end
) private pure returns (bool success, uint256 value) {
bytes memory buffer = bytes(input);
// skip 0x prefix if present
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(buffer, begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 offset = hasPrefix.toUint() * 2;
uint256 result = 0;
for (uint256 i = begin + offset; i < end; ++i) {
uint8 chr = _tryParseChr(bytes1(_unsafeReadBytesOffset(buffer, i)));
if (chr > 15) return (false, 0);
result *= 16;
unchecked {
// Multiplying by 16 is equivalent to a shift of 4 bits (with additional overflow check).
// This guarantees that adding a value < 16 will not cause an overflow, hence the unchecked.
result += chr;
}
}
return (true, result);
}
/**
* @dev Parse a hexadecimal string (with or without "0x" prefix), and returns the value as an `address`.
*
* Requirements:
* - The string must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input) internal pure returns (address) {
return parseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string} that parses a substring of `input` located between position `begin` (included) and
* `end` (excluded).
*
* Requirements:
* - The substring must be formatted as `(0x)?[0-9a-fA-F]{40}`
*/
function parseAddress(string memory input, uint256 begin, uint256 end) internal pure returns (address) {
(bool success, address value) = tryParseAddress(input, begin, end);
if (!success) revert StringsInvalidAddressFormat();
return value;
}
/**
* @dev Variant of {parseAddress-string} that returns false if the parsing fails because the input is not a properly
* formatted address. See {parseAddress-string} requirements.
*/
function tryParseAddress(string memory input) internal pure returns (bool success, address value) {
return tryParseAddress(input, 0, bytes(input).length);
}
/**
* @dev Variant of {parseAddress-string-uint256-uint256} that returns false if the parsing fails because input is not a properly
* formatted address. See {parseAddress-string-uint256-uint256} requirements.
*/
function tryParseAddress(
string memory input,
uint256 begin,
uint256 end
) internal pure returns (bool success, address value) {
if (end > bytes(input).length || begin > end) return (false, address(0));
bool hasPrefix = (end > begin + 1) && bytes2(_unsafeReadBytesOffset(bytes(input), begin)) == bytes2("0x"); // don't do out-of-bound (possibly unsafe) read if sub-string is empty
uint256 expectedLength = 40 + hasPrefix.toUint() * 2;
// check that input is the correct length
if (end - begin == expectedLength) {
// length guarantees that this does not overflow, and value is at most type(uint160).max
(bool s, uint256 v) = _tryParseHexUintUncheckedBounds(input, begin, end);
return (s, address(uint160(v)));
} else {
return (false, address(0));
}
}
function _tryParseChr(bytes1 chr) private pure returns (uint8) {
uint8 value = uint8(chr);
// Try to parse `chr`:
// - Case 1: [0-9]
// - Case 2: [a-f]
// - Case 3: [A-F]
// - otherwise not supported
unchecked {
if (value > 47 && value < 58) value -= 48;
else if (value > 96 && value < 103) value -= 87;
else if (value > 64 && value < 71) value -= 55;
else return type(uint8).max;
}
return value;
}
/**
* @dev Escape special characters in JSON strings. This can be useful to prevent JSON injection in NFT metadata.
*
* WARNING: This function should only be used in double quoted JSON strings. Single quotes are not escaped.
*
* NOTE: This function escapes all unicode characters, and not just the ones in ranges defined in section 2.5 of
* RFC-4627 (U+0000 to U+001F, U+0022 and U+005C). ECMAScript's `JSON.parse` does recover escaped unicode
* characters that are not in this range, but other tooling may provide different results.
*/
function escapeJSON(string memory input) internal pure returns (string memory) {
bytes memory buffer = bytes(input);
bytes memory output = new bytes(2 * buffer.length); // worst case scenario
uint256 outputLength = 0;
for (uint256 i; i < buffer.length; ++i) {
bytes1 char = bytes1(_unsafeReadBytesOffset(buffer, i));
if (((SPECIAL_CHARS_LOOKUP & (1 << uint8(char))) != 0)) {
output[outputLength++] = "\\";
if (char == 0x08) output[outputLength++] = "b";
else if (char == 0x09) output[outputLength++] = "t";
else if (char == 0x0a) output[outputLength++] = "n";
else if (char == 0x0c) output[outputLength++] = "f";
else if (char == 0x0d) output[outputLength++] = "r";
else if (char == 0x5c) output[outputLength++] = "\\";
else if (char == 0x22) {
// solhint-disable-next-line quotes
output[outputLength++] = '"';
}
} else {
output[outputLength++] = char;
}
}
// write the actual length and deallocate unused memory
assembly ("memory-safe") {
mstore(output, outputLength)
mstore(0x40, add(output, shl(5, shr(5, add(outputLength, 63)))))
}
return string(output);
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
StorageSlot.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @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 756 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.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 Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = 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 = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @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 {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(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 {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @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 {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 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 low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, 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 ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, 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 high into low.
low |= high * 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 high
// is no longer required.
result = low * 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 Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @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 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @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;
}
/**
* @dev Counts the number of leading zero bits in a uint256.
*/
function clz(uint256 x) internal pure returns (uint256) {
return ternary(x == 0, 256, 255 - log2(x));
}
}
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))
}
}
}
SignedMath.sol 68 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @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, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
Bytes.sol 216 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Bytes.sol)
pragma solidity ^0.8.24;
import {Math} from "./math/Math.sol";
/**
* @dev Bytes operations.
*/
library Bytes {
/**
* @dev Forward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the first instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return indexOf(buffer, s, 0);
}
/**
* @dev Forward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or after `pos`), returns the index of the next instance
* * If `s` is not present in the buffer (at or after `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf[Javascript's `Array.indexOf`]
*/
function indexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
uint256 length = buffer.length;
for (uint256 i = pos; i < length; ++i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i)) == s) {
return i;
}
}
return type(uint256).max;
}
/**
* @dev Backward search for `s` in `buffer`
* * If `s` is present in the buffer, returns the index of the last instance
* * If `s` is not present in the buffer, returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s) internal pure returns (uint256) {
return lastIndexOf(buffer, s, type(uint256).max);
}
/**
* @dev Backward search for `s` in `buffer` starting at position `pos`
* * If `s` is present in the buffer (at or before `pos`), returns the index of the previous instance
* * If `s` is not present in the buffer (at or before `pos`), returns type(uint256).max
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf[Javascript's `Array.lastIndexOf`]
*/
function lastIndexOf(bytes memory buffer, bytes1 s, uint256 pos) internal pure returns (uint256) {
unchecked {
uint256 length = buffer.length;
for (uint256 i = Math.min(Math.saturatingAdd(pos, 1), length); i > 0; --i) {
if (bytes1(_unsafeReadBytesOffset(buffer, i - 1)) == s) {
return i - 1;
}
}
return type(uint256).max;
}
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to the end of `buffer` into a new bytes object in
* memory.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return slice(buffer, start, buffer.length);
}
/**
* @dev Copies the content of `buffer`, from `start` (included) to `end` (excluded) into a new bytes object in
* memory. The `end` argument is truncated to the length of the `buffer`.
*
* NOTE: replicates the behavior of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice[Javascript's `Array.slice`]
*/
function slice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
uint256 length = buffer.length;
end = Math.min(end, length);
start = Math.min(start, end);
// allocate and copy
bytes memory result = new bytes(end - start);
assembly ("memory-safe") {
mcopy(add(result, 0x20), add(add(buffer, 0x20), start), sub(end, start))
}
return result;
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to the end of `buffer` to the start of that buffer.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
*/
function splice(bytes memory buffer, uint256 start) internal pure returns (bytes memory) {
return splice(buffer, start, buffer.length);
}
/**
* @dev Moves the content of `buffer`, from `start` (included) to end (excluded) to the start of that buffer. The
* `end` argument is truncated to the length of the `buffer`.
*
* NOTE: This function modifies the provided buffer in place. If you need to preserve the original buffer, use {slice} instead
*/
function splice(bytes memory buffer, uint256 start, uint256 end) internal pure returns (bytes memory) {
// sanitize
uint256 length = buffer.length;
end = Math.min(end, length);
start = Math.min(start, end);
// allocate and copy
assembly ("memory-safe") {
mcopy(add(buffer, 0x20), add(add(buffer, 0x20), start), sub(end, start))
mstore(buffer, sub(end, start))
}
return buffer;
}
/**
* @dev Returns true if the two byte buffers are equal.
*/
function equal(bytes memory a, bytes memory b) internal pure returns (bool) {
return a.length == b.length && keccak256(a) == keccak256(b);
}
/**
* @dev Reverses the byte order of a bytes32 value, converting between little-endian and big-endian.
* Inspired in https://graphics.stanford.edu/~seander/bithacks.html#ReverseParallel[Reverse Parallel]
*/
function reverseBytes32(bytes32 value) internal pure returns (bytes32) {
value = // swap bytes
((value >> 8) & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value >> 16) & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value >> 32) & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32);
value = // swap 8-byte long pairs
((value >> 64) & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) |
((value & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64);
return (value >> 128) | (value << 128); // swap 16-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 128-bit values.
function reverseBytes16(bytes16 value) internal pure returns (bytes16) {
value = // swap bytes
((value & 0xFF00FF00FF00FF00FF00FF00FF00FF00) >> 8) |
((value & 0x00FF00FF00FF00FF00FF00FF00FF00FF) << 8);
value = // swap 2-byte long pairs
((value & 0xFFFF0000FFFF0000FFFF0000FFFF0000) >> 16) |
((value & 0x0000FFFF0000FFFF0000FFFF0000FFFF) << 16);
value = // swap 4-byte long pairs
((value & 0xFFFFFFFF00000000FFFFFFFF00000000) >> 32) |
((value & 0x00000000FFFFFFFF00000000FFFFFFFF) << 32);
return (value >> 64) | (value << 64); // swap 8-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 64-bit values.
function reverseBytes8(bytes8 value) internal pure returns (bytes8) {
value = ((value & 0xFF00FF00FF00FF00) >> 8) | ((value & 0x00FF00FF00FF00FF) << 8); // swap bytes
value = ((value & 0xFFFF0000FFFF0000) >> 16) | ((value & 0x0000FFFF0000FFFF) << 16); // swap 2-byte long pairs
return (value >> 32) | (value << 32); // swap 4-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 32-bit values.
function reverseBytes4(bytes4 value) internal pure returns (bytes4) {
value = ((value & 0xFF00FF00) >> 8) | ((value & 0x00FF00FF) << 8); // swap bytes
return (value >> 16) | (value << 16); // swap 2-byte long pairs
}
/// @dev Same as {reverseBytes32} but optimized for 16-bit values.
function reverseBytes2(bytes2 value) internal pure returns (bytes2) {
return (value >> 8) | (value << 8);
}
/**
* @dev Counts the number of leading zero bits a bytes array. Returns `8 * buffer.length`
* if the buffer is all zeros.
*/
function clz(bytes memory buffer) internal pure returns (uint256) {
for (uint256 i = 0; i < buffer.length; i += 32) {
bytes32 chunk = _unsafeReadBytesOffset(buffer, i);
if (chunk != bytes32(0)) {
return Math.min(8 * i + Math.clz(uint256(chunk)), 8 * buffer.length);
}
}
return 8 * buffer.length;
}
/**
* @dev Reads a bytes32 from a bytes array without bounds checking.
*
* NOTE: making this function internal would mean it could be used with memory unsafe offset, and marking the
* assembly block as such would prevent some optimizations.
*/
function _unsafeReadBytesOffset(bytes memory buffer, uint256 offset) private pure returns (bytes32 value) {
// This is not memory safe in the general case, but all calls to this private function are within bounds.
assembly ("memory-safe") {
value := mload(add(add(buffer, 0x20), offset))
}
}
}
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)
}
}
}
Read Contract
DEAD_ADDRESS 0x4e6fd6c4 → address
DISPUTE_PERIOD 0xa5bbe22b → uint256
EMERGENCY_PAUSE_TYPE_HASH 0x7d98ce0f → bytes32
EMERGENCY_UNPAUSE_TYPE_HASH 0x0958022b → bytes32
REMOVE_COLLATERAL_TYPE_HASH 0xc47ecab0 → bytes32
SWAP_TYPE_HASH 0x261cfe6d → bytes32
UPDATE_DISPUTER_TYPE_HASH 0x79d5817f → bytes32
VALIDATOR_STRUCT_TYPE_HASH 0xfeafed84 → bytes32
VALIDATOR_UPDATE_TYPE_HASH 0x96a9a285 → bytes32
WITHDRAWAL_TYPE_HASH 0x1f79a60e → bytes32
checkValidatorNonce 0x7c1ced04 → bool
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
getValidatorSet 0xcf331250 → tuple[]
isDisputer 0x5a125c29 → bool
isRelayer 0x541d5548 → bool
isTokenSupported 0x75151b63 → bool
owner 0x8da5cb5b → address
paused 0x5c975abb → bool
pendingWithdrawal 0x13d5e886 → tuple
totalValidatorWeight 0x35fc9266 → uint256
validatorLength 0xaed1d403 → uint256
Write Contract 18 functions
These functions modify contract state and require a wallet transaction to execute.
addCollateral 0xf0d2d5a8
address token
batchFinalizeWithdraw 0xf4f54e37
uint256[] _nonces
batchRequestWithdraw 0x26dfb744
tuple[] requests
deposit 0xf45346dc
address token
uint256 amount
address receiver
depositWithPermit 0xe8c0da23
tuple request
disputeWithdrawal 0x9688cc24
uint256 _nonce
emergencyPause 0x51858e27
No parameters
emergencyUnpause 0x688ca81f
bytes[] signatures
uint256 validatorNonce
finalizeWithdraw 0x0928d152
uint256 _nonce
removeCollateral 0x06dd6ff3
address token
bytes[] signatures
uint256 validatorNonce
renounceOwnership 0x715018a6
No parameters
requestWithdraw 0x95ed4acf
tuple request
swap 0x93eca257
tuple request
transferOwnership 0xf2fde38b
address newOwner
updateDisputer 0x1a85d0a1
address disputer
bool isDisputer
bytes[] signatures
uint256 validatorNonce
updateRelayer 0x9dbf5eca
address _relayer
bool update
updateSpotSwap 0x0d5ee320
address newSpotSwap
updateValidatorSet 0x61b786a1
bytes signedData
bytes[] signatures
Token Balances (1)
View Transfers →Recent Transactions
No transactions found for this address