Address Contract Verified
Address
0x98A37eF1e3eC4f6dD1f66D771ff133d0B394BE8b
Balance
0 ETH
Nonce
9
Code Size
17467 bytes
Creator
0x9951Fb73...e0F2 at tx 0x61590934...6b10c3
Indexed Transactions
0
Contract Bytecode
17467 bytes
0x6080806040526004361015610012575f80fd5b5f905f3560e01c90816301ffc9a71461258857508063051781c014611e965780630608958f14611e4d5780631b4a5cc814611e085780631da649cf14611d085780632fd3959714611c6157806335738b8614611ac1578063401cd5ab14611a6f578063430084a914611a26578063460a060e146119bd57806351bfe9bb1461195d5780635224372c14611851578063525aaae0146114a6578063560044a9146110185780636337f14e14610fae578063715018a614610f5457806376f43a3814610f0b57806384b0196e14610e0f578063862c840914610d685780638da5cb5b14610d415780638e93987f14610d00578063a6d49dca14610c8d578063aceb774b14610aea578063b166a09f14610aab578063b291538514610a63578063bb6fadd414610a22578063bc197c811461098c578063ca41363e146106ed578063cccbdbd3146106c4578063da36f56b14610691578063e6e3b63814610658578063f23a6e61146105fe578063f2fde38b14610578578063f940e38514610291578063fda25df41461024c5763fe91c394146101aa575f80fd5b34610249576020366003190112610249576101c36125db565b906101cc613fb7565b600354916001600160a01b0380841690821680821461023a576001600160a01b031994909416909317600355604080516001600160a01b03948516815291909316602082015290917f1fdcd6de09f918c1764958c243eaacaefc18ad8e2044671a1363de4cee030c3e91a180f35b63246dcad160e11b8452600484fd5b80fd5b50346102495780600319360112610249576040517f000000000000000000000000fbc92996f333b6cdee639a88243dfa560103f4f16001600160a01b03168152602090f35b5034610249576040366003190112610249576102ab6125db565b6102b36125f1565b6001600160a01b039091168083526004602052604083205490919060ff16156105695760408051636aeef37560e11b81523360048201526001600160a01b0383166024820152908160448187875af190811561055e5784908592610520575b50604051633cf4964160e21b8152906101c082600481885afa91821561051557869261039b575b508151602092830151604080516001600160a01b039788168152928716948301949094529281019190915292166060830152608082015233907f8ca80b0f70aefb2ef0830b90f8195beb9cb8145876ea41b7e6e7fcdddf6ee8199060a090a380f35b809192506101c03d811161050e575b6103b481836126ba565b810103906101c0821261050257604051916103ce83612655565b6103d782612cba565b83526103e560208301612cba565b60208401526103f660408301612cba565b604084015261040760608301613b4e565b606084015261041860808301613421565b608084015260a0609f1982011261050a576040519061043682612684565b61044260a08401612cba565b825261045060c08401613b62565b602083015261046160e08401613b62565b60408301526104736101008401613b4e565b6060830152610120830151916001600160401b0383168303610506576080928382015260a085015261013f190112610502576104f16101a0604051926104b88461269f565b6104c56101408201613421565b84526104d46101608201612cba565b60208501526104e66101808201612cba565b604085015201613421565b606082015260c0820152905f610339565b8680fd5b8980fd5b8780fd5b503d6103aa565b6040513d88823e3d90fd5b9150506040813d604011610556575b8161053c604093836126ba565b810103126105525760208151910151905f610312565b8380fd5b3d915061052f565b6040513d86823e3d90fd5b6340d8c4db60e11b8352600483fd5b5034610249576020366003190112610249576105926125db565b61059a613fb7565b6001600160a01b031680156105ea5781546001600160a01b03198116821783556001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08380a380f35b631e4fbdf760e01b82526004829052602482fd5b50346102495760a0366003190112610249576106186125db565b506106216125f1565b506084356001600160401b038111610654576106419036906004016129f8565b5060405163f23a6e6160e01b8152602090f35b5080fd5b5034610249576020366003190112610249576020906040906001600160a01b036106806125db565b168152600883522054604051908152f35b503461024957602036600319011261024957602090600435815260068252604060018060a01b0391205416604051908152f35b50346102495780600319360112610249576003546040516001600160a01b039091168152602090f35b50346102495760a0366003190112610249576107076125db565b61070f6125f1565b6044356064358015159384820361090d57608435906001600160401b03821161050257366023830112156105025781600401359061074c8261293f565b9261075a60405194856126ba565b828452602084019260051b8101602401833682116109885760248301905b82821061095557505050506001600160a01b03168088526004602052604088205490969060ff1615610946576040516318e6a73160e11b81523360048201526001600160a01b038716602482015260448101869052606481019190915260a06084820152915160a4830181905260c4600582901b8401810192849290918a9084015b828210610919575050505080606092038189895af1801561051557869287928892610897575b509161087593917f7d024ac48f7c96ef108648f96e2f8f2a2cd9c639a7538432e7fb000b34778420959361087b575b5050604080516001600160a01b0390961686526020860192909252503393918291820190565b0390a380f35b61088f9233906001600160a01b0316613b75565b5f808061084f565b9492509250506060833d606011610911575b816108b6606093836126ba565b8101031261090d5782610875926108ed7f7d024ac48f7c96ef108648f96e2f8f2a2cd9c639a7538432e7fb000b3477842095612cba565b906108ff604060208501519401612cba565b919291929450909294610820565b8580fd5b3d91506108a9565b919350919360208061093760019360c3198a8203018652885161291b565b960192019201859391926107fa565b6340d8c4db60e11b8852600488fd5b81356001600160401b038111610984576020916109798392602436918901016129f8565b815201910190610778565b8c80fd5b8a80fd5b50346102495760a0366003190112610249576109a66125db565b506109af6125f1565b506044356001600160401b038111610654576109cf903690600401612956565b506064356001600160401b038111610654576109ef903690600401612956565b506084356001600160401b03811161065457610a0f9036906004016129f8565b5060405163bc197c8160e01b8152602090f35b5034610249576020366003190112610249576020906001600160a01b03610a476125db565b168152600a8252604060018060a01b0391205416604051908152f35b503461024957602036600319011261024957600435906001600160401b0382116102495760c06003198336030112610249576020610aa383600401613ac2565b604051908152f35b50346102495760203660031901126102495760209060ff906040906001600160a01b03610ad66125db565b168152600484522054166040519015158152f35b503461024957604036600319011261024957610b046125db565b90602435916001600160401b038311610654578260040160c06003198536030112610c895760848401354211610c7a57610b6e84610b65610b4c60a4610b5f9798018561309b565b9690610b5786613ac2565b9736916129b3565b866140f3565b9093919361412d565b60018060a01b0382169485875260076020526040872081885260205260ff604088205416610c6b57858752600560205260408720908088528160205260ff604089205416610c5c57875260205260408620805460ff19166001179055610c1390610bf16001600160a01b03610be286612ca6565b16846024840135913390613b75565b848360646001600160a01b03610c0960448601612ca6565b1693013592613b75565b507fcb8bbbfbeb1b2e281417b6bd5cb3c25b8f195c02e63ac3c434c3bf837d944494604051926020845260018060a01b03169280610c56339460208301906133af565b0390a480f35b6307387c7360e31b8852600488fd5b63562374ff60e01b8752600487fd5b638727a7f960e01b8352600483fd5b8280fd5b503461024957610c9c3661261b565b90338452600460205260ff60408520541615610cf1576040519182526001600160a01b0390811692169033907fd1398bee19313d6bf672ccb116e51f4a1a947e91c757907f51fbb5b5e56c698f90602090a480f35b6340d8c4db60e11b8452600484fd5b503461024957602036600319011261024957600435906001600160401b038211610249576101e06003198336030112610249576020610aa3836004016136e3565b5034610249578060031936011261024957546040516001600160a01b039091168152602090f35b50346102495760c036600319011261024957610d826125db565b906024356001600160401b03811161065457610da2903690600401612863565b909160a435906001600160401b0382116102495750610df593610de7610b6593610dd3610def943690600401612893565b969093608435926064359260443592612e56565b9336916129b3565b826140f3565b604080519182526001600160a01b03929092166020820152f35b5034610249578060031936011261024957610eaf90610e4d7f44657269466c6f7700000000000000000000000000000000000000000000000861418d565b90610e777f31000000000000000000000000000000000000000000000000000000000000016142b3565b906020610ebd60405193610e8b83866126ba565b8385525f368137604051968796600f60f81b885260e08589015260e088019061291b565b90868203604088015261291b565b904660608601523060808601528260a086015284820360c08601528080855193848152019401925b828110610ef457505050500390f35b835185528695509381019392810192600101610ee5565b50346102495760403660031901126102495760209060ff906040906001600160a01b03610f366125db565b16815260078452818120602435825284522054166040519015158152f35b5034610249578060031936011261024957610f6d613fb7565b80546001600160a01b03198116825581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b503461024957604036600319011261024957600435906001600160401b038211610249576101e0600319833603011261024957602435906001600160401b03821161024957610df5610de7610b65610def8661100d3660048901612893565b9490916004016136e3565b50346102495760c0366003190112610249576110326125db565b9061103b6125f1565b6044356001600160401b038111610c895761105a903690600401612863565b9390916064356084359160a4356001600160401b03811161050257611083903690600401612893565b979060018060a01b03861694858952600460205260ff60408a20541615611497578042116114885785895260086020526040808a205490516304a407f960e51b815290926080826004818b5afa92831561147d578b998c80948196611415575b501561140657611114926111068d9e9f938b61111d9e9f8b8b9161110e97612e56565b9236916129b3565b906140f3565b9099919961412d565b6001600160a01b031696871515908190816113f3575b6001600160a01b039081169a9681169682159291168b149082806113eb575b806113e1575b6113d257916113ca575b50156113995750833314908115611386575b505b1561137757600181018091116113635784895260086020526040892055875b8181106111a0578880f35b6111ab81838a61342e565b60208101846001600160a01b036111c183612ca6565b16141580611348575b8061132d575b61131f57866001600160a01b036111e684612ca6565b1603611293575090853b15610506576040516332f5e75760e11b815261120f600482018461343e565b8a8082608481838c5af1918215611286578a9261126d575b50506001925b61123a604051809261343e565b866080820152877fbd48b84c8740f85aeb848fa8da9767b1ae659a7ce7c72884cc4641041f1c490360a03393a401611195565b8192509061127a916126ba565b61050657878a5f611227565b50604051903d90823e3d90fd5b336001600160a01b036112a584612ca6565b16141580611304575b6112f5576001929189916112f0906001600160a01b036112d060408501612ca6565b16906112e46112de85612ca6565b91612ca6565b90606085013592613b75565b61122d565b6303e2df4d60e41b8b5260048bfd5b50886001600160a01b0361131784612ca6565b1614156112ae565b6211f58160e11b8b5260048bfd5b50866001600160a01b0361134083612ca6565b1614156111d0565b50876001600160a01b0361135b83612ca6565b1614156111ca565b634e487b7160e01b89526011600452602489fd5b636edaef2f60e11b8952600489fd5b6001600160a01b0316331490505f611174565b90816113c0575b81156113ad575b50611176565b6001600160a01b0316331490505f6113a7565b33881491506113a0565b90505f611162565b632057875960e21b8e5260048efd5b50878c1415611158565b508115611152565b6001600160a01b0381168a149150611133565b63030cd96760e41b8d5260048dfd5b945050995092506080823d608011611475575b81611435608093836126ba565b810103126109885761144682612cba565b9261145360208401612cba565b9961146c606061146560408701613421565b9501612cba565b949a935f6110e3565b3d9150611428565b6040513d8d823e3d90fd5b6379ec73d960e01b8952600489fd5b6340d8c4db60e11b8952600489fd5b5034610249576060366003190112610249576114c06125db565b906114c96125f1565b604435906001600160401b038211610c8957816004019060c060031984360301126105525760848301354211611842576001600160a01b031691821580156117f4575b9481611539959661153f61152660a461154896018761309b565b989061153188613ac2565b9936916129b3565b886140f3565b9095919561412d565b60018060a01b03841696878952600760205260408920818a5260205260ff60408a2054166117e55787895260056020526040892090808a528160205260ff60408b2054166117d657895260205260408820805460ff1916600117905587906115c96001600160a01b036115ba88612ca6565b16866024860135913390613b75565b1561163557507f5c5c752b15241119c7529c7dcf77073079cdf0d3bc1663fd0492e1a60f81f383929061160e90838360646001600160a01b03610c0960448601612ca6565b506040519384526040602085015260018060a01b03169280610c56339460408301906133af565b9061165d60646001600160a01b0361164f60448501612ca6565b169201358092863091613b75565b60405163a495408560e01b8152600481018790527f0000000000000000000000005c590b3851820edbae5c2686ea5437ec5b8b4f686001600160a01b031691602082602481865afa91821561055e57849261179b575b50823b156105525760c48492836040519586948593637921219560e11b85523360048601523060248601526044850152606484015260a060848401528160a48401525af1801561177b57611786575b5050833b1561090d576040516395a2251f60e01b81526001600160a01b038216600482015286908181602481838a5af1801561177b57611766575b50507f5c5c752b15241119c7529c7dcf77073079cdf0d3bc1663fd0492e1a60f81f3839161160e565b81611770916126ba565b61090d57855f61173d565b6040513d84823e3d90fd5b81611790916126ba565b61090d57855f611702565b935090506020833d6020116117ce575b816117b8602093836126ba565b810103126117ca57889251905f6116b3565b5f80fd5b3d91506117ab565b6307387c7360e31b8a5260048afd5b63562374ff60e01b8952600489fd5b838552600460205260ff6040862054161561183357836001600160a01b0361181e60448501612ca6565b161461150c5763929eb08960e01b8552600485fd5b6340d8c4db60e11b8552600485fd5b638727a7f960e01b8452600484fd5b5034610249576118603661261b565b6001600160a01b0383168085526004602052604085205490939060ff16156118335760408051637022215160e01b81523360048201526001600160a01b03851660248201526044810184905292908360648189895af1918215610515577f96558a334f4759f0e7c423d68c84721860bd8fbf94ddc4e55158ecb125ad04b59387908894611927575b506118ff91849133906001600160a01b0316613b75565b604080516001600160a01b039095168552602085019190915283015233918060608101610875565b6118ff92945061194f915060403d604011611956575b61194781836126ba565b810190612cce565b93916118e8565b503d61193d565b5034610249576080366003190112610249576119776125db565b90602435906001600160401b038211610249576101e060031983360301126102495760e06119ae6064356044356004860187613108565b6119bb60405180926128c0565bf35b503461024957604036600319011261024957600435906001600160401b0382116102495760c0600319833603011261024957602435906001600160401b03821161024957610df5610de7610b65610def86611a1b3660048901612893565b949091600401613ac2565b50346102495760403660031901126102495760209060ff906040906001600160a01b03611a516125db565b16815260058452818120602435825284522054166040519015158152f35b50346102495760a036600319011261024957611a896125db565b90602435906001600160401b038211610249576020610aa384611aaf3660048701612863565b91608435926064359260443592612e56565b5034610249576101c03660031901126102495760405190611ae182612655565b6004356001600160a01b03811681036106545782526024356001600160a01b03811681036106545760208301526044356001600160a01b03811681036106545760408301526064356001600160801b0381168103610654576060830152608435801515810361065457608083015260a03660a319011261024957604051611b6781612684565b60a4356001600160a01b0381168103610c8957815260c43565ffffffffffff81168103610c8957602082015260e43565ffffffffffff81168103610c89576040820152610104356001600160801b0381168103610c89576060820152610124356001600160401b0381168103610c8957608082015260a08301526080610143193601126102495760405190611bfb8261269f565b610144358015158103610654578252610164356001600160a01b0381168103610654576020830152610184356001600160a01b03811681036106545760408301526101a435908115158203610249576020610aa3858585606082015260c0820152612ceb565b50346102495760203660031901126102495760043533825260076020526040822033835260056020526040832082845260205260ff6040842054168015611cf3575b611ce45781835260205260408220805460ff19166001179055337f1715400073dad0f0c03c0187a1507605bd7e0fcbc871b9a2fdfe4b79ebaa64dd8380a380f35b637c42bf6160e01b8352600483fd5b508183528060205260ff604084205416611ca3565b503461024957611d173661261b565b6001600160a01b03831680855260046020526040852054909392919060ff161561183357604080516301fca7dd60e61b81523360048201526001600160a01b03841660248201526044810183905292908360648189895af19283156105155785947f81cfb79463601de705d4cf6b8d69112983d76a685120e5e4d3581f30871b87fc9484610875938a908b93611de4575b509192611dbf9233906001600160a01b0316613b75565b60405193849384604091949392606082019560018060a01b0316825260208201520152565b611dbf9350611e02915060403d6040116119565761194781836126ba565b92611da8565b50346102495780600319360112610249576040517f0000000000000000000000005c590b3851820edbae5c2686ea5437ec5b8b4f686001600160a01b03168152602090f35b50346102495760403660031901126102495760209060ff906040906001600160a01b03611e786125db565b16815260098452818120602435825284522054166040519015158152f35b50346117ca5760603660031901126117ca576004356001600160401b0381116117ca5780600401906101e060031982360301126117ca5760243591604435611ee081858433613108565b918251600d8110156125745761256557604083019160018060a01b038351165f52600560205260405f2060208501515f5260205260405f20600160ff1982541617905560018060a01b038351165f52600960205260405f206101c486019060e0611f4a8386612a16565b01355f5260205260405f20600160ff19825416179055611f756040611f6f8386612a16565b01612a2c565b1561255e5783516001600160a01b0316935b611f966040611f6f8487612a16565b1561254e575033905b611fb560c0611faf5f9387612a16565b01612ca6565b90611fc8611fc33687612723565b612ceb565b916001600160a01b03811690816124bb575050604051631d5e528f60e21b81529790506020886004817f0000000000000000000000005c590b3851820edbae5c2686ea5437ec5b8b4f686001600160a01b03165afa978815612444575f98612487575b50876e5af43d82803e903d91602b57fd5bf37f000000000000000000000000fbc92996f333b6cdee639a88243dfa560103f4f19160405160208101918252602081526120786040826126ba565b51902091763d602d80600a3d3981f3363d3d373d3d3d363d7300000062ffffff8260881c16175f5260781b17602052603760095ff56001600160a01b0381169081156124785792815f52600460205260405f20600160ff198254161790556120e36101a48401612a2c565b61244f575b505060015b6123d8575b6120fe60848201612a2c565b90816123c4575b50806123a5575b612375575b6001600160a01b038116978990893b15610654576040516340c10f1960e01b81526001600160a01b0388166004820152602481018290528281604481838f5af190811561236a578391612355575b50507f0000000000000000000000005c590b3851820edbae5c2686ea5437ec5b8b4f686001600160a01b0316803b15610c895760405163b3f1c93d60e01b81526001600160a01b03861660048201819052602482018d9052604482019b909b5260648101929092528290829081835a92608493f1801561177b5761233c575b506122049190506001600160a01b036121f686612ca6565b16908360c089015192613b75565b608085019060018060a01b038251169060608701519060a088019283518303928311612328579161223991888d969594613b75565b8151600354825161225a9290916001600160a01b03908116918a9116613b75565b600354915190516001600160a01b039283169290911690823b156105525760648492836040519586948593631dd5482960e21b85528a6004860152602485015260448401525af1801561177b5761230f575b5050907ff90a67ae8df96b6c05d0c423e3d944c30c96d0049fcef0ba1a63953d2e19a173926122ee926122f96040519485946101208652610120860190612a8a565b9660208501906128c0565b6101008301526001600160a01b0316930390a480f35b8161231c919493946126ba565b6105025790865f6122ac565b634e487b7160e01b8c52601160045260248cfd5b81612346916126ba565b61235157885f6121de565b8880fd5b8161235f916126ba565b61065457815f61215f565b6040513d85823e3d90fd5b6001600160a01b038181168a52600a60205260408a2080546001600160a01b031916918716919091179055612111565b506001600160a01b038181168a52600a60205260408a2054161561210c565b6123d291506101a401612a2c565b5f612105565b6001600160a01b038216803b156117ca575f8981926040518094818094639c0f607d60e01b8252604060048301526124148d6044840190612a8a565b90602483015203925af180156124445761242f575b506120f2565b61243c919a505f906126ba565b5f985f612429565b6040513d5f823e3d90fd5b5f52600660205260405f20906bffffffffffffffffffffffff60a01b8254161790555f806120e8565b63b06ebf3d60e01b5f5260045ffd5b9097506020813d6020116124b3575b816124a3602093836126ba565b810103126117ca5751965f61202b565b3d9150612496565b60405163a495408560e01b8152600481019290925291989192506020816024817f0000000000000000000000005c590b3851820edbae5c2686ea5437ec5b8b4f686001600160a01b03165afa908115612444575f9161251c575b50976120ed565b90506020813d602011612546575b81612537602093836126ba565b810103126117ca57515f612515565b3d915061252a565b516001600160a01b031690611f9f565b3393611f87565b63e30578ab60e01b5f5260045ffd5b634e487b7160e01b5f52602160045260245ffd5b346117ca5760203660031901126117ca576004359063ffffffff60e01b82168092036117ca57602091630271189760e51b81149081156125ca575b5015158152f35b6301ffc9a760e01b149050836125c3565b600435906001600160a01b03821682036117ca57565b602435906001600160a01b03821682036117ca57565b35906001600160a01b03821682036117ca57565b60609060031901126117ca576004356001600160a01b03811681036117ca57906024356001600160a01b03811681036117ca579060443590565b60e081019081106001600160401b0382111761267057604052565b634e487b7160e01b5f52604160045260245ffd5b60a081019081106001600160401b0382111761267057604052565b608081019081106001600160401b0382111761267057604052565b90601f801991011681019081106001600160401b0382111761267057604052565b35906001600160801b03821682036117ca57565b359081151582036117ca57565b359065ffffffffffff821682036117ca57565b35906001600160401b03821682036117ca57565b80929103916101c083126117ca5760405161273d81612655565b809361274883612607565b825261275660208401612607565b602083015261276760408401612607565b6040830152612778606084016126db565b6060830152612789608084016126ef565b608083015260a0609f198201126117ca576080906040516127a981612684565b6127b560a08601612607565b81526127c360c086016126fc565b60208201526127d460e086016126fc565b60408201526127e661010086016126db565b60608201526127f8610120860161270f565b8184015260a084015261013f1901126117ca5760c09061285a6101a0604051946128218661269f565b61282e61014082016126ef565b865261283d6101608201612607565b602087015261284f6101808201612607565b6040870152016126ef565b60608401520152565b9181601f840112156117ca578235916001600160401b0383116117ca576020808501948460071b0101116117ca57565b9181601f840112156117ca578235916001600160401b0383116117ca57602083818601950101116117ca57565b8051600d8110156125745760c091829184526020810151602085015260018060a01b0360408201511660408501526060810151606085015260018060a01b03608082015116608085015260a081015160a08501520151910152565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b6001600160401b0381116126705760051b60200190565b9080601f830112156117ca57813561296d8161293f565b9261297b60405194856126ba565b81845260208085019260051b8201019283116117ca57602001905b8282106129a35750505090565b8135815260209182019101612996565b9291926001600160401b03821161267057604051916129dc601f8201601f1916602001846126ba565b8294818452818301116117ca578281602093845f960137010152565b9080601f830112156117ca57816020612a13933591016129b3565b90565b90359061011e19813603018212156117ca570190565b3580151581036117ca5790565b9035601e19823603018112156117ca5701602081359101916001600160401b0382116117ca5781360383136117ca57565b908060209392818452848401375f828201840152601f01601f1916010190565b906001600160a01b03612a9c83612607565b1681526001600160a01b03612ab360208401612607565b1660208201526001600160a01b03612acd60408401612607565b1660408201526001600160801b03612ae7606084016126db565b166060820152612af9608083016126ef565b151560808201526001600160a01b03612b1460a08401612607565b1660a082015265ffffffffffff612b2d60c084016126fc565b1660c082015265ffffffffffff612b4660e084016126fc565b1660e08201526001600160801b03612b6161010084016126db565b166101008201526001600160401b03612b7d610120840161270f565b16610120820152612b9161014083016126ef565b15156101408201526001600160a01b03612bae6101608401612607565b166101608201526001600160a01b03612bca6101808401612607565b16610180820152612bde6101a083016126ef565b15156101a08201526101c08201359161011e19813603018312156117ca57612c9361030091612a1394016101e06101c085015280356101e08501526020810135610200850152612c30604082016126ef565b1515610220850152612c44606082016126ef565b1515610240850152608081013561026085015260a08101356102808501526001600160a01b03612c7660c08301612607565b166102a085015260e08101356102c0850152610100810190612a39565b9190926101206102e08201520191612a6a565b356001600160a01b03811681036117ca5790565b51906001600160a01b03821682036117ca57565b91908260409103126117ca576020612ce583612cba565b92015190565b604051606060c0602083019360018060a01b03815116855260018060a01b03602082015116604085015260018060a01b03604082015116838501526001600160801b03838201511660808501526080810151151560a08501526001600160401b03608060a083015160018060a01b038151168588015265ffffffffffff60208201511660e088015265ffffffffffff6040820151166101008801526001600160801b03868201511661012088015201511661014085015201518051151561016084015260018060a01b0360208201511661018084015260018060a01b036040820151166101a0840152015115156101c08201526101c08152612def6101e0826126ba565b51902090565b60405190612e046060836126ba565b604082527f746f2c6164647265737320746f6b656e2c75696e7432353620616d6f756e74296040837f5061796d656e744c656728616464726573732066726f6d2c616464726573732060208201520152565b92939095949195612e668761293f565b90612e7460405192836126ba565b878252612e808861293f565b602083019890601f1901368a375f5b818110612fe457505050604051602081018092519098905f5b818110612fce57505050612ec981612a13989903601f1981018352826126ba565b51902093612ed5612df5565b604051612f87608b826020808201957f536574746c656d656e74286164647265737320657363726f772c5061796d656e87527f744c65675b5d207061796d656e744c6567732c75696e74323536206e6f6e636560408401527f2c75696e7432353620736574746c656d656e74436f64652c75696e743235362060608401526a76616c6964556e74696c2960a81b60808401528051918291018484015e81015f838201520301601f1981018352826126ba565b51902094604051946020860196875260018060a01b031660408601526060850152608084015260a083015260c082015260c08152612fc660e0826126ba565b519020613c0c565b82518b5260209a8b019a90920191600101612ea8565b612fef81838561342e565b612ff7612df5565b6020815191012090606061300a82612ca6565b9161301760208201612ca6565b61302360408301612ca6565b60408051602081019788526001600160a01b0396871691810191909152918516848301529093166080840152013560a080830191909152815261306760c0826126ba565b5190209084518110156130875760019160208260051b8701015201612e8f565b634e487b7160e01b5f52603260045260245ffd5b903590601e19813603018212156117ca57018035906001600160401b0382116117ca576020019181360383136117ca57565b818102929181159184041417156130e057565b634e487b7160e01b5f52601160045260245ffd5b356001600160801b03811681036117ca5790565b9291906040519261311884612655565b5f845260208401945f865260408501945f86525f60608201525f60808201525f60a08201525f60c08201526131a881976101c086019761316661315b8a89612a16565b61010081019061309b565b909261319361318a61318461317a8c6136e3565b96879536916129b3565b846140f3565b9092919261412d565b6001600160a01b031692839052528787613c32565b600d811015612574578082526133a557506131cd846131c78786612a16565b356130cd565b90600460206001600160a01b036131e387612ca6565b166040519283809263313ce56760e01b82525afa8015612444575f90613368575b60ff915016604d81116130e057600a0a918215613354576060611f6f602094613235930498828b01998a5287612a16565b156133445761324384612ca6565b6001600160a01b0390811660808901526003546040516378b7433760e01b815292821660048401526060602484015291938492909116908290819061328b6064830189612a8a565b90604483015203915afa908115612444575f9161330a575b506132f460606132fb9493670de0b6b3a76400006132e881986001600160801b03966706f05b59d3b2000081115f1461330457506706f05b59d3b20000905b516130cd565b0460a0890152016130f4565b16906130cd565b0460c082015290565b906132e2565b929190506020833d60201161333c575b81613327602093836126ba565b810103126117ca5791519091906132f46132a3565b3d915061331a565b61334f828501612ca6565b613243565b634e487b7160e01b5f52601260045260245ffd5b506020813d60201161339d575b81613382602093836126ba565b810103126117ca575160ff811681036117ca5760ff90613204565b3d9150613375565b9550505050505090565b612a13919060c090613411906001600160a01b036133cc82612607565b168452602081810135908501526001600160a01b036133ed60408301612607565b166040850152606081013560608501526080810135608085015260a0810190612a39565b9190928160a08201520191612a6a565b519081151582036117ca57565b91908110156130875760071b0190565b60609081906001600160a01b0361345482612607565b1684526001600160a01b0361346b60208301612607565b1660208501526001600160a01b0361348560408301612607565b1660408501520135910152565b604051906134a160a0836126ba565b60668252656f774361702960d01b6080837f457865726369736553657474696e67732861646472657373206f7261636c652c60208201527f75696e743438206578706972792c75696e743438206561726c6965737445786560408201527f72636973652c75696e7431323820737472696b652c75696e74363420626f727260608201520152565b3565ffffffffffff811681036117ca5790565b356001600160401b03811681036117ca5790565b6040519061355e60c0836126ba565b608b82526a7450726f7669646572732960a81b60a0837f416476616e63656453657474696e677328626f6f6c20766f74696e6744656c6560208201527f676174696f6e416c6c6f7765642c6164647265737320616c6c6f77656444656c60408201527f656761746552656769737472792c6164647265737320736574746c656d656e7460608201527f466163696c697461746f722c626f6f6c20616c6c6f774d756c7469436f6c6c6160808201520152565b6040519061361f60c0836126ba565b609b82527f61784e6f74696f6e616c2c75696e743235362071756f7465496429000000000060a0837f51756f74652875696e74323536207072656d69756d5065724e6f74696f6e616c60208201527f556e69742c75696e743235362076616c6964556e74696c2c626f6f6c2069734260408201527f69642c626f6f6c207072656d69756d4973496e436f6c6c61746572616c546f6b60608201527f656e2c75696e74323536206d696e4e6f74696f6e616c2c75696e74323536206d60808201520152565b612a13906136ef613492565b6020815191012061370260a08301612ca6565b6001600160401b0361371660c08501613528565b6001600160801b0361372a60e08701613528565b65ffffffffffff61373e61010089016130f4565b918161374d6101208b0161353b565b956040519860208a019a8b5260018060a01b031660408a01521660608801521660808601521660a08401521660c082015260c0815261378d60e0826126ba565b5190209061379961354f565b602081519101206137ad6101408301612a2c565b6137ba6101608401612ca6565b6137c76101808501612ca6565b6137d46101a08601612a2c565b6040805160208101968752941515908501526001600160a01b03928316606085015291166080830152151560a080830191909152815261381560c0826126ba565b519020613820613610565b602081519101206101c083016138368185612a16565b359060206138448287612a16565b0135906138566040611f6f8389612a16565b6138656060611f6f848a612a16565b6080613871848a612a16565b01359160e061388e60a0613885878d612a16565b0135958b612a16565b01359460405196602088019889526040880152606087015215156080860152151560a085015260c084015260e083015261010082015261010081526138d5610120826126ba565b519020906138e161354f565b6020613a396138ee613492565b826138f7613610565b60f060405195869481808701997f457363726f7751756f74655061796c6f6164286164647265737320636f6c6c618b527f746572616c546f6b656e2c6164647265737320636f6e76657273696f6e546f6b60408901527f656e2c6164647265737320636f6c6c617450726f766964657244656c6567617460608901527f652c626f6f6c2067656e65726963536574746c656d656e74416c6c6f7765642c60808901527f457865726369736553657474696e677320657865726369736553657474696e6760a08901527f732c416476616e63656453657474696e677320616476616e636564536574746960c08901526f6e67732c51756f74652071756f74652960801b60e08901528051918291018589015e8601908382015f8152815193849201905e0101905f8252805192839101825e015f815203601f1981018352826126ba565b51902093613a4684612ca6565b93613a5360208201612ca6565b90613a6c6080613a6560408401612ca6565b9201612a2c565b6040805160208101998a526001600160a01b039889169181019190915292871660608401529516608082015293151560a085015260c084015260e0830152610100808301919091528152612fc6610120826126ba565b612a1390613acf81612ca6565b906080613ade60408301612ca6565b916040519260208401947f4ace8171b5b304b249a072fc839ae84d201f86d88190fa4c019449bb0cf5999d865260018060a01b031660408501526020820135606085015260018060a01b031682840152606081013560a0840152013560c082015260c08152612fc660e0826126ba565b51906001600160801b03821682036117ca57565b519065ffffffffffff821682036117ca57565b6040516323b872dd60e01b60208083019182526001600160a01b039485166024840152949093166044820152606480820195909552938452925f9190613bbc6084826126ba565b519082855af115612444575f513d613c0357506001600160a01b0381163b155b613be35750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b60011415613bdc565b604290613c17613fdd565b906040519161190160f01b8352600283015260228201522090565b916101c08301916020613c458486612a16565b01354211613fad576080613c598486612a16565b01358110908115613f95575b8115613f8c575b50613f835760c0830190613c7f82613528565b91620151804201928342116130e05765ffffffffffff84911610613f78576080850192613cab84612a2c565b159182613e79575b5050613e6f5760018060a01b031693845f52600560205260405f20815f5260205260ff60405f205416613e6557845f52600760205260405f20905f5260205260ff60405f205416613e5c57835f52600960205260405f2060e0613d168486612a16565b01355f5260205260ff60405f205416613e53576001600160a01b03613d4060c0611faf8587612a16565b16613d4e575b505050505f90565b6001600160a01b03613d6560c0611faf8587612a16565b165f52600460205260ff60405f20541615613e4a57613d87611fc33685612723565b613d9660c0611faf8587612a16565b5f91825260066020526040909120546001600160a01b03908116911603613e4157613dc090612a2c565b613dcb575b80613d46565b613dda6040611f6f8385612a16565b15613e39576001600160a01b0391613df99160c091611faf9190612a16565b165f908152600a60205260409020546001600160a01b03168015918215613e2e575b5050613e29575f8080613dc5565b600a90565b141590505f80613e1b565b505050600b90565b50505050600690565b50505050600590565b50505050600990565b50505050600490565b5050505050600390565b5050505050600290565b909150613e8586612ca6565b6001600160a01b03613e9960208901612ca6565b6001600160a01b03909216911614918215613f5c575b508115613f19575b508015613ef3575b8015613ecd575b5f80613cb3565b50670de0b6b3a76400006001600160401b03613eec610120870161353b565b1611613ec6565b50670de0b6b3a76400006001600160801b03613f11606087016130f4565b161415613ebf565b613f239150613528565b6201518065ffffffffffff613f3a60e08801613528565b160165ffffffffffff81116130e05765ffffffffffff8091169116105f613eb7565b90915065ffffffffffff613f6f83613528565b1610905f613eaf565b505050505050600c90565b50505050600890565b9050155f613c6c565b905060a0613fa38486612a16565b0135811190613c65565b5050505050600190565b5f546001600160a01b03163303613fca57565b63118cdaa760e01b5f523360045260245ffd5b307f00000000000000000000000098a37ef1e3ec4f6dd1f66d771ff133d0b394be8b6001600160a01b031614806140ca575b15614038577fbf7201fc899397c16ac5e8c1792f13b3eb245ab487fe10a64e0dcd9d5a1c270590565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527ff9349e5091c505a3d3ac4c7d319631defb15743aa48857ea1719772fe306fad560408201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260a08152612def60c0826126ba565b507f0000000000000000000000000000000000000000000000000000000000000001461461400f565b81519190604183036141235761411c9250602082015190606060408401519301515f1a90614383565b9192909190565b50505f9160029190565b6004811015612574578061413f575050565b600181036141565763f645eedf60e01b5f5260045ffd5b60028103614171575063fce698f760e01b5f5260045260245ffd5b60031461417b5750565b6335e2f38360e21b5f5260045260245ffd5b60ff81146141d35760ff811690601f82116141c457604051916141b16040846126ba565b6020808452838101919036833783525290565b632cd44ac360e21b5f5260045ffd5b506040515f6001548060011c91600182169182156142a9575b6020841083146142955783855284929081156142765750600114614217575b612a13925003826126ba565b5060015f90815290917fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf65b81831061425a575050906020612a139282010161420b565b6020919350806001915483858801015201910190918392614242565b60209250612a1394915060ff191682840152151560051b82010161420b565b634e487b7160e01b5f52602260045260245ffd5b92607f16926141ec565b60ff81146142d75760ff811690601f82116141c457604051916141b16040846126ba565b506040515f6002548060011c9160018216918215614379575b602084108314614295578385528492908115614276575060011461431a57612a13925003826126ba565b5060025f90815290917f405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5ace5b81831061435d575050906020612a139282010161420b565b6020919350806001915483858801015201910190918392614345565b92607f16926142f0565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084116143fa579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa15612444575f516001600160a01b038116156143f057905f905f90565b505f906001905f90565b5050505f916003919056fea26469706673582212205d6e82aa6673f298e404d79bafbf59e705e6e17d7b7185b1c9ef77955cd548eb64736f6c634300081c0033
Verified Source Code Full Match
Compiler: v0.8.28+commit.7893614a
EVM: cancun
Optimization: Yes (200 runs)
Initializable.sol 238 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
ERC20Upgradeable.sol 330 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {IERC20Metadata} from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import {ContextUpgradeable} from "../../utils/ContextUpgradeable.sol";
import {IERC20Errors} from "@openzeppelin/contracts/interfaces/draft-IERC6093.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20, IERC20Metadata, IERC20Errors {
/// @custom:storage-location erc7201:openzeppelin.storage.ERC20
struct ERC20Storage {
mapping(address account => uint256) _balances;
mapping(address account => mapping(address spender => uint256)) _allowances;
uint256 _totalSupply;
string _name;
string _symbol;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ERC20")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ERC20StorageLocation = 0x52c63247e1f47db19d5ce0460030c497f067ca4cebf71ba98eeadabe20bace00;
function _getERC20Storage() private pure returns (ERC20Storage storage $) {
assembly {
$.slot := ERC20StorageLocation
}
}
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
ERC20Storage storage $ = _getERC20Storage();
$._name = name_;
$._symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
ERC20Storage storage $ = _getERC20Storage();
return $._symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
ERC20Storage storage $ = _getERC20Storage();
return $._allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
$._totalSupply += value;
} else {
uint256 fromBalance = $._balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
$._balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
$._totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
$._balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
ERC20Storage storage $ = _getERC20Storage();
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
$._allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
ContextUpgradeable.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
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;
}
}
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);
}
}
IVotes.sol 59 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (governance/utils/IVotes.sol)
pragma solidity >=0.8.4;
/**
* @dev Common interface for {ERC20Votes}, {ERC721Votes}, and other {Votes}-enabled contracts.
*/
interface IVotes {
/**
* @dev The signature used has expired.
*/
error VotesExpiredSignature(uint256 expiry);
/**
* @dev Emitted when an account changes their delegate.
*/
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/**
* @dev Emitted when a token transfer or delegate change results in changes to a delegate's number of voting units.
*/
event DelegateVotesChanged(address indexed delegate, uint256 previousVotes, uint256 newVotes);
/**
* @dev Returns the current amount of votes that `account` has.
*/
function getVotes(address account) external view returns (uint256);
/**
* @dev Returns the amount of votes that `account` had at a specific moment in the past. If the `clock()` is
* configured to use block numbers, this will return the value at the end of the corresponding block.
*/
function getPastVotes(address account, uint256 timepoint) external view returns (uint256);
/**
* @dev Returns the total supply of votes available at a specific moment in the past. If the `clock()` is
* configured to use block numbers, this will return the value at the end of the corresponding block.
*
* NOTE: This value is the sum of all available votes, which is not necessarily the sum of all delegated votes.
* Votes that have not been delegated are still part of total supply, even though they would not participate in a
* vote.
*/
function getPastTotalSupply(uint256 timepoint) external view returns (uint256);
/**
* @dev Returns the delegate that `account` has chosen.
*/
function delegates(address account) external view returns (address);
/**
* @dev Delegates votes from the sender to `delegatee`.
*/
function delegate(address delegatee) external;
/**
* @dev Delegates votes from signer to `delegatee`.
*/
function delegateBySig(address delegatee, uint256 nonce, uint256 expiry, uint8 v, bytes32 r, bytes32 s) external;
}
draft-IERC6093.sol 161 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
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);
}
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";
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";
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
);
}
Clones.sol 294 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (proxy/Clones.sol)
pragma solidity ^0.8.20;
import {Create2} from "../utils/Create2.sol";
import {Errors} from "../utils/Errors.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[ERC-1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*/
library Clones {
error CloneArgumentsTooLong();
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
*
* This function uses the create opcode, which should never revert.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function clone(address implementation) internal returns (address instance) {
return clone(implementation, 0);
}
/**
* @dev Same as {xref-Clones-clone-address-}[clone], but with a `value` parameter to send native currency
* to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function clone(address implementation, uint256 value) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
assembly ("memory-safe") {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create(value, 0x09, 0x37)
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple times will revert, since
* the clones cannot be deployed twice at the same address.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
return cloneDeterministic(implementation, salt, 0);
}
/**
* @dev Same as {xref-Clones-cloneDeterministic-address-bytes32-}[cloneDeterministic], but with
* a `value` parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneDeterministic(
address implementation,
bytes32 salt,
uint256 value
) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
assembly ("memory-safe") {
// Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes
// of the `implementation` address with the bytecode before the address.
mstore(0x00, or(shr(0xe8, shl(0x60, implementation)), 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000))
// Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
mstore(0x20, or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3))
instance := create2(value, 0x09, 0x37, salt)
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(add(ptr, 0x38), deployer)
mstore(add(ptr, 0x24), 0x5af43d82803e903d91602b57fd5bf3ff)
mstore(add(ptr, 0x14), implementation)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73)
mstore(add(ptr, 0x58), salt)
mstore(add(ptr, 0x78), keccak256(add(ptr, 0x0c), 0x37))
predicted := and(keccak256(add(ptr, 0x43), 0x55), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
* immutable arguments. These are provided through `args` and cannot be changed after deployment. To
* access the arguments within the implementation, use {fetchCloneArgs}.
*
* This function uses the create opcode, which should never revert.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneWithImmutableArgs(address implementation, bytes memory args) internal returns (address instance) {
return cloneWithImmutableArgs(implementation, args, 0);
}
/**
* @dev Same as {xref-Clones-cloneWithImmutableArgs-address-bytes-}[cloneWithImmutableArgs], but with a `value`
* parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneWithImmutableArgs(
address implementation,
bytes memory args,
uint256 value
) internal returns (address instance) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
assembly ("memory-safe") {
instance := create(value, add(bytecode, 0x20), mload(bytecode))
}
if (instance == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Deploys and returns the address of a clone that mimics the behavior of `implementation` with custom
* immutable arguments. These are provided through `args` and cannot be changed after deployment. To
* access the arguments within the implementation, use {fetchCloneArgs}.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy the clone. Using the same
* `implementation`, `args` and `salt` multiple times will revert, since the clones cannot be deployed twice
* at the same address.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*/
function cloneDeterministicWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt
) internal returns (address instance) {
return cloneDeterministicWithImmutableArgs(implementation, args, salt, 0);
}
/**
* @dev Same as {xref-Clones-cloneDeterministicWithImmutableArgs-address-bytes-bytes32-}[cloneDeterministicWithImmutableArgs],
* but with a `value` parameter to send native currency to the new contract.
*
* WARNING: This function does not check if `implementation` has code. A clone that points to an address
* without code cannot be initialized. Initialization calls may appear to be successful when, in reality, they
* have no effect and leave the clone uninitialized, allowing a third party to initialize it later.
*
* NOTE: Using a non-zero value at creation will require the contract using this function (e.g. a factory)
* to always have enough balance for new deployments. Consider exposing this function under a payable method.
*/
function cloneDeterministicWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt,
uint256 value
) internal returns (address instance) {
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
return Create2.deploy(value, salt, bytecode);
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
*/
function predictDeterministicAddressWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
bytes memory bytecode = _cloneCodeWithImmutableArgs(implementation, args);
return Create2.computeAddress(salt, keccak256(bytecode), deployer);
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministicWithImmutableArgs}.
*/
function predictDeterministicAddressWithImmutableArgs(
address implementation,
bytes memory args,
bytes32 salt
) internal view returns (address predicted) {
return predictDeterministicAddressWithImmutableArgs(implementation, args, salt, address(this));
}
/**
* @dev Get the immutable args attached to a clone.
*
* - If `instance` is a clone that was deployed using `clone` or `cloneDeterministic`, this
* function will return an empty array.
* - If `instance` is a clone that was deployed using `cloneWithImmutableArgs` or
* `cloneDeterministicWithImmutableArgs`, this function will return the args array used at
* creation.
* - If `instance` is NOT a clone deployed using this library, the behavior is undefined. This
* function should only be used to check addresses that are known to be clones.
*/
function fetchCloneArgs(address instance) internal view returns (bytes memory) {
bytes memory result = new bytes(instance.code.length - 45); // revert if length is too short
assembly ("memory-safe") {
extcodecopy(instance, add(result, 32), 45, mload(result))
}
return result;
}
/**
* @dev Helper that prepares the initcode of the proxy with immutable args.
*
* An assembly variant of this function requires copying the `args` array, which can be efficiently done using
* `mcopy`. Unfortunately, that opcode is not available before cancun. A pure solidity implementation using
* abi.encodePacked is more expensive but also more portable and easier to review.
*
* NOTE: https://eips.ethereum.org/EIPS/eip-170[EIP-170] limits the length of the contract code to 24576 bytes.
* With the proxy code taking 45 bytes, that limits the length of the immutable args to 24531 bytes.
*/
function _cloneCodeWithImmutableArgs(
address implementation,
bytes memory args
) private pure returns (bytes memory) {
if (args.length > 24531) revert CloneArgumentsTooLong();
return
abi.encodePacked(
hex"61",
uint16(args.length + 45),
hex"3d81600a3d39f3363d3d373d3d3d363d73",
implementation,
hex"5af43d82803e903d91602b57fd5bf3",
args
);
}
}
ERC1155.sol 389 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.20;
import {IERC1155} from "./IERC1155.sol";
import {IERC1155MetadataURI} from "./extensions/IERC1155MetadataURI.sol";
import {ERC1155Utils} from "./utils/ERC1155Utils.sol";
import {Context} from "../../utils/Context.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {Arrays} from "../../utils/Arrays.sol";
import {IERC1155Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*/
abstract contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI, IERC1155Errors {
using Arrays for uint256[];
using Arrays for address[];
mapping(uint256 id => mapping(address account => uint256)) private _balances;
mapping(address account => mapping(address operator => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256 /* id */) public view virtual returns (string memory) {
return _uri;
}
/// @inheritdoc IERC1155
function balanceOf(address account, uint256 id) public view virtual returns (uint256) {
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
) public view virtual returns (uint256[] memory) {
if (accounts.length != ids.length) {
revert ERC1155InvalidArrayLength(ids.length, accounts.length);
}
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts.unsafeMemoryAccess(i), ids.unsafeMemoryAccess(i));
}
return batchBalances;
}
/// @inheritdoc IERC1155
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/// @inheritdoc IERC1155
function isApprovedForAll(address account, address operator) public view virtual returns (bool) {
return _operatorApprovals[account][operator];
}
/// @inheritdoc IERC1155
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) public virtual {
address sender = _msgSender();
if (from != sender && !isApprovedForAll(from, sender)) {
revert ERC1155MissingApprovalForAll(sender, from);
}
_safeTransferFrom(from, to, id, value, data);
}
/// @inheritdoc IERC1155
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) public virtual {
address sender = _msgSender();
if (from != sender && !isApprovedForAll(from, sender)) {
revert ERC1155MissingApprovalForAll(sender, from);
}
_safeBatchTransferFrom(from, to, ids, values, data);
}
/**
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`. Will mint (or burn) if `from`
* (or `to`) is the zero address.
*
* Emits a {TransferSingle} event if the arrays contain one element, and {TransferBatch} otherwise.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement either {IERC1155Receiver-onERC1155Received}
* or {IERC1155Receiver-onERC1155BatchReceived} and return the acceptance magic value.
* - `ids` and `values` must have the same length.
*
* NOTE: The ERC-1155 acceptance check is not performed in this function. See {_updateWithAcceptanceCheck} instead.
*/
function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal virtual {
if (ids.length != values.length) {
revert ERC1155InvalidArrayLength(ids.length, values.length);
}
address operator = _msgSender();
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids.unsafeMemoryAccess(i);
uint256 value = values.unsafeMemoryAccess(i);
if (from != address(0)) {
uint256 fromBalance = _balances[id][from];
if (fromBalance < value) {
revert ERC1155InsufficientBalance(from, fromBalance, value, id);
}
unchecked {
// Overflow not possible: value <= fromBalance
_balances[id][from] = fromBalance - value;
}
}
if (to != address(0)) {
_balances[id][to] += value;
}
}
if (ids.length == 1) {
uint256 id = ids.unsafeMemoryAccess(0);
uint256 value = values.unsafeMemoryAccess(0);
emit TransferSingle(operator, from, to, id, value);
} else {
emit TransferBatch(operator, from, to, ids, values);
}
}
/**
* @dev Version of {_update} that performs the token acceptance check by calling
* {IERC1155Receiver-onERC1155Received} or {IERC1155Receiver-onERC1155BatchReceived} on the receiver address if it
* contains code (eg. is a smart contract at the moment of execution).
*
* IMPORTANT: Overriding this function is discouraged because it poses a reentrancy risk from the receiver. So any
* update to the contract state after this function would break the check-effect-interaction pattern. Consider
* overriding {_update} instead.
*/
function _updateWithAcceptanceCheck(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal virtual {
_update(from, to, ids, values);
if (to != address(0)) {
address operator = _msgSender();
if (ids.length == 1) {
uint256 id = ids.unsafeMemoryAccess(0);
uint256 value = values.unsafeMemoryAccess(0);
ERC1155Utils.checkOnERC1155Received(operator, from, to, id, value, data);
} else {
ERC1155Utils.checkOnERC1155BatchReceived(operator, from, to, ids, values, data);
}
}
}
/**
* @dev Transfers a `value` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes memory data) internal {
if (to == address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
if (from == address(0)) {
revert ERC1155InvalidSender(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(from, to, ids, values, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
* - `ids` and `values` must have the same length.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal {
if (to == address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
if (from == address(0)) {
revert ERC1155InvalidSender(address(0));
}
_updateWithAcceptanceCheck(from, to, ids, values, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the ERC].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the values in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates a `value` amount of tokens of type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address to, uint256 id, uint256 value, bytes memory data) internal {
if (to == address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(address(0), to, ids, values, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `values` must have the same length.
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory values, bytes memory data) internal {
if (to == address(0)) {
revert ERC1155InvalidReceiver(address(0));
}
_updateWithAcceptanceCheck(address(0), to, ids, values, data);
}
/**
* @dev Destroys a `value` amount of tokens of type `id` from `from`
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `value` amount of tokens of type `id`.
*/
function _burn(address from, uint256 id, uint256 value) internal {
if (from == address(0)) {
revert ERC1155InvalidSender(address(0));
}
(uint256[] memory ids, uint256[] memory values) = _asSingletonArrays(id, value);
_updateWithAcceptanceCheck(from, address(0), ids, values, "");
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `value` amount of tokens of type `id`.
* - `ids` and `values` must have the same length.
*/
function _burnBatch(address from, uint256[] memory ids, uint256[] memory values) internal {
if (from == address(0)) {
revert ERC1155InvalidSender(address(0));
}
_updateWithAcceptanceCheck(from, address(0), ids, values, "");
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the zero address.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
if (operator == address(0)) {
revert ERC1155InvalidOperator(address(0));
}
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Creates an array in memory with only one value for each of the elements provided.
*/
function _asSingletonArrays(
uint256 element1,
uint256 element2
) private pure returns (uint256[] memory array1, uint256[] memory array2) {
assembly ("memory-safe") {
// Load the free memory pointer
array1 := mload(0x40)
// Set array length to 1
mstore(array1, 1)
// Store the single element at the next word after the length (where content starts)
mstore(add(array1, 0x20), element1)
// Repeat for next array locating it right after the first array
array2 := add(array1, 0x40)
mstore(array2, 1)
mstore(add(array2, 0x20), element2)
// Update the free memory pointer by pointing after the second array
mstore(0x40, add(array2, 0x40))
}
}
}
ERC1155Supply.sol 88 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/extensions/ERC1155Supply.sol)
pragma solidity ^0.8.20;
import {ERC1155} from "../ERC1155.sol";
import {Arrays} from "../../../utils/Arrays.sol";
/**
* @dev Extension of ERC-1155 that adds tracking of total supply per id.
*
* Useful for scenarios where Fungible and Non-fungible tokens have to be
* clearly identified. Note: While a totalSupply of 1 might mean the
* corresponding is an NFT, there is no guarantees that no other token with the
* same id are not going to be minted.
*
* NOTE: This contract implies a global limit of 2**256 - 1 to the number of tokens
* that can be minted.
*
* CAUTION: This extension should not be added in an upgrade to an already deployed contract.
*/
abstract contract ERC1155Supply is ERC1155 {
using Arrays for uint256[];
mapping(uint256 id => uint256) private _totalSupply;
uint256 private _totalSupplyAll;
/**
* @dev Total value of tokens in with a given id.
*/
function totalSupply(uint256 id) public view virtual returns (uint256) {
return _totalSupply[id];
}
/**
* @dev Total value of tokens.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupplyAll;
}
/**
* @dev Indicates whether any token exist with a given id, or not.
*/
function exists(uint256 id) public view virtual returns (bool) {
return totalSupply(id) > 0;
}
/// @inheritdoc ERC1155
function _update(
address from,
address to,
uint256[] memory ids,
uint256[] memory values
) internal virtual override {
super._update(from, to, ids, values);
if (from == address(0)) {
uint256 totalMintValue = 0;
for (uint256 i = 0; i < ids.length; ++i) {
uint256 value = values.unsafeMemoryAccess(i);
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply[ids.unsafeMemoryAccess(i)] += value;
totalMintValue += value;
}
// Overflow check required: The rest of the code assumes that totalSupplyAll never overflows
_totalSupplyAll += totalMintValue;
}
if (to == address(0)) {
uint256 totalBurnValue = 0;
for (uint256 i = 0; i < ids.length; ++i) {
uint256 value = values.unsafeMemoryAccess(i);
unchecked {
// Overflow not possible: values[i] <= balanceOf(from, ids[i]) <= totalSupply(ids[i])
_totalSupply[ids.unsafeMemoryAccess(i)] -= value;
// Overflow not possible: sum_i(values[i]) <= sum_i(totalSupply(ids[i])) <= totalSupplyAll
totalBurnValue += value;
}
}
unchecked {
// Overflow not possible: totalBurnValue = sum_i(values[i]) <= sum_i(totalSupply(ids[i])) <= totalSupplyAll
_totalSupplyAll -= totalBurnValue;
}
}
}
}
IERC1155MetadataURI.sol 20 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity >=0.6.2;
import {IERC1155} from "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[ERC].
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
IERC1155.sol 123 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[ERC].
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` amount of tokens of type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the value of tokens of token type `id` owned by `account`.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] calldata accounts,
uint256[] calldata ids
) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the zero address.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers a `value` amount of tokens of type `id` from `from` to `to`.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {IERC1155Receiver-onERC1155Received} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `value` amount.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 value, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* WARNING: This function can potentially allow a reentrancy attack when transferring tokens
* to an untrusted contract, when invoking {IERC1155Receiver-onERC1155BatchReceived} on the receiver.
* Ensure to follow the checks-effects-interactions pattern and consider employing
* reentrancy guards when interacting with untrusted contracts.
*
* Emits either a {TransferSingle} or a {TransferBatch} event, depending on the length of the array arguments.
*
* Requirements:
*
* - `ids` and `values` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external;
}
IERC1155Receiver.sol 59 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/IERC1155Receiver.sol)
pragma solidity >=0.6.2;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Interface that must be implemented by smart contracts in order to receive
* ERC-1155 token transfers.
*/
interface IERC1155Receiver is IERC165 {
/**
* @dev Handles the receipt of a single ERC-1155 token type. This function is
* called at the end of a `safeTransferFrom` after the balance has been updated.
*
* NOTE: To accept the transfer, this must return
* `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
* (i.e. 0xf23a6e61, or its own function selector).
*
* @param operator The address which initiated the transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param id The ID of the token being transferred
* @param value The amount of tokens being transferred
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
* @dev Handles the receipt of a multiple ERC-1155 token types. This function
* is called at the end of a `safeBatchTransferFrom` after the balances have
* been updated.
*
* NOTE: To accept the transfer(s), this must return
* `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
* (i.e. 0xbc197c81, or its own function selector).
*
* @param operator The address which initiated the batch transfer (i.e. msg.sender)
* @param from The address which previously owned the token
* @param ids An array containing ids of each token being transferred (order and length must match values array)
* @param values An array containing amounts of each token being transferred (order and length must match ids array)
* @param data Additional data with no specified format
* @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
ERC1155Holder.sol 40 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.20;
import {IERC165, ERC165} from "../../../utils/introspection/ERC165.sol";
import {IERC1155Receiver} from "../IERC1155Receiver.sol";
/**
* @dev Simple implementation of `IERC1155Receiver` that will allow a contract to hold ERC-1155 tokens.
*
* IMPORTANT: When inheriting this contract, you must include a way to use the received tokens, otherwise they will be
* stuck.
*/
abstract contract ERC1155Holder is ERC165, IERC1155Receiver {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
ERC1155Utils.sol 88 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC1155/utils/ERC1155Utils.sol)
pragma solidity ^0.8.20;
import {IERC1155Receiver} from "../IERC1155Receiver.sol";
import {IERC1155Errors} from "../../../interfaces/draft-IERC6093.sol";
/**
* @dev Library that provide common ERC-1155 utility functions.
*
* See https://eips.ethereum.org/EIPS/eip-1155[ERC-1155].
*
* _Available since v5.1._
*/
library ERC1155Utils {
/**
* @dev Performs an acceptance check for the provided `operator` by calling {IERC1155Receiver-onERC1155Received}
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
*
* The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
* Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
* the transfer.
*/
function checkOnERC1155Received(
address operator,
address from,
address to,
uint256 id,
uint256 value,
bytes memory data
) internal {
if (to.code.length > 0) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, value, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
// Tokens rejected
revert IERC1155Errors.ERC1155InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-IERC1155Receiver implementer
revert IERC1155Errors.ERC1155InvalidReceiver(to);
} else {
assembly ("memory-safe") {
revert(add(reason, 0x20), mload(reason))
}
}
}
}
}
/**
* @dev Performs a batch acceptance check for the provided `operator` by calling {IERC1155Receiver-onERC1155BatchReceived}
* on the `to` address. The `operator` is generally the address that initiated the token transfer (i.e. `msg.sender`).
*
* The acceptance call is not executed and treated as a no-op if the target address doesn't contain code (i.e. an EOA).
* Otherwise, the recipient must implement {IERC1155Receiver-onERC1155Received} and return the acceptance magic value to accept
* the transfer.
*/
function checkOnERC1155BatchReceived(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory values,
bytes memory data
) internal {
if (to.code.length > 0) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, values, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
// Tokens rejected
revert IERC1155Errors.ERC1155InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-IERC1155Receiver implementer
revert IERC1155Errors.ERC1155InvalidReceiver(to);
} else {
assembly ("memory-safe") {
revert(add(reason, 0x20), mload(reason))
}
}
}
}
}
}
IERC20Metadata.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
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);
}
SafeERC20.sol 212 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 {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev 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 _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @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 _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
Arrays.sol 552 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Arrays.sol)
// This file was procedurally generated from scripts/generate/templates/Arrays.js.
pragma solidity ^0.8.20;
import {Comparators} from "./Comparators.sol";
import {SlotDerivation} from "./SlotDerivation.sol";
import {StorageSlot} from "./StorageSlot.sol";
import {Math} from "./math/Math.sol";
/**
* @dev Collection of functions related to array types.
*/
library Arrays {
using SlotDerivation for bytes32;
using StorageSlot for bytes32;
/**
* @dev Sort an array of uint256 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
uint256[] memory array,
function(uint256, uint256) pure returns (bool) comp
) internal pure returns (uint256[] memory) {
_quickSort(_begin(array), _end(array), comp);
return array;
}
/**
* @dev Variant of {sort} that sorts an array of uint256 in increasing order.
*/
function sort(uint256[] memory array) internal pure returns (uint256[] memory) {
sort(array, Comparators.lt);
return array;
}
/**
* @dev Sort an array of address (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
address[] memory array,
function(address, address) pure returns (bool) comp
) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of address in increasing order.
*/
function sort(address[] memory array) internal pure returns (address[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Sort an array of bytes32 (in memory) following the provided comparator function.
*
* This function does the sorting "in place", meaning that it overrides the input. The object is returned for
* convenience, but that returned value can be discarded safely if the caller has a memory pointer to the array.
*
* NOTE: this function's cost is `O(n · log(n))` in average and `O(n²)` in the worst case, with n the length of the
* array. Using it in view functions that are executed through `eth_call` is safe, but one should be very careful
* when executing this as part of a transaction. If the array being sorted is too large, the sort operation may
* consume more gas than is available in a block, leading to potential DoS.
*
* IMPORTANT: Consider memory side-effects when using custom comparator functions that access memory in an unsafe way.
*/
function sort(
bytes32[] memory array,
function(bytes32, bytes32) pure returns (bool) comp
) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), _castToUint256Comp(comp));
return array;
}
/**
* @dev Variant of {sort} that sorts an array of bytes32 in increasing order.
*/
function sort(bytes32[] memory array) internal pure returns (bytes32[] memory) {
sort(_castToUint256Array(array), Comparators.lt);
return array;
}
/**
* @dev Performs a quick sort of a segment of memory. The segment sorted starts at `begin` (inclusive), and stops
* at end (exclusive). Sorting follows the `comp` comparator.
*
* Invariant: `begin <= end`. This is the case when initially called by {sort} and is preserved in subcalls.
*
* IMPORTANT: Memory locations between `begin` and `end` are not validated/zeroed. This function should
* be used only if the limits are within a memory array.
*/
function _quickSort(uint256 begin, uint256 end, function(uint256, uint256) pure returns (bool) comp) private pure {
unchecked {
if (end - begin < 0x40) return;
// Use first element as pivot
uint256 pivot = _mload(begin);
// Position where the pivot should be at the end of the loop
uint256 pos = begin;
for (uint256 it = begin + 0x20; it < end; it += 0x20) {
if (comp(_mload(it), pivot)) {
// If the value stored at the iterator's position comes before the pivot, we increment the
// position of the pivot and move the value there.
pos += 0x20;
_swap(pos, it);
}
}
_swap(begin, pos); // Swap pivot into place
_quickSort(begin, pos, comp); // Sort the left side of the pivot
_quickSort(pos + 0x20, end, comp); // Sort the right side of the pivot
}
}
/**
* @dev Pointer to the memory location of the first element of `array`.
*/
function _begin(uint256[] memory array) private pure returns (uint256 ptr) {
assembly ("memory-safe") {
ptr := add(array, 0x20)
}
}
/**
* @dev Pointer to the memory location of the first memory word (32bytes) after `array`. This is the memory word
* that comes just after the last element of the array.
*/
function _end(uint256[] memory array) private pure returns (uint256 ptr) {
unchecked {
return _begin(array) + array.length * 0x20;
}
}
/**
* @dev Load memory word (as a uint256) at location `ptr`.
*/
function _mload(uint256 ptr) private pure returns (uint256 value) {
assembly {
value := mload(ptr)
}
}
/**
* @dev Swaps the elements memory location `ptr1` and `ptr2`.
*/
function _swap(uint256 ptr1, uint256 ptr2) private pure {
assembly {
let value1 := mload(ptr1)
let value2 := mload(ptr2)
mstore(ptr1, value2)
mstore(ptr2, value1)
}
}
/// @dev Helper: low level cast address memory array to uint256 memory array
function _castToUint256Array(address[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 memory array to uint256 memory array
function _castToUint256Array(bytes32[] memory input) private pure returns (uint256[] memory output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast address comp function to uint256 comp function
function _castToUint256Comp(
function(address, address) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/// @dev Helper: low level cast bytes32 comp function to uint256 comp function
function _castToUint256Comp(
function(bytes32, bytes32) pure returns (bool) input
) private pure returns (function(uint256, uint256) pure returns (bool) output) {
assembly {
output := input
}
}
/**
* @dev Searches a sorted `array` and returns the first index that contains
* a value greater or equal to `element`. If no such index exists (i.e. all
* values in the array are strictly less than `element`), the array length is
* returned. Time complexity O(log n).
*
* NOTE: The `array` is expected to be sorted in ascending order, and to
* contain no repeated elements.
*
* IMPORTANT: Deprecated. This implementation behaves as {lowerBound} but lacks
* support for repeated elements in the array. The {lowerBound} function should
* be used instead.
*/
function findUpperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
low = mid + 1;
}
}
// At this point `low` is the exclusive upper bound. We will return the inclusive upper bound.
if (low > 0 && unsafeAccess(array, low - 1).value == element) {
return low - 1;
} else {
return low;
}
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value greater or equal than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/lower_bound[lower_bound].
*/
function lowerBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Searches an `array` sorted in ascending order and returns the first
* index that contains a value strictly greater than `element`. If no such index
* exists (i.e. all values in the array are strictly less than `element`), the array
* length is returned. Time complexity O(log n).
*
* See C++'s https://en.cppreference.com/w/cpp/algorithm/upper_bound[upper_bound].
*/
function upperBound(uint256[] storage array, uint256 element) internal view returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeAccess(array, mid).value > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Same as {lowerBound}, but with an array in memory.
*/
function lowerBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) < element) {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
} else {
high = mid;
}
}
return low;
}
/**
* @dev Same as {upperBound}, but with an array in memory.
*/
function upperBoundMemory(uint256[] memory array, uint256 element) internal pure returns (uint256) {
uint256 low = 0;
uint256 high = array.length;
if (high == 0) {
return 0;
}
while (low < high) {
uint256 mid = Math.average(low, high);
// Note that mid will always be strictly less than high (i.e. it will be a valid array index)
// because Math.average rounds towards zero (it does integer division with truncation).
if (unsafeMemoryAccess(array, mid) > element) {
high = mid;
} else {
// this cannot overflow because mid < high
unchecked {
low = mid + 1;
}
}
}
return low;
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(address[] storage arr, uint256 pos) internal pure returns (StorageSlot.AddressSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getAddressSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes32[] storage arr, uint256 pos) internal pure returns (StorageSlot.Bytes32Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytes32Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(uint256[] storage arr, uint256 pos) internal pure returns (StorageSlot.Uint256Slot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getUint256Slot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(bytes[] storage arr, uint256 pos) internal pure returns (StorageSlot.BytesSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getBytesSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeAccess(string[] storage arr, uint256 pos) internal pure returns (StorageSlot.StringSlot storage) {
bytes32 slot;
assembly ("memory-safe") {
slot := arr.slot
}
return slot.deriveArray().offset(pos).getStringSlot();
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(address[] memory arr, uint256 pos) internal pure returns (address res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes32[] memory arr, uint256 pos) internal pure returns (bytes32 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(uint256[] memory arr, uint256 pos) internal pure returns (uint256 res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(bytes[] memory arr, uint256 pos) internal pure returns (bytes memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Access an array in an "unsafe" way. Skips solidity "index-out-of-range" check.
*
* WARNING: Only use if you are certain `pos` is lower than the array length.
*/
function unsafeMemoryAccess(string[] memory arr, uint256 pos) internal pure returns (string memory res) {
assembly {
res := mload(add(add(arr, 0x20), mul(pos, 0x20)))
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(address[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes32[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(uint256[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(bytes[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
/**
* @dev Helper to set the length of a dynamic array. Directly writing to `.length` is forbidden.
*
* WARNING: this does not clear elements if length is reduced, of initialize elements if length is increased.
*/
function unsafeSetLength(string[] storage array, uint256 len) internal {
assembly ("memory-safe") {
sstore(array.slot, len)
}
}
}
Comparators.sol 19 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Comparators.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides a set of functions to compare values.
*
* _Available since v5.1._
*/
library Comparators {
function lt(uint256 a, uint256 b) internal pure returns (bool) {
return a < b;
}
function gt(uint256 a, uint256 b) internal pure returns (bool) {
return a > b;
}
}
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;
}
}
Create2.sol 92 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Create2.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
* `CREATE2` can be used to compute in advance the address where a smart
* contract will be deployed, which allows for interesting new mechanisms known
* as 'counterfactual interactions'.
*
* See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
* information.
*/
library Create2 {
/**
* @dev There's no code to deploy.
*/
error Create2EmptyBytecode();
/**
* @dev Deploys a contract using `CREATE2`. The address where the contract
* will be deployed can be known in advance via {computeAddress}.
*
* The bytecode for a contract can be obtained from Solidity with
* `type(contractName).creationCode`.
*
* Requirements:
*
* - `bytecode` must not be empty.
* - `salt` must have not been used for `bytecode` already.
* - the factory must have a balance of at least `amount`.
* - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
*/
function deploy(uint256 amount, bytes32 salt, bytes memory bytecode) internal returns (address addr) {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
if (bytecode.length == 0) {
revert Create2EmptyBytecode();
}
assembly ("memory-safe") {
addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
// if no address was created, and returndata is not empty, bubble revert
if and(iszero(addr), not(iszero(returndatasize()))) {
let p := mload(0x40)
returndatacopy(p, 0, returndatasize())
revert(p, returndatasize())
}
}
if (addr == address(0)) {
revert Errors.FailedDeployment();
}
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
* `bytecodeHash` or `salt` will result in a new destination address.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
return computeAddress(salt, bytecodeHash, address(this));
}
/**
* @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
* `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
*/
function computeAddress(bytes32 salt, bytes32 bytecodeHash, address deployer) internal pure returns (address addr) {
assembly ("memory-safe") {
let ptr := mload(0x40) // Get free memory pointer
// | | ↓ ptr ... ↓ ptr + 0x0B (start) ... ↓ ptr + 0x20 ... ↓ ptr + 0x40 ... |
// |-------------------|---------------------------------------------------------------------------|
// | bytecodeHash | CCCCCCCCCCCCC...CC |
// | salt | BBBBBBBBBBBBB...BB |
// | deployer | 000000...0000AAAAAAAAAAAAAAAAAAA...AA |
// | 0xFF | FF |
// |-------------------|---------------------------------------------------------------------------|
// | memory | 000000...00FFAAAAAAAAAAAAAAAAAAA...AABBBBBBBBBBBBB...BBCCCCCCCCCCCCC...CC |
// | keccak(start, 85) | ↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑ |
mstore(add(ptr, 0x40), bytecodeHash)
mstore(add(ptr, 0x20), salt)
mstore(ptr, deployer) // Right-aligned with 12 preceding garbage bytes
let start := add(ptr, 0x0b) // The hashed data starts at the final garbage byte which we will set to 0xff
mstore8(start, 0xff)
addr := and(keccak256(start, 85), 0xffffffffffffffffffffffffffffffffffffffff)
}
}
}
ECDSA.sol 180 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 Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM precompile allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {MessageHashUtils-toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error, bytes32 errorArg) = tryRecover(hash, signature);
_throwError(error, errorArg);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[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.20;
import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
*
* The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
* encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
* does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
* produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
// 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);
}
}
MessageHashUtils.sol 99 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/MessageHashUtils.sol)
pragma solidity ^0.8.20;
import {Strings} from "../Strings.sol";
/**
* @dev Signature message hash utilities for producing digests to be consumed by {ECDSA} recovery or signing.
*
* The library provides methods for generating a hash of a message that conforms to the
* https://eips.ethereum.org/EIPS/eip-191[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)
}
}
}
Errors.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
ERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
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 749 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;
}
}
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);
}
}
}
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)
}
}
}
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;
}
}
}
SlotDerivation.sol 155 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/SlotDerivation.sol)
// This file was procedurally generated from scripts/generate/templates/SlotDerivation.js.
pragma solidity ^0.8.20;
/**
* @dev Library for computing storage (and transient storage) locations from namespaces and deriving slots
* corresponding to standard patterns. The derivation method for array and mapping matches the storage layout used by
* the solidity language / compiler.
*
* See https://docs.soliditylang.org/en/v0.8.20/internals/layout_in_storage.html#mappings-and-dynamic-arrays[Solidity docs for mappings and dynamic arrays.].
*
* Example usage:
* ```solidity
* contract Example {
* // Add the library methods
* using StorageSlot for bytes32;
* using SlotDerivation for bytes32;
*
* // Declare a namespace
* string private constant _NAMESPACE = "<namespace>"; // eg. OpenZeppelin.Slot
*
* function setValueInNamespace(uint256 key, address newValue) internal {
* _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value = newValue;
* }
*
* function getValueInNamespace(uint256 key) internal view returns (address) {
* return _NAMESPACE.erc7201Slot().deriveMapping(key).getAddressSlot().value;
* }
* }
* ```
*
* TIP: Consider using this library along with {StorageSlot}.
*
* NOTE: This library provides a way to manipulate storage locations in a non-standard way. Tooling for checking
* upgrade safety will ignore the slots accessed through this library.
*
* _Available since v5.1._
*/
library SlotDerivation {
/**
* @dev Derive an ERC-7201 slot from a string (namespace).
*/
function erc7201Slot(string memory namespace) internal pure returns (bytes32 slot) {
assembly ("memory-safe") {
mstore(0x00, sub(keccak256(add(namespace, 0x20), mload(namespace)), 1))
slot := and(keccak256(0x00, 0x20), not(0xff))
}
}
/**
* @dev Add an offset to a slot to get the n-th element of a structure or an array.
*/
function offset(bytes32 slot, uint256 pos) internal pure returns (bytes32 result) {
unchecked {
return bytes32(uint256(slot) + pos);
}
}
/**
* @dev Derive the location of the first element in an array from the slot where the length is stored.
*/
function deriveArray(bytes32 slot) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, slot)
result := keccak256(0x00, 0x20)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, address key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, and(key, shr(96, not(0))))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bool key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, iszero(iszero(key)))
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes32 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, uint256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, int256 key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
mstore(0x00, key)
mstore(0x20, slot)
result := keccak256(0x00, 0x40)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, string memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
/**
* @dev Derive the location of a mapping element from the key.
*/
function deriveMapping(bytes32 slot, bytes memory key) internal pure returns (bytes32 result) {
assembly ("memory-safe") {
let length := mload(key)
let begin := add(key, 0x20)
let end := add(begin, length)
let cache := mload(end)
mstore(end, slot)
result := keccak256(begin, add(length, 0x20))
mstore(end, cache)
}
}
}
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
}
}
}
Strings.sol 490 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SafeCast} from "./math/SafeCast.sol";
import {SignedMath} from "./math/SignedMath.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 Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
/**
* @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))
}
}
}
DeriFlowEscrow.sol 459 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { DataTypes } from "./misc/DataTypes.sol";
import { Errors } from "./misc/Errors.sol";
import { Events } from "./misc/Events.sol";
import { DeriFlowCBToken } from "./tokens/DeriFlowCBToken.sol";
import { IVotes } from "@openzeppelin/contracts/governance/utils/IVotes.sol";
import { IDeriFlowEscrow } from "./interfaces/IDeriFlowEscrow.sol";
import { IDeriFlowRouter } from "./interfaces/IDeriFlowRouter.sol";
import { IDeriFlowCPToken } from "./interfaces/IDeriFlowCPToken.sol";
import { IOracleAdapter } from "./interfaces/IOracleAdapter.sol";
import { IDelegation } from "./interfaces/IDelegation.sol";
contract DeriFlowEscrow is DeriFlowCBToken, IDeriFlowEscrow {
using SafeERC20 for IERC20Metadata;
uint256 internal constant BASE = 1 ether;
uint256 public totalNotional;
uint256 public totalBorrowed;
address public immutable router;
mapping(address => uint256) public borrowedCollateralAmounts;
DataTypes.EscrowInfo internal _escrowInfo;
constructor() {
router = msg.sender;
}
function initialize(DataTypes.EscrowQuotePayload calldata payload, uint256 tokenId) external initializer {
if (msg.sender != router) {
revert Errors.InvalidSender();
}
_escrowInfo = payload.escrowInfo;
string memory symbol = string.concat("O", Strings.toString(tokenId));
uint8 decimals = IERC20Metadata(payload.escrowInfo.collateralToken).decimals();
super.initialize(symbol, symbol, decimals);
}
function handleExercise(
address exerciser,
address collateralReceiver,
uint256 collateralExerciseAmount,
bool payInConversionToken,
bytes[] memory oracleData
) external returns (address conversionToken, uint256 conversionAmount, address conversionReceiver) {
if (msg.sender != router) {
revert Errors.InvalidSender();
}
DataTypes.EscrowInfo memory escrow = _escrowInfo;
// @dev: disabled in case generic settlement is allowed
if (escrow.genericSettlementAllowed) {
revert Errors.CannotUseIfGenericSettlementAllowed();
}
if (
block.timestamp > escrow.exerciseSettings.expiry ||
block.timestamp < escrow.exerciseSettings.earliestExercise
) {
revert Errors.InvalidExerciseTime();
}
if (collateralExerciseAmount == 0 || collateralExerciseAmount > totalSupply()) {
revert Errors.InvalidExerciseAmount();
}
// @dev: determine conversion amount receiver (single holder if exists, escrow otherwise)
(, address cpSingleHolder, , ) = getSettlementAuthorizationInfo();
// @dev: if there's a single holder, send tokens directly to them; otherwise send to escrow
conversionReceiver = (cpSingleHolder != address(0)) ? cpSingleHolder : address(this);
// @dev: caching
address collateralToken = escrow.collateralToken;
uint256 strike = escrow.exerciseSettings.strike;
uint256 collateralTokenDecimals = IERC20Metadata(collateralToken).decimals();
conversionToken = escrow.conversionToken;
uint256 conversionTokenDecimals = IERC20Metadata(conversionToken).decimals();
// @dev: round conversion amount up
conversionAmount = _getConversionAmount(strike, collateralExerciseAmount, collateralTokenDecimals, true);
uint256 exerciseCostInCollateral;
if (!payInConversionToken) {
exerciseCostInCollateral =
((strike * collateralExerciseAmount) *
IOracleAdapter(escrow.exerciseSettings.oracle).getPrice(
conversionToken,
collateralToken,
oracleData
)) / ((10 ** collateralTokenDecimals) * (10 ** conversionTokenDecimals));
if (exerciseCostInCollateral > collateralExerciseAmount || exerciseCostInCollateral == 0) {
// @dev: revert if OTM or exercise cost is null
revert Errors.InvalidExercise();
}
}
// @dev: update total notional and total supply
totalNotional -= collateralExerciseAmount;
_burn(exerciser, collateralExerciseAmount);
// @dev: if exerciser pays exercise cost in collateral tokens send the net amount
// after deducting exerciseCostInCollateral; if paid in conversionToken exerciseCostInCollateral
// will be zero and no effect
uint256 netAmount;
unchecked {
netAmount = collateralExerciseAmount - exerciseCostInCollateral;
}
IERC20Metadata(collateralToken).safeTransfer(collateralReceiver, netAmount);
if (!payInConversionToken && conversionReceiver != address(this)) {
// @dev: if there's just one party as collat beneficiary and settlement is done
// in collateral token then can send the remainder directly to single beneficiary
IERC20Metadata(collateralToken).safeTransfer(conversionReceiver, exerciseCostInCollateral);
}
}
function handleBorrow(
address borrower,
address borrowAmountReceiver,
uint256 borrowAmount
) external returns (address conversionToken, uint256 conversionAmount) {
if (msg.sender != router) {
revert Errors.InvalidSender();
}
DataTypes.EscrowInfo memory escrow = _escrowInfo;
// @dev: disabled in case generic settlement is allowed
if (escrow.genericSettlementAllowed) {
revert Errors.CannotUseIfGenericSettlementAllowed();
}
if (
block.timestamp > escrow.exerciseSettings.expiry ||
block.timestamp < escrow.exerciseSettings.earliestExercise
) {
revert Errors.InvalidBorrowTime();
}
// @dev: cast borrowCap to uint256 to ensure RHS multiplication
// @dev: check borrow cap wrt total notional
if (
borrowAmount == 0 ||
(totalBorrowed + borrowAmount) * BASE > totalNotional * uint256(escrow.exerciseSettings.borrowCap)
) {
revert Errors.InvalidBorrowAmount();
}
conversionToken = escrow.conversionToken;
address collateralToken = escrow.collateralToken;
// @dev: conversion amount is pledged to
// borrow borrowAmount; conversion amount is rounded up
conversionAmount = _getConversionAmount(
escrow.exerciseSettings.strike, // @dev: strike denominated in conversion tokens
borrowAmount,
IERC20Metadata(collateralToken).decimals(),
true
);
totalBorrowed += borrowAmount;
borrowedCollateralAmounts[borrower] += borrowAmount;
// @dev: burn CB tokens; note, total notional remains unchanged
_burn(borrower, borrowAmount);
IERC20Metadata(collateralToken).safeTransfer(borrowAmountReceiver, borrowAmount);
}
function handleRepay(
address repayer,
address conversionAmountReceiver,
uint256 collateralRepayAmount
) external returns (address collateralToken, uint256 unlockedConversionAmount) {
if (msg.sender != router) {
revert Errors.InvalidSender();
}
// @dev: disabled in case generic settlement is allowed
if (_escrowInfo.genericSettlementAllowed) {
revert Errors.CannotUseIfGenericSettlementAllowed();
}
if (block.timestamp > _escrowInfo.exerciseSettings.expiry) {
revert Errors.InvalidRepayTime();
}
if (totalBorrowed == 0) {
revert Errors.NothingToRepay();
}
if (collateralRepayAmount == 0 || collateralRepayAmount > borrowedCollateralAmounts[repayer]) {
revert Errors.InvalidRepayAmount();
}
collateralToken = _escrowInfo.collateralToken;
// @dev: round released conversion amount downwards
unlockedConversionAmount = _getConversionAmount(
_escrowInfo.exerciseSettings.strike, // @dev: strike denominated in conversion tokens
collateralRepayAmount,
IERC20Metadata(collateralToken).decimals(),
false
);
// @dev: guaranteed to be performed safely by logical inference
unchecked {
totalBorrowed -= collateralRepayAmount;
borrowedCollateralAmounts[repayer] -= collateralRepayAmount;
}
// @dev: mint CB tokens back; note, total notional remains unchanged
_mint(repayer, collateralRepayAmount);
IERC20Metadata(_escrowInfo.conversionToken).safeTransfer(conversionAmountReceiver, unlockedConversionAmount);
}
function handleOnChainVoting(address votingDelegate) external {
(address cpDelegate, address cpSingleHolder, , ) = getSettlementAuthorizationInfo();
// @dev: allow access if caller is single holder (if exists) OR cpDelegate
bool isSingleHolder = (cpSingleHolder != address(0)) && (msg.sender == cpSingleHolder);
bool isDelegate = msg.sender == cpDelegate;
if (!isSingleHolder && !isDelegate) {
revert Errors.InvalidSender();
}
if (!_escrowInfo.advancedSettings.votingDelegationAllowed) {
revert Errors.VotingDelegationNotAllowed();
}
IVotes(_escrowInfo.collateralToken).delegate(votingDelegate);
emit Events.OnChainVotingDelegation(votingDelegate);
}
function handleOffChainVoting(bytes32 spaceId, address votingDelegate) external {
(address cpDelegate, address cpSingleHolder, , ) = getSettlementAuthorizationInfo();
// @dev: allow access if caller is single holder (if exists) OR cpDelegate
bool isSingleHolder = (cpSingleHolder != address(0)) && (msg.sender == cpSingleHolder);
bool isDelegate = msg.sender == cpDelegate;
if (!isSingleHolder && !isDelegate) {
revert Errors.InvalidSender();
}
address allowedDelegateRegistry = _escrowInfo.advancedSettings.allowedDelegateRegistry;
if (allowedDelegateRegistry == address(0)) {
revert Errors.NoAllowedDelegateRegistry();
}
// @dev: for off-chain voting via Gnosis Delegate Registry
// see: https://docs.snapshot.org/user-guides/delegation#delegation-contract
IDelegation(allowedDelegateRegistry).setDelegate(spaceId, votingDelegate);
emit Events.OffChainVotingDelegation(allowedDelegateRegistry, spaceId, votingDelegate);
}
function handleWithdraw(
address user,
address to
) external returns (uint256 collateralAmount, uint256 conversionAmount) {
if (msg.sender != router) {
revert Errors.InvalidSender();
}
// @dev: prevent withdrawal before expiry
if (block.timestamp <= _escrowInfo.exerciseSettings.expiry) {
revert Errors.InvalidWithdraw();
}
// @dev: get total supply for pro rata calculations
address deriFlowCPToken = IDeriFlowRouter(router).cpToken();
uint256 tokenId = IDeriFlowCPToken(deriFlowCPToken).getTokenIdByEscrow(address(this));
uint256 totalCPTokenSupply = IDeriFlowCPToken(deriFlowCPToken).totalSupply(tokenId);
if (totalCPTokenSupply == 0) {
revert Errors.ZeroSupply();
}
// @dev: get user's cpToken balance for pro rata calculations
uint256 userCPTokenBalance = IDeriFlowCPToken(deriFlowCPToken).balanceOf(user, tokenId);
if (userCPTokenBalance == 0) {
revert Errors.NothingToWithdraw();
}
// @dev: calculate withdrawal amount for both collateral and conversion tokens
address collateralToken = _escrowInfo.collateralToken;
address conversionToken = _escrowInfo.conversionToken;
uint256 collateralBalance = IERC20Metadata(collateralToken).balanceOf(address(this));
uint256 conversionBalance = IERC20Metadata(conversionToken).balanceOf(address(this));
bool withdrawFullAmount = userCPTokenBalance == totalCPTokenSupply;
uint256 collateralWithdrawAmount = withdrawFullAmount
? collateralBalance
: (userCPTokenBalance * collateralBalance) / totalCPTokenSupply;
uint256 conversionWithdrawAmount = withdrawFullAmount
? conversionBalance
: (userCPTokenBalance * conversionBalance) / totalCPTokenSupply;
IDeriFlowCPToken(deriFlowCPToken).burn(tokenId, user, userCPTokenBalance);
if (collateralWithdrawAmount > 0) {
IERC20Metadata(collateralToken).safeTransfer(to, collateralWithdrawAmount);
}
if (conversionWithdrawAmount > 0) {
IERC20Metadata(conversionToken).safeTransfer(to, conversionWithdrawAmount);
}
emit Events.WithdrawEscrow(
user,
to,
collateralToken,
collateralWithdrawAmount,
conversionToken,
conversionWithdrawAmount
);
return (collateralWithdrawAmount, conversionWithdrawAmount);
}
function redeem(address to) external {
// @dev: disabled in case generic settlement is allowed
if (_escrowInfo.genericSettlementAllowed) {
revert Errors.CannotUseIfGenericSettlementAllowed();
}
// @dev: if user has both collat provider and collat beneficiary tokens
// they can redeem those 1:1 for collateral any time
uint256 collatBenTokenBalance = balanceOf(msg.sender);
if (collatBenTokenBalance == 0) {
revert Errors.NoCBTokensToRedeem();
}
address deriFlowCPToken = IDeriFlowRouter(router).cpToken();
uint256 tokenId = IDeriFlowCPToken(deriFlowCPToken).getTokenIdByEscrow(address(this));
uint256 collatProviderCPTokenBalance = IDeriFlowCPToken(deriFlowCPToken).balanceOf(msg.sender, tokenId);
if (collatProviderCPTokenBalance == 0) {
revert Errors.NoCPTokensToRedeem();
}
// @dev: minimum of both balances is redeemable
uint256 redemptionAmount = collatBenTokenBalance > collatProviderCPTokenBalance
? collatProviderCPTokenBalance
: collatBenTokenBalance;
address collateralToken = _escrowInfo.collateralToken;
// @dev: update total notional
totalNotional -= redemptionAmount;
// @dev: burn both CP and CB token 1:1
_burn(msg.sender, redemptionAmount);
IDeriFlowCPToken(deriFlowCPToken).burn(tokenId, msg.sender, redemptionAmount);
IERC20Metadata(collateralToken).safeTransfer(to, redemptionAmount);
emit Events.Redeem(msg.sender, to, collateralToken, redemptionAmount);
}
function handleSettle(DataTypes.PaymentLeg calldata paymentLeg) external {
if (msg.sender != router) {
revert Errors.InvalidSender();
}
// @dev: execute payment leg from escrow (authorization validated at router level)
IERC20Metadata(paymentLeg.token).safeTransfer(paymentLeg.to, paymentLeg.amount);
}
function recover(address token, address to, uint256 amount) external {
// @dev: only allow recovery of erc20s post expiry
if (block.timestamp <= _escrowInfo.exerciseSettings.expiry) {
revert Errors.InvalidRecoverTime();
}
// @dev: only allow single CP token holder to recover
(, address cpSingleHolder, , ) = getSettlementAuthorizationInfo();
if (cpSingleHolder == address(0) || msg.sender != cpSingleHolder) {
revert Errors.InvalidRecoverSender();
}
// @dev: prevent recovery of collateral and conversion tokens
// these must be claimed via withdraw
address collateralToken = _escrowInfo.collateralToken;
address conversionToken = _escrowInfo.conversionToken;
if (token == collateralToken || token == conversionToken) {
revert Errors.InvalidRecoverToken();
}
// @dev: transfer the specified amount to the target address
IERC20Metadata(token).safeTransfer(to, amount);
emit Events.Recover(msg.sender, to, token, amount);
}
function transferCPDelegate(address newDelegate) external {
(address cpDelegate, address cpSingleHolder, , ) = getSettlementAuthorizationInfo();
bool isSingleHolder = (cpSingleHolder != address(0)) && (msg.sender == cpSingleHolder);
bool isDelegate = msg.sender == cpDelegate;
if (!isSingleHolder && !isDelegate) revert Errors.InvalidSender();
address oldDelegate = _escrowInfo.collatProviderDelegate;
_escrowInfo.collatProviderDelegate = newDelegate;
emit Events.CPDelegateTransferred(address(this), oldDelegate, newDelegate);
}
function transferSettlementFacilitator(address newFacilitator) external {
address currentFacilitator = _escrowInfo.advancedSettings.settlementFacilitator;
if (msg.sender != currentFacilitator) revert Errors.InvalidSender();
_escrowInfo.advancedSettings.settlementFacilitator = newFacilitator;
emit Events.SettlementFacilitatorTransferred(address(this), currentFacilitator, newFacilitator);
}
function escrowInfo() external view returns (DataTypes.EscrowInfo memory) {
return _escrowInfo;
}
function transfer(address to, uint256 value) public override returns (bool success) {
success = super.transfer(to, value);
// @dev: trigger event on router for easier tracking of transfers
IDeriFlowRouter(router).emitTransferEvent(msg.sender, to, value);
}
function transferFrom(address from, address to, uint256 value) public override returns (bool success) {
success = super.transferFrom(from, to, value);
// @dev: trigger event on router for easier tracking of transfers
IDeriFlowRouter(router).emitTransferEvent(from, to, value);
}
function mint(address collatBeneficiary, uint256 notional) public override {
address _router = router;
if (msg.sender != _router) {
revert Errors.InvalidSender();
}
// @dev: update total notional
totalNotional += notional;
// @dev: mint collateral beneficiary tokens (ERC20) and auto-approve router to
// minimize potential follow-up overhead wrt takeSwapQuote / takeRedemptionQuote
_mint(collatBeneficiary, notional);
_approve(collatBeneficiary, _router, type(uint256).max);
}
function getSettlementAuthorizationInfo()
public
view
returns (
address cpDelegate,
address cpSingleHolder,
bool genericSettlementAllowed,
address settlementFacilitator
)
{
cpDelegate = _escrowInfo.collatProviderDelegate;
address deriFlowCPToken = IDeriFlowRouter(router).cpToken();
uint256 tokenId = IDeriFlowCPToken(deriFlowCPToken).getTokenIdByEscrow(address(this));
cpSingleHolder = IDeriFlowCPToken(deriFlowCPToken).tokenIdToSingleHolder(tokenId);
genericSettlementAllowed = _escrowInfo.genericSettlementAllowed;
settlementFacilitator = _escrowInfo.advancedSettings.settlementFacilitator;
}
function _getConversionAmount(
uint256 strike,
uint256 collateralAmount,
uint256 collateralTokenDecimals,
bool roundUp
) internal pure returns (uint256) {
uint256 nominator = strike * collateralAmount;
uint256 denominator = 10 ** collateralTokenDecimals;
if (roundUp) {
return ((nominator - 1) / denominator) + 1;
} else {
return nominator / denominator;
}
}
function _requiresSingleHolder() internal view override returns (bool) {
// @dev: enforce a single CB token holder when generic settlement is enabled,
// ensuring unanimous decision-making by the CB holder
return _escrowInfo.genericSettlementAllowed;
}
}
DeriFlowRouter.sol 467 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { IERC1155 } from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import { ERC1155Holder } from "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import { Clones } from "@openzeppelin/contracts/proxy/Clones.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { DataTypes } from "./misc/DataTypes.sol";
import { Errors } from "./misc/Errors.sol";
import { Events } from "./misc/Events.sol";
import { DeriFlowEscrow } from "./DeriFlowEscrow.sol";
import { DeriFlowVerification } from "./DeriFlowVerification.sol";
import { DeriFlowCPToken } from "./tokens/DeriFlowCPToken.sol";
import { IDistributionManager } from "./interfaces/IDistributionManager.sol";
import { IDeriFlowEscrow } from "./interfaces/IDeriFlowEscrow.sol";
import { IDeriFlowRouter } from "./interfaces/IDeriFlowRouter.sol";
import { IDeriFlowCPToken } from "./interfaces/IDeriFlowCPToken.sol";
import { IDeriFlowCBToken } from "./interfaces/IDeriFlowCBToken.sol";
contract DeriFlowRouter is Ownable, ERC1155Holder, DeriFlowVerification, IDeriFlowRouter {
using SafeERC20 for IERC20Metadata;
uint64 internal constant BASE = 1 ether;
uint96 internal constant MAX_MATCH_FEE_RATE = 0.5 ether;
address public immutable cpToken;
address public immutable escrowImpl;
address public distributionManager;
mapping(address => bool) public isEscrow;
mapping(address => mapping(bytes32 => bool)) public isQuoteUsed;
mapping(bytes32 => address) public multiHolderEscrowByHash;
mapping(address => mapping(bytes32 => bool)) public isQuoteInvalidated;
mapping(address => uint256) public escrowNonces;
mapping(address => mapping(uint256 => bool)) public isQuoteIdUsed;
mapping(address => address) public authorizedMaker;
modifier onlyEscrow(address escrow) {
if (!isEscrow[escrow]) revert Errors.NotAnEscrow();
_;
}
constructor() Ownable(msg.sender) {
escrowImpl = address(new DeriFlowEscrow());
cpToken = address(new DeriFlowCPToken());
}
function withdraw(address escrow, address to) external onlyEscrow(escrow) {
// @dev: users can -post expiry- withdraw their pro rata share based on their collateral
// provider token balance; the escrow will calculate pro rata amounts for both collateral
// and conversion tokens, transfer them and burn the user's cpToken balance
(uint256 collateralAmount, uint256 conversionAmount) = IDeriFlowEscrow(escrow).handleWithdraw(msg.sender, to);
DataTypes.EscrowInfo memory escrowInfo = IDeriFlowEscrow(escrow).escrowInfo();
emit Events.Withdraw(
msg.sender,
escrow,
to,
escrowInfo.collateralToken,
collateralAmount,
escrowInfo.conversionToken,
conversionAmount
);
}
function exercise(
address escrow,
address collateralReceiver,
uint256 collateralAmount,
bool payInConversionToken,
bytes[] memory oracleData
) external onlyEscrow(escrow) {
(address conversionToken, uint256 conversionAmount, address conversionReceiver) = IDeriFlowEscrow(escrow)
.handleExercise(msg.sender, collateralReceiver, collateralAmount, payInConversionToken, oracleData);
if (payInConversionToken) {
IERC20Metadata(conversionToken).safeTransferFrom(msg.sender, conversionReceiver, conversionAmount);
}
emit Events.Exercise(msg.sender, escrow, collateralReceiver, collateralAmount);
}
function borrow(address escrow, address borrowAmountReceiver, uint256 borrowAmount) external onlyEscrow(escrow) {
// @dev: if enabled via borrow cap, CB token holder can borrow collateral tokens by pledging
// conversion tokens as collateral
(address conversionToken, uint256 conversionAmount) = IDeriFlowEscrow(escrow).handleBorrow(
msg.sender,
borrowAmountReceiver,
borrowAmount
);
IERC20Metadata(conversionToken).safeTransferFrom(msg.sender, escrow, conversionAmount);
emit Events.Borrow(msg.sender, escrow, borrowAmountReceiver, borrowAmount, conversionAmount);
}
function repay(
address escrow,
address conversionAmountReceiver,
uint256 repayCollateralAmount
) external onlyEscrow(escrow) {
// @dev: if CB token holder borrowed collateral tokens they can repay tokens
// to receive back conversion tokens they pledged as collateral
(address collateralToken, uint256 unlockedConversionAmount) = IDeriFlowEscrow(escrow).handleRepay(
msg.sender,
conversionAmountReceiver,
repayCollateralAmount
);
IERC20Metadata(collateralToken).safeTransferFrom(msg.sender, escrow, repayCollateralAmount);
emit Events.Repay(escrow, escrow, conversionAmountReceiver, repayCollateralAmount, unlockedConversionAmount);
}
function takeEscrowQuote(
DataTypes.EscrowQuotePayload calldata payload,
uint256 notional,
uint256 partnerCode
) external {
DataTypes.TakeEscrowQuotePreview memory preview = previewTakeEscrowQuote(
msg.sender,
payload,
notional,
partnerCode
);
if (preview.status != DataTypes.QuoteStatus.Success) {
revert Errors.InvalidTakeQuote();
}
isQuoteUsed[preview.maker][preview.msgHash] = true;
isQuoteIdUsed[preview.maker][payload.quote.quoteId] = true;
// @dev: isBid = true (DEFAULT CASE): means signer is collateral beneficiary and pays premium (bid)
// isBid = false: means signer is collateral provider and receives premium (ask)
address collatBeneficiary = payload.quote.isBid
? preview.maker // maker receives collateral (bid)
: msg.sender; // taker receives collateral
address collatProvider = payload.quote.isBid
? msg.sender // taker provides collateral
: preview.maker; // maker provides collateral (ask)
// @dev: create escrow where provider sends tokens and beneficiary has possible recourse;
// recourse either via exercise or managed off-chain via settle() and enforced with settlementFacilitator
// @dev: delegate is static from payload.escrowInfo.collatProviderDelegate
(address escrow, uint256 tokenId, bool isNewEscrow) = _getOrCreateEscrow(payload);
// @dev: initialize new escrow if needed
if (isNewEscrow) {
IDeriFlowEscrow(escrow).initialize(payload, tokenId);
}
bool multiGeneric = payload.escrowInfo.genericSettlementAllowed &&
payload.escrowInfo.advancedSettings.allowMultiCollatProviders;
if (multiGeneric && authorizedMaker[escrow] == address(0)) {
authorizedMaker[escrow] = collatBeneficiary;
}
// @dev: mint tokens for both parties based on notional (not collateral)
IDeriFlowCBToken(escrow).mint(collatBeneficiary, notional);
IDeriFlowCPToken(cpToken).mint(collatProvider, escrow, tokenId, notional);
IERC20Metadata(payload.escrowInfo.collateralToken).safeTransferFrom(collatProvider, escrow, preview.collateral);
// @dev: transfer premium from collatBeneficiary to collatProvider (minus fee)
IERC20Metadata(preview.premiumToken).safeTransferFrom(
collatBeneficiary,
collatProvider,
preview.premium - preview.totalMatchFee
);
IERC20Metadata(preview.premiumToken).safeTransferFrom(
collatBeneficiary,
distributionManager,
preview.totalMatchFee
);
// @dev: distribute match fee based on code
IDistributionManager(distributionManager).distribute(partnerCode, preview.premiumToken, preview.totalMatchFee);
emit Events.TakeEscrowQuote(collatBeneficiary, collatProvider, escrow, payload, preview, partnerCode);
}
function takeSwapQuote(address to, DataTypes.SwapQuote calldata swapQuote) external {
address maker = _takeSwapQuote(to, address(0), swapQuote);
emit Events.TakeSwapQuote(msg.sender, to, maker, swapQuote);
}
function takeRedemptionQuote(address to, address escrow, DataTypes.SwapQuote calldata swapQuote) external {
address maker = _takeSwapQuote(to, escrow, swapQuote);
emit Events.TakeRedemptionQuote(msg.sender, to, maker, escrow, swapQuote);
}
function invalidateQuote(bytes32 msgHash) external {
mapping(bytes32 => bool) storage isQuoteInvalidatedPerMaker = isQuoteInvalidated[msg.sender];
if (isQuoteUsed[msg.sender][msgHash] || isQuoteInvalidatedPerMaker[msgHash]) {
revert Errors.NothingToInvalidate();
}
isQuoteInvalidatedPerMaker[msgHash] = true;
emit Events.QuoteInvalidated(msg.sender, msgHash);
}
function settle(
address escrow,
address collatBeneficiary,
DataTypes.PaymentLeg[] calldata legs,
uint256 settlementCode,
uint256 validUntil,
bytes calldata signature
) external onlyEscrow(escrow) {
if (block.timestamp > validUntil) {
revert Errors.SettlementExpired();
}
uint256 nonce = escrowNonces[escrow];
(
address cpDelegate,
address cpSingleHolder,
bool genericSettlementAllowed,
address settlementFacilitator
) = IDeriFlowEscrow(escrow).getSettlementAuthorizationInfo();
// @dev: check that generic settlement is enabled for this escrow
if (!genericSettlementAllowed) {
revert Errors.SettleNotEnabled();
}
(, address signer) = hashSettlementAndRecover(escrow, legs, nonce, settlementCode, validUntil, signature);
// @dev: allowed signers:
// - CP single holder (if defined)
// - CP delegate
// - Collateral beneficiary
// settlement facilitator cannot sign (only execute).
// note: generic settlement disallows partial transfers, so the collateral
// beneficiary is always a single party.
bool signerIsCPSingleHolder = (cpSingleHolder != address(0)) && (signer == cpSingleHolder);
bool signerIsCPDelegate = signer == cpDelegate;
bool signerIsCollatBeneficiary = signer == collatBeneficiary;
if (!signerIsCPSingleHolder && !signerIsCPDelegate && !signerIsCollatBeneficiary) revert Errors.InvalidSigner();
// @dev: 2-out-of-3 trust model:
// * if CP single holder signed -> collat beneficiary or settlement facilitator must call
// * if CP delegate signed -> collat beneficiary or settlement facilitator must call
// * if collat beneficiary signed -> CP single holder (if exists) or settlement facilitator can call
bool senderOk;
if (signerIsCPSingleHolder || signerIsCPDelegate) {
// single holder signed: beneficiary or settlementFacilitator can call
senderOk = (msg.sender == collatBeneficiary || msg.sender == settlementFacilitator);
} else {
// collat beneficiary signed: single CP holder (if exists) or settlementFacilitator can call
bool senderIsCPSingleHolder = (cpSingleHolder != address(0)) && (msg.sender == cpSingleHolder);
senderOk = (senderIsCPSingleHolder || msg.sender == settlementFacilitator);
}
if (!senderOk) revert Errors.InvalidSender();
escrowNonces[escrow] = nonce + 1;
for (uint256 i; i < legs.length; ++i) {
DataTypes.PaymentLeg calldata leg = legs[i];
if (leg.to != collatBeneficiary && leg.to != cpSingleHolder && leg.to != escrow) {
// @dev: cannot send tokens to uninvoled party
revert Errors.InvalidLegTo();
}
if (leg.from == escrow) {
IDeriFlowEscrow(escrow).handleSettle(leg);
} else {
if (leg.from != msg.sender && leg.from != signer) {
// @dev: cannot call transferFrom on uninvolved party
revert Errors.InvalidLegFrom();
}
IERC20Metadata(leg.token).safeTransferFrom(leg.from, leg.to, leg.amount);
}
emit Events.Settlement(escrow, msg.sender, signer, leg, settlementCode);
}
}
function setDistributionManager(address newDistributionManager) external onlyOwner {
address oldDistributionManager = distributionManager;
if (oldDistributionManager == newDistributionManager) {
revert Errors.DistributionManagerAlreadySet();
}
distributionManager = newDistributionManager;
emit Events.NewDistributionManager(oldDistributionManager, newDistributionManager);
}
function emitTransferEvent(address from, address to, uint256 value) external onlyEscrow(msg.sender) {
emit Events.Transfer(msg.sender, from, to, value);
}
function previewTakeEscrowQuote(
address taker,
DataTypes.EscrowQuotePayload calldata payload,
uint256 notional,
uint256 partnerCode
) public view returns (DataTypes.TakeEscrowQuotePreview memory preview) {
(preview.msgHash, preview.maker) = hashEscrowQuotePayloadAndRecover(payload, payload.quote.signature);
preview.status = _escrowQuoteStatus(payload, notional, preview.maker, preview.msgHash);
if (preview.status != DataTypes.QuoteStatus.Success) {
return preview;
}
// success path only: compute fees and full preview
DataTypes.EscrowInfo calldata escrow = payload.escrowInfo;
// @dev: calculate premium based on premiumPerNotionalUnit * notional
preview.premium =
(payload.quote.premiumPerNotionalUnit * notional) / 10 ** IERC20Metadata(escrow.collateralToken).decimals();
preview.premiumToken = payload.quote.premiumIsInCollateralToken
? escrow.collateralToken
: escrow.conversionToken;
uint256 rate = IDistributionManager(distributionManager).getMatchFeeRate(taker, payload, partnerCode);
uint256 cappedRate = rate > MAX_MATCH_FEE_RATE ? MAX_MATCH_FEE_RATE : rate;
// @dev: calculate match fee based on premium
preview.totalMatchFee = (preview.premium * cappedRate) / BASE;
preview.collateral = (notional * escrow.collateralization) / BASE;
return preview;
}
function _takeSwapQuote(
address to,
address escrow,
DataTypes.SwapQuote calldata swapQuote
) internal returns (address) {
if (block.timestamp > swapQuote.validUntil) {
revert Errors.QuoteExpired();
}
// @dev: redemption-specific validations
if (escrow != address(0)) {
if (!isEscrow[escrow]) {
revert Errors.NotAnEscrow();
}
// @dev: verify makerGiveToken is the escrow (option tokens) for redemption
if (swapQuote.makerGiveToken != escrow) {
revert Errors.InvalidMakerGiveToken();
}
}
(bytes32 msgHash, address maker) = hashSwapQuoteAndRecover(swapQuote, swapQuote.signature);
if (isQuoteInvalidated[maker][msgHash]) {
revert Errors.QuoteInvalidated();
}
mapping(bytes32 => bool) storage isQuoteUsedPerMaker = isQuoteUsed[maker];
if (isQuoteUsedPerMaker[msgHash]) {
revert Errors.QuoteAlreadyUsed();
}
isQuoteUsedPerMaker[msgHash] = true;
// @dev: taker pays premium/tokens to maker
IERC20Metadata(swapQuote.takerGiveToken).safeTransferFrom(msg.sender, maker, swapQuote.takerGiveAmount);
// @dev: regular swap - maker sends tokens to recipient
if (escrow == address(0)) {
IERC20Metadata(swapQuote.makerGiveToken).safeTransferFrom(maker, to, swapQuote.makerGiveAmount);
} else {
// @dev: redemption quote - router temporarily holds both option tokens and cpTokens
// 1) maker sends option tokens to router
IERC20Metadata(swapQuote.makerGiveToken).safeTransferFrom(maker, address(this), swapQuote.makerGiveAmount);
// 2) taker sends cpTokens to router (router needs both to call redeem)
uint256 tokenId = IDeriFlowCPToken(cpToken).getTokenIdByEscrow(escrow);
IERC1155(cpToken).safeTransferFrom(msg.sender, address(this), tokenId, swapQuote.makerGiveAmount, "");
// 3) atomically redeem (router burns both tokens and sends collateral to recipient)
// @dev: note both option tokens and CP tokens are sent in equal amounts (swapQuote.makerGiveAmount)
// abd the redeem() function burns the minimum of both balances, which will always be the full amount;
// hence after redeem(), router balance of both tokens will always be 0
IDeriFlowEscrow(escrow).redeem(to);
}
return maker;
}
function _getOrCreateEscrow(
DataTypes.EscrowQuotePayload calldata payload
) internal returns (address escrow, uint256 tokenId, bool isNewEscrow) {
address targetEscrow = payload.quote.targetEscrow;
bytes32 rawEscrowHash = rawEscrowInfoHash(payload.escrowInfo);
if (targetEscrow == address(0)) {
// @dev: create new escrow instance for this configuration
tokenId = IDeriFlowCPToken(cpToken).nextTokenId();
escrow = Clones.cloneDeterministic(escrowImpl, keccak256(abi.encode(tokenId)));
isEscrow[escrow] = true;
if (payload.escrowInfo.advancedSettings.allowMultiCollatProviders) {
// @dev: store mapping for potential future reminting
// note: only escrows with allowMultiCollatProviders=true are stored
multiHolderEscrowByHash[rawEscrowHash] = escrow;
}
isNewEscrow = true;
} else {
// @dev: if targetEscrow is set its validity has already been checked
// in previewTakeEscrowQuote() via _escrowQuoteStatus()
escrow = targetEscrow;
tokenId = IDeriFlowCPToken(cpToken).getTokenIdByEscrow(escrow);
}
}
function _escrowQuoteStatus(
DataTypes.EscrowQuotePayload calldata payload,
uint256 notional,
address maker,
bytes32 msgHash
) internal view returns (DataTypes.QuoteStatus) {
DataTypes.EscrowInfo calldata escrow = payload.escrowInfo;
uint256 nowTs = block.timestamp;
if (nowTs > payload.quote.validUntil) return DataTypes.QuoteStatus.Expired;
// @dev: validate notional is within allowed range
if (notional < payload.quote.minNotional || notional > payload.quote.maxNotional || notional == 0) {
return DataTypes.QuoteStatus.InvalidNotional;
}
if (escrow.exerciseSettings.expiry < nowTs + 1 days) {
return DataTypes.QuoteStatus.ExpiryTooClose;
}
// @dev: standard case checks:
// - tokens must differ
// - exercise window must be ≥ 1 day
// - escrow must be fully collateralized
// - borrow cap must be ≤ 100%
if (
!escrow.genericSettlementAllowed &&
(escrow.collateralToken == escrow.conversionToken ||
escrow.exerciseSettings.expiry < nowTs + 1 days ||
escrow.exerciseSettings.expiry < escrow.exerciseSettings.earliestExercise + 1 days ||
escrow.collateralization != BASE ||
escrow.exerciseSettings.borrowCap > BASE)
) {
return DataTypes.QuoteStatus.InvalidQuote;
}
// @dev: note, generic-settlement mode requires no additional checks because
// exercise, borrow, repay and redemption are disabled
if (isQuoteUsed[maker][msgHash]) return DataTypes.QuoteStatus.AlreadyExecuted;
if (isQuoteInvalidated[maker][msgHash]) return DataTypes.QuoteStatus.QuoteInvalidated;
if (isQuoteIdUsed[maker][payload.quote.quoteId]) return DataTypes.QuoteStatus.QuoteIdAlreadyUsed;
if (payload.quote.targetEscrow != address(0)) {
// @dev: check 1/3 - does escrow exist
if (!isEscrow[payload.quote.targetEscrow]) {
return DataTypes.QuoteStatus.InvalidTargetEscrow;
}
// @dev: check 2/3 - intended payload matches existing escrow parameters
// @dev: on remint, since we only store escrows that allowMultiCollatProviders in multiHolderEscrowByHash,
// a match here guarantees allowMultiCollatProviders=true
bytes32 rawEscrowHash = rawEscrowInfoHash(payload.escrowInfo);
if (payload.quote.targetEscrow != multiHolderEscrowByHash[rawEscrowHash]) {
return DataTypes.QuoteStatus.TargetEscrowParameterMismatch;
}
// @dev: check 3/3 - special checks for generic settlement with multiple collat providers
if (payload.escrowInfo.genericSettlementAllowed) {
// @dev: check that maker is on bid side; reverse case not supported
if (!payload.quote.isBid) {
return DataTypes.QuoteStatus.MustBeBid;
}
// @dev: check consistent maker; disallow new makers
// to ensure single CB token holder for generic settle cannot be griefed
address authorized = authorizedMaker[payload.quote.targetEscrow];
if (authorized == address(0) || maker != authorized) {
return DataTypes.QuoteStatus.UnauthorizedMaker;
}
}
}
return DataTypes.QuoteStatus.Success;
}
}
DeriFlowVerification.sol 200 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import { EIP712 } from "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import { DataTypes } from "./misc/DataTypes.sol";
contract DeriFlowVerification is EIP712 {
string private constant EXERCISE_SETTINGS_TYPE =
"ExerciseSettings(address oracle,uint48 expiry,uint48 earliestExercise,uint128 strike,uint64 borrowCap)";
string private constant ADVANCED_SETTINGS_TYPE =
"AdvancedSettings(bool votingDelegationAllowed,address allowedDelegateRegistry,address settlementFacilitator,bool allowMultiCollatProviders)";
string private constant QUOTE_TYPE =
"Quote(uint256 premiumPerNotionalUnit,uint256 validUntil,bool isBid,bool premiumIsInCollateralToken,uint256 minNotional,uint256 maxNotional,uint256 quoteId)";
string private constant PAYMENT_LEG_TYPE = "PaymentLeg(address from,address to,address token,uint256 amount)";
// Parent struct type strings, built from components
string private constant ESCROW_QUOTE_PAYLOAD_TYPE =
string(
abi.encodePacked(
"EscrowQuotePayload("
"address collateralToken,"
"address conversionToken,"
"address collatProviderDelegate,"
"bool genericSettlementAllowed,"
"ExerciseSettings exerciseSettings,"
"AdvancedSettings advancedSettings,"
"Quote quote"
")",
ADVANCED_SETTINGS_TYPE,
EXERCISE_SETTINGS_TYPE,
QUOTE_TYPE
)
);
string private constant SETTLEMENT_TYPE =
string(
abi.encodePacked(
"Settlement("
"address escrow,"
"PaymentLeg[] paymentLegs,"
"uint256 nonce,"
"uint256 settlementCode,"
"uint256 validUntil"
")",
PAYMENT_LEG_TYPE
)
);
// -----------------------------------------
// EIP-712 typehashes
// -----------------------------------------
bytes32 private constant EXERCISE_SETTINGS_TYPEHASH = keccak256(bytes(EXERCISE_SETTINGS_TYPE));
bytes32 private constant ADVANCED_SETTINGS_TYPEHASH = keccak256(bytes(ADVANCED_SETTINGS_TYPE));
bytes32 private constant QUOTE_TYPEHASH = keccak256(bytes(QUOTE_TYPE));
bytes32 private constant PAYMENT_LEG_TYPEHASH = keccak256(bytes(PAYMENT_LEG_TYPE));
bytes32 private constant ESCROW_QUOTE_PAYLOAD_TYPEHASH = keccak256(bytes(ESCROW_QUOTE_PAYLOAD_TYPE));
bytes32 private constant SETTLEMENT_TYPEHASH = keccak256(bytes(SETTLEMENT_TYPE));
bytes32 private constant SWAP_QUOTE_TYPEHASH =
keccak256(
"SwapQuote(address takerGiveToken,uint256 takerGiveAmount,address makerGiveToken,uint256 makerGiveAmount,uint256 validUntil)"
);
constructor() EIP712("DeriFlow", "1") {}
// @dev: public hashing functions for external verification
function hashSwapQuote(DataTypes.SwapQuote calldata swapQuote) public view returns (bytes32) {
bytes32 swapQuoteHash = keccak256(
abi.encode(
SWAP_QUOTE_TYPEHASH,
swapQuote.takerGiveToken,
swapQuote.takerGiveAmount,
swapQuote.makerGiveToken,
swapQuote.makerGiveAmount,
swapQuote.validUntil
)
);
return _hashTypedDataV4(swapQuoteHash);
}
function hashEscrowQuotePayload(DataTypes.EscrowQuotePayload calldata payload) public view returns (bytes32) {
// Hash nested structs (fields in struct definition order)
bytes32 exerciseSettingsHash = keccak256(
abi.encode(
EXERCISE_SETTINGS_TYPEHASH,
payload.escrowInfo.exerciseSettings.oracle,
payload.escrowInfo.exerciseSettings.expiry,
payload.escrowInfo.exerciseSettings.earliestExercise,
payload.escrowInfo.exerciseSettings.strike,
payload.escrowInfo.exerciseSettings.borrowCap
)
);
bytes32 advancedSettingsHash = keccak256(
abi.encode(
ADVANCED_SETTINGS_TYPEHASH,
payload.escrowInfo.advancedSettings.votingDelegationAllowed,
payload.escrowInfo.advancedSettings.allowedDelegateRegistry,
payload.escrowInfo.advancedSettings.settlementFacilitator,
payload.escrowInfo.advancedSettings.allowMultiCollatProviders
)
);
bytes32 quoteHash = keccak256(
abi.encode(
QUOTE_TYPEHASH,
payload.quote.premiumPerNotionalUnit,
payload.quote.validUntil,
payload.quote.isBid,
payload.quote.premiumIsInCollateralToken,
payload.quote.minNotional,
payload.quote.maxNotional,
payload.quote.quoteId
)
);
// Hash the main payload (fields in struct definition order)
bytes32 payloadHash = keccak256(
abi.encode(
ESCROW_QUOTE_PAYLOAD_TYPEHASH,
payload.escrowInfo.collateralToken,
payload.escrowInfo.conversionToken,
payload.escrowInfo.collatProviderDelegate,
payload.escrowInfo.genericSettlementAllowed,
exerciseSettingsHash,
advancedSettingsHash,
quoteHash
)
);
return _hashTypedDataV4(payloadHash);
}
function hashSettlement(
address escrow,
DataTypes.PaymentLeg[] calldata paymentLegs,
uint256 nonce,
uint256 settlementCode,
uint256 validUntil
) public view returns (bytes32) {
bytes32 paymentLegsHash = _hashPaymentLegs(paymentLegs);
bytes32 settlementHash = keccak256(
abi.encode(SETTLEMENT_TYPEHASH, escrow, paymentLegsHash, nonce, settlementCode, validUntil)
);
return _hashTypedDataV4(settlementHash);
}
function hashSwapQuoteAndRecover(
DataTypes.SwapQuote calldata swapQuote,
bytes calldata signature
) public view returns (bytes32 hash, address signer) {
hash = hashSwapQuote(swapQuote);
signer = ECDSA.recover(hash, signature);
}
function hashEscrowQuotePayloadAndRecover(
DataTypes.EscrowQuotePayload calldata payload,
bytes calldata signature
) public view returns (bytes32 hash, address signer) {
hash = hashEscrowQuotePayload(payload);
signer = ECDSA.recover(hash, signature);
}
function hashSettlementAndRecover(
address escrow,
DataTypes.PaymentLeg[] calldata paymentLegs,
uint256 nonce,
uint256 settlementCode,
uint256 validUntil,
bytes calldata signature
) public view returns (bytes32 hash, address signer) {
hash = hashSettlement(escrow, paymentLegs, nonce, settlementCode, validUntil);
signer = ECDSA.recover(hash, signature);
}
function rawEscrowInfoHash(DataTypes.EscrowInfo memory escrowInfo) public pure returns (bytes32) {
return keccak256(abi.encode(escrowInfo));
}
function _hashPaymentLegs(DataTypes.PaymentLeg[] calldata paymentLegs) internal pure returns (bytes32) {
bytes32[] memory legHashes = new bytes32[](paymentLegs.length);
for (uint256 i = 0; i < paymentLegs.length; i++) {
DataTypes.PaymentLeg calldata leg = paymentLegs[i];
legHashes[i] = keccak256(abi.encode(PAYMENT_LEG_TYPEHASH, leg.from, leg.to, leg.token, leg.amount));
}
return keccak256(abi.encodePacked(legHashes));
}
}
IDelegation.sol 6 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IDelegation {
function setDelegate(bytes32 spaceId, address delegate) external;
}
IDeriFlowCBToken.sol 10 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IDeriFlowCBToken {
function mint(address to, uint256 amount) external;
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
}
IDeriFlowCPToken.sol 20 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IDeriFlowCPToken {
function getTokenIdByEscrow(address escrow) external view returns (uint256);
function getEscrowByTokenId(uint256 tokenId) external view returns (address);
function nextTokenId() external view returns (uint256);
function balanceOf(address account, uint256 id) external view returns (uint256);
function burn(uint256 tokenId, address account, uint256 amount) external;
function mint(address to, address escrow, uint256 tokenId, uint256 amount) external;
function tokenIdToSingleHolder(uint256 tokenId) external view returns (address);
function totalSupply(uint256 id) external view returns (uint256);
}
IDeriFlowEscrow.sol 67 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { DataTypes } from "../misc/DataTypes.sol";
interface IDeriFlowEscrow {
// External functions
function handleExercise(
address exerciser,
address collateralReceiver,
uint256 collateralExerciseAmount,
bool payInConversionToken,
bytes[] memory oracleData
) external returns (address conversionToken, uint256 conversionAmount, address conversionReceiver);
function handleBorrow(
address borrower,
address borrowAmountReceiver,
uint256 borrowAmount
) external returns (address conversionToken, uint256 conversionAmount);
function handleRepay(
address repayer,
address conversionAmountReceiver,
uint256 collateralRepayAmount
) external returns (address collateralToken, uint256 unlockedConversionAmount);
function handleWithdraw(
address user,
address to
) external returns (uint256 collateralAmount, uint256 conversionAmount);
function handleOnChainVoting(address delegate) external;
function handleOffChainVoting(bytes32 spaceId, address delegate) external;
function handleSettle(DataTypes.PaymentLeg calldata paymentLeg) external;
function redeem(address to) external;
function recover(address token, address to, uint256 amount) external;
function initialize(DataTypes.EscrowQuotePayload calldata payload, uint256 tokenId) external;
function transferCPDelegate(address newDelegate) external;
function transferSettlementFacilitator(address newFacilitator) external;
// Public variables/getters
function getSettlementAuthorizationInfo()
external
view
returns (
address cpDelegate,
address cpSingleHolder,
bool genericSettlementAllowed,
address settlementFacilitator
);
function totalBorrowed() external view returns (uint256);
function router() external view returns (address);
function borrowedCollateralAmounts(address) external view returns (uint256);
function escrowInfo() external view returns (DataTypes.EscrowInfo memory);
}
IDeriFlowRouter.sol 69 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { DataTypes } from "../misc/DataTypes.sol";
interface IDeriFlowRouter {
// External functions
function withdraw(address escrow, address to) external;
function exercise(
address escrow,
address collateralReceiver,
uint256 collateralAmount,
bool payInConversionToken,
bytes[] memory oracleData
) external;
function borrow(address escrow, address borrowAmountReceiver, uint256 borrowAmount) external;
function repay(address escrow, address conversionAmountReceiver, uint256 repayCollateralAmount) external;
function takeEscrowQuote(
DataTypes.EscrowQuotePayload calldata payload,
uint256 notional,
uint256 partnerCode
) external;
function takeSwapQuote(address to, DataTypes.SwapQuote calldata swapQuote) external;
function takeRedemptionQuote(address to, address escrow, DataTypes.SwapQuote calldata swapQuote) external;
function invalidateQuote(bytes32 msgHash) external;
function settle(
address escrow,
address collatBeneficiary,
DataTypes.PaymentLeg[] calldata legs,
uint256 settlementCode,
uint256 validUntil,
bytes calldata signature
) external;
function setDistributionManager(address newDistributionManager) external;
function emitTransferEvent(address from, address to, uint256 value) external;
// View functions
function previewTakeEscrowQuote(
address taker,
DataTypes.EscrowQuotePayload calldata payload,
uint256 notional,
uint256 partnerCode
) external view returns (DataTypes.TakeEscrowQuotePreview memory);
function cpToken() external view returns (address);
function isQuoteIdUsed(address maker, uint256 quoteId) external view returns (bool);
// Public variables/getters
function escrowImpl() external view returns (address);
function distributionManager() external view returns (address);
function isEscrow(address) external view returns (bool);
function isQuoteUsed(address maker, bytes32 msgHash) external view returns (bool);
function isQuoteInvalidated(address maker, bytes32 msgHash) external view returns (bool);
}
IDistributionManager.sol 43 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import { DataTypes } from "../misc/DataTypes.sol";
interface IDistributionManager {
function distribute(uint256 partnerCode, address token, uint256 matchFeeAmount) external;
function setGlobalMatchFeeRate(uint256 globalMatchFeeRate) external;
function setPairMatchFeeRate(address collateralToken, address conversionToken, uint128 matchFeeRate) external;
function deletePairMatchFeeRate(address collateralToken, address conversionToken) external;
function setUserDiscount(address user, uint256 discount) external;
function deleteUserDiscount(address user) external;
function setDistribution(
uint256 partnerCode,
address[] calldata recipients,
uint256[] calldata percentages
) external;
function deleteDistribution(uint256 partnerCode) external;
function withdrawTokens(address[] calldata tokens, uint256[] calldata amounts) external;
function getMatchFeeRate(
address user,
DataTypes.EscrowQuotePayload calldata payload,
uint256 partnerCode
) external view returns (uint256);
function getDistribution(
address user,
DataTypes.EscrowQuotePayload calldata payload,
uint256 partnerCode
) external view returns (address[] memory recipients, uint256[] memory percentages, bool active);
function globalMatchFeeRate() external view returns (uint256);
function owner() external view returns (address);
}
IOracleAdapter.sol 7 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
interface IOracleAdapter {
// @dev: returns the price of tokenA in units of tokenB (tokenB per 1 tokenA), scaled to tokenB decimals
function getPrice(address tokenA, address tokenB, bytes[] memory data) external view returns (uint256);
}
DataTypes.sol 88 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
library DataTypes {
struct EscrowQuotePayload {
EscrowInfo escrowInfo;
Quote quote;
}
struct EscrowInfo {
address collateralToken;
address conversionToken;
address collatProviderDelegate; // optional: delegate in case of multiple collat providers
uint128 collateralization; // collateralization in BASE (eg fully collat. = 100% = BASE)
bool genericSettlementAllowed; // optional: if generic settle() method allowed for generic payoffs
ExerciseSettings exerciseSettings;
AdvancedSettings advancedSettings;
}
struct ExerciseSettings {
address oracle;
uint48 expiry;
uint48 earliestExercise;
uint128 strike;
uint64 borrowCap; // in BASE (eg fully borrowable = 100% = BASE)
}
struct AdvancedSettings {
bool votingDelegationAllowed;
address allowedDelegateRegistry;
address settlementFacilitator; // optional: facilitator for 2-out-of-3 enabled settlements via settle()
bool allowMultiCollatProviders; // optional: in case multiple collat providers allowed
}
struct Quote {
uint256 premiumPerNotionalUnit;
uint256 validUntil;
bool isBid; // true = bid (signer pays premium, receives collateral), false = ask (signer provides collateral, receives premium)
bool premiumIsInCollateralToken; // true = premium paid in collateral token, false = premium paid in conversion token
uint256 minNotional;
uint256 maxNotional;
address targetEscrow;
uint256 quoteId; // unique identifier for the quote (per maker) to control exposure when quoting concurrently
bytes signature;
}
enum QuoteStatus {
Success,
Expired,
InvalidQuote,
AlreadyExecuted,
QuoteInvalidated,
InvalidTargetEscrow,
TargetEscrowParameterMismatch,
TargetEscrowNotRemintable,
InvalidNotional,
QuoteIdAlreadyUsed,
UnauthorizedMaker,
MustBeBid,
ExpiryTooClose
}
struct TakeEscrowQuotePreview {
QuoteStatus status;
bytes32 msgHash;
address maker;
uint256 premium;
address premiumToken;
uint256 totalMatchFee;
uint256 collateral;
}
struct SwapQuote {
address takerGiveToken;
uint256 takerGiveAmount;
address makerGiveToken;
uint256 makerGiveAmount;
uint256 validUntil;
bytes signature;
}
struct PaymentLeg {
address from;
address to;
address token;
uint256 amount;
}
}
Errors.sol 80 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
library Errors {
// General errors
error AlreadyInitialized();
error InvalidAddress();
error InvalidSender();
error NotAnEscrow();
error CannotUseIfGenericSettlementAllowed();
// Exercise errors
error InvalidExerciseTime();
error InvalidExerciseAmount();
error InvalidExercise();
// Borrow/Repay errors
error InvalidBorrowAmount();
error InvalidBorrowTime();
error InvalidRepayAmount();
error InvalidRepayTime();
error NothingToRepay();
// Withdraw/Redeem errors
error InvalidWithdraw();
error NoCBTokensToRedeem();
error NoCPTokensToRedeem();
error ZeroSupply();
error NothingToWithdraw();
// Recover errors
error InvalidRecoverTime();
error InvalidRecoverSender();
error InvalidRecoverToken();
// Quote errors
error InvalidTakeQuote();
error QuoteExpired();
error QuoteAlreadyUsed();
error QuoteInvalidated();
error NothingToInvalidate();
error QuoteIdAlreadyUsed();
error InvalidMakerGiveToken();
// Distribution manager errors
error DistributionManagerAlreadySet();
error InvalidDiscount();
error InvalidDistribution();
error ArrayLengthMismatch();
error InvalidPercentage();
// Voting errors
error VotingDelegationNotAllowed();
error NoAllowedDelegateRegistry();
// Query errors
error InvalidEscrowsQuery();
// Settlement errors
error SettlementExpired();
error SettleNotEnabled();
error InvalidSigner();
error InvalidLegTo();
error InvalidLegFrom();
// Escrow reminting errors
error InvalidTargetEscrow();
// Single holder errors
error SingleHolderViolation();
error PartialTransferDisallowed();
error InvariantBroken();
// Oracle errors
error LengthMismatch();
error NoOracleConfigured();
error InvalidPrice();
error UnsupportedQuote();
error StalePrice();
}
Events.sol 124 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import { DataTypes } from "./DataTypes.sol";
library Events {
// Router Events
event Withdraw(
address indexed sender,
address indexed escrow,
address to,
address collateralToken,
uint256 collateralAmount,
address conversionToken,
uint256 conversionAmount
);
event Exercise(
address indexed sender,
address indexed escrow,
address collateralReceiver,
uint256 collateralAmount
);
event Borrow(
address indexed sender,
address indexed escrow,
address borrowAmountReceiver,
uint256 borrowAmount,
uint256 conversionAmount
);
event Repay(
address indexed sender,
address indexed escrow,
address conversionAmountReceiver,
uint256 repayCollateralAmount,
uint256 unlockedConversionAmount
);
event TakeEscrowQuote(
address indexed collatBeneficiary,
address indexed collatProvider,
address indexed escrow,
DataTypes.EscrowQuotePayload payload,
DataTypes.TakeEscrowQuotePreview takeEscrowQuotePreview,
uint256 partnerCode
);
event TakeSwapQuote(
address indexed sender,
address indexed to,
address indexed maker,
DataTypes.SwapQuote swapQuote
);
event TakeRedemptionQuote(
address indexed sender,
address indexed to,
address indexed maker,
address escrow,
DataTypes.SwapQuote swapQuote
);
event NewDistributionManager(address oldDistributionManager, address newDistributionManager);
event Transfer(address indexed token, address indexed from, address indexed to, uint256 value);
// Escrow Events
event OnChainVotingDelegation(address delegate);
event OffChainVotingDelegation(address indexed allowedDelegateRegistry, bytes32 indexed spaceId, address delegate);
event WithdrawEscrow(
address indexed user,
address indexed to,
address collateralToken,
uint256 collateralAmount,
address conversionToken,
uint256 conversionAmount
);
event Redeem(address indexed sender, address to, address collateralToken, uint256 amount);
event Recover(address indexed sender, address indexed to, address indexed token, uint256 amount);
event Settlement(
address indexed escrow,
address indexed caller,
address indexed authorizer,
DataTypes.PaymentLeg paymentLeg,
uint256 settlementCode
);
event QuoteInvalidated(address indexed sender, bytes32 indexed msgHash);
event SingleHolderChanged(uint256 indexed tokenId, address oldSingleHolder, address newSingleHolder);
event CPDelegateTransferred(address indexed escrow, address indexed oldDelegate, address indexed newDelegate);
event SettlementFacilitatorTransferred(
address indexed escrow,
address indexed oldFacilitator,
address indexed newFacilitator
);
event TokenDistribution(
uint256 indexed partnerCode,
address indexed recipient,
address indexed token,
uint256 percentage,
uint256 amount
);
// DistributionManager Events
event GlobalMatchFeeRateSet(uint256 oldRate, uint256 newRate);
event PairMatchFeeRateSet(address indexed collateralToken, address indexed conversionToken, uint128 matchFeeRate);
event PairMatchFeeRateDeleted(address indexed collateralToken, address indexed conversionToken);
event UserDiscountSet(address indexed user, uint256 discount);
event UserDiscountDeleted(address indexed user);
event DistributionSet(uint256 indexed partnerCode, address[] recipients, uint256[] percentages);
event DistributionDeleted(uint256 indexed partnerCode);
event RouterSet(address oldRouter, address newRouter);
}
DeriFlowCBToken.sol 60 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import { ERC20Upgradeable } from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { Errors } from "../misc/Errors.sol";
/// @title DeriFlow Collateral Beneficiary (CB) Token
abstract contract DeriFlowCBToken is Initializable, ERC20Upgradeable {
uint8 private _decimals;
address internal _soleHolder;
constructor() {
_disableInitializers();
}
function initialize(string memory name_, string memory symbol_, uint8 decimals_) internal {
__ERC20_init(name_, symbol_);
_decimals = decimals_;
}
function decimals() public view override returns (uint8) {
return _decimals;
}
function mint(address to, uint256 amount) external virtual;
function _update(address from, address to, uint256 amount) internal override {
bool single = _requiresSingleHolder();
if (single) {
if (totalSupply() != 0) {
address holder = _soleHolder;
if (from == address(0)) {
if (to != holder) {
revert Errors.SingleHolderViolation();
}
} else if (to != address(0)) {
// @dev: transfer (not mint/burn)
// only sole holder may send tokens and must transfer their *entire* balance
if (from != holder) {
revert Errors.SingleHolderViolation();
}
if (amount != balanceOf(from)) {
revert Errors.PartialTransferDisallowed();
}
}
// @dev: burn checks not relevant as only the sole holder ever has a balance
}
}
super._update(from, to, amount);
if (single) {
// @dev: after update, the sole holder becomes `to`
_soleHolder = to;
}
}
function _requiresSingleHolder() internal virtual returns (bool);
}
DeriFlowCPToken.sol 115 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.28;
import { ERC1155 } from "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import { ERC1155Supply } from "@openzeppelin/contracts/token/ERC1155/extensions/ERC1155Supply.sol";
import { Errors } from "../misc/Errors.sol";
import { Events } from "../misc/Events.sol";
import { IDeriFlowRouter } from "../interfaces/IDeriFlowRouter.sol";
/// @title DeriFlow Collateral Provider (CP) Token
contract DeriFlowCPToken is ERC1155Supply {
address public immutable router;
mapping(address => uint256) public escrowToTokenId;
mapping(uint256 => address) public tokenIdToEscrow;
mapping(uint256 => address) public tokenIdToSingleHolder; // @dev: tracks if single addr holds all CP tokens of given escrow
address[] internal _escrows;
constructor() ERC1155("") {
router = msg.sender;
}
function mint(address to, address escrow, uint256 tokenId, uint256 amount) external {
if (msg.sender != router) {
revert Errors.InvalidSender();
}
bool isNewEscrow = tokenIdToEscrow[tokenId] == address(0);
escrowToTokenId[escrow] = tokenId;
tokenIdToEscrow[tokenId] = escrow;
// @dev: on initial mint, `to` automatically becomes single holder, see _updateWithAcceptanceCheck
_mint(to, tokenId, amount, "");
// @dev: auto-approve to minimize overhead wrt takeRedemptionQuote()
_setApprovalForAll(to, router, true);
if (isNewEscrow) {
_escrows.push(escrow);
}
}
function burn(uint256 tokenId, address account, uint256 amount) external {
address escrow = tokenIdToEscrow[tokenId];
if (msg.sender != escrow) {
revert Errors.InvalidSender();
}
_burn(account, tokenId, amount);
}
function getEscrowByTokenId(uint256 tokenId) external view returns (address) {
return tokenIdToEscrow[tokenId];
}
function getTokenIdByEscrow(address escrow) external view returns (uint256) {
return escrowToTokenId[escrow];
}
function nextTokenId() external view returns (uint256) {
return _escrows.length;
}
function getEscrows(uint256 from, uint256 numElements) external view returns (address[] memory _escrowArray) {
uint256 length = _escrows.length;
if (from >= length) {
return new address[](0);
}
uint256 to = from + numElements;
if (to > length) {
to = length;
}
uint256 size;
unchecked {
size = to - from;
}
_escrowArray = new address[](size);
for (uint256 i = from; i < to; i++) {
uint256 k;
unchecked {
k = i - from;
}
_escrowArray[k] = _escrows[i];
}
}
function _update(address from, address to, uint256[] memory ids, uint256[] memory values) internal override {
// @dev: disallow CP token transfers to known escrows to avoid stuck erc1155 tokens
if (IDeriFlowRouter(router).isEscrow(to)) {
revert Errors.InvalidAddress();
}
super._update(from, to, ids, values);
// @dev: track single holder - if one address holds all tokens, store it; otherwise clear it
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
address oldSingleHolder = tokenIdToSingleHolder[id];
uint256 totalSupplyForId = totalSupply(id);
address newSingleHolder = oldSingleHolder;
// check if 'to' now holds full supply (mint or full transfer)
if (to != address(0) && totalSupplyForId > 0 && balanceOf(to, id) == totalSupplyForId) {
newSingleHolder = to;
}
// check if previous single holder no longer holds full supply
else if (oldSingleHolder != address(0)) {
if (balanceOf(oldSingleHolder, id) != totalSupplyForId || totalSupplyForId == 0) {
newSingleHolder = address(0);
}
}
if (newSingleHolder != oldSingleHolder) {
tokenIdToSingleHolder[id] = newSingleHolder;
emit Events.SingleHolderChanged(id, oldSingleHolder, newSingleHolder);
}
}
}
}
Read Contract
authorizedMaker 0xbb6fadd4 → address
cpToken 0x1b4a5cc8 → address
distributionManager 0xcccbdbd3 → address
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
escrowImpl 0xfda25df4 → address
escrowNonces 0xe6e3b638 → uint256
hashEscrowQuotePayload 0x40399402 → bytes32
hashEscrowQuotePayloadAndRecover 0x88d868e2 → bytes32, address
hashSettlement 0x2b62869e → bytes32
hashSettlementAndRecover 0xbcc90dda → bytes32, address
hashSwapQuote 0x25f5fcb4 → bytes32
hashSwapQuoteAndRecover 0x7a100cb9 → bytes32, address
isEscrow 0xb166a09f → bool
isQuoteIdUsed 0x0608958f → bool
isQuoteInvalidated 0x76f43a38 → bool
isQuoteUsed 0x430084a9 → bool
multiHolderEscrowByHash 0xda36f56b → address
owner 0x8da5cb5b → address
previewTakeEscrowQuote 0x04e53dd0 → tuple
rawEscrowInfoHash 0xf96daa73 → bytes32
supportsInterface 0x01ffc9a7 → bool
Write Contract 15 functions
These functions modify contract state and require a wallet transaction to execute.
borrow 0x5224372c
address escrow
address borrowAmountReceiver
uint256 borrowAmount
emitTransferEvent 0xa6d49dca
address from
address to
uint256 value
exercise 0xca41363e
address escrow
address collateralReceiver
uint256 collateralAmount
bool payInConversionToken
bytes[] oracleData
invalidateQuote 0x2fd39597
bytes32 msgHash
onERC1155BatchReceived 0xbc197c81
address
address
uint256[]
uint256[]
bytes
returns: bytes4
onERC1155Received 0xf23a6e61
address
address
uint256
uint256
bytes
returns: bytes4
renounceOwnership 0x715018a6
No parameters
repay 0x1da649cf
address escrow
address conversionAmountReceiver
uint256 repayCollateralAmount
setDistributionManager 0xfe91c394
address newDistributionManager
settle 0x345a4a1f
address escrow
address collatBeneficiary
tuple[] legs
uint256 settlementCode
uint256 validUntil
bytes signature
takeEscrowQuote 0xa51c5cac
tuple payload
uint256 notional
uint256 partnerCode
takeRedemptionQuote 0x48c9b1ac
address to
address escrow
tuple swapQuote
takeSwapQuote 0x8205d84f
address to
tuple swapQuote
transferOwnership 0xf2fde38b
address newOwner
withdraw 0xf940e385
address escrow
address to
Recent Transactions
No transactions found for this address