Address Contract Verified
Address
0x0B4C3D5FFA70589917A9D68c899C607c8E606Ff8
Balance
0 ETH
Nonce
1
Code Size
21530 bytes
Creator
0xC83B7f46...d0Fc at tx 0x9bb5bf0b...f21f5e
Indexed Transactions
0
Contract Bytecode
21530 bytes
0x608060405234801561000f575f80fd5b5060043610610255575f3560e01c806384b0196e11610140578063bc758a95116100bf578063cd217f7f11610084578063cd217f7f146105ed578063d547741f14610600578063d755c47914610613578063e5111da714610626578063f122977714610651578063f12a623b14610664575f80fd5b8063bc758a951461056d578063c2a672e014610580578063c49baebe14610593578063c50daecc146105ba578063c55897bf146105da575f80fd5b806394fc06711161010557806394fc06711461051a57806397ad1cce1461052d578063a217fddf14610540578063b6cc524314610547578063bbad64641461055a575f80fd5b806384b0196e1461049e57806385e710b0146104b95780638b4d7577146104e15780638d9a6ed2146104f457806391d1485414610507575f80fd5b80633f4ba83a116101d7578063637212d01161019c578063637212d0146103e557806367cdb47f146104245780636f44bb691461044c57806375b238fc1461046f5780637e989e54146104835780638456cb5914610496575f80fd5b80633f4ba83a1461038a5780634268121e146103925780634c75b707146103a557806359b4c4b4146103b85780635c975abb146103da575f80fd5b8063269149b41161021d578063269149b41461031c5780632f2ff15d1461033c5780632f9904e01461035157806336568abe146103645780633899ff1414610377575f80fd5b806301ffc9a71461025957806304082ff414610281578063150b7a02146102a15780632328c402146102d9578063248a9ca3146102fa575b5f80fd5b61026c61026736600461481f565b610677565b60405190151581526020015b60405180910390f35b61029461028f366004614861565b6106ad565b604051610278919061487a565b6102c06102af3660046148c8565b630a85bd0160e11b95945050505050565b6040516001600160e01b03199091168152602001610278565b6102ec6102e7366004614861565b610775565b604051908152602001610278565b6102ec61030836600461495a565b5f9081526003602052604090206001015490565b61032f61032a366004614971565b6107ce565b60405161027891906149f4565b61034f61034a366004614a02565b6108cc565b005b61034f61035f366004614a2c565b6108f6565b61034f610372366004614a02565b610c12565b61034f610385366004614a5c565b610c45565b61034f610d60565b61034f6103a0366004614a5c565b610d82565b61034f6103b3366004614861565b610da2565b6103cb6103c6366004614a84565b610ece565b60405161027893929190614ac3565b60025460ff1661026c565b61040c7f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad581565b6040516001600160a01b039091168152602001610278565b6102ec610432366004614861565b6001600160a01b03165f9081526006602052604090205490565b61045f61045a366004614861565b611112565b6040516102789493929190614b6b565b6102ec5f805160206153c583398151915281565b6102ec610491366004614b99565b6112c8565b61034f6113bd565b6104a66113dc565b6040516102789796959493929190614c1c565b6102ec6104c7366004614861565b6001600160a01b03165f9081526015602052604090205490565b6102ec6104ef366004614971565b61141e565b61034f610502366004614861565b611518565b61026c610515366004614a02565b61153b565b61034f610528366004614a5c565b611565565b61034f61053b366004614a5c565b6115a7565b6102ec5f81565b61034f610555366004614a2c565b6116ac565b6102ec610568366004614cb3565b6116f6565b61034f61057b366004614cdb565b611815565b61034f61058e366004614a5c565b611861565b6102ec7f21702c8af46127c7fa207f89d0b0a8441bb32959a0ac7df790e9ab1a25c9892681565b6105cd6105c8366004614a5c565b61187b565b6040516102789190614d11565b61034f6105e8366004614861565b611a4b565b61034f6105fb366004614d86565b611a64565b61034f61060e366004614a02565b611dcf565b61034f610621366004614e7d565b611df3565b61026c610634366004614861565b6001600160a01b03165f9081526016602052604090205460ff1690565b6102ec61065f366004614861565b61206a565b61034f610672366004615002565b6121d0565b5f6001600160e01b03198216637965db0b60e01b14806106a757506301ffc9a760e01b6001600160e01b03198316145b92915050565b60606001600160a01b0382166106d65760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0382165f908152600b6020908152604080832080548251818502810185019093528083529192909190849084015b8282101561074e578382905f5260205f2090600202016040518060400160405290815f82015481526020016001820154815250508152602001906001019061070b565b50505050905080515f036106a7576040516388cde06f60e01b815260040160405180910390fd5b6001600160a01b0381165f908152600d602090815260408083205460139092528220548183036107a857505f9392505050565b816107bc8268056bc75e2d63100000615064565b6107c6919061507b565b949350505050565b6107d66147a9565b6001600160a01b03831615806107f357506001600160a01b038416155b156108115760405163e6c4247b60e01b815260040160405180910390fd5b815f03610831576040516307ed98ed60e31b815260040160405180910390fd5b6001600160a01b038085165f908152600760209081526040808320878516845282528083208684528252808320815160e081018352815490951685526001810154928501929092526002820154908401526003810154606084015260048101546080840152600581015460a0840181905260069091015460c084015290036107c657604051630a49bbc360e21b815260040160405180910390fd5b5f828152600360205260409020600101546108e681612329565b6108f08383612333565b50505050565b6108fe6123c4565b6109066123ea565b6001600160a01b0383165f9081526016602052604090205460ff161561093f5760405163237686b360e01b815260040160405180910390fd5b815f0361095f576040516307ed98ed60e31b815260040160405180910390fd5b3361096b838583612414565b6001600160a01b038416610992576040516388cde06f60e01b815260040160405180910390fd5b815f036109b9576040516324e33dfb60e21b81525f60048201526024015b60405180910390fd5b6001600160a01b038082165f908152600760209081526040808320938816835292815282822086835290522060018101548414610a0957604051630a49bbc360e21b815260040160405180910390fd5b5f610a1886836002015461187b565b90505f848360060154610a2b919061509a565b8251909150811115610a565781516040516324e33dfb60e21b815260048101919091526024016109b0565b5f610a6b8885600201548487600401546112c8565b6001600160a01b0389165f90815260056020819052604090912090860154815492935090918391610a9b916150ad565b610aa5919061509a565b815560058501829055600685018390556001600160a01b038087165f818152600960209081526040808320948e168084529482528083208d84528252808320549383526008825280832094835293905291909120805487919083908110610b0e57610b0e6150c0565b5f9182526020909120825460079092020180546001600160a01b0319166001600160a01b039283161781556001808401549082015560028084015490820155600380840154908201556004808401549082015560058084015490820155600692830154920191909155610ba5907f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad51688308b6124ab565b60028601546040805191825260208201859052810185905289906001600160a01b03808a1691908d16907fa55bcd1fdd8a4453f4c5481757c1808ebd3c38647bbb340094f6fb1aa060cd149060600160405180910390a450505050505050610c0d6001600455565b505050565b6001600160a01b0381163314610c3b5760405163334bd91960e11b815260040160405180910390fd5b610c0d8282612505565b610c4d6123c4565b5f805160206153c5833981519152610c6481612329565b6001600160a01b038316610c8b5760405163e6c4247b60e01b815260040160405180910390fd5b815f03610cae57604051633728b83d60e01b8152600481018390526024016109b0565b678ac7230489e80000821115610cd7576040516367e3b83560e01b815260040160405180910390fd5b6001600160a01b0383165f9081526005602052604081206002810154909103610d1e57604051631a7e275f60e11b81526001600160a01b03851660048201526024016109b0565b6001810183905560405183906001600160a01b038616907f9b1afbc58afefe24863c46a8f0375d91643c9e13c9e8d7a6ffdafbf9a4dc837e905f90a350505050565b5f805160206153c5833981519152610d7781612329565b610d7f612570565b50565b610d8a6123ea565b610d9482826125c2565b610d9e6001600455565b5050565b610daa6123ea565b610db26123c4565b5f805160206153c5833981519152610dc981612329565b6001600160a01b038216610df05760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0382165f9081526006602052604081205490819003610e2c57604051633728b83d60e01b8152600481018290526024016109b0565b6001600160a01b038381165f908152600660205260408120553390610e74907f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad5168284612b52565b806001600160a01b0316846001600160a01b03167f6dff6a50991143b581f6ccff8e56f1b6a5bba64f6253b3194b0a3ad14f961daf84604051610eb991815260200190565b60405180910390a3505050610d7f6001600455565b60605f805f8511610f215760405162461bcd60e51b815260206004820152601960248201527f50616765206e756d626572207374617274732066726f6d20310000000000000060448201526064016109b0565b6001600160a01b038088165f908152600860209081526040808320938a168352929052908120549085610f556001896150ad565b610f5f9190615064565b90505f610f6c878361509a565b905082811115610f795750815b5f610f8483836150ad565b90505f816001600160401b03811115610f9f57610f9f614def565b604051908082528060200260200182016040528015610fd857816020015b610fc56147a9565b815260200190600190039081610fbd5790505b5090505f5b828110156110d65760056003015f8e6001600160a01b03166001600160a01b031681526020019081526020015f205f8d6001600160a01b03166001600160a01b031681526020019081526020015f208186611038919061509a565b81548110611048576110486150c0565b5f9182526020918290206040805160e081018252600790930290910180546001600160a01b031683526001810154938301939093526002830154908201526003820154606082015260048201546080820152600582015460a082015260069091015460c082015282518390839081106110c3576110c36150c0565b6020908102919091010152600101610fdd565b505f8960016110e5828961509a565b6110ef91906150ad565b6110f9919061507b565b9198508a975090955050505050505b9450945094915050565b5f808060606001600160a01b03851661113e5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0385165f908152600560209081526040808320815160808101835281548152600182015481850152600282015481840152600382018054845181870281018701909552808552919492936060860193909290879084015b828210156111e9578382905f5260205f2090600302016040518060600160405290815f8201548152602001600182015481526020016002820154815250508152602001906001019061119c565b50505091525050805160408201516020830151919750955093509050836001600160401b0381111561121d5761121d614def565b60405190808252806020026020018201604052801561126f57816020015b61125c60405180606001604052805f81526020015f81526020015f81525090565b81526020019060019003908161123b5790505b5091505f5b848110156112bf5781606001518181518110611292576112926150c0565b60200260200101518382815181106112ac576112ac6150c0565b6020908102919091010152600101611274565b50509193509193565b5f806112d3866106ad565b90505f6112e0878761187b565b90505f805b8351816001600160801b031610156113635783816001600160801b031681518110611312576113126150c0565b60200260200101515f015186036113515783816001600160801b03168151811061133e5761133e6150c0565b6020026020010151602001519150611363565b8061135b816150d4565b9150506112e5565b50805f03611384576040516337bf561360e11b815260040160405180910390fd5b5f61138e87612b83565b90505f8284602001516113a19190615064565b90505f6113ae838361509a565b9b9a5050505050505050505050565b5f805160206153c58339815191526113d481612329565b610d7f612be8565b5f6060805f805f60606113ed612c25565b6113f5612c56565b604080515f80825260208201909252600f60f81b9b939a50919850469750309650945092509050565b6001600160a01b038084165f8181526007602090815260408083208786168085529083528184208785528352818420825160e081018452815490971687526001810154878501526002810154878401526003810154606088015260048101546080880152600581015460a08801526006015460c087015284845260128352818420818552835281842087855283528184205494845260118352818420908452825280832086845290915281205490929190670de0b6b3a7640000906114e28761206a565b6114ec91906150ad565b8360a001516114fb9190615064565b611505919061507b565b61150f919061509a565b95945050505050565b5f805160206153c583398151915261152f81612329565b610d9e8260015f612c83565b5f9182526003602090815260408084206001600160a01b0393909316845291905290205460ff1690565b5f805160206153c583398151915261157c81612329565b815f0361159c576040516308af88a160e21b815260040160405180910390fd5b610c0d835f84612c83565b5f805160206153c58339815191526115be81612329565b5f82116115e157604051633728b83d60e01b8152600481018390526024016109b0565b6001600160a01b0383166116085760405163e6c4247b60e01b815260040160405180910390fd5b61163d7f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad56001600160a01b03163330856124ab565b6001600160a01b0383165f908152601560205260408120805484929061166490849061509a565b90915550506040518281526001600160a01b038416907fb9ad861b752f80117b35bea6dec99933d8a5ae360f2839ee8784b750d56134099060200160405180910390a2505050565b6116b46123c4565b5f805160206153c58339815191526116cb81612329565b825f036116eb576040516308af88a160e21b815260040160405180910390fd5b6108f0848484612d9c565b6001600160a01b038083165f90815260086020908152604080832093851683529281528282208054845181840281018401909552808552929384938493919291849084015b828210156117b5575f8481526020908190206040805160e0810182526007860290920180546001600160a01b03168352600180820154848601526002820154928401929092526003810154606084015260048101546080840152600581015460a08401526006015460c0830152908352909201910161173b565b5050505090505f5b815181101561180b575f8282815181106117d9576117d96150c0565b60200260200101516020015190505f6117f388888461141e565b90506117ff818661509a565b945050506001016117bd565b5090949350505050565b61181d6123c4565b6118256123ea565b61182e81612f1b565b61185761183e6020830183614861565b8260200135836040013584606001358560800135613035565b610d7f6001600455565b6118696123c4565b6118716123ea565b610d948282613629565b61189d60405180606001604052805f81526020015f8152602001606081525090565b6001600160a01b0383166118c45760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0383165f908152600a6020908152604080832080548251818502810185019093528083529192909190849084015b828210156119cc578382905f5260205f2090600302016040518060600160405290815f82015481526020016001820154815260200160028201805461193d906150f9565b80601f0160208091040260200160405190810160405280929190818152602001828054611969906150f9565b80156119b45780601f1061198b576101008083540402835291602001916119b4565b820191905f5260205f20905b81548152906001019060200180831161199757829003601f168201915b505050505081525050815260200190600101906118f9565b50505050905080515f036119f3576040516388cde06f60e01b815260040160405180910390fd5b821580611a005750805183115b15611a1e576040516307f8da6560e01b815260040160405180910390fd5b80611a2a6001856150ad565b81518110611a3a57611a3a6150c0565b602002602001015191505092915050565b611a536123c4565b611a5b6123ea565b61185781613b9a565b611a6c6123c4565b5f805160206153c5833981519152611a8381612329565b6001600160a01b0386161580611aa057506001600160a01b038516155b15611abe5760405163e6c4247b60e01b815260040160405180910390fd5b5f866001600160a01b03166306fdde036040518163ffffffff1660e01b81526004015f60405180830381865afa158015611afa573d5f803e3d5ffd5b505050506040513d5f823e601f3d908101601f19168201604052611b219190810190615131565b6001600160a01b038881165f908152600c602052604090205491925016158015611b73576001600160a01b038881165f908152600c6020526040902080546001600160a01b0319169189169190911790555b5f5b84811015611d5a57858582818110611b8f57611b8f6150c0565b9050604002015f01355f1480611bbf5750858582818110611bb257611bb26150c0565b905060400201602001355f145b15611bdd5760405163b4fa3fb360e01b815260040160405180910390fd5b8015611ca2578585611bf06001846150ad565b818110611bff57611bff6150c0565b9050604002015f0135868683818110611c1a57611c1a6150c0565b9050604002015f01351115611c41576040516229bb9160e41b815260040160405180910390fd5b8585611c4e6001846150ad565b818110611c5d57611c5d6150c0565b90506040020160200135868683818110611c7957611c796150c0565b905060400201602001351115611ca257604051633b3c3bfd60e11b815260040160405180910390fd5b5f6040518060600160405280888885818110611cc057611cc06150c0565b9050604002015f01358152602001888885818110611ce057611ce06150c0565b60206040918202939093018301358452928201889052506001600160a01b038d165f908152600a825282812080546001818101835591835291839020855160039093020191825591840151918101919091559082015191925082916002820190611d4a908261520a565b505060019092019150611b759050565b5085611d6e670de0b6b3a764000082615064565b6001600160a01b038a165f818152600d6020526040908190209290925590517f628692fc3a7416c446a8100777d9a12cc83b2719ea5770251656dcb975c33c0190611dbc90899089906152c9565b60405180910390a2505050505050505050565b5f82815260036020526040902060010154611de981612329565b6108f08383612505565b611dfb6123c4565b5f805160206153c5833981519152611e1281612329565b5f5b8251811015610c0d575f838281518110611e3057611e306150c0565b60209081029190910101515190506001600160a01b038116611e655760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0381165f9081526005602052604090206002015415611e9e57604051637983c05160e01b815260040160405180910390fd5b838281518110611eb057611eb06150c0565b60200260200101516040015151600114611edd576040516365b6e2ff60e01b815260040160405180910390fd5b678ac7230489e80000848381518110611ef857611ef86150c0565b6020026020010151602001511115611f23576040516367e3b83560e01b815260040160405180910390fd5b838281518110611f3557611f356150c0565b6020908102919091018101518101516001600160a01b0383165f9081526005909252604090912060018082019290925560028101919091558451600390910190859084908110611f8757611f876150c0565b6020026020010151604001515f81518110611fa457611fa46150c0565b6020908102919091018101518254600181810185555f94855293839020825160039092020190815591810151928201929092556040909101516002909101558351849083908110611ff757611ff76150c0565b602002602001015160200151816001600160a01b03167f9ee96876e131c231f94f6aea63fae2f04070be2e5f3f412a4c8e34ee8cec58d6868581518110612040576120406150c0565b602002602001015160400151604051612059919061530e565b60405180910390a350600101611e14565b6001600160a01b0381165f908152600560205260408120805482036120a55750506001600160a01b03165f908152600f602052604090205490565b6001600160a01b0383165f908152600f60205260408120546003830180549192916120d2906001906150ad565b815481106120e2576120e26150c0565b5f918252602091829020604080516060810182526003909302909101805483526001810154938301849052600201549082015291504211156121c8575f8082604001511180156121355750816040015142115b61213f5742612145565b81604001515b6001600160a01b0387165f908152600e60205260409020549091508111156121c6576001600160a01b0386165f908152600e602052604081205461218990836150ad565b855484519192509061219c908390615064565b6121ae90670de0b6b3a7640000615064565b6121b8919061507b565b6121c2908561509a565b9350505b505b509392505050565b6121d86123c4565b5f805160206153c58339815191526121ef81612329565b6001600160a01b0384166122165760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0384165f908152600b60205260409020805415612254576001600160a01b0385165f908152600b60205260408120612254916147e8565b5f5b61ffff81168411156122de576001600160a01b0386165f908152600b60205260409020858561ffff841681811061228f5761228f6150c0565b83546001810185555f94855260209094206040909102929092019260020290910190506122c9828281358155602082013560018201555050565b505080806122d690615320565b915050612256565b50846001600160a01b03167fafb975b469c50c753530b2b9cb85ad704d66cfe99be1c351d424893386531392858560405161231a9291906152c9565b60405180910390a25050505050565b610d7f8133613f47565b5f61233e838361153b565b6123bd575f8381526003602090815260408083206001600160a01b03861684529091529020805460ff191660011790556123753390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45060016106a7565b505f6106a7565b60025460ff16156123e85760405163d93c066560e01b815260040160405180910390fd5b565b60026004540361240d57604051633ee5aeb560e01b815260040160405180910390fd5b6002600455565b61241d8261206a565b6001600160a01b0383165f908152600f6020908152604080832093909355600e90522042905561244e81838561141e565b6001600160a01b039182165f81815260126020908152604080832096909516808352958152848220878352815284822093909355848152600f83528381205491815260118352838120948152938252828420948452939052902055565b6108f084856001600160a01b03166323b872dd8686866040516024016124d393929190615336565b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050613f80565b5f612510838361153b565b156123bd575f8381526003602090815260408083206001600160a01b0386168085529252808320805460ff1916905551339286917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45060016106a7565b612578613fec565b6002805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6001600160a01b0382166125e95760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0382165f9081526016602052604090205460ff166126205760405162e0699b60e51b815260040160405180910390fd5b805f03612640576040516307ed98ed60e31b815260040160405180910390fd5b335f8181526007602090815260408083206001600160a01b038781168552908352818420868552835292819020815160e0810183528154909416845260018101549284018390526002810154918401919091526003810154606084015260048101546080840152600581015460a08401526006015460c083015283146126d957604051630a49bbc360e21b815260040160405180910390fd5b6126e4838584612414565b60a08101516001600160a01b0385165f90815260056020526040812080548392906127109084906150ad565b90915550506001600160a01b0385165f9081526013602052604081208054670de0b6b3a764000092906127449084906150ad565b90915550506001600160a01b038084165f818152600760209081526040808320948a16808452948252808320898452825280832080546001600160a01b031916815560018082018590556002820185905560038201859055600482018590556005820185905560069091018490558484526014835281842086855283528184208a855283528184208490558484526009835281842086855283528184208a855283528184205494845260088352818420958452949091528120549192909161280c91906150ad565b6001600160a01b038087165f908152601260209081526040808320938c1683529281528282208a835290529081205590508181146129a0576001600160a01b038086165f908152600860209081526040808320938b16835292905290812080548390811061287c5761287c6150c0565b5f91825260208083206040805160e081018252600790940290910180546001600160a01b0390811685526001820154858501526002820154858401526003820154606086015260048201546080860152600582015460a086015260069091015460c08501528a8116855260088352818520908d168552909152909120805491925082918590811061290f5761290f6150c0565b5f918252602080832084516007939093020180546001600160a01b0319166001600160a01b039384161781558482015160018201556040808601516002830155606086015160038301556080860151600483015560a0860151600583015560c090950151600690910155898216835260098152838320918c1683529081528282209381015182529290925290208290555b6001600160a01b038086165f908152600860209081526040808320938b168352929052208054806129d3576129d361535a565b5f828152602080822060075f199094019384020180546001600160a01b03191681556001810183905560028101839055600381018390556004810183905560058101839055600601829055919092556001600160a01b038781168352600982526040808420918b168452908252808320898452909152812055612a56878761400f565b6040516323b872dd60e01b81526001600160a01b038816906323b872dd90612a8690309089908b90600401615336565b5f604051808303815f87803b158015612a9d575f80fd5b505af1158015612aaf573d5f803e3d5ffd5b50505060c0850151612aee91506001600160a01b037f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad516908790612b52565b85856001600160a01b0316886001600160a01b03167f1569b24fee1440a841734fd3f2284d7bd8a0108a991d69f836140266b88d497b868860c00151604051612b41929190918252602082015260400190565b60405180910390a450505050505050565b6040516001600160a01b03838116602483015260448201839052610c0d91859182169063a9059cbb906064016124d3565b5f80670de0b6b3a76400007f0000000000000000000000000000000000000000000000008ac7230489e80000612bb98286615064565b612bc3919061507b565b612bcd9190615064565b9050612be1670de0b6b3a76400008261507b565b9392505050565b612bf06123c4565b6002805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586125a53390565b6060612c517f47616c696c656f2d5374616b696e67000000000000000000000000000000000f5f61407d565b905090565b6060612c517f3100000000000000000000000000000000000000000000000000000000000001600161407d565b6001600160a01b038316612caa5760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b0383165f908152600560205260408120600201549003612ce4576040516388cde06f60e01b815260040160405180910390fd5b6001600160a01b0383165f9081526016602052604090205482151560ff909116151503612d245760405163e8b2a2cb60e01b815260040160405180910390fd5b6001600160a01b0383165f908152601660205260408120805460ff1916841515179055612d549084908390612d9c565b604080516001600160a01b038516815283151560208201527f8a83e637d585ab195bd567bc9ce1ad02d66a844867f4ea8fdb2e4fea1fffd38c910160405180910390a1505050565b6001600160a01b0383165f9081526005602052604081206002015490819003612dd8576040516388cde06f60e01b815260040160405180910390fd5b612de18461206a565b6001600160a01b0385165f908152600f6020908152604080832093909355600e8152828220429081905560059091529181206003810154909190612e27906001906150ad565b90508415801590612e385750828511155b15612e56576040516338af65f760e01b815260040160405180910390fd5b82826003018281548110612e6c57612e6c6150c0565b5f9182526020808320600392830201600290810194909455604080516060810182528b81528083018981528183018c8152898601805460018082018355828a529887902094519702909301958655905195850195909555935192850192909255915492850192909255905184815287916001600160a01b038a16917f1d75b4af369dd9c67d43994eea5f98a89dcaa2d64156061ae12a4eaaeb43ff08910160405180910390a350505050505050565b5f612f9f7f9d4721e33d89534ce8747d048acf2bc45235b1b32ee2a34351518528db058825612f4d6020850185614861565b604080516020818101949094526001600160a01b03909216828201529185013560608201529084013560808201524660a082015260c00160405160208183030381529060405280519060200120614126565b90505f612fec82612fb360a086018661536e565b8080601f0160208091040260200160405190810160405280939291908181526020018383808284375f9201919091525061415292505050565b90506130187f21702c8af46127c7fa207f89d0b0a8441bb32959a0ac7df790e9ab1a25c989268261153b565b610c0d57604051638baa579f60e01b815260040160405180910390fd5b6001600160a01b0385165f9081526016602052604090205460ff161561306e5760405163237686b360e01b815260040160405180910390fd5b835f0361308e576040516307ed98ed60e31b815260040160405180910390fd5b3361309a858783612414565b6001600160a01b0386166130c15760405163e6c4247b60e01b815260040160405180910390fd5b6001600160a01b038082165f9081526007602090815260408083208a851684528252808320888452825291829020825160e0810184528154909416845260018101549184018290526002810154928401929092526003820154606084015260048201546080840152600582015460a084015260069091015460c083015286900361315e576040516316e9ad8f60e01b815260040160405180910390fd5b428061316a818761509a565b11613188576040516337bf561360e11b815260040160405180910390fd5b6001600160a01b0388165f90815260056020526040812060028101549091036131cf57604051631a7e275f60e11b81526001600160a01b038a1660048201526024016109b0565b5f6131da8a8961187b565b90508060400151515f03613201576040516388cde06f60e01b815260040160405180910390fd5b80518611156132295780516040516324e33dfb60e21b815260048101919091526024016109b0565b5f6132368b8a898b6112c8565b905080835f015f82825461324a919061509a565b925050819055505f6040518060e001604052808d6001600160a01b031681526020018c81526020018b81526020018681526020018a81526020018381526020018981525090508060056002015f896001600160a01b03166001600160a01b031681526020019081526020015f205f8e6001600160a01b03166001600160a01b031681526020019081526020015f205f8d81526020019081526020015f205f820151815f015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055506020820151816001015560408201518160020155606082015181600301556080820151816004015560a0820151816005015560c0820151816006015590505060056003015f886001600160a01b03166001600160a01b031681526020019081526020015f205f8d6001600160a01b03166001600160a01b031681526020019081526020015f2081908060018154018082558091505060019003905f5260205f2090600702015f909190919091505f820151815f015f6101000a8154816001600160a01b0302191690836001600160a01b031602179055506020820151816001015560408201518160020155606082015181600301556080820151816004015560a0820151816005015560c082015181600601555050600160056003015f896001600160a01b03166001600160a01b031681526020019081526020015f205f8e6001600160a01b03166001600160a01b031681526020019081526020015f208054905061347d91906150ad565b60056004015f896001600160a01b03166001600160a01b031681526020019081526020015f205f8e6001600160a01b03166001600160a01b031681526020019081526020015f205f8d81526020019081526020015f2081905550670de0b6b3a76400006005600e015f8e6001600160a01b03166001600160a01b031681526020019081526020015f205f828254613514919061509a565b925050819055508b6001600160a01b03166323b872dd88308e6040518463ffffffff1660e01b815260040161354b93929190615336565b5f604051808303815f87803b158015613562575f80fd5b505af1158015613574573d5f803e3d5ffd5b506135af9250506001600160a01b037f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad516905088308b6124ab565b6135ba8c888d614170565b8a6001600160a01b03808916908e167f5a7d4798422b818434e18058d8df205ee02d50ddbd7b2028c1f42c19b23a26268d6135f58e8b61509a565b6040805192835260208301919091528101879052606081018d905260800160405180910390a4505050505050505050505050565b6001600160a01b0382166136505760405163e6c4247b60e01b815260040160405180910390fd5b805f03613670576040516307ed98ed60e31b815260040160405180910390fd5b335f8181526007602090815260408083206001600160a01b038781168552908352818420868552835292819020815160e0810183528154909416845260018101549284018390526002810154918401919091526003810154606084015260048101546080840152600581015460a08401526006015460c0830152831461370957604051630a49bbc360e21b815260040160405180910390fd5b5f8160800151826060015161371e919061509a565b90508042101561374457604051635c8385b360e01b8152600481018290526024016109b0565b61374f848685612414565b61375a8386866141e7565b60a08201516001600160a01b0386165f90815260056020526040812080548392906137869084906150ad565b90915550506001600160a01b0386165f9081526013602052604081208054670de0b6b3a764000092906137ba9084906150ad565b90915550506001600160a01b038085165f818152600760209081526040808320948b168084529482528083208a8452825280832080546001600160a01b031916815560018082018590556002820185905560038201859055600482018590556005820185905560069091018490558484526014835281842086855283528184208b855283528184208490558484526009835281842086855283528184208b855283528184205494845260088352818420958452949091528120549192909161388291906150ad565b90508082146139e7576001600160a01b038087165f908152600860209081526040808320938c1683529290529081208054839081106138c3576138c36150c0565b5f91825260208083206040805160e081018252600790940290910180546001600160a01b0390811685526001820154858501526002820154858401526003820154606086015260048201546080860152600582015460a086015260069091015460c08501528b8116855260088352818520908e1685529091529091208054919250829185908110613956576139566150c0565b5f918252602080832084516007939093020180546001600160a01b0319166001600160a01b039384161781558482015160018201556040808601516002830155606086015160038301556080860151600483015560a0860151600583015560c0909501516006909101558a8216835260098152838320918d1683529081528282209381015182529290925290208290555b6001600160a01b038087165f908152600860209081526040808320938c16835292905220805480613a1a57613a1a61535a565b5f828152602080822060075f199094019384020180546001600160a01b03191681556001810183905560028101839055600381018390556004810183905560058101839055600601829055919092556001600160a01b038881168352600982526040808420918c1684529082528083208a8452909152812055613a9d888861400f565b6040516323b872dd60e01b81526001600160a01b038916906323b872dd90613acd9030908a908c90600401615336565b5f604051808303815f87803b158015613ae4575f80fd5b505af1158015613af6573d5f803e3d5ffd5b50505060c0860151613b3591506001600160a01b037f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad516908890612b52565b86866001600160a01b0316896001600160a01b03167f9e6a005a25cc2e5f4cc8ab7d01c8bc5ceeb3f74aff04147dd2d4b4abd89f0853868960c00151604051613b88929190918252602082015260400190565b60405180910390a45050505050505050565b6001600160a01b038116613bc15760405163e6c4247b60e01b815260040160405180910390fd5b335f8181526008602090815260408083206001600160a01b0386168452825280832080548251818502810185019093528083529192909190849084015b82821015613c78575f8481526020908190206040805160e0810182526007860290920180546001600160a01b03168352600180820154848601526002820154928401929092526003810154606084015260048101546080840152600581015460a08401526006015460c08301529083529092019101613bfe565b50505050905080515f03613c9f57604051630a49bbc360e21b815260040160405180910390fd5b5f42613caa8561206a565b6001600160a01b0386165f908152600f6020908152604080832093909355600e90529081208290555b8351811015613d7b575f848281518110613cef57613cef6150c0565b60200260200101516020015190505f613d0987898461141e565b6001600160a01b038089165f818152601260209081526040808320948e168084529482528083208884528252808320839055848352600f82528083205493835260118252808320948352938152838220878352905291909120559050613d6f818661509a565b94505050600101613cd3565b50815f03613d9f576040516324e33dfb60e21b8152600481018390526024016109b0565b6001600160a01b0385165f908152600560209081526040808320815160808101835281548152600182015481850152600282015481840152600382018054845181870281018701909552808552919492936060860193909290879084015b82821015613e4a578382905f5260205f2090600302016040518060600160405290815f82015481526020016001820154815260200160028201548152505081526020019060010190613dfd565b505050508152505090505f613e64878584602001516143ef565b6001600160a01b0388165f9081526015602052604090205490915084811015613ea057604051631bc8970f60e31b815260040160405180910390fd5b6001600160a01b0388165f9081526015602052604081208054879290613ec79084906150ad565b90915550613f0190506001600160a01b037f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad5168884612b52565b81876001600160a01b0316896001600160a01b03167fc5c78598ad30cffeebab36aea1e0a984cfa6d9df37b0408e589a17a1e4c8ce5087604051613b8891815260200190565b613f51828261153b565b610d9e5760405163e2517d3f60e01b81526001600160a01b0382166004820152602481018390526044016109b0565b5f8060205f8451602086015f885af180613f9f576040513d5f823e3d81fd5b50505f513d91508115613fb6578060011415613fc3565b6001600160a01b0384163b155b156108f057604051635274afe760e01b81526001600160a01b03851660048201526024016109b0565b60025460ff166123e857604051638dfc202b60e01b815260040160405180910390fd5b6001600160a01b038281165f908152600c602052604090819020549051630852cd8d60e31b81526004810184905291169081906342966c68906024015f604051808303815f87803b158015614062575f80fd5b505af1158015614074573d5f803e3d5ffd5b50505050505050565b606060ff83146140975761409083614457565b90506106a7565b8180546140a3906150f9565b80601f01602080910402602001604051908101604052809291908181526020018280546140cf906150f9565b801561411a5780601f106140f15761010080835404028352916020019161411a565b820191905f5260205f20905b8154815290600101906020018083116140fd57829003601f168201915b505050505090506106a7565b5f6106a7614132614494565b8360405161190160f01b8152600281019290925260228201526042902090565b5f805f8061416086866145bd565b92509250925061180b8282614606565b6001600160a01b038381165f908152600c60205260409081902054905163219e412d60e21b8152848316600482015260248101849052911690819063867904b4906044015f604051808303815f87803b1580156141cb575f80fd5b505af11580156141dd573d5f803e3d5ffd5b5050505050505050565b5f6141f384848461141e565b6001600160a01b0384165f9081526005602090815260408083208151608081018352815481526001820154818501526002820154818401526003820180548451818702810187019095528085529697509495909491936060860193929190879084015b828210156142a3578382905f5260205f2090600302016040518060600160405290815f82015481526020016001820154815260200160028201548152505081526020019060010190614256565b505050508152505090505f6142bd858484602001516143ef565b9050805f036142e257604051633728b83d60e01b8152600481018290526024016109b0565b6001600160a01b0385165f9081526015602052604090205483811161431a57604051631bc8970f60e31b815260040160405180910390fd5b6001600160a01b038088165f908152601260209081526040808320938a1680845293825280832089845282528083208390559282526015905290812080548692906143669084906150ad565b909155506143a090506001600160a01b037f000000000000000000000000a444ec96ee01bb219a44b285de47bf33c3447ad5168884612b52565b84866001600160a01b0316886001600160a01b03167fec2dbca33bce849c88f50479a2201a22b1027e27f4ce0682074fb39d285c94d88542604051612b41929190918252602082015260400190565b5f8068056bc75e2d631000006144058486615064565b61440f919061507b565b90505f61441c82866150ad565b6001600160a01b0387165f9081526006602052604081208054929350849290919061444890849061509a565b90915550909695505050505050565b60605f614463836146be565b6040805160208082528183019092529192505f91906020820181803683375050509182525060208101929092525090565b5f306001600160a01b037f0000000000000000000000000b4c3d5ffa70589917a9d68c899c607c8e606ff8161480156144ec57507f000000000000000000000000000000000000000000000000000000000000000146145b1561451657507f8bd0dd2420be6decdee089b158aa24acd6cd7c3258152d1a5ffb08afdfa9ac1990565b612c51604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527fd9fcc1295fc6f39c027b810af24730ccd6bcaa835bb73fd3d3cae0fe8fb2f3b3918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a08201525f9060c00160405160208183030381529060405280519060200120905090565b5f805f83516041036145f4576020840151604085015160608601515f1a6145e6888285856146e5565b9550955095505050506145ff565b505081515f91506002905b9250925092565b5f826003811115614619576146196153b0565b03614622575050565b6001826003811115614636576146366153b0565b036146545760405163f645eedf60e01b815260040160405180910390fd5b6002826003811115614668576146686153b0565b036146895760405163fce698f760e01b8152600481018290526024016109b0565b600382600381111561469d5761469d6153b0565b03610d9e576040516335e2f38360e21b8152600481018290526024016109b0565b5f60ff8216601f8111156106a757604051632cd44ac360e21b815260040160405180910390fd5b5f80807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a084111561471e57505f91506003905082611108565b604080515f808252602082018084528a905260ff891692820192909252606081018790526080810186905260019060a0016020604051602081039080840390855afa15801561476f573d5f803e3d5ffd5b5050604051601f1901519150506001600160a01b03811661479a57505f925060019150829050611108565b975f9750879650945050505050565b6040518060e001604052805f6001600160a01b031681526020015f81526020015f81526020015f81526020015f81526020015f81526020015f81525090565b5080545f8255600202905f5260205f2090810190610d7f91905b8082111561481b575f8082556001820155600201614802565b5090565b5f6020828403121561482f575f80fd5b81356001600160e01b031981168114612be1575f80fd5b80356001600160a01b038116811461485c575f80fd5b919050565b5f60208284031215614871575f80fd5b612be182614846565b602080825282518282018190525f919060409081850190868401855b828110156148bb57815180518552860151868501529284019290850190600101614896565b5091979650505050505050565b5f805f805f608086880312156148dc575f80fd5b6148e586614846565b94506148f360208701614846565b93506040860135925060608601356001600160401b0380821115614915575f80fd5b818801915088601f830112614928575f80fd5b813581811115614936575f80fd5b896020828501011115614947575f80fd5b9699959850939650602001949392505050565b5f6020828403121561496a575f80fd5b5035919050565b5f805f60608486031215614983575f80fd5b61498c84614846565b925061499a60208501614846565b9150604084013590509250925092565b80516001600160a01b031682526020808201519083015260408082015190830152606080820151908301526080808201519083015260a0818101519083015260c090810151910152565b60e081016106a782846149aa565b5f8060408385031215614a13575f80fd5b82359150614a2360208401614846565b90509250929050565b5f805f60608486031215614a3e575f80fd5b614a4784614846565b95602085013595506040909401359392505050565b5f8060408385031215614a6d575f80fd5b614a7683614846565b946020939093013593505050565b5f805f8060808587031215614a97575f80fd5b614aa085614846565b9350614aae60208601614846565b93969395505050506040820135916060013590565b606080825284519082018190525f906020906080840190828801845b82811015614b0557614af28483516149aa565b60e0939093019290840190600101614adf565b5050506020840195909552505060400152919050565b5f815180845260208085019450602084015f5b83811015614b605781518051885283810151848901526040908101519088015260609096019590820190600101614b2e565b509495945050505050565b848152836020820152826040820152608060608201525f614b8f6080830184614b1b565b9695505050505050565b5f805f8060808587031215614bac575f80fd5b614bb585614846565b966020860135965060408601359560600135945092505050565b5f5b83811015614be9578181015183820152602001614bd1565b50505f910152565b5f8151808452614c08816020860160208601614bcf565b601f01601f19169290920160200192915050565b60ff60f81b881681525f602060e06020840152614c3c60e084018a614bf1565b8381036040850152614c4e818a614bf1565b606085018990526001600160a01b038816608086015260a0850187905284810360c0860152855180825260208088019350909101905f5b81811015614ca157835183529284019291840191600101614c85565b50909c9b505050505050505050505050565b5f8060408385031215614cc4575f80fd5b614ccd83614846565b9150614a2360208401614846565b5f60208284031215614ceb575f80fd5b81356001600160401b03811115614d00575f80fd5b820160c08185031215612be1575f80fd5b6020815281516020820152602082015160408201525f60408301516060808401526107c66080840182614bf1565b5f8083601f840112614d4f575f80fd5b5081356001600160401b03811115614d65575f80fd5b6020830191508360208260061b8501011115614d7f575f80fd5b9250929050565b5f805f805f60808688031215614d9a575f80fd5b614da386614846565b9450614db160208701614846565b93506040860135925060608601356001600160401b03811115614dd2575f80fd5b614dde88828901614d3f565b969995985093965092949392505050565b634e487b7160e01b5f52604160045260245ffd5b604051606081016001600160401b0381118282101715614e2557614e25614def565b60405290565b604051601f8201601f191681016001600160401b0381118282101715614e5357614e53614def565b604052919050565b5f6001600160401b03821115614e7357614e73614def565b5060051b60200190565b5f60208284031215614e8d575f80fd5b6001600160401b038083351115614ea2575f80fd5b8235830184601f820112614eb4575f80fd5b614ec6614ec18235614e5b565b614e2b565b81358082526020808301929160051b84010187811115614ee4575f80fd5b602084015b81811015614ff5578581351115614efe575f80fd5b803585016060818b03601f19011215614f15575f80fd5b614f1d614e03565b614f2960208301614846565b8152604082013560208201528760608301351115614f45575f80fd5b6060820135820191508a603f830112614f5c575f80fd5b6020820135614f6d614ec182614e5b565b818152606090910283016040019060208101908d831115614f8c575f80fd5b6040850194505b82851015614fdf576060858f031215614faa575f80fd5b614fb2614e03565b85358152602086013560208201526040860135604082015280835250602082019150606085019450614f93565b6040840152505085525060209384019301614ee9565b5090979650505050505050565b5f805f60408486031215615014575f80fd5b61501d84614846565b925060208401356001600160401b03811115615037575f80fd5b61504386828701614d3f565b9497909650939450505050565b634e487b7160e01b5f52601160045260245ffd5b80820281158282048414176106a7576106a7615050565b5f8261509557634e487b7160e01b5f52601260045260245ffd5b500490565b808201808211156106a7576106a7615050565b818103818111156106a7576106a7615050565b634e487b7160e01b5f52603260045260245ffd5b5f6001600160801b038083168181036150ef576150ef615050565b6001019392505050565b600181811c9082168061510d57607f821691505b60208210810361512b57634e487b7160e01b5f52602260045260245ffd5b50919050565b5f60208284031215615141575f80fd5b81516001600160401b0380821115615157575f80fd5b818401915084601f83011261516a575f80fd5b81518181111561517c5761517c614def565b61518f601f8201601f1916602001614e2b565b91508082528560208285010111156151a5575f80fd5b6151b6816020840160208601614bcf565b50949350505050565b601f821115610c0d57805f5260205f20601f840160051c810160208510156151e45750805b601f840160051c820191505b81811015615203575f81556001016151f0565b5050505050565b81516001600160401b0381111561522357615223614def565b6152378161523184546150f9565b846151bf565b602080601f83116001811461526a575f84156152535750858301515b5f19600386901b1c1916600185901b1785556152c1565b5f85815260208120601f198616915b8281101561529857888601518255948401946001909101908401615279565b50858210156152b557878501515f19600388901b60f8161c191681555b505060018460011b0185555b505050505050565b602080825281018290525f604080830185835b8681101561530257813583526020808301359084015291830191908301906001016152dc565b50909695505050505050565b602081525f612be16020830184614b1b565b5f61ffff8083168181036150ef576150ef615050565b6001600160a01b039384168152919092166020820152604081019190915260600190565b634e487b7160e01b5f52603160045260245ffd5b5f808335601e19843603018112615383575f80fd5b8301803591506001600160401b0382111561539c575f80fd5b602001915036819003821315614d7f575f80fd5b634e487b7160e01b5f52602160045260245ffdfea49807205ce4d355092ef5a8a18f56e8913cf4a201fbe287825b095693c21775a26469706673582212204786a09fdfe1e6d195bc914a22fe9b184649d466e7255fcf679eb47f834dfcb064736f6c63430008180033
Verified Source Code Full Match
Compiler: v0.8.24+commit.e11b9ed9
EVM: cancun
Optimization: Yes (200 runs)
GalileoStaking.sol 1591 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./interfaces/IGalileoSoulBoundToken.sol";
import "./libraries/GalileoStakingStorage.sol";
import "./libraries/GalileoStakingErrors.sol";
contract GalileoStaking is EIP712, Pausable, AccessControl, ReentrancyGuard, IERC721Receiver {
// ██████╗ █████╗ ██╗ ██╗██╗ ███████╗ ██████╗
// ██╔════╝ ██╔══██╗██║ ██║██║ ██╔════╝ ██╔═══██╗
// ██║ ██╗ ███████║██║ ██║██║ █████╗ ██║ ██║
// ██║ █║ ██╔══██║██║ ██║██║ ██╔══╝ ██║ ██║
// ╚██████║ ██║ ██║███████╗██║███████╗███████╗ ╚██████╔╝
// ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═╝╚══════╝╚══════╝ ╚═════╝
// ═══════════════════════ VARIABLES ════════════════════════
using SafeERC20 for IERC20;
// Constant variable defining the ADMIN_ROLE using keccak256 hash
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
// Constant variable defining the VALIDATOR_ROLE using keccak256 hash
bytes32 public constant VALIDATOR_ROLE = keccak256("VALIDATOR_ROLE");
// The domain name used for signing and verifying off-chain data, typically part of an EIP-712 structured data signature.
string private constant SIGNING_DOMAIN = "Galileo-Staking";
// The version of the signature schema, used in conjunction with the signing domain for EIP-712 signatures.
string private constant SIGNATURE_VERSION = "1";
// Importing the GalileoStakingStorage library for the State struct
using GalileoStakingStorage for GalileoStakingStorage.State;
// Declaring a private state variable of type GalileoStakingStorage.State
GalileoStakingStorage.State private state;
// Importing the GalileoStakingErrors library for all types (*)
using GalileoStakingErrors for *;
// Immutable variable storing the address of the LEOX token
address public immutable LEOX;
// Constant for INCREMENT value
uint256 private immutable INCREMENT; // INCREMENT indicates one point
/// A constant multiplier to reduce overflow in staking calculations.
uint256 private constant PRECISION = 1 ether;
// Define a maximum tax rate of 10%
uint256 private constant MAX_TAX_LIMIT = 10 ether;
// ═══════════════════════ EVENTS ════════════════════════
/**
* @dev Event emitted when a collection is configured with its address and total number of categories.
*
* @param collectionAddress The address of the collection contract.
* @param _stakeInfo _stakeInfo An array of StakeInfo structs containing information about LEOX tokens.
*/
event ConfigureCollection(address indexed collectionAddress, GalileoStakingStorage.StakeInfoInput[] _stakeInfo);
/**
* @dev Event emitted when a token is staked within a collection
*
* @param collectionAddress The address of the collection contract.
* @param tokenId The ID of the token to which more tokens are staked.
* @param citizen The citizen of the token.
* @param timelockEndTime End time of the timelock for the staked token.
* @param points Points associated with the staked token.
* @param stakedLEOX Amount of LEOX tokens staked with the token.
*/
event StakeTokens(
address indexed collectionAddress,
address indexed recipient,
uint256 indexed tokenId,
uint256 citizen,
uint256 timelockEndTime,
uint256 points,
uint256 stakedLEOX
);
/**
* @dev Event emitted when more LEOX tokens are added to an existing stake.
*
* @param collectionAddress The address of the collection contract.
* @param tokenId The ID of the token to which more tokens are staked.
* @param citizen The citizen of the token.
* @param newPoints The updated points after adding more tokens.
* @param totalLeox The total amount of LEOX tokens staked after adding more tokens.
*/
event StakeLeoxTokens(
address indexed collectionAddress,
address indexed recipient,
uint256 indexed tokenId,
uint256 citizen,
uint256 newPoints,
uint256 totalLeox
);
/**
* @dev Emitted when tax percent is updated of a collection.
*
* @param collectionAddress The address of the collection contract from which tax is withdrawn.
* @param newTaxPercent The new percentage of tax against the collection.
*/
event UpdateTax(address indexed collectionAddress, uint256 indexed newTaxPercent);
/**
* @dev Event emitted when multipliers are set for a collection.
*
* @param collectionAddress The address of the collection contract.
* @param multipliers Multipliers based on staking time period.
*/
event SetMultipliers(address indexed collectionAddress, GalileoStakingStorage.Multiplier[] multipliers);
/**
* @dev Event emitted when a recipient withdraws rewards for a staked NFT
*
* @param recipient Address of the recipient who withdraw the rewards
* @param collectionAddress Address of the collection the NFT belongs to.
* @param tokenId The ID of the token to which more tokens are staked.
* @param rewardAmount Amount of rewards withdrawn.
* @param currentTime Timestamp of the withdrawal.
*/
event WithdrawRewards(
address indexed recipient,
address indexed collectionAddress,
uint256 indexed tokenId,
uint256 rewardAmount,
uint256 currentTime
);
/**
* @dev Event emitted when a recipient withdraws all rewards for all staked tokens
*
* @param collectionAddress Address of the collection the NFT belongs to.
* @param recipient Address of the recipient who withdraw the rewards
* @param rewardAmount Amount of rewards of all tokens withdrawn.
* @param currentTime Timestamp of the withdrawal.
*/
event WithdrawAllRewards(address indexed collectionAddress, address indexed recipient, uint256 indexed rewardAmount, uint256 currentTime);
/**
* @dev Event emitted when a recipient unstake Tokens and get rewards for a staked NFT
*
* @param collectionAddress Address of the collection the NFT belongs to.
* @param recipient Address of the recipient who withdrew the rewards
* @param tokenId The ID of the token to which more tokens are staked.
* @param points Points associated with the staked token.
* @param totalLeox Amount of LEOX tokens unstaked with the token.
*/
event UnstakeToken(
address indexed collectionAddress,
address indexed recipient,
uint256 indexed tokenId,
uint256 points,
uint256 totalLeox
);
/**
* @dev Event emitted when a recipient unstake Tokens and get rewards for a staked NFT
*
* @param collectionAddress Address of the collection the NFT belongs to.
* @param recipient Address of the recipient who withdrew the rewards
* @param tokenId The ID of the token to which more tokens are staked.
* @param points Points associated with the staked token.
* @param totalLeox Amount of LEOX tokens unstaked with the token.
*/
event EmergencyUnstakeToken(
address indexed collectionAddress,
address indexed recipient,
uint256 indexed tokenId,
uint256 points,
uint256 totalLeox
);
/**
* @dev Emitted when the emission rate is updated for a specific collection.
*
* @param collectionAddress The address of the collection contract for which the emission rate is updated.
* @param rewardRate The new reward rate set for the collection.
* @param endTimePreviousRewardWindow The end time of the previous reward window before the emission rate update.
*/
event UpdateEmissionRate(address indexed collectionAddress, uint256 indexed rewardRate, uint256 endTimePreviousRewardWindow);
/**
* @dev Emitted when tax is withdrawn from a collection.
*
* @param collectionAddress The address of the collection contract from which tax is withdrawn.
* @param recipient The address of the recipient who receives the withdrawn tax amount.
* @param taxAmount The total amount of tax withdrawn from the collection.
*/
event WithdrawTax(address indexed collectionAddress, address indexed recipient, uint256 taxAmount);
/**
* @dev Emitted when rewards are deposited into the reward pool for a specific NFT collection.
*
* @param collectionAddress The address of the NFT collection for which rewards are being deposited.
* @param leoxAmount The amount of LEOX tokens deposited as rewards.
*/
event DepositRewards(address indexed collectionAddress, uint256 leoxAmount);
/**
* @dev Emitted whenever the emergency status is changed.
*
* @param collectionAddress The address of the NFT collection.
* @param isEmergencyDeclared A boolean value indicating the current state of emergency
*/
event DeclareEmergency(address collectionAddress, bool isEmergencyDeclared);
/**
* @dev Emitted when a pool is configured or updated.
*
* @param collectionAddress The address of the collection contract for which the pool is configured.
* @param tax The tax rate applied to the pool for the collection.
* @param rewardWindows An array of reward windows configured for the pool.
*/
event ConfigurePool(address indexed collectionAddress, uint256 indexed tax, GalileoStakingStorage.RewardWindow[] rewardWindows);
// ═══════════════════════ CONSTRUCTOR ════════════════════════
/**
* @dev Constructor to initialize the contract.
*
* @param leox The address of the LEOX token contract.
* @param increment INCREMENT value that indicates one point
*/
constructor(address leox, uint256 increment) EIP712(SIGNING_DOMAIN, SIGNATURE_VERSION) {
// Ensure that the LEOX token address is not zero
if (leox == address(0)) revert GalileoStakingErrors.InvalidAddress();
// Ensure that the INCREMENT is not zero
if (increment == 0) revert GalileoStakingErrors.InvalidIncrement();
// Grant the default admin role to the deploying address
_grantRole(DEFAULT_ADMIN_ROLE, _msgSender());
// Grant the admin role to the deploying address
_grantRole(ADMIN_ROLE, _msgSender());
// Set the LEOX token address
LEOX = leox;
// Set the INCREMENT value that indicates one point
INCREMENT = increment;
}
// ═══════════════════════ FUNCTIONS ════════════════════════
/**
* @dev Function to stake tokens into the specified collection.
*
* This function handles the staking of a token along with LEOX tokens, ensuring that the token is not already
* staked by the caller and that all provided parameters are valid before proceeding with the staking process.
*
* @param stakeTokens The address of the NFT collection contract.
*- tokenId The ID of the NFT to be staked.
*- citizen The citizen ID associated with the token (used for yield trait points).
*- stakedLeox The amount of LEOX tokens to be staked alongside the NFT.
*- timelockEndTime The end time of the timelock for the stake (when the stake will be unlocked).
*/
function stake(GalileoStakingStorage.StakeTokens calldata stakeTokens) external whenNotPaused nonReentrant {
// Recover and verify the voucher signature to ensure its authenticity.
_recover(stakeTokens);
// Call the internal function to handle the actual staking process
_stakeTokens(
stakeTokens.collectionAddress,
stakeTokens.tokenId,
stakeTokens.citizen,
stakeTokens.timelockEndTime,
stakeTokens.stakedLeox
);
}
/**
* @dev Internal function to handle the staking process for tokens.
*
* This function is used to stake a given token along with LEOX tokens, managing the staking position,
* pool points, and transferring assets from the user to the contract.
*
* @param collectionAddress The address of the NFT collection being staked.
* @param tokenId The ID of the NFT to be staked.
* @param citizen The citizen ID associated with the token (yield trait specific).
* @param timelockEndTime The time until which the stake is locked.
* @param stakedLeox The amount of LEOX tokens to be staked alongside the NFT.
*/
function _stakeTokens(address collectionAddress, uint256 tokenId, uint256 citizen, uint256 timelockEndTime, uint256 stakedLeox) internal {
// Validate that the emergency is declared yet
if (state.isEmergencyDeclared[collectionAddress]) revert GalileoStakingErrors.EmergencyDeclared();
// This ensures that the token id must not be zero.
if (tokenId == 0) revert GalileoStakingErrors.InvalidTokenId();
// Get the address of the user who is calling the function (msg.sender).
address recipient = _msgSender();
// This ensures that the reward calculations are up-to-date before executing the stake function logic.
_updateReward(tokenId, collectionAddress, recipient);
// Check if the collection address is valid and initialized
if (collectionAddress == address(0)) revert GalileoStakingErrors.InvalidAddress();
// Retrieve the staker's current staking position for the specified citizen within the collection
GalileoStakingStorage.StakePerCitizen memory _stakePerCitizen = state.stakersPosition[recipient][collectionAddress][citizen];
// Ensure that the token is not already staked by the caller
if (_stakePerCitizen.tokenId == tokenId) revert GalileoStakingErrors.TokenAlreadyStaked();
// Get the current time
uint256 currentTime = block.timestamp;
// Check if the timelock end time is in the future
if (timelockEndTime + currentTime <= currentTime) revert GalileoStakingErrors.InvalidTime();
// Retrieve pool data for the collection
GalileoStakingStorage.PoolData storage poolData = state.pools[collectionAddress];
// Check if the pool is initialized
if (poolData.rewardCount == 0) revert GalileoStakingErrors.PoolUninitialized(collectionAddress);
// Get the maximum LEOX information for the specified citizen
GalileoStakingStorage.StakeInfo memory _stakeInfo = getYieldTraitPoints(collectionAddress, citizen);
// Check if the collection is initialized
if (bytes(_stakeInfo.collectionName).length == 0) revert GalileoStakingErrors.CollectionUninitialized();
// Check if the staked LEOX tokens exceed the maximum allowed
if (stakedLeox > _stakeInfo.maxLeox) revert GalileoStakingErrors.InvalidTokensCount(_stakeInfo.maxLeox);
// Calculate the points for the stake
uint256 points = calculatePoints(collectionAddress, citizen, stakedLeox, timelockEndTime);
// Update the total points for the pool
poolData.totalPoints += points;
// Create a StakePerCitizen struct to store staking information
GalileoStakingStorage.StakePerCitizen memory stakePerCitizen = GalileoStakingStorage.StakePerCitizen(
collectionAddress,
tokenId,
citizen,
currentTime,
timelockEndTime,
points,
stakedLeox
);
// Store staking information for the user, collection, and token ID
state.stakersPosition[recipient][collectionAddress][tokenId] = stakePerCitizen;
// Add the StakePerCitizen struct to the user's staked NFTs list for this collection
state.stakedNFTs[recipient][collectionAddress].push(stakePerCitizen);
// Store the index of the newly added stake within the stakedNFTs list
state.stakedNFTIndex[recipient][collectionAddress][tokenId] = state.stakedNFTs[recipient][collectionAddress].length - 1;
// Increment the total staked amount for the collection
state.erc721Staked[collectionAddress] += PRECISION;
// Transfer the token to this contract
IERC721(collectionAddress).transferFrom(recipient, address(this), tokenId);
// Transfer the staked LEOX tokens to this contract
IERC20(LEOX).safeTransferFrom(recipient, address(this), stakedLeox);
// Issue Sould Bound Token to the staker
_issueSoulBoundToken(collectionAddress, recipient, tokenId);
// Emit an event to signify the staking of tokens
emit StakeTokens(collectionAddress, recipient, tokenId, citizen, currentTime + timelockEndTime, points, stakedLeox);
}
/**
* @dev External function to update the share per window and set a new emission rate.
*
* @param collectionAddress The address of the collection contract.
* @param rewardRate The new reward rate to be set for the upcoming reward window.
* @param endTime The end time of the new reward window.
*/
function updateEmissionRate(address collectionAddress, uint256 rewardRate, uint256 endTime) external whenNotPaused onlyRole(ADMIN_ROLE) {
// Revert if the reward rate is 0 (invalid for emissions).
if (rewardRate == 0) revert GalileoStakingErrors.InvalidRewardRate();
// Update the emission rate for the collection with the provided reward rate and end time.
_updateEmissionRate(collectionAddress, rewardRate, endTime);
}
/**
* @dev Internal function to update the share per window and set a new emission rate.
*
* @param collectionAddress The address of the collection contract.
* @param rewardRate The new reward rate to be set for the upcoming reward window.
* @param endTime The end time of the new reward window.
*/
function _updateEmissionRate(address collectionAddress, uint256 rewardRate, uint256 endTime) internal {
// Retrieve the total number of reward windows for the specified collection.
uint256 totalRewardWindows = state.pools[collectionAddress].rewardCount;
// Check if there are any reward windows initialized for the collection.
if (totalRewardWindows == 0) revert GalileoStakingErrors.CollectionUninitialized();
// Update the stored reward per token for the collection to the current value.
state.rewardPerTokenStored[collectionAddress] = rewardPerToken(collectionAddress);
// Set start time to current block timestamp
uint256 startTime = block.timestamp;
// Update the last update time for the collection to the current block timestamp.
state.lastUpdateTime[collectionAddress] = startTime;
// Access the pool data associated with the collection address.
GalileoStakingStorage.PoolData storage pool = state.pools[collectionAddress];
// Determine the index for the new reward window.
uint256 lastIndex = pool.rewardWindows.length - 1;
// Allow endTime to be 0 (no end time) or greater than startTime
if (endTime != 0 && endTime <= startTime) revert GalileoStakingErrors.InvalidEndTime();
// Close the last reward window by setting its end time
pool.rewardWindows[lastIndex].endTime = startTime;
// Create and add a new reward window
pool.rewardWindows.push(GalileoStakingStorage.RewardWindow({ rewardRate: rewardRate, startTime: startTime, endTime: endTime }));
// Update reward window count
pool.rewardCount = pool.rewardWindows.length;
// Emit an event indicating that emission rate is updated.
emit UpdateEmissionRate(collectionAddress, rewardRate, startTime);
}
/**
* @dev Stakes additional LEOX tokens for a staked NFT, updating the staker's position and points.
*
* This function allows users to add more LEOX tokens to an existing staked NFT position.
* It updates the staker's points based on the new total of staked LEOX tokens and ensures
* the staked amount does not exceed the maximum allowed per NFT.
*
* @param collectionAddress The address of the NFT collection.
* @param tokenId The unique identifier of the staked NFT.
* @param stakeMoreLeox The amount of additional LEOX tokens to be staked.
*/
function stakeLeoxTokens(address collectionAddress, uint256 tokenId, uint256 stakeMoreLeox) external whenNotPaused nonReentrant {
// Validate that the emergency is declared yet
if (state.isEmergencyDeclared[collectionAddress]) revert GalileoStakingErrors.EmergencyDeclared();
// This ensures that the token id must not be zero.
if (tokenId == 0) revert GalileoStakingErrors.InvalidTokenId();
// Get the address of the user who is calling the function (msg.sender).
address recipient = _msgSender();
// This ensures that the reward calculations are up-to-date before executing the stake leox tokens function logic.
_updateReward(tokenId, collectionAddress, recipient);
// Ensure the collection address is not zero.
if (collectionAddress == address(0)) revert GalileoStakingErrors.CollectionUninitialized();
// Ensure a valid amount of LEOX tokens is provided for staking.
if (stakeMoreLeox == 0) revert GalileoStakingErrors.InvalidTokensCount(0);
// Retrieve the staker's position for the specified token within the collection.
GalileoStakingStorage.StakePerCitizen storage stakePerCitizen = state.stakersPosition[recipient][collectionAddress][tokenId];
// Ensure the token is already staked by the sender.
if (stakePerCitizen.tokenId != tokenId) {
revert GalileoStakingErrors.TokenNotStaked();
}
// Retrieve the maximum allowed LEOX tokens for the token based on yield traits.
GalileoStakingStorage.StakeInfo memory _stakeInfo = getYieldTraitPoints(collectionAddress, stakePerCitizen.citizen);
// Calculate the new total LEOX staked.
uint256 totalLeox = stakePerCitizen.stakedLEOX + stakeMoreLeox;
// Ensure the total LEOX tokens do not exceed the maximum allowed.
if (totalLeox > _stakeInfo.maxLeox) {
revert GalileoStakingErrors.InvalidTokensCount(_stakeInfo.maxLeox);
}
// Calculate the updated points for the staked NFT with the new LEOX amount.
uint256 newPoints = calculatePoints(collectionAddress, stakePerCitizen.citizen, totalLeox, stakePerCitizen.timelockEndTime);
// Update the total points for the pool by subtracting the old points and adding the new points.
GalileoStakingStorage.PoolData storage pool = state.pools[collectionAddress];
pool.totalPoints = pool.totalPoints - stakePerCitizen.points + newPoints;
// Update the staker's position with the new points and staked LEOX tokens.
stakePerCitizen.points = newPoints;
stakePerCitizen.stakedLEOX = totalLeox;
// Update the stakedNFTs list for the user.
uint256 index = state.stakedNFTIndex[recipient][collectionAddress][tokenId];
state.stakedNFTs[recipient][collectionAddress][index] = stakePerCitizen;
// Transfer the additional LEOX tokens from the staker to the contract.
IERC20(LEOX).safeTransferFrom(recipient, address(this), stakeMoreLeox);
// Emit an event indicating that more LEOX tokens were added to the stake.
emit StakeLeoxTokens(collectionAddress, recipient, tokenId, stakePerCitizen.citizen, newPoints, totalLeox);
}
/**
* @dev calculatePoints public function to calculate the staking points
* @param collectionAddress : collection address of the pNFT collection
* @param stakedLeox : token id of the collection
* @param timelockEndTime : stake time lock
* @return total calculated points
*/
function calculatePoints(
address collectionAddress, // Address of the collection
uint256 citizen, // Citizen Id
uint256 stakedLeox, // Amount of staked LEOX tokens
uint256 timelockEndTime // The end time of the timelock
) public view returns (uint256) {
// Get the multipliers for the given collection address
GalileoStakingStorage.Multiplier[] memory _multiplier = getMultipliers(collectionAddress);
// Get the maximum LEOX information for the specified citizen
GalileoStakingStorage.StakeInfo memory _stakeInfo = getYieldTraitPoints(collectionAddress, citizen);
// Initialize the staking boost to zero
uint256 stakingBoost = 0;
// Iterate over the multipliers to find the matching staking time
for (uint128 i = 0; i < _multiplier.length; i++) {
if (timelockEndTime == _multiplier[i].stakingTime) {
// Set the staking boost if the timelock end time matches
stakingBoost = _multiplier[i].stakingBoost;
break;
}
}
// Revert the transaction if no matching staking boost is found
if (stakingBoost == 0) revert GalileoStakingErrors.InvalidTime();
// Calculate the points for the staked LEOX tokens
uint256 leoxPoints = _calculateStakeLeoxPoints(stakedLeox);
// Calculate the yield point boost based on the yield trait points and staking boost
uint256 yieldPointBoost = _stakeInfo.yieldTraitPoints * stakingBoost;
// Calculate the total points by adding yield point boost and LEOX points
uint256 points = yieldPointBoost + leoxPoints;
// Return the total points
return points;
}
/**
* @dev Function to calculate the points for staked LEOX tokens.
*
* @param stakedTokens The number of staked LEOX tokens.
* @return The calculated points for the staked tokens.
*/
function _calculateStakeLeoxPoints(uint256 stakedTokens) internal view returns (uint256) {
// Calculate the base points by dividing the staked tokens by the INCREMENT
uint256 points = ((stakedTokens * PRECISION) / INCREMENT) * PRECISION;
// return points and adjust with percision
return points / PRECISION;
}
/**
* @dev Calculates the reward per token for a specific collection based on the reward windows.
*
* @param collectionAddress The address of the NFT collection for which rewards are being calculated.
* @return The calculated reward per token, scaled to 18 decimals.
*/
function rewardPerToken(address collectionAddress) public view returns (uint256) {
// Retrieve the pool data for the specified collection.
GalileoStakingStorage.PoolData storage pool = state.pools[collectionAddress];
// If no tokens are staked in the pool, return the last stored reward per token value.
if (pool.totalPoints == 0) return state.rewardPerTokenStored[collectionAddress];
// Start with the last stored reward per token.
uint256 rewardPerTokenAcc = state.rewardPerTokenStored[collectionAddress];
// Loop through the reward windows in reverse order, starting with the most recent.
GalileoStakingStorage.RewardWindow memory rewardWindow = pool.rewardWindows[pool.rewardWindows.length - 1];
// Only consider reward windows that have already started.
if (block.timestamp > rewardWindow.startTime) {
// Use the lesser of `block.timestamp` or `endTime` to calculate the reward period
uint256 effectiveEndTime = (rewardWindow.endTime > 0 && block.timestamp > rewardWindow.endTime)
? rewardWindow.endTime
: block.timestamp;
// Prevent underflow by ensuring effectiveEndTime > lastUpdateTime
if (effectiveEndTime > state.lastUpdateTime[collectionAddress]) {
// Calculate the time period for which rewards are being distributed
uint256 timePeriod = effectiveEndTime - state.lastUpdateTime[collectionAddress];
// Calculate and accumulate the reward per token based on the time period
rewardPerTokenAcc += (rewardWindow.rewardRate * timePeriod * 1e18) / pool.totalPoints;
}
}
// Return the accumulated reward per token.
return rewardPerTokenAcc;
}
/**
* @dev Calculates the rewards earned by a staker for a specific token in a collection.
* @param recipient The address of the staker.
* @param collectionAddress The address of the NFT collection.
* @param tokenId The ID of the staked token.
* @return The calculated reward for the staker.
*/
function calculateRewards(address recipient, address collectionAddress, uint256 tokenId) public view returns (uint256) {
// Fetching the staker's position information for the specified token in the collection.
GalileoStakingStorage.StakePerCitizen memory stakeInfo = state.stakersPosition[recipient][collectionAddress][tokenId];
// Calculating the reward based on the staked points, reward per token, and previously paid reward per token.
return
(stakeInfo.points * (rewardPerToken(collectionAddress) - state.userRewardPerTokenPaid[recipient][collectionAddress][tokenId])) /
PRECISION +
state.rewards[recipient][collectionAddress][tokenId];
}
/**
* @dev Calculates the rewards earned by a staker for all tokens staked in a collection.
* @param recipient The address of the staker.
* @param collectionAddress The address of the NFT collection.
* @return The calculated reward for the staker.
*/
function calculateRewardsAllRewards(address recipient, address collectionAddress) public view returns (uint256) {
// Initialize total rewards to zero.
uint256 totalRewards = 0;
// Retrieve all the staked NFTs for the user in the given collection.
GalileoStakingStorage.StakePerCitizen[] memory stakedNFTs = state.stakedNFTs[recipient][collectionAddress];
// Iterate over each staked token ID and calculate its respective rewards.
for (uint256 i = 0; i < stakedNFTs.length; i++) {
// Fetch the tokenId of the staked NFT.
uint256 tokenId = stakedNFTs[i].tokenId;
// Calculate rewards for the specific tokenId by calling the reward calculation logic.
uint256 reward = calculateRewards(recipient, collectionAddress, tokenId);
// Add the reward for this tokenId to the total rewards.
totalRewards += reward;
}
return totalRewards; // Return the total accumulated rewards across all staked NFTs.
}
/**
* @dev Internal function to withdraw the accumulated rewards for a staked token.
* It calculates the rewards, resets the reward balance, transfers the reward, and emits an event.
*
* @param recipient The address of the staker withdrawing the rewards.
* @param collectionAddress The address of the NFT collection.
* @param tokenId The ID of the staked token.
*/
function _withdrawRewards(address recipient, address collectionAddress, uint256 tokenId) internal {
// Calculate the rewards earned by the recipient for the given collection and token ID.
uint256 rewardAmount = calculateRewards(recipient, collectionAddress, tokenId);
// Fetch the pool data for the given collection address.
GalileoStakingStorage.PoolData memory pool = state.pools[collectionAddress];
// Apply tax deductions to the reward amount based on the pool's tax rate.
uint256 rewardsAfterTax = _calculateTax(collectionAddress, rewardAmount, pool.tax);
// Revert the transaction if the reward amount after tax is zero.
if (rewardsAfterTax == 0) revert GalileoStakingErrors.InvalidAmount(rewardsAfterTax);
// Get available rewards for the collection
uint256 poolRewardTokenAmount = state.rewardPool[collectionAddress];
// Revert the transaction if the reward token amount in the pool is less than reward value.
if (poolRewardTokenAmount <= rewardAmount) revert GalileoStakingErrors.InvalidAmountRewardPoolBalance();
// Reset the reward balance for this token and collection to zero after withdrawal.
state.rewards[recipient][collectionAddress][tokenId] = 0;
// Deduct the reward amount after tax from the pool
state.rewardPool[collectionAddress] -= rewardAmount;
// Transfer the net reward amount (after tax) to the recipient.
IERC20(LEOX).safeTransfer(recipient, rewardsAfterTax);
// Emit an event to log the withdrawal of rewards, including timestamp for tracking.
emit WithdrawRewards(recipient, collectionAddress, tokenId, rewardsAfterTax, block.timestamp);
}
/**
* @dev Withdraw all rewards for a user for all staked token IDs in a specific collection.
* The function ensures the caller has a valid collection address.
* It updates the reward before processing the withdrawal.
*
* @param collectionAddress The address of the NFT collection.
*/
function withdrawAllRewards(address collectionAddress) external whenNotPaused nonReentrant {
// Call the internal function that handles the reward withdrawal logic.
_withdrawAllRewards(collectionAddress);
}
/**
* @dev Internal function to handle the logic of withdrawing all rewards for a given collection address.
* This function iterates over all staked token IDs of the user and accumulates the rewards.
*
* @param collectionAddress The address of the NFT collection.
*/
function _withdrawAllRewards(address collectionAddress) internal {
// Input Validation: Ensure the collection address is not the zero address.
if (collectionAddress == address(0)) revert GalileoStakingErrors.InvalidAddress();
// Get the address of the user who is calling the function (msg.sender).
address recipient = _msgSender();
// Fetch the array of all staked NFTs for the user in the specified collection.
GalileoStakingStorage.StakePerCitizen[] memory stakedNFTs = state.stakedNFTs[recipient][collectionAddress];
// Ensure that the user has staked NFTs. If not, revert with a TokenNotStaked error.
if (stakedNFTs.length == 0) revert GalileoStakingErrors.TokenNotStaked();
// Initialize a variable to accumulate the total reward amount across all token IDs.
uint256 totalRewardAmount = 0;
// Get the current time
uint256 currentTime = block.timestamp;
// Update the reward per token stored value for the collection to the most current value.
state.rewardPerTokenStored[collectionAddress] = rewardPerToken(collectionAddress);
// Update the last update time for the collection to the current block timestamp.
state.lastUpdateTime[collectionAddress] = currentTime;
// Loop through each staked NFT token in the collection.
for (uint256 i = 0; i < stakedNFTs.length; i++) {
// Extract the token ID of the staked NFT.
uint256 tokenId = stakedNFTs[i].tokenId;
// Calculate the rewards once per token ID
uint256 rewards = calculateRewards(recipient, collectionAddress, tokenId);
// Reset the reward mapping for this token ID
state.rewards[recipient][collectionAddress][tokenId] = 0;
// Update the user's paid reward per token to reflect the latest value
state.userRewardPerTokenPaid[recipient][collectionAddress][tokenId] = state.rewardPerTokenStored[collectionAddress];
// Accumulate rewards for final transfer
totalRewardAmount += rewards;
}
// If the reward is zero, revert the transaction with an InvalidAmount error.
if (totalRewardAmount == 0) revert GalileoStakingErrors.InvalidTokensCount(totalRewardAmount);
// Retrieve the pool data for the specified collection (e.g., tax, etc.).
GalileoStakingStorage.PoolData memory pool = state.pools[collectionAddress];
// Calculate the rewards after applying any applicable tax from the pool's tax rate.
uint256 rewardsAfterTax = _calculateTax(collectionAddress, totalRewardAmount, pool.tax);
// Get available rewards for the collection
uint256 poolRewardTokenAmount = state.rewardPool[collectionAddress];
// Revert if reward pool has insufficient balance
if (poolRewardTokenAmount < totalRewardAmount) revert GalileoStakingErrors.InvalidAmountRewardPoolBalance();
// Deduct the full reward amount from the reward pool
state.rewardPool[collectionAddress] -= totalRewardAmount;
// If the reward after tax is greater than zero, transfer the reward tokens to the user.
IERC20(LEOX).safeTransfer(recipient, rewardsAfterTax);
// Emit an event to log the reward withdrawal for the user across all token IDs in the collection.
emit WithdrawAllRewards(collectionAddress, recipient, rewardsAfterTax, currentTime);
}
/**
* @dev Calculates the tax on a given reward amount and updates the state with the tax amount.
*
* @param collectionAddress The address of the collection for which the tax is being calculated.
* @param rewardAmount The total amount of rewards from which the tax will be deducted.
* @param taxPercent The percentage of the reward amount that will be taken as tax. This value should be represented as a percentage multiplied by 100 ether for precision.
* @return totalRewardTokens The amount of reward tokens remaining after the tax has been deducted.
*/
function _calculateTax(address collectionAddress, uint256 rewardAmount, uint256 taxPercent) internal returns (uint256) {
// Calculate the tax amount by multiplying the reward amount with the tax percent and dividing by 100 ether.
uint256 taxAmount = (rewardAmount * taxPercent) / 100 ether;
// Subtract the calculated tax amount from the reward amount to get the total reward tokens.
uint256 totalRewardTokens = rewardAmount - taxAmount;
// Update the state with the calculated tax amount for the given collection address.
state.tax[collectionAddress] += taxAmount;
// Return the total reward tokens after deducting the tax.
return totalRewardTokens;
}
/**
* @dev Unstakes a previously staked token and claims any associated rewards.
*
* This function performs the following operations:
* - Validates the collection address and token ID.
* - Calls the internal `_unstake` function to handle the actual unstaking process.
*
* @param collectionAddress The address of the NFT collection contract to which the staked token belongs.
* @param tokenId The unique identifier of the staked token to be unstaked.
*/
function unstake(address collectionAddress, uint256 tokenId) external whenNotPaused nonReentrant {
// Call the internal function to handle the unstaking process
_unstake(collectionAddress, tokenId);
}
/**
* @dev Internal function to unstake a token, withdraw rewards, and return staked assets.
*
* This function handles the complete process of unstaking a token, which includes:
* - Validating that the token is indeed staked.
* - Withdrawing rewards associated with the token.
* - Adjusting the pool's total points.
* - Updating and cleaning up the staker's information.
* - Burning the Soul Bound Token if applicable.
* - Transferring the token and staked LEOX tokens back to the recipient.
*
* @param collectionAddress The address of the collection contract from which the token is staked.
* @param tokenId The ID of the token that is being unstaked.
*/
function _unstake(address collectionAddress, uint256 tokenId) internal {
// Validate the collection address to ensure it is not a zero address
if (collectionAddress == address(0)) revert GalileoStakingErrors.InvalidAddress();
// Validate the token ID to ensure it is greater than zero
if (tokenId == 0) revert GalileoStakingErrors.InvalidTokenId();
// Get the address of the sender, who is the recipient of the unstaked token
address recipient = _msgSender();
// Retrieve the staker's position for the specified token within the collection
GalileoStakingStorage.StakePerCitizen memory stakeInfo = state.stakersPosition[recipient][collectionAddress][tokenId];
// Ensure that the token is currently staked by checking its ID
if (stakeInfo.tokenId != tokenId) revert GalileoStakingErrors.TokenNotStaked();
// Calculate the total lock period.
uint256 lockTimePeriod = stakeInfo.timelockStartTime + stakeInfo.timelockEndTime;
// Ensure that unstaking is not allowed until the lock period has passed.
if (block.timestamp < lockTimePeriod) revert GalileoStakingErrors.UnstakeBeforeLockPeriod(lockTimePeriod);
// This ensures that the reward calculations are up-to-date before executing the unstake function logic.
_updateReward(tokenId, collectionAddress, recipient);
// Withdraw any rewards associated with the staked token
_withdrawRewards(recipient, collectionAddress, tokenId);
// Calculate the points to be subtracted from the pool's total points
uint256 points = stakeInfo.points;
// Update the pool's total points by subtracting the points of the unstaked token
state.pools[collectionAddress].totalPoints -= points;
// Decrement the total staked amount for the collection
state.erc721Staked[collectionAddress] -= PRECISION;
// Remove the staker's position record for the token
delete state.stakersPosition[recipient][collectionAddress][tokenId];
delete state.lastRewardTime[recipient][collectionAddress][tokenId];
// Retrieve the index of the token in the staked NFTs array
uint256 index = state.stakedNFTIndex[recipient][collectionAddress][tokenId];
uint256 lastIndex = state.stakedNFTs[recipient][collectionAddress].length - 1;
if (index != lastIndex) {
// Swap the token to be removed with the last element in the array
GalileoStakingStorage.StakePerCitizen memory lastStakeInfo = state.stakedNFTs[recipient][collectionAddress][lastIndex];
state.stakedNFTs[recipient][collectionAddress][index] = lastStakeInfo;
state.stakedNFTIndex[recipient][collectionAddress][lastStakeInfo.tokenId] = index;
}
// Remove the last element from the staked NFTs array
state.stakedNFTs[recipient][collectionAddress].pop();
delete state.stakedNFTIndex[recipient][collectionAddress][tokenId];
// Burn the Soul Bound Token associated with the unstaked token
_burnSoulBoundToken(collectionAddress, tokenId);
// Transfer the unstaked token back to the recipient
IERC721(collectionAddress).transferFrom(address(this), recipient, tokenId);
// Transfer the staked LEOX tokens back to the recipient
IERC20(LEOX).safeTransfer(recipient, stakeInfo.stakedLEOX);
// Emit an event to notify that the token has been unstaked
emit UnstakeToken(collectionAddress, recipient, tokenId, points, stakeInfo.stakedLEOX);
}
/**
* @dev Emergency Unstake Tokens a previously staked token without claims any associated rewards.
*
* This function performs the following operations:
* - Validates the collection address and token ID.
* - Calls the internal `_emergencyUnstake` function to handle the actual unstaking process.
*
* @param collectionAddress The address of the NFT collection contract to which the staked token belongs.
* @param tokenId The unique identifier of the staked token to be unstaked.
*/
function emergencyUnstake(address collectionAddress, uint256 tokenId) external nonReentrant {
// Call the internal function to handle the unstaking process
_emergencyUnstake(collectionAddress, tokenId);
}
/**
* @dev Internal function to emergency unstake tokens, does not withdraw rewards, and return staked assets.
*
* This function handles the complete process of unstaking a token, which includes:
* - Validating that the token is indeed staked.
* - Adjusting the pool's total points.
* - Updating and cleaning up the staker's information.
* - Burning the Soul Bound Token if applicable.
* - Transferring the token and staked LEOX tokens back to the recipient.
*
* @param collectionAddress The address of the collection contract from which the token is staked.
* @param tokenId The ID of the token that is being unstaked.
*/
function _emergencyUnstake(address collectionAddress, uint256 tokenId) internal {
// Validate the collection address to ensure it is not a zero address
if (collectionAddress == address(0)) revert GalileoStakingErrors.InvalidAddress();
// Validate that the emergency is not declared yet
if (!state.isEmergencyDeclared[collectionAddress]) revert GalileoStakingErrors.EmergencyNotDeclared();
// Validate the token ID to ensure it is greater than zero
if (tokenId == 0) revert GalileoStakingErrors.InvalidTokenId();
// Get the address of the sender, who is the recipient of the unstaked token
address recipient = _msgSender();
// Retrieve the staker's position for the specified token within the collection
GalileoStakingStorage.StakePerCitizen memory stakeInfo = state.stakersPosition[recipient][collectionAddress][tokenId];
// Ensure that the token is currently staked by checking its ID
if (stakeInfo.tokenId != tokenId) revert GalileoStakingErrors.TokenNotStaked();
// This ensures that the reward calculations are up-to-date before executing the unstake function logic.
_updateReward(tokenId, collectionAddress, recipient);
// Calculate the points to be subtracted from the pool's total points
uint256 points = stakeInfo.points;
// Update the pool's total points by subtracting the points of the unstaked token
state.pools[collectionAddress].totalPoints -= points;
// Decrement the total staked amount for the collection
state.erc721Staked[collectionAddress] -= PRECISION;
// Remove the staker's position record for the token
delete state.stakersPosition[recipient][collectionAddress][tokenId];
delete state.lastRewardTime[recipient][collectionAddress][tokenId];
// Retrieve the index of the token in the staked NFTs array
uint256 index = state.stakedNFTIndex[recipient][collectionAddress][tokenId];
uint256 lastIndex = state.stakedNFTs[recipient][collectionAddress].length - 1;
// Set reward to zero
state.rewards[recipient][collectionAddress][tokenId] = 0;
if (index != lastIndex) {
// Swap the token to be removed with the last element in the array
GalileoStakingStorage.StakePerCitizen memory lastStakeInfo = state.stakedNFTs[recipient][collectionAddress][lastIndex];
state.stakedNFTs[recipient][collectionAddress][index] = lastStakeInfo;
state.stakedNFTIndex[recipient][collectionAddress][lastStakeInfo.tokenId] = index;
}
// Remove the last element from the staked NFTs array
state.stakedNFTs[recipient][collectionAddress].pop();
delete state.stakedNFTIndex[recipient][collectionAddress][tokenId];
// Burn the Soul Bound Token associated with the unstaked token
_burnSoulBoundToken(collectionAddress, tokenId);
// Transfer the unstaked token back to the recipient
IERC721(collectionAddress).transferFrom(address(this), recipient, tokenId);
// Transfer the staked LEOX tokens back to the recipient
IERC20(LEOX).safeTransfer(recipient, stakeInfo.stakedLEOX);
// Emit an event to notify that the token has been unstaked
emit EmergencyUnstakeToken(collectionAddress, recipient, tokenId, points, stakeInfo.stakedLEOX);
}
/**
* @dev Function to configure a collection with stake information for LEOX tokens.
*
* @param collectionAddress The address of the collection contract.
* @param soulboundToken The address of the Soul Bound Token.
* @param stakeInfo An array of StakeInfo structs containing information about LEOX tokens.
*/
function configureNewCollection(
address collectionAddress,
address soulboundToken,
uint256 tokenIdsCount,
GalileoStakingStorage.StakeInfoInput[] calldata stakeInfo
) external whenNotPaused onlyRole(ADMIN_ROLE) {
if (collectionAddress == address(0) || soulboundToken == address(0)) revert GalileoStakingErrors.InvalidAddress();
// Get the collection's name from the ERC721 contract
string memory collectionName = ERC721(collectionAddress).name();
// Check if the collection is new
bool isNewCollection = (state.soulboundTokenToCollection[collectionAddress] == address(0));
// If it's a new collection, associate the collection with the SBT contract
if (isNewCollection) {
state.soulboundTokenToCollection[collectionAddress] = soulboundToken;
}
// Loop through the provided staking details
for (uint256 i = 0; i < stakeInfo.length; i++) {
if (stakeInfo[i].maxLeox == 0 || stakeInfo[i].yieldTraitPoints == 0) revert GalileoStakingErrors.InvalidInput();
// Check that the maxLeox and yieldTraitPoints follow a consistent hierarchy
if (i > 0) {
// Ensure that maxLeox decreases (is in descending order) compared to the previous tier
if (stakeInfo[i].maxLeox > stakeInfo[i - 1].maxLeox) revert GalileoStakingErrors.InvalidLeoxHierarchy();
// Ensure that yieldTraitPoints do not decrease compared to the previous tier
if (stakeInfo[i].yieldTraitPoints > stakeInfo[i - 1].yieldTraitPoints) revert GalileoStakingErrors.InvalidTraitPointsHierarchy();
}
// Create a new stake info object
GalileoStakingStorage.StakeInfo memory newStakeInfo = GalileoStakingStorage.StakeInfo(
stakeInfo[i].maxLeox, // Maximum LEOX reward for this tier
stakeInfo[i].yieldTraitPoints, // Yield trait points associated with this tier
collectionName // Name of the collection (fetched earlier)
);
// Append the new staking info to the existing array for this collection
state.stakeTokensInfo[collectionAddress].push(newStakeInfo);
}
// set the total number of nebula tokens as the total supply
uint256 totalSupply = tokenIdsCount;
// Store the updated total supply of the collection (converted to 18 decimals)
state.erc721Supply[co...
// [truncated — 75187 bytes total]
IERC721.sol 135 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
ERC721.sol 456 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.20;
import {IERC721} from "./IERC721.sol";
import {IERC721Metadata} from "./extensions/IERC721Metadata.sol";
import {ERC721Utils} from "./utils/ERC721Utils.sol";
import {Context} from "../../utils/Context.sol";
import {Strings} from "../../utils/Strings.sol";
import {IERC165, ERC165} from "../../utils/introspection/ERC165.sol";
import {IERC721Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC-721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Errors {
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
mapping(uint256 tokenId => address) private _owners;
mapping(address owner => uint256) private _balances;
mapping(uint256 tokenId => address) private _tokenApprovals;
mapping(address owner => mapping(address operator => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual returns (uint256) {
if (owner == address(0)) {
revert ERC721InvalidOwner(address(0));
}
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual returns (address) {
return _requireOwned(tokenId);
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual returns (string memory) {
_requireOwned(tokenId);
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string.concat(baseURI, tokenId.toString()) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overridden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual {
_approve(to, tokenId, _msgSender());
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual returns (address) {
_requireOwned(tokenId);
return _getApproved(tokenId);
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(address from, address to, uint256 tokenId) public virtual {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
// Setting an "auth" arguments enables the `_isAuthorized` check which verifies that the token exists
// (from != 0). Therefore, it is not needed to verify that the return value is not 0 here.
address previousOwner = _update(to, tokenId, _msgSender());
if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public virtual {
transferFrom(from, to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
}
/**
* @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
*
* IMPORTANT: Any overrides to this function that add ownership of tokens not tracked by the
* core ERC-721 logic MUST be matched with the use of {_increaseBalance} to keep balances
* consistent with ownership. The invariant to preserve is that for any address `a` the value returned by
* `balanceOf(a)` must be equal to the number of tokens such that `_ownerOf(tokenId)` is `a`.
*/
function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
return _owners[tokenId];
}
/**
* @dev Returns the approved address for `tokenId`. Returns 0 if `tokenId` is not minted.
*/
function _getApproved(uint256 tokenId) internal view virtual returns (address) {
return _tokenApprovals[tokenId];
}
/**
* @dev Returns whether `spender` is allowed to manage `owner`'s tokens, or `tokenId` in
* particular (ignoring whether it is owned by `owner`).
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _isAuthorized(address owner, address spender, uint256 tokenId) internal view virtual returns (bool) {
return
spender != address(0) &&
(owner == spender || isApprovedForAll(owner, spender) || _getApproved(tokenId) == spender);
}
/**
* @dev Checks if `spender` can operate on `tokenId`, assuming the provided `owner` is the actual owner.
* Reverts if:
* - `spender` does not have approval from `owner` for `tokenId`.
* - `spender` does not have approval to manage all of `owner`'s assets.
*
* WARNING: This function assumes that `owner` is the actual owner of `tokenId` and does not verify this
* assumption.
*/
function _checkAuthorized(address owner, address spender, uint256 tokenId) internal view virtual {
if (!_isAuthorized(owner, spender, tokenId)) {
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else {
revert ERC721InsufficientApproval(spender, tokenId);
}
}
}
/**
* @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
*
* NOTE: the value is limited to type(uint128).max. This protect against _balance overflow. It is unrealistic that
* a uint256 would ever overflow from increments when these increments are bounded to uint128 values.
*
* WARNING: Increasing an account's balance using this function tends to be paired with an override of the
* {_ownerOf} function to resolve the ownership of the corresponding tokens so that balances and ownership
* remain consistent with one another.
*/
function _increaseBalance(address account, uint128 value) internal virtual {
unchecked {
_balances[account] += value;
}
}
/**
* @dev Transfers `tokenId` from its current owner to `to`, or alternatively mints (or burns) if the current owner
* (or `to`) is the zero address. Returns the owner of the `tokenId` before the update.
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that
* `auth` is either the owner of the token, or approved to operate on the token (by the owner).
*
* Emits a {Transfer} event.
*
* NOTE: If overriding this function in a way that tracks balances, see also {_increaseBalance}.
*/
function _update(address to, uint256 tokenId, address auth) internal virtual returns (address) {
address from = _ownerOf(tokenId);
// Perform (optional) operator check
if (auth != address(0)) {
_checkAuthorized(from, auth, tokenId);
}
// Execute the update
if (from != address(0)) {
// Clear approval. No need to re-authorize or emit the Approval event
_approve(address(0), tokenId, address(0), false);
unchecked {
_balances[from] -= 1;
}
}
if (to != address(0)) {
unchecked {
_balances[to] += 1;
}
}
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
return from;
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner != address(0)) {
revert ERC721InvalidSender(address(0));
}
}
/**
* @dev Mints `tokenId`, transfers it to `to` and checks for `to` acceptance.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(address to, uint256 tokenId, bytes memory data) internal virtual {
_mint(to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), address(0), to, tokenId, data);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
* This is an internal function that does not check if the sender is authorized to operate on the token.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal {
address previousOwner = _update(address(0), tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(address from, address to, uint256 tokenId) internal {
if (to == address(0)) {
revert ERC721InvalidReceiver(address(0));
}
address previousOwner = _update(to, tokenId, address(0));
if (previousOwner == address(0)) {
revert ERC721NonexistentToken(tokenId);
} else if (previousOwner != from) {
revert ERC721IncorrectOwner(from, tokenId, previousOwner);
}
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking that contract recipients
* are aware of the ERC-721 standard to prevent tokens from being forever locked.
*
* `data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is like {safeTransferFrom} in the sense that it invokes
* {IERC721Receiver-onERC721Received} on the receiver, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `tokenId` token must exist and be owned by `from`.
* - `to` cannot be the zero address.
* - `from` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(address from, address to, uint256 tokenId) internal {
_safeTransfer(from, to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeTransfer-address-address-uint256-}[`_safeTransfer`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal virtual {
_transfer(from, to, tokenId);
ERC721Utils.checkOnERC721Received(_msgSender(), from, to, tokenId, data);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* The `auth` argument is optional. If the value passed is non 0, then this function will check that `auth` is
* either the owner of the token, or approved to operate on all tokens held by this owner.
*
* Emits an {Approval} event.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address to, uint256 tokenId, address auth) internal {
_approve(to, tokenId, auth, true);
}
/**
* @dev Variant of `_approve` with an optional flag to enable or disable the {Approval} event. The event is not
* emitted in the context of transfers.
*/
function _approve(address to, uint256 tokenId, address auth, bool emitEvent) internal virtual {
// Avoid reading the owner unless necessary
if (emitEvent || auth != address(0)) {
address owner = _requireOwned(tokenId);
// We do not use _isAuthorized because single-token approvals should not be able to call approve
if (auth != address(0) && owner != auth && !isApprovedForAll(owner, auth)) {
revert ERC721InvalidApprover(auth);
}
if (emitEvent) {
emit Approval(owner, to, tokenId);
}
}
_tokenApprovals[tokenId] = to;
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Requirements:
* - operator can't be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function _setApprovalForAll(address owner, address operator, bool approved) internal virtual {
if (operator == address(0)) {
revert ERC721InvalidOperator(operator);
}
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Reverts if the `tokenId` doesn't have a current owner (it hasn't been minted, or it has been burned).
* Returns the owner.
*
* Overrides to ownership logic should be done to {_ownerOf}.
*/
function _requireOwned(uint256 tokenId) internal view returns (address) {
address owner = _ownerOf(tokenId);
if (owner == address(0)) {
revert ERC721NonexistentToken(tokenId);
}
return owner;
}
}
IERC721Receiver.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 value) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 value) external returns (bool);
}
SafeERC20.sol 198 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
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.1.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;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {IERC-5267}.
*/
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);
}
}
AccessControl.sol 209 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```solidity
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```solidity
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it. We recommend using {AccessControlDefaultAdminRules}
* to enforce additional security measures for this role.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
mapping(bytes32 role => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with an {AccessControlUnauthorizedAccount} error including the required role.
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual returns (bool) {
return _roles[role].hasRole[account];
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
* is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
* is missing `role`.
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert AccessControlUnauthorizedAccount(account, role);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) public virtual {
if (callerConfirmation != _msgSender()) {
revert AccessControlBadConfirmation();
}
_revokeRole(role, callerConfirmation);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
if (!hasRole(role, account)) {
_roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` to `account` and returns a boolean indicating if `role` was revoked.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
if (hasRole(role, account)) {
_roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
ReentrancyGuard.sol 87 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
Pausable.sol 119 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
IGalileoSoulBoundToken.sol 20 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
interface IGALILEOSOULBOUNDTOKEN {
/**
* @dev Issues a new Soulbound token to the specified address.
* @param to The address of the recipient to whom the Soulbound token will be issued.
*
* Soulbound tokens are typically non-transferable and tied to the recipient forever.
*/
function issue(address to, uint256 tokenId) external;
/**
* @dev Burns the specified Soulbound token, removing it from existence.
* @param _tokenId The unique identifier of the Soulbound token to be burned.
*
* Once a token is burned, it is permanently removed from the contract and can no longer be used.
*/
function burn(uint256 _tokenId) external;
}
GalileoStakingStorage.sol 135 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
library GalileoStakingStorage {
// Struct to store details of a single staked NFT by a citizen
struct StakePerCitizen {
// Address of the NFT collection
address collectionAddress;
// Token ID of the staked NFT
uint256 tokenId;
// Citizen ID associated with the staked NFT
uint256 citizen;
// Start time of the staking timelock
uint256 timelockStartTime;
// End time of the staking timelock
uint256 timelockEndTime;
// Points earned from staking
uint256 points;
// Amount of LEOX tokens staked
uint256 stakedLEOX;
}
// Struct to store staking information for a collection
struct StakeInfo {
// Maximum LEOX tokens staked in this citizen
uint256 maxLeox;
// Points earned by staking in this citizen
uint256 yieldTraitPoints;
// Name of the NFT collection
string collectionName;
}
struct StakeTokens {
// Address of the NFT collection
address collectionAddress;
// Token ID of the staked NFT
uint256 tokenId;
//Citizen ID associated with the staked NFT
uint256 citizen;
// The timestamp representing the end time of the staking period.
uint256 timelockEndTime;
// The amount of LEOX tokens staked along with the NFT.
uint256 stakedLeox;
// A cryptographic signature to verify the validity of the staked data, ensuring security and authenticity.
bytes signature;
}
// Input struct for providing stake information
struct StakeInfoInput {
// Maximum LEOX tokens staked in this citizen
uint256 maxLeox;
// Points earned by staking in this citizen
uint256 yieldTraitPoints;
}
// Struct to store multiplier data for staking boost calculations
struct Multiplier {
// Duration of staking
uint256 stakingTime;
// Boost percentage for staking
uint256 stakingBoost;
}
// Struct to define a reward window in the staking contract
struct RewardWindow {
// The reward rate applicable during this window (e.g., tokens per second)
uint256 rewardRate;
// The start time of this reward window (in seconds since epoch)
uint256 startTime;
// The end time of this reward window (in seconds since epoch)
uint256 endTime;
}
// Struct to store data of a staking pool
struct PoolData {
// Total points accumulated in the pool
uint256 totalPoints;
// Tax rate for staking
uint256 tax;
// Count of rewards in the pool
uint256 rewardCount;
// Array of reward windows
RewardWindow[] rewardWindows;
}
// Input struct for configuring a staking pool
struct PoolConfigurationInput {
// Address of the NFT collection
address collectionAddress;
// Tax rate for staking
uint256 tax;
// Array of reward windows
RewardWindow[] rewardWindows;
}
// Main state struct to store all staking-related data
struct State {
// Mapping from collection address to pool data
mapping(address => PoolData) pools;
// Mapping from store the tax amount against collection address
mapping(address => uint256) tax;
// Mapping to store staking positions
mapping(address => mapping(address => mapping(uint256 => StakePerCitizen))) stakersPosition;
// Mapping to store staked NFTs by user
mapping(address => mapping(address => StakePerCitizen[])) stakedNFTs;
// Mapping to store index of staked NFTs
mapping(address => mapping(address => mapping(uint256 => uint256))) stakedNFTIndex;
// Mapping to store LEOX staking info and token IDs by citizen
mapping(address => StakeInfo[]) stakeTokensInfo;
// Mapping to store staking boost multipliers by collection
mapping(address => Multiplier[]) stakingBoostPerCollection;
// Mapping to associate soulbound tokens to collections
mapping(address => address) soulboundTokenToCollection;
// Mapping to store ERC721 token supply
mapping(address => uint256) erc721Supply;
// Mapping to store last update time of collections
mapping(address => uint256) lastUpdateTime;
// Mapping to store reward per token stored
mapping(address => uint256) rewardPerTokenStored;
// Mapping to store reward per token stored
mapping(address => uint256) rewardPerTokenStoredNewRewardWindow;
// Mapping to store rewards paid per user per token
mapping(address => mapping(address => mapping(uint256 => uint256))) userRewardPerTokenPaid;
// Mapping to store rewards by user and token
mapping(address => mapping(address => mapping(uint256 => uint256))) rewards;
// Mapping to store the number of staked ERC721 tokens
mapping(address => uint256) erc721Staked;
// Mapping to store the last reward time for users
mapping(address => mapping(address => mapping(uint256 => uint256))) lastRewardTime;
// Tracks total rewards per collection
mapping(address => uint256) rewardPool;
// Mapping to store emergency status against collection
mapping(address => bool) isEmergencyDeclared;
}
}
GalileoStakingErrors.sol 89 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
library GalileoStakingErrors {
// ═══════════════════════ ERORRS ════════════════════════
// Error indicating an invalid address for a collection
error InvalidAddress();
// Error indicating an input is invalid
error InvalidInput();
// Error indicating an INCREMENT is invalid
error InvalidIncrement();
// Error indicating that a collection has not been initialized
error CollectionUninitialized();
// Error indicating that a pool associated with a collection has not been initialized
error PoolUninitialized(address collectionAddress);
// Error indicating that a pool associated with a collection has been already initialized
error PoolAlreadyInitialized();
// Error indicating that multiple reward windows detected at pool config input
error MultipleRewardWindowsNotAllowed();
// Error indicating an invalid count of tokens
error InvalidTokensCount(uint256 maxLeox);
// Error indicating an invalid time
error InvalidTime();
// Error indicating that endtime of reward window is invalid
error InvalidEndTime();
// Error indicating that stake time is not completed yet
error UnstakeBeforeLockPeriod(uint256 lockPeriodEnd);
// Error indicating an invalid reward rate
error InvalidRewardRate();
// Error indicating an invalid token ID
error InvalidTokenId();
// Error indicating that a token is already staked
error TokenAlreadyStaked();
// Error indicating that the pool doesn't have reward amount
error InvalidAmountRewardPoolBalance();
// Error indicating that the input amount is zero
error InvalidAmount(uint256 amount);
error Insufficient();
// Error indicating that the owner is incorrect
error IncorrectOwner();
// Error indicating that the staker has not enough LEOX tokens
error InsufficientLEOXTokens(address staker);
// Error indicating that a token ID is not staked
error TokenNotStaked();
// Error indicating that the citizen index is invalid
error InvalidCitizenIndex();
// Error indicating that signature is invalid
error InvalidSignature();
// Error indicating that tax input value is more than
error InvalidTaxRate();
// Error indicating that LEOX hierarchy is invalid in configure collection
error InvalidLeoxHierarchy();
// Error indicating that Yield Trait Points hierarchy is invalid in configure collection
error InvalidTraitPointsHierarchy();
// Error indicating that an emergency is not declared
error EmergencyNotDeclared();
// Error indicating that an emergency is declared
error EmergencyDeclared();
// Error indicating that the emergency state is the same as the current state
error StateAlreadyDeclared();
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
IERC721Metadata.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
ERC721Utils.sol 50 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/utils/ERC721Utils.sol)
pragma solidity ^0.8.20;
import {IERC721Receiver} from "../IERC721Receiver.sol";
import {IERC721Errors} from "../../../interfaces/draft-IERC6093.sol";
/**
* @dev Library that provide common ERC-721 utility functions.
*
* See https://eips.ethereum.org/EIPS/eip-721[ERC-721].
*
* _Available since v5.1._
*/
library ERC721Utils {
/**
* @dev Performs an acceptance check for the provided `operator` by calling {IERC721-onERC721Received}
* 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 {IERC721Receiver-onERC721Received} and return the acceptance magic value to accept
* the transfer.
*/
function checkOnERC721Received(
address operator,
address from,
address to,
uint256 tokenId,
bytes memory data
) internal {
if (to.code.length > 0) {
try IERC721Receiver(to).onERC721Received(operator, from, tokenId, data) returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
// Token rejected
revert IERC721Errors.ERC721InvalidReceiver(to);
}
} catch (bytes memory reason) {
if (reason.length == 0) {
// non-IERC721Receiver implementer
revert IERC721Errors.ERC721InvalidReceiver(to);
} else {
assembly ("memory-safe") {
revert(add(32, reason), mload(reason))
}
}
}
}
}
}
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;
}
}
Strings.sol 441 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.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;
/**
* @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(buffer, add(32, 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} 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} 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} 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} 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} 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 guaratees 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} 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} 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} 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 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(buffer, add(0x20, offset)))
}
}
}
ERC165.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
draft-IERC6093.sol 161 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
MessageHashUtils.sol 84 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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://eth.wiki/json-rpc/API#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://eth.wiki/json-rpc/API#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 Returns the keccak256 digest of an EIP-712 typed data (ERC-191 version `0x01`).
*
* The digest is calculated from a `domainSeparator` and a `structHash`, by prefixing them with
* `\x19\x01` and hashing the result. It corresponds to the hash signed by the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] JSON-RPC method as part of EIP-712.
*
* See {ECDSA-recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 digest) {
assembly ("memory-safe") {
let ptr := mload(0x40)
mstore(ptr, hex"19_01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
digest := keccak256(ptr, 0x42)
}
}
}
ShortStrings.sol 122 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.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 {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using
* {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
IERC5267.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.20;
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
);
}
IAccessControl.sol 98 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (access/IAccessControl.sol)
pragma solidity ^0.8.20;
/**
* @dev External interface of AccessControl declared to support ERC-165 detection.
*/
interface IAccessControl {
/**
* @dev The `account` is missing a role.
*/
error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);
/**
* @dev The caller of a function is not the expected one.
*
* NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
*/
error AccessControlBadConfirmation();
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call. This account bears the admin role (for the granted role).
* Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
}
Math.sol 685 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
SafeCast.sol 1162 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
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);
}
}
}
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../utils/introspection/IERC165.sol";
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
}
}
}
Panic.sol 57 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
Read Contract
ADMIN_ROLE 0x75b238fc → bytes32
DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
LEOX 0x637212d0 → address
VALIDATOR_ROLE 0xc49baebe → bytes32
calculatePoints 0x7e989e54 → uint256
calculateRewards 0x8b4d7577 → uint256
calculateRewardsAllRewards 0xbbad6464 → uint256
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
getAccumulatedTax 0x67cdb47f → uint256
getCollectionEmergencyStatus 0xe5111da7 → bool
getMultipliers 0x04082ff4 → tuple[]
getPoolConfiguration 0x6f44bb69 → uint256, uint256, uint256, tuple[]
getRewardPoolBalance 0x85e710b0 → uint256
getRoleAdmin 0x248a9ca3 → bytes32
getStakedInfoPagination 0x59b4c4b4 → tuple[], uint256, uint256
getStakedPercentage 0x2328c402 → uint256
getStakersPosition 0x269149b4 → tuple
getYieldTraitPoints 0xc50daecc → tuple
hasRole 0x91d14854 → bool
paused 0x5c975abb → bool
rewardPerToken 0xf1229777 → uint256
supportsInterface 0x01ffc9a7 → bool
Write Contract 20 functions
These functions modify contract state and require a wallet transaction to execute.
configureNewCollection 0x6c356ca8
address collectionAddress
address soulboundToken
uint256 tokenIdsCount
tuple[] stakeInfo
configurePool 0x99bc2edb
tuple[] poolConfigurationsInput
declareEmergency 0x8d9a6ed2
address collectionAddress
depositRewards 0x97ad1cce
address collectionAddress
uint256 leoxAmount
emergencyUnstake 0x4268121e
address collectionAddress
uint256 tokenId
grantRole 0x2f2ff15d
bytes32 role
address account
liftEmergency 0x94fc0671
address collectionAddress
uint256 rewardRate
onERC721Received 0x150b7a02
address operator
address from
uint256 tokenId
bytes data
returns: bytes4
pause 0x8456cb59
No parameters
renounceRole 0x36568abe
bytes32 role
address callerConfirmation
revokeRole 0xd547741f
bytes32 role
address account
setMultipliers 0xb6bdccf3
address collectionAddress
tuple[] multipliers
stake 0x0d86c714
tuple stakeTokens
stakeLeoxTokens 0x2f9904e0
address collectionAddress
uint256 tokenId
uint256 stakeMoreLeox
unpause 0x3f4ba83a
No parameters
unstake 0xc2a672e0
address collectionAddress
uint256 tokenId
updateEmissionRate 0xb6cc5243
address collectionAddress
uint256 rewardRate
uint256 endTime
updateTax 0x3899ff14
address collectionAddress
uint256 newTaxPercent
withdrawAllRewards 0xc55897bf
address collectionAddress
withdrawTax 0x4c75b707
address collectionAddress
Recent Transactions
No transactions found for this address