Address Contract Verified
Address
0xDd3EeA0D0ADc2a21a5ffF235cf376Af4df931237
Balance
0 ETH
Nonce
1
Code Size
20597 bytes
Creator
0xf01410D2...5c78 at tx 0x15245301...d49a26
Indexed Transactions
0
Contract Bytecode
20597 bytes
0x60806040526004361015610023575b3615610018575f80fd5b61002134613872565b005b5f3560e01c8063017baf801461314857806301ffc9a7146130f25780630900804d146130c8578063091490201461309957806309d2e7661461307e5780630f3ba0231461305757806310e51e1414612a6257806311f1fc991461298c578063141edd581461296257806315aaea1714612947578063183dd4031461292a5780631c39d42b1461290e5780631c9eeebf146128ee57806323c7e09c146128c657806323fa495a146128a1578063248a9ca31461286a578063258ae5821461280057806325c33e13146128055780632749deb1146128005780632e6b86cb146127e35780632f2ff15d14612799578063313dab201461277c57806336568abe1461273857806338635dd6146127175780633f4ba83a1461269857806340e58ee5146124c5578063474bf3b51461248d5780634b359e04146124235780634c2adcb0146123f95780634f1ef2861461221757806352d1902d146121b1578063564ef91d1461218a57806358ce98e7146121555780635c975abb146121275780635f5581e4146120b357806361e98db814612096578063622edc201461207957806366a78e6c1461205c578063688b308b14611ff75780636bd8035314611f195780636dbf165514611e7957806375829def14611e12578063778822e314611da4578063787c3b3814611cd5578063787dce3d14611cb0578063798af41f14611c865780637df325e114611be05780638456cb5914611b6e57806384b0196e14611a4f57806384d76f5e14611a285780638a5a456d146119d45780638b2d141d146119aa57806391d1485414611955578063920a78a81461192b57806392826eda1461121c578063a217fddf14611202578063a41c9d5a14611195578063ab664c4814611178578063ad3cb1cc1461112d578063aec2259f146110f0578063af156d4b146110d3578063b0e21e8a146110b6578063b1a9f8091461108f578063b2118a8d14610fe9578063b28c8ac314610fa1578063b2fb7c2d14610f84578063b5ab1c5d14610f68578063b6a1cb2b14610f03578063b84c139214610e7f578063ba16d60014610e62578063c0a3f32914610e38578063ca29195c14610e1b578063cdf92c2714610dec578063d371f92414610d62578063d4cbb9d214610d45578063d547741f14610cf4578063d9eb594714610cd7578063db2e21bc14610b49578063e9b6302c14610ad5578063eb97d8d114610a58578063f57f678414610a3d578063f63f28c11461041b578063fb1c11f3146103f15763fb74f6a70361000e57346103ed5760203660031901126103ed576100216103df613223565b6103e833613cb6565b61425c565b5f80fd5b346103ed5760203660031901126103ed5761002161040d613223565b61041633613cb6565b614160565b60c03660031901126103ed5761042f613223565b6104376131f7565b906044359060643560028110156103ed576084356001600160401b0381116103ed57610467903690600401613436565b9160a4356001600160401b0381116103ed576104879036906004016133c5565b61048f61384b565b3415610a2f5760175480341115610a20576104b5906104b0601454346136c0565b613c7a565b916010548310610a11576011548311610a02576001600160a01b03169586156109f3576001600160a01b03169586156109e457865f52600a60205260ff60405f205416156109d55760018551106105b85760068551116105b857600e54600f545f98959790959194895b88518b101561061a576105328b8a6137aa565b51602081019081511561060b576040019081511561060b57805182511061060b578890511061060b578890511161060b5761056d8b8a6137aa565b518051156105b8576127109051116105b85788515f1981019081116105f7578b10806105c7575b6105b8576105b06001916105a88d8c6137aa565b5151906136b3565b9a019961051f565b6322e55e0960e11b5f5260045ffd5b5060406105d48c8b6137aa565b51015160018c01808d116105f7576105ee6020918c6137aa565b51015110610594565b634e487b7160e01b5f52601160045260245ffd5b6314414f4160e11b5f5260045ffd5b8896506127108a91036105b85761063f610638888461064894613809565b9687614b6e565b90929192614ba8565b6001600160a01b03168381036109c6575f52600a60205260ff60405f205416156109b75760025494845f52600b60205260405f208054905f1982146105f7576001820190556040519061069a8261331c565b87825260208201908782526040830190878252606084018781526080850191825260a085019287845260c086019c8d5260e0860194878652600254600160401b811015610990578060016106f192016002556135e3565b9790976109a457518755516001870180546001600160a01b03199081166001600160a01b03938416179091559151600288018054909316911617905551600385015551600484015551600583015597518051600683019991600160401b8211610990578a54828c55808310610942575b50602001995f5260205f20995f905b828210610917578351600786015560208b8b818c8c8c8c6107918234613c7a565b855f526016895260405f2055845f52601688526107b460405f20546015546136b3565b6015556017548015158080610903575b156108e35750505f80808060018060a01b0360015416601754905af16107e8613c87565b50156108cd575b6107fb826005546136b3565b60055561080a600654426136b3565b855f526007895260405f2055610822600854426136b3565b855f526009895260405f205561084861084361083d876135e3565b50614363565b61443b565b90815f52600389528560405f20556004610861876135e3565b50015492865f5260168a5260405f205493601754956040519788528b88015260408701526060860152608085015260a084015260c083015260e08201527fed507b948c31c0910cd35b724e74ad217905d0e6d754ae43a18f75d76776bacf6101003392a4604051908152f35b6108db6017546004546136b3565b6004556107ef565b6108ee575b506107ef565b6108fa906004546136b3565b600455886108e8565b506001546001600160a01b031615156107c4565b60036020828e60026040600196518051845585810151888501550151910155019c019101909a610770565b806003029060038204036105f757826003026003810484036105f7578c5f5260205f2091820191015b8181106109785750610761565b805f600392555f60018201555f60028201550161096b565b634e487b7160e01b5f52604160045260245ffd5b634e487b7160e01b5f525f60045260245ffd5b63ee2dbfcf60e01b5f5260045ffd5b633b13dbb360e21b5f5260045ffd5b636076bf8f60e11b5f5260045ffd5b631ee0273360e31b5f5260045ffd5b630ce16b5160e01b5f5260045ffd5b63251767c560e21b5f5260045ffd5b634d16581960e11b5f5260045ffd5b6337dbf6eb60e11b5f5260045ffd5b62df677960e51b5f5260045ffd5b346103ed575f3660031901126103ed576020604051601e8152f35b346103ed5760203660031901126103ed57610a71613223565b610a7a33613d03565b6001600160a01b038116908115610ac657610a9e90610a98336141de565b50613b31565b50337f80acf2f79a4dfe0caf6e77f8ad8c8468f2e6be9ee862d901edd70cd5300e7feb5f80a3005b63296d5bdd60e21b5f5260045ffd5b346103ed5760203660031901126103ed57600435610af233613cb6565b8015610b3a576011548111610b3a5760407fd3fc3f1a25a1a4e1e35a99f8a06f6bb9e67dce0b35ae9e24b1cbf0a33336abe891601054908060105582519182526020820152a1005b637b2d293f60e01b5f5260045ffd5b346103ed575f3660031901126103ed57610b61613c42565b610b6a33613cb6565b5f6004819055600581905560155560015447906001600160a01b03168015610cc8578115610cb957814710610caa575f80808085855af1610ba9613c87565b5015610c9b57604080516001600160a01b03929092168252602082018390527fb3579861130e4da8bb7b87c54d2d139937f23bcd6e4ebed9e75d0f78ab1cc11891a1610bf361384b565b600160ff195f516020614f805f395f51905f525416175f516020614f805f395f51905f52557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1600154604080519283526001600160a01b03909116602083015233917f3ab9db27a4cdd8c603a752b62d5fbd93b4b3509fe2596708e9688e42bbac357691819081015b0390a260015f516020614fc05f395f51905f5255005b6312171d8360e31b5f5260045ffd5b631e9acf1760e31b5f5260045ffd5b63162908e360e11b5f5260045ffd5b63e6c4247b60e01b5f5260045ffd5b346103ed575f3660031901126103ed576020601754604051908152f35b346103ed5760403660031901126103ed57610021600435610d136131f7565b90610d40610d39825f525f516020614f405f395f51905f52602052600160405f20015490565b3390613e23565b6142da565b346103ed575f3660031901126103ed576020601354604051908152f35b346103ed5760203660031901126103ed57610d7b613223565b610d8433613cb6565b6001600160a01b03165f818152600a602052604090205460ff1615610ddd57805f52600a60205260405f2060ff1981541690557f38b7b3681542fcc6180d9061bd856f02ced2138f14eba25334973c6f881003f45f80a2005b632f041fb560e01b5f5260045ffd5b346103ed5760203660031901126103ed576004355f52600d602052602060ff60405f2054166040519015158152f35b346103ed575f3660031901126103ed576020600854604051908152f35b346103ed5760203660031901126103ed57610021610e54613223565b610e5d33613cb6565b613a31565b346103ed575f3660031901126103ed576020600e54604051908152f35b346103ed5760203660031901126103ed576004356002548110156103ed57610ea860e0916135e3565b5080549060018060a01b036001820154169060018060a01b0360028201541660038201546004830154916007600585015494015494604051968752602087015260408601526060850152608084015260a083015260c0820152f35b346103ed5760203660031901126103ed57600435610f2033613cb6565b801561060b57600f54811161060b5760407fb7f03b24f260f6916e8db92db6297575c4bb14396e4e161593501102a808815991600e549080600e5582519182526020820152a1005b346103ed575f3660031901126103ed5760206040516127108152f35b346103ed575f3660031901126103ed576020601054604051908152f35b346103ed57610021610fd3610fdb610fe3610fbb366132aa565b9693610fcc98929895919533613d63565b3691613613565b953691613613565b923691613667565b91614833565b346103ed57610021610ffa36613552565b919061100533613d63565b6040928351916110158584613353565b60018352601f19850193843660208601378551946110338787613353565b600186528036602088013761104a87519788613353565b6001875236602088013761105d8461379d565b6001600160a01b0390911690526110738461379d565b6001600160a01b0390911690526110898461379d565b52613eeb565b346103ed575f3660031901126103ed5760206040515f5160206150205f395f51905f528152f35b346103ed575f3660031901126103ed576020601454604051908152f35b346103ed575f3660031901126103ed576020600554604051908152f35b346103ed5760203660031901126103ed576001600160a01b03611111613223565b165f52600a602052602060ff60405f2054166040519015158152f35b346103ed575f3660031901126103ed5761117460405161114e604082613353565b60058152640352e302e360dc1b602082015260405191829160208352602083019061358c565b0390f35b346103ed575f3660031901126103ed576020600254604051908152f35b346103ed5760203660031901126103ed576004356111b233613cb6565b601e81106111f35760407f85cb82ecd716544f28be67fbc7423b62151044de9e312eb5bafa1c1fbaf45ab591600854908060085582519182526020820152a1005b636c9b6cf160e01b5f5260045ffd5b346103ed575f3660031901126103ed5760206040515f8152f35b6101403660031901126103ed576004356112346131f7565b6044356001600160401b0381116103ed5761125390369060040161324d565b919061125d61320d565b9160e4356001600160401b0381116103ed5761127d90369060040161324d565b939091610104356001600160401b0381116103ed576112a090369060040161324d565b96909560026101243510156103ed576112b761384b565b5f60e06040516112c68161331c565b8281528260208201528260408201528260608201528260808201528260a0820152606060c0820152015260025489101561191c57611303896135e3565b50600201546001600160a01b0316330361190d576001600160a01b038316156118fe57346118f0575b600454606435116118e157885f52600c60205260ff60405f2054166118d257885f52600d60205260ff60405f2054166118c35760643560c435116118b45761137661083d8a6135e3565b9461139661063f61138836858561338f565b6113918961443b565b614b6e565b60408701516001600160a01b03918216911681036118a5575f52600a60205260ff60405f20541615611896578160209160018060a01b035f5416906044604051809681958294638d9dca6f60e01b8452886004850152816024850152848401375f828201840152601f01601f191681010301915afa90811561188b575f9161184a575b5061063f63ffffffff61146b9216986114656114348861443b565b9961145d610124358c8c8b60c4359261145260a435938d369161338f565b908d60643591613720565b92369161338f565b90614b6e565b60408501516001600160a01b039182169116810361183b575f52600a60205260ff60405f2054161561182c5760c0840151915f604080516114ab81613338565b82815282602082015201526114ca6114c3848a614c08565b80946137aa565b51916020830180516064351061181d57604084019081516064351161180e575160c435106117ff575160c435116117f057611508610124358b614b38565b9661156861154260a08901518d5f52600c60205260405f20600160ff1982541617905561153781600554613c7a565b6005556004546136b3565b806004558c5f52601660205260405f20549061156082601554613c7a565b6015556136b3565b60045561157488613702565b8761171f5791815f938493604051928392833781018481520391606435905af161159c613c87565b501561164c576115b0606435600454613c7a565b600455516020938401516040805198895294880191909152928601525f60608601526001600160a01b03908116608086015260a43560a086015260643560c08601521660e084015261160461012435613702565b6101243561010084015261161781613702565b6101208301526101408201527f79aca79eb9427e50f574c0dbfd1dab0d52d04e57f203f46c1331b92c29c55dcf6101603392a3005b6116d8925093839460207f79aca79eb9427e50f574c0dbfd1dab0d52d04e57f203f46c1331b92c29c55dcf9793989501955f80808060643560018060a01b038c51165af1611698613c87565b50156116dd57506116ad606435600454613c7a565b6004555b51945160405133989096879661012435936001600160a01b03169260643592909189614c4a565b0390a3005b5160018060a01b03875116907fae90ca74b32df77c39af0a6d193aa4100a88d287a675031ae588bafdc9e43dee604080516064358152876020820152a36116b1565b5050506116d8925093839460207f79aca79eb9427e50f574c0dbfd1dab0d52d04e57f203f46c1331b92c29c55dcf9793989501955f80808060c43560018060a01b038c51165af161176e613c87565b50156117ae575061178360c435600454613c7a565b6004555b51945160405133989096879661012435936001600160a01b03169260c43592909189614c4a565b5160018060a01b03875116907fae90ca74b32df77c39af0a6d193aa4100a88d287a675031ae588bafdc9e43dee6040805160c4358152876020820152a3611787565b636017cb3d60e01b5f5260045ffd5b636a34f57960e01b5f5260045ffd5b6331794b0760e01b5f5260045ffd5b63558366e960e01b5f5260045ffd5b6360a1990160e11b5f5260045ffd5b631b37f47d60e31b5f5260045ffd5b90506020813d602011611883575b8161186560209383613353565b810103126103ed575163ffffffff811681036103ed5761063f611419565b3d9150611858565b6040513d5f823e3d90fd5b6374948acb60e11b5f5260045ffd5b631a3f2cf560e31b5f5260045ffd5b634240a3f360e11b5f5260045ffd5b6304ccf4d560e21b5f5260045ffd5b634a4117f960e01b5f5260045ffd5b631c7b597b60e11b5f5260045ffd5b6118f934613872565b61132c565b6359aaae1f60e11b5f5260045ffd5b6312767c6360e11b5f5260045ffd5b633e1d0a9160e11b5f5260045ffd5b346103ed5760203660031901126103ed576004355f526003602052602060405f2054604051908152f35b346103ed5760403660031901126103ed5761196e6131f7565b6004355f525f516020614f405f395f51905f5260205260405f209060018060a01b03165f52602052602060ff60405f2054166040519015158152f35b346103ed5760203660031901126103ed576004355f526009602052602060405f2054604051908152f35b346103ed5760603660031901126103ed5760043560028110156103ed576044356001600160401b0381116103ed57602091611a16611a20923690600401613436565b9060243590613809565b604051908152f35b346103ed575f3660031901126103ed5760206040515f516020614e605f395f51905f528152f35b346103ed575f3660031901126103ed577fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100541580611b45575b15611b0857611ada611a98614991565b611174611aa3614a60565b611ae860405191611ab5602084613353565b5f83525f368137604051958695600f60f81b875260e0602088015260e087019061358c565b90858203604087015261358c565b904660608501523060808501525f60a085015283820360c08501526135b0565b60405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b6044820152606490fd5b507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d1015415611a88565b346103ed575f3660031901126103ed57611b8733613cb6565b611b8f61384b565b600160ff195f516020614f805f395f51905f525416175f516020614f805f395f51905f52557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a1005b346103ed57610021611bf136613552565b9190611bfc33613d63565b604092835191611c0c8584613353565b60018352601f1985019384366020860137855194611c2a8787613353565b6001865280366020880137611c4187519788613353565b60018752366020880137611c548461379d565b6001600160a01b039091169052611c6a8461379d565b6001600160a01b039091169052611c808461379d565b52614833565b346103ed5760203660031901126103ed576004355f526016602052602060405f2054604051908152f35b346103ed5760203660031901126103ed57611cca33613dc3565b6100216004356138af565b346103ed5760803660031901126103ed576004356001600160401b0381116103ed57611d0590369060040161327a565b906024356001600160401b0381116103ed57611d2590369060040161327a565b91906044356001600160401b0381116103ed57611d4690369060040161327a565b919094606435916001600160401b0383116103ed5761002196611d8e611d9692611d86611d7a611d9e97369060040161327a565b999096610fcc33613d63565b983691613613565b943691613667565b933691613667565b92614575565b346103ed5760203660031901126103ed57600435611dc133613cb6565b610e108110611e035760407f15c5fb1eab366b7926ae691891590eeed09db94b870081c268b98778042d7d2591600654908060065582519182526020820152a1005b63317eae7160e21b5f5260045ffd5b346103ed5760203660031901126103ed57611e2b613223565b611e3433613cb6565b6001600160a01b03811615611e6a5780611e50611e56926139bb565b50613a31565b50611e60336140f1565b5061002133614160565b6349e27cff60e01b5f5260045ffd5b346103ed5760203660031901126103ed57611e92613223565b611e9b33613cb6565b6001600160a01b03168015611f0a57805f52600a60205260ff60405f205416611efb57805f52600a60205260405f20600160ff198254161790557f758f46d6402b2cfe183c96029286524f6abcfbe17b1cc7db2834ecc3f23640d55f80a2005b633628149f60e21b5f5260045ffd5b63281a2b6360e11b5f5260045ffd5b346103ed5760803660031901126103ed57610021611f35613223565b611f3d6131f7565b611f4633613d63565b6040918251611f558482613353565b60018152601f1984019283366020840137845192611f738685613353565b6001845284366020860137855194611f8b8787613353565b6001865280366020880137611fa287519788613353565b60018752366020880137611fb58361379d565b6001600160a01b039091169052611fcb8361379d565b6001600160a01b039091169052604435611fe48461379d565b52606435611ff18561379d565b52614575565b346103ed5760203660031901126103ed5760043561201433613cb6565b8015610b3a576010548110610b3a5760407f905618debd54082867e8ff4edb7cea7d2cc41b4e445ce11dc92482a6821a70df91601154908060115582519182526020820152a1005b346103ed575f3660031901126103ed576020600f54604051908152f35b346103ed575f3660031901126103ed576020600654604051908152f35b346103ed575f3660031901126103ed576020601554604051908152f35b346103ed5760403660031901126103ed576004356001600160401b0381116103ed576120e39036906004016134c1565b602435906001600160401b0382116103ed5761063f6121159161139161210f60209536906004016133c5565b9161443b565b6040516001600160a01b039091168152f35b346103ed575f3660031901126103ed57602060ff5f516020614f805f395f51905f5254166040519015158152f35b346103ed5760203660031901126103ed576004356001600160401b0381116103ed57611a2061084360209236906004016134c1565b346103ed575f3660031901126103ed575f546040516001600160a01b039091168152602090f35b346103ed575f3660031901126103ed577f000000000000000000000000dd3eea0d0adc2a21a5fff235cf376af4df9312376001600160a01b031630036122085760206040515f516020614f205f395f51905f528152f35b63703e46dd60e11b5f5260045ffd5b60403660031901126103ed5761222b613223565b6024356001600160401b0381116103ed5761224a9036906004016133c5565b6001600160a01b037f000000000000000000000000dd3eea0d0adc2a21a5fff235cf376af4df931237163081149081156123d7575b506122085761228d33613cb6565b6001600160a01b0382169182156123c8576040516352d1902d60e01b8152602081600481875afa5f9181612394575b506122d45783634c9c8ce360e01b5f5260045260245ffd5b805f516020614f205f395f51905f528592036123825750813b15612370575f516020614f205f395f51905f5280546001600160a01b031916821790557fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b5f80a2815115612358575f8083602061002195519101845af4612352613c87565b91614d32565b50503461236157005b63b398979f60e01b5f5260045ffd5b634c9c8ce360e01b5f5260045260245ffd5b632a87526960e21b5f5260045260245ffd5b9091506020813d6020116123c0575b816123b060209383613353565b810103126103ed575190856122bc565b3d91506123a3565b63f6b2911f60e01b5f5260045ffd5b5f516020614f205f395f51905f52546001600160a01b0316141590508361227f565b346103ed5760203660031901126103ed57610021612415613223565b61241e33613cb6565b613ab1565b346103ed576101003660031901126103ed5761243d6131f7565b6064356001600160401b0381116103ed5761245c9036906004016133c5565b61246461320d565b9060e4359060028210156103ed57602093611a209360c4359260a4359260443590600435613720565b346103ed5760203660031901126103ed576001600160a01b036124ae613223565b165f52600b602052602060405f2054604051908152f35b346103ed5760203660031901126103ed576004356124e1613c42565b6124ea816135e3565b50600101546001600160a01b031633141580612678575b6126695760025481101561191c57805f52600c60205260ff60405f2054166118d257805f52600d60205260ff60405f2054166118c357805f52600760205260405f2054421061265a57805f52600d60205260405f20600160ff198254161790557f2098a796054c29fb8d38c92790a9c3b03dba43191b368bfb66b6437197eef4e660206125f261259361083d856135e3565b6125c360a08201516125a781600554613c7a565b600555865f526016855260405f20549061156082601554613c7a565b818401516001600160a01b03169086905f80808084875af16125e3613c87565b501561260c575b50505061443b565b604051908152a260015f516020614fc05f395f51905f5255005b60408161263c7fb831896736f2ddc5199663092702c1bc1f300555f8c6b7b60e12c0bd764398a4936004546136b3565b6004556126488661443b565b825191825288820152a38585816125ea565b635b4ffa6560e01b5f5260045ffd5b63b8036d5560e01b5f5260045ffd5b50612682816135e3565b50600201546001600160a01b0316331415612501565b346103ed575f3660031901126103ed576126b133613cb6565b5f516020614f805f395f51905f525460ff8116156127085760ff19165f516020614f805f395f51905f52557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a1005b638dfc202b60e01b5f5260045ffd5b346103ed5760403660031901126103ed576020611a206024356004356136c0565b346103ed5760403660031901126103ed576127516131f7565b336001600160a01b0382160361276d57610021906004356142da565b63334bd91960e11b5f5260045ffd5b346103ed575f3660031901126103ed576020600454604051908152f35b346103ed5760403660031901126103ed576100216004356127b86131f7565b906127de610d39825f525f516020614f405f395f51905f52602052600160405f20015490565b613bb1565b346103ed575f3660031901126103ed576020601154604051908152f35b6133e3565b346103ed5760203660031901126103ed5760043561282233613cb6565b801561060b57600e54811061060b5760407f64cc8b0bc5d539e03bf1ff414d078447028c16f47fc95ef5b7612a6a0b72360791600f549080600f5582519182526020820152a1005b346103ed5760203660031901126103ed576020611a206004355f525f516020614f405f395f51905f52602052600160405f20015490565b346103ed5760203660031901126103ed576128bb33613dc3565b610021600435613900565b346103ed575f3660031901126103ed576001546040516001600160a01b039091168152602090f35b346103ed57610021610fd3610fdb612908610fbb366132aa565b91613eeb565b346103ed575f3660031901126103ed576020604051610e108152f35b346103ed575f3660031901126103ed576020601254604051908152f35b346103ed575f3660031901126103ed57602060405160068152f35b346103ed5760203660031901126103ed5761002161297e613223565b61298733613d03565b613939565b346103ed5760203660031901126103ed576004356129a8613c42565b6129b133613cb6565b8015612a5357600454808211612a4457816129cb91613c7a565b6004555f8080808460018060a01b03600154165af16129e8613c87565b5015612a3557600154604080519283526001600160a01b03909116602083015233917f15596072c803eddeee7aae343e846f411bf951c23ef910e91eff4cc1a84110a79181908101610c85565b6327fcd9d160e01b5f5260045ffd5b632624c66960e11b5f5260045ffd5b63375bfb0160e11b5f5260045ffd5b346103ed5760c03660031901126103ed576044356001600160a01b0381168082036103ed57606435916001600160a01b03831683036103ed57612aa361320d565b60a435906001600160a01b03821682036103ed575f5160206150005f395f51905f52549360ff8560401c1615946001600160401b0381168015908161304f575b6001149081613045575b15908161303c575b5061302d5767ffffffffffffffff1981166001175f5160206150005f395f51905f525585613001575b50156123c857612b2c614b0d565b612b34614b0d565b60015f516020614fc05f395f51905f5255612b4d614b0d565b612b56336139bb565b50612b6033613a31565b50612b6a33613ab1565b50612b73614b0d565b6040948551612b828782613353565b60058152645061636b7360d81b6020820152865190612ba18883613353565b60018252603160f81b6020830152612bb7614b0d565b612bbf614b0d565b612bc7614b0d565b612bcf614b0d565b8051906001600160401b038211610990578190612bf95f516020614e805f395f51905f5254614959565b601f8111612f87575b50602090601f8311600114612f09575f92612efe575b50508160011b915f199060031b1c1916175f516020614e805f395f51905f52555b8051906001600160401b03821161099057612c615f516020614ee05f395f51905f5254614959565b601f8111612e8f575b50602090601f8311600114612e05579282612d399593612d1693612d8e9998965f92612dfa575b50508160011b915f199060031b1c1916175f516020614ee05f395f51905f52555b5f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100555f7fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d101554780612deb575b50612d0b6004356138af565b612987602435613900565b60018060a01b03166bffffffffffffffffffffffff60a01b5f5416175f55613b31565b50662386f26fc10000600e55674563918244f40000600f55662386f26fc100006010556703782dace9d9000060115562015180600655610258600855612d7e816139bb565b50612d8881613a31565b50613ab1565b50612d9557005b60207fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d29168ff0000000000000000195f5160206150005f395f51905f5254165f5160206150005f395f51905f52555160018152a1005b612df490613872565b89612cff565b015190508b80612c91565b90601f198316915f516020614ee05f395f51905f525f52815f20925f5b818110612e77575093612d1693612d8e9998969360019383612d399a9810612e5f575b505050811b015f516020614ee05f395f51905f5255612cb2565b01515f1960f88460031b161c191690558b8080612e45565b92936020600181928786015181550195019301612e22565b5f516020614ee05f395f51905f525f527f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b75601f840160051c81019160208510612ef4575b601f0160051c01905b818110612ee95750612c6a565b5f8155600101612edc565b9091508190612ed3565b015190508980612c18565b5f516020614e805f395f51905f525f9081528281209350601f198516905b818110612f6f5750908460019594939210612f57575b505050811b015f516020614e805f395f51905f5255612c39565b01515f1960f88460031b161c19169055898080612f3d565b92936020600181928786015181550195019301612f27565b5f516020614e805f395f51905f525f529091507f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d601f840160051c81019160208510612ff7575b90601f859493920160051c01905b818110612fe95750612c02565b5f8155849350600101612fdc565b9091508190612fce565b68ffffffffffffffffff191668010000000000000001175f5160206150005f395f51905f525586612b1e565b63f92ee8a960e01b5f5260045ffd5b90501588612af5565b303b159150612aed565b879150612ae3565b346103ed575f3660031901126103ed5760206040515f516020614ec05f395f51905f528152f35b346103ed575f3660031901126103ed57602060405160018152f35b346103ed5760203660031901126103ed576004355f52600c602052602060ff60405f2054166040519015158152f35b346103ed5760203660031901126103ed576004355f526007602052602060405f2054604051908152f35b346103ed5760203660031901126103ed5760043563ffffffff60e01b81168091036103ed57602090637965db0b60e01b8114908115613137575b506040519015158152f35b6301ffc9a760e01b1490508261312c565b6101403660031901126103ed5761315d6131f7565b6044356001600160401b0381116103ed5761317c90369060040161324d565b61318792919261320d565b9260e4356001600160401b0381116103ed576131a790369060040161324d565b94610104356001600160401b0381116103ed576131c890369060040161324d565b95909460026101243510156103ed576131df61384b565b6004355f52600360205260405f2054976112b761384b565b602435906001600160a01b03821682036103ed57565b608435906001600160a01b03821682036103ed57565b600435906001600160a01b03821682036103ed57565b35906001600160a01b03821682036103ed57565b9181601f840112156103ed578235916001600160401b0383116103ed57602083818601950101116103ed57565b9181601f840112156103ed578235916001600160401b0383116103ed576020808501948460051b0101116103ed57565b60606003198201126103ed576004356001600160401b0381116103ed57816132d49160040161327a565b929092916024356001600160401b0381116103ed57816132f69160040161327a565b92909291604435906001600160401b0382116103ed576133189160040161327a565b9091565b61010081019081106001600160401b0382111761099057604052565b606081019081106001600160401b0382111761099057604052565b90601f801991011681019081106001600160401b0382111761099057604052565b6001600160401b03811161099057601f01601f191660200190565b92919261339b82613374565b916133a96040519384613353565b8294818452818301116103ed578281602093845f960137010152565b9080601f830112156103ed578160206133e09335910161338f565b90565b346103ed5760403660031901126103ed576024356004356001600160401b0382116103ed5761063f6121159161146560209436906004016133c5565b6001600160401b0381116109905760051b60200190565b81601f820112156103ed5780359061344d8261341f565b9261345b6040519485613353565b828452602060608186019402830101918183116103ed57602001925b828410613485575050505090565b6060848303126103ed5760206060916040516134a081613338565b86358152828701358382015260408701356040820152815201930192613477565b919091610100818403126103ed57604051906134dc8261331c565b8193813583526134ee60208301613239565b60208401526134ff60408301613239565b6040840152606082013560608401526080820135608084015260a082013560a084015260c0820135916001600160401b0383116103ed5761354660e0939284938301613436565b60c08501520135910152565b60609060031901126103ed576004356001600160a01b03811681036103ed57906024356001600160a01b03811681036103ed579060443590565b805180835260209291819084018484015e5f828201840152601f01601f1916010190565b90602080835192838152019201905f5b8181106135cd5750505090565b82518452602093840193909201916001016135c0565b6002548110156135ff5760025f5260205f209060031b01905f90565b634e487b7160e01b5f52603260045260245ffd5b92919061361f8161341f565b9361362d6040519586613353565b602085838152019160051b81019283116103ed57905b82821061364f57505050565b6020809161365c84613239565b815201910190613643565b9291906136738161341f565b936136816040519586613353565b602085838152019160051b81019283116103ed57905b8282106136a357505050565b8135815260209182019101613697565b919082018092116105f757565b9061271082029180830461271014901517156105f757612710019081612710116105f75781156136ee570490565b634e487b7160e01b5f52601260045260245ffd5b6002111561370c57565b634e487b7160e01b5f52602160045260245ffd5b9691959093929461376061379796604051988997602089019b8c5260018060a01b031660408901526060880152610100608088015261012087019061358c565b6001600160a01b0390941660a086015260c085015260e084015261378381613702565b61010083015203601f198101835282613353565b51902090565b8051156135ff5760200190565b80518210156135ff5760209160051b010190565b90602080835192838152019201905f5b8181106137db5750505090565b90919260206060600192604087518051835284810151858401520151604082015201940191019190916137ce565b91906137979061383d604051938492602084019661382681613702565b8752604084015260608084015260808301906137be565b03601f198101835282613353565b60ff5f516020614f805f395f51905f52541661386357565b63d93c066560e01b5f5260045ffd5b61387e816004546136b3565b6004556040519081527fe3407208b14fa025330ca187030f118a1c0cdb604aba93ba45c862e6095aee2760203392a2565b61271081116138f15760407fb404cac19fb1cbeff98d325795b08886e3cd8fe8cb1a2f193aac66f13fb239c391601454908060145582519182526020820152a1565b631752ff0760e31b5f5260045ffd5b60407f957f8e165512616cc1b935b3ba999a8a0870b6e18300af633ba488f7926bce2d91601754908060175582519182526020820152a1565b6001600160a01b031680156139ac575f8181525f516020614fe05f395f51905f52602052604090205460ff16610ac657600180546001600160a01b0319811683179091556001600160a01b03167f8e72b2cf2be54e3a933095b67f13c3927802840d4808120dc36219da676d79175f80a3565b637c67e5ff60e01b5f5260045ffd5b6001600160a01b0381165f9081525f516020614f005f395f51905f52602052604090205460ff16613a2c576001600160a01b03165f8181525f516020614f005f395f51905f5260205260408120805460ff191660011790553391905f516020614e405f395f51905f528180a4600190565b505f90565b6001600160a01b0381165f9081525f516020614ea05f395f51905f52602052604090205460ff16613a2c576001600160a01b03165f8181525f516020614ea05f395f51905f5260205260408120805460ff191660011790553391905f516020614ec05f395f51905f52905f516020614e405f395f51905f529080a4600190565b6001600160a01b0381165f9081525f516020614fa05f395f51905f52602052604090205460ff16613a2c576001600160a01b03165f8181525f516020614fa05f395f51905f5260205260408120805460ff191660011790553391905f5160206150205f395f51905f52905f516020614e405f395f51905f529080a4600190565b6001600160a01b0381165f9081525f516020614fe05f395f51905f52602052604090205460ff16613a2c576001600160a01b03165f8181525f516020614fe05f395f51905f5260205260408120805460ff191660011790553391905f516020614e605f395f51905f52905f516020614e405f395f51905f529080a4600190565b5f8181525f516020614f405f395f51905f52602090815260408083206001600160a01b038616845290915290205460ff16613c3c575f8181525f516020614f405f395f51905f52602090815260408083206001600160a01b0395909516808452949091528120805460ff19166001179055339291905f516020614e405f395f51905f529080a4600190565b50505f90565b60025f516020614fc05f395f51905f525414613c6b5760025f516020614fc05f395f51905f5255565b633ee5aeb560e01b5f5260045ffd5b919082039182116105f757565b3d15613cb1573d90613c9882613374565b91613ca66040519384613353565b82523d5f602084013e565b606090565b6001600160a01b0381165f9081525f516020614f005f395f51905f52602052604090205460ff1615613ce55750565b63e2517d3f60e01b5f5260018060a01b03166004525f60245260445ffd5b6001600160a01b0381165f9081525f516020614fe05f395f51905f52602052604090205460ff1615613d325750565b63e2517d3f60e01b5f9081526001600160a01b03919091166004525f516020614e605f395f51905f52602452604490fd5b6001600160a01b0381165f9081525f516020614fa05f395f51905f52602052604090205460ff1615613d925750565b63e2517d3f60e01b5f9081526001600160a01b03919091166004525f5160206150205f395f51905f52602452604490fd5b6001600160a01b0381165f9081525f516020614ea05f395f51905f52602052604090205460ff1615613df25750565b63e2517d3f60e01b5f9081526001600160a01b03919091166004525f516020614ec05f395f51905f52602452604490fd5b90815f525f516020614f405f395f51905f5260205260405f2060018060a01b0382165f5260205260ff60405f20541615613e5b575050565b63e2517d3f60e01b5f5260018060a01b031660045260245260445ffd5b90602080835192838152019201905f5b818110613e955750505090565b82516001600160a01b0316845260209384019390920191600101613e88565b91613edd90613ecf6133e09593606086526060860190613e78565b908482036020860152613e78565b9160408184039101526135b0565b9091815115610cb957815183518114908115916140e5575b506140d6575f5b825181101561409d576001600160a01b03613f2582856137aa565b511615610cc8576001600160a01b03613f3e82866137aa565b511615610cc857613f4f81836137aa565b5115610cb957602460206001600160a01b03613f6b84876137aa565b5116604051928380926370a0823160e01b82523060048301525afa90811561188b575f9161406c575b50613f9f82846137aa565b5111610caa5761401260206001600160a01b03613fbc84876137aa565b51166001600160a01b03613fd085896137aa565b511690613fdd85876137aa565b5160405163a9059cbb60e01b81526001600160a01b0390931660048401526024830152909283919082905f9082906044820190565b03925af190811561188b575f91614032575b5015610c9b57600101613f0a565b90506020813d8211614064575b8161404c60209383613353565b810103126103ed575180151581036103ed575f614024565b3d915061403f565b90506020813d8211614095575b8161408660209383613353565b810103126103ed57515f613f94565b3d9150614079565b50906140d17fda7ef1de52bffe1a49c51eaed4b15496c10b01f18b30ac2c65249fd7b4f9fe84939260405193849384613eb4565b0390a1565b63512509d360e11b5f5260045ffd5b9050815114155f613f03565b6001600160a01b0381165f9081525f516020614f005f395f51905f52602052604090205460ff1615613a2c576001600160a01b03165f8181525f516020614f005f395f51905f5260205260408120805460ff191690553391905f516020614f605f395f51905f528180a4600190565b6001600160a01b0381165f9081525f516020614ea05f395f51905f52602052604090205460ff1615613a2c576001600160a01b03165f8181525f516020614ea05f395f51905f5260205260408120805460ff191690553391905f516020614ec05f395f51905f52905f516020614f605f395f51905f529080a4600190565b6001600160a01b0381165f9081525f516020614fe05f395f51905f52602052604090205460ff1615613a2c576001600160a01b03165f8181525f516020614fe05f395f51905f5260205260408120805460ff191690553391905f516020614e605f395f51905f52905f516020614f605f395f51905f529080a4600190565b6001600160a01b0381165f9081525f516020614fa05f395f51905f52602052604090205460ff1615613a2c576001600160a01b03165f8181525f516020614fa05f395f51905f5260205260408120805460ff191690553391905f5160206150205f395f51905f52905f516020614f605f395f51905f529080a4600190565b5f8181525f516020614f405f395f51905f52602090815260408083206001600160a01b038616845290915290205460ff1615613c3c575f8181525f516020614f405f395f51905f52602090815260408083206001600160a01b0395909516808452949091528120805460ff19169055339291905f516020614f605f395f51905f529080a4600190565b906040516143708161331c565b8254815260018301546001600160a01b03908116602083015260028401541660408201526003830154606082015260048301546080820152600583015460a0820152600683018054919384929091906143c88161341f565b916143d66040519384613353565b81835260208301905f5260205f205f915b838310614404575050505060e09160079160c08501520154910152565b6003602060019260405161441781613338565b855481528486015483820152600286015460408201528152019201920191906143e7565b6042908051906144f360018060a01b0360208301511660018060a01b03604084015116926144de606082015191608081015160a08201519060e060c084015193015194604051988997602089019b7fe5de7d62401712d7e4d89bb245a67effccc12acfbb86de1e24564e2e1f9dd0788d5260408a01526060890152608088015260a087015260c086015260e08501526101206101008501526101408401906137be565b9061012083015203601f198101835282613353565b5190206144fe614d90565b614506614dfa565b6040519060208201927f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f8452604083015260608201524660808201523060a082015260a0815261455760c082613353565b519020906040519161190160f01b8352600283015260228201522090565b92939091835115610cb95783518351811490811591614827575b811561481b575b506140d65760409491936020925f5b82518110156147aa576001600160a01b036145c082856137aa565b511615610cc8576001600160a01b036145d982886137aa565b511615610cc8576145ea81836137aa565b5115610cb95761463c60206001600160a01b0361460784876137aa565b511661461384886137aa565b518b51627eeac760e11b8152306004820152602481019190915292839190829081906044820190565b03915afa90811561476f575f91614779575b5061465982846137aa565b5111610caa5787519061466c8983613353565b600182528536602084013788516146838a82613353565b600181528636602083013761469882876137aa565b516146a28461379d565b526146ad82856137aa565b516146b78261379d565b526001600160a01b036146ca83876137aa565b5116926001600160a01b036146df848b6137aa565b511693803b156103ed57614723945f60206147358f96839751998a978896631759616b60e11b8852306004890152602488015260a0604488015260a48701906135b0565b858103600319016064870152906135b0565b8284820391600319830160848701525201925af191821561476f5760019261475f575b50016145a5565b5f61476991613353565b5f614758565b89513d5f823e3d90fd5b90506020813d82116147a2575b8161479360209383613353565b810103126103ed57515f61464e565b3d9150614786565b5090925061480d7f6eb41c7cf392c11c85d5ce898f2565141e8120cff8a13a0bf8e4a9c3b6df52b295966140d1936148006147f297835198899860808a5260808a0190613e78565b9088820360208a0152613e78565b91868303908701526135b0565b9083820360608501526135b0565b9050855114155f614596565b8251811415915061458f565b92919092805115610cb9578051845181149081159161494d575b506140d6575f5b8151811015614919576001600160a01b0361486f82846137aa565b511615610cc8576001600160a01b0361488882876137aa565b511615610cc8576001600160a01b036148a182846137aa565b5116906001600160a01b036148b682886137aa565b51166148c282866137aa565b51833b156103ed5760645f92836040519687948593632142170760e11b8552306004860152602485015260448401525af191821561188b57600192614909575b5001614854565b5f61491391613353565b5f614902565b506140d17f0c1a5e4c986b93e894a5c3eeedeee9d54f3433ff530d2ca7631bc00271bde56793949260405193849384613eb4565b9050825114155f61484d565b90600182811c92168015614987575b602083101461497357565b634e487b7160e01b5f52602260045260245ffd5b91607f1691614968565b604051905f825f516020614e805f395f51905f5254916149b083614959565b8083529260018116908115614a4157506001146149d6575b6149d492500383613353565b565b505f516020614e805f395f51905f525f90815290917f42ad5d3e1f2e6e70edcf6d991b8a3023d3fca8047a131592f9edb9fd9b89d57d5b818310614a255750509060206149d4928201016149c8565b6020919350806001915483858901015201910190918492614a0d565b602092506149d494915060ff191682840152151560051b8201016149c8565b604051905f825f516020614ee05f395f51905f525491614a7f83614959565b8083529260018116908115614a415750600114614aa2576149d492500383613353565b505f516020614ee05f395f51905f525f90815290917f5f9ce34815f8e11431c7bb75a8e6886a91478f7ffc1dbb0a98dc240fddd76b755b818310614af15750509060206149d4928201016149c8565b6020919350806001915483858901015201910190918492614ad9565b60ff5f5160206150005f395f51905f525460401c1615614b2957565b631afcd79f60e31b5f5260045ffd5b614b4182613702565b81159081614b58575b50614b525790565b50600190565b90505f52600960205260405f205442115f614b4a565b8151919060418303614b9e57614b979250602082015190606060408401519301515f1a90614cb0565b9192909190565b50505f9160029190565b600481101561370c5780614bba575050565b60018103614bd15763f645eedf60e01b5f5260045ffd5b60028103614bec575063fce698f760e01b5f5260045260245ffd5b600314614bf65750565b6335e2f38360e21b5f5260045260245ffd5b5f91825b8151841015614c3b57614c23906105a885846137aa565b92838310614c345760010192614c0c565b9250505090565b6303fb883760e51b5f5260045ffd5b949192610140969399989794919961016087019a87526020870152604086015260608501525f60808501525f60a08501525f60c085015260018060a01b031660e0840152614c9781613702565b610100830152614ca681613702565b6101208201520152565b91907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411614d27579160209360809260ff5f9560405194855216868401526040830152606082015282805260015afa1561188b575f516001600160a01b03811615614d1d57905f905f90565b505f906001905f90565b5050505f9160039190565b90614d565750805115614d4757805190602001fd5b63d6bda27560e01b5f5260045ffd5b81511580614d87575b614d67575090565b639996b31560e01b5f9081526001600160a01b0391909116600452602490fd5b50803b15614d5f565b614d98614991565b8051908115614da8576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100548015614dd55790565b507fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a47090565b614e02614a60565b8051908115614e12576020012090565b50507fa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d101548015614dd5579056fe2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d9b0ee324ca44438714d8c36348cae5ef5f61255bb6eb57c650755cacd7a2c29ba16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d102f9232fdb47376373f124299514419be5e88f294fb4878ffd53802c02c557618f65aa5eac1b32fde55d4db583460221274367300ae805596cf543907b5d458c00a16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d103b7db2dd08fcb62d0c9e08c51941cae53c267786a0b75803fb7960902fc8ef97d360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800f6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171bcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300d5eca2275ae5468fc6328d5f7139b0650ff887f5f59eaa13cdf410f2b835045e9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00eb60d83878932ca9f4ef6c58d9b49b043f87557ed40301271762dace2b0af9c6f0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00c4c453d647953c0fd35db5a34ee76e60fb4abc3a8fb891a25936b70b38f29253a26469706673582212205e5cf154b92490a0f9ef8f011f27c8a713f437e489124a58144000efc894a70164736f6c634300081c0033
Verified Source Code Full Match
Compiler: v0.8.28+commit.7893614a
EVM: prague
Optimization: Yes (200 runs)
IERC1155.sol 105 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2;
import "./IERC165.sol";
/// @title ERC-1155 Multi Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-1155
/// Note: The ERC-165 identifier for this interface is 0xd9b67a26.
interface IERC1155 is IERC165 {
/// @dev
/// - Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
/// - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
/// - The `_from` argument MUST be the address of the holder whose balance is decreased.
/// - The `_to` argument MUST be the address of the recipient whose balance is increased.
/// - The `_id` argument MUST be the token type being transferred.
/// - The `_value` argument MUST be the number of tokens the holder balance is decreased by and match what the recipient balance is increased by.
/// - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
/// - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
event TransferSingle(
address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _value
);
/// @dev
/// - Either `TransferSingle` or `TransferBatch` MUST emit when tokens are transferred, including zero value transfers as well as minting or burning (see "Safe Transfer Rules" section of the standard).
/// - The `_operator` argument MUST be the address of an account/contract that is approved to make the transfer (SHOULD be msg.sender).
/// - The `_from` argument MUST be the address of the holder whose balance is decreased.
/// - The `_to` argument MUST be the address of the recipient whose balance is increased.
/// - The `_ids` argument MUST be the list of tokens being transferred.
/// - The `_values` argument MUST be the list of number of tokens (matching the list and order of tokens specified in _ids) the holder balance is decreased by and match what the recipient balance is increased by.
/// - When minting/creating tokens, the `_from` argument MUST be set to `0x0` (i.e. zero address).
/// - When burning/destroying tokens, the `_to` argument MUST be set to `0x0` (i.e. zero address).
event TransferBatch(
address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _values
);
/// @dev MUST emit when approval for a second party/operator address to manage all tokens for an owner address is enabled or disabled (absence of an event assumes disabled).
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @dev MUST emit when the URI is updated for a token ID. URIs are defined in RFC 3986.
/// The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema".
event URI(string _value, uint256 indexed _id);
/// @notice Transfers `_value` amount of an `_id` from the `_from` address to the `_to` address specified (with safety call).
/// @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
/// - MUST revert if `_to` is the zero address.
/// - MUST revert if balance of holder for token `_id` is lower than the `_value` sent.
/// - MUST revert on any other error.
/// - MUST emit the `TransferSingle` event to reflect the balance change (see "Safe Transfer Rules" section of the standard).
/// - After the above conditions are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call `onERC1155Received` on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
/// @param _from Source address
/// @param _to Target address
/// @param _id ID of the token type
/// @param _value Transfer amount
/// @param _data Additional data with no specified format, MUST be sent unaltered in call to `onERC1155Received` on `_to`
function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _value, bytes calldata _data) external;
/// @notice Transfers `_values` amount(s) of `_ids` from the `_from` address to the `_to` address specified (with safety call).
/// @dev Caller must be approved to manage the tokens being transferred out of the `_from` account (see "Approval" section of the standard).
/// - MUST revert if `_to` is the zero address.
/// - MUST revert if length of `_ids` is not the same as length of `_values`.
/// - MUST revert if any of the balance(s) of the holder(s) for token(s) in `_ids` is lower than the respective amount(s) in `_values` sent to the recipient.
/// - MUST revert on any other error.
/// - MUST emit `TransferSingle` or `TransferBatch` event(s) such that all the balance changes are reflected (see "Safe Transfer Rules" section of the standard).
/// - Balance changes and events MUST follow the ordering of the arrays (_ids[0]/_values[0] before _ids[1]/_values[1], etc).
/// - After the above conditions for the transfer(s) in the batch are met, this function MUST check if `_to` is a smart contract (e.g. code size > 0). If so, it MUST call the relevant `ERC1155TokenReceiver` hook(s) on `_to` and act appropriately (see "Safe Transfer Rules" section of the standard).
/// @param _from Source address
/// @param _to Target address
/// @param _ids IDs of each token type (order and length must match _values array)
/// @param _values Transfer amounts per token type (order and length must match _ids array)
/// @param _data Additional data with no specified format, MUST be sent unaltered in call to the `ERC1155TokenReceiver` hook(s) on `_to`
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _ids,
uint256[] calldata _values,
bytes calldata _data
) external;
/// @notice Get the balance of an account's tokens.
/// @param _owner The address of the token holder
/// @param _id ID of the token
/// @return The _owner's balance of the token type requested
function balanceOf(address _owner, uint256 _id) external view returns (uint256);
/// @notice Get the balance of multiple account/token pairs
/// @param _owners The addresses of the token holders
/// @param _ids ID of the tokens
/// @return The _owner's balance of the token types requested (i.e. balance for each (owner, id) pair)
function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids)
external
view
returns (uint256[] memory);
/// @notice Enable or disable approval for a third party ("operator") to manage all of the caller's tokens.
/// @dev MUST emit the ApprovalForAll event on success.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Queries the approval status of an operator for a given owner.
/// @param _owner The owner of the tokens
/// @param _operator Address of authorized operator
/// @return True if the operator is approved, false if not
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
IERC165.sol 12 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2;
interface IERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
IERC20.sol 43 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2;
/// @dev Interface of the ERC20 standard as defined in the EIP.
/// @dev This includes the optional name, symbol, and decimals metadata.
interface IERC20 {
/// @dev Emitted when `value` tokens are moved from one account (`from`) to another (`to`).
event Transfer(address indexed from, address indexed to, uint256 value);
/// @dev Emitted when the allowance of a `spender` for an `owner` is set, where `value`
/// is the new allowance.
event Approval(address indexed owner, address indexed spender, uint256 value);
/// @notice Returns the amount of tokens in existence.
function totalSupply() external view returns (uint256);
/// @notice Returns the amount of tokens owned by `account`.
function balanceOf(address account) external view returns (uint256);
/// @notice Moves `amount` tokens from the caller's account to `to`.
function transfer(address to, uint256 amount) external returns (bool);
/// @notice Returns the remaining number of tokens that `spender` is allowed
/// to spend on behalf of `owner`
function allowance(address owner, address spender) external view returns (uint256);
/// @notice Sets `amount` as the allowance of `spender` over the caller's tokens.
/// @dev Be aware of front-running risks: https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
function approve(address spender, uint256 amount) external returns (bool);
/// @notice Moves `amount` tokens from `from` to `to` using the allowance mechanism.
/// `amount` is then deducted from the caller's allowance.
function transferFrom(address from, address to, uint256 amount) external returns (bool);
/// @notice Returns the name of the token.
function name() external view returns (string memory);
/// @notice Returns the symbol of the token.
function symbol() external view returns (string memory);
/// @notice Returns the decimals places of the token.
function decimals() external view returns (uint8);
}
IERC721.sol 164 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2;
import "./IERC165.sol";
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface IERC721 is IERC165 {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface IERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes calldata _data)
external
returns (bytes4);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface IERC721Metadata is IERC721 {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string memory _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string memory _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://eips.ethereum.org/EIPS/eip-721
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface IERC721Enumerable is IERC721 {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
AccessControlUpgradeable.sol 233 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/AccessControl.sol)
pragma solidity ^0.8.20;
import {IAccessControl} from "@openzeppelin/contracts/access/IAccessControl.sol";
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {ERC165Upgradeable} from "../utils/introspection/ERC165Upgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControl, ERC165Upgradeable {
struct RoleData {
mapping(address account => bool) hasRole;
bytes32 adminRole;
}
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/// @custom:storage-location erc7201:openzeppelin.storage.AccessControl
struct AccessControlStorage {
mapping(bytes32 role => RoleData) _roles;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.AccessControl")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant AccessControlStorageLocation = 0x02dd7bc7dec4dceedda775e58dd541e08a116c6c53815c0bd028192f7b626800;
function _getAccessControlStorage() private pure returns (AccessControlStorage storage $) {
assembly {
$.slot := AccessControlStorageLocation
}
}
/**
* @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);
_;
}
function __AccessControl_init() internal onlyInitializing {
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
/**
* @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) {
AccessControlStorage storage $ = _getAccessControlStorage();
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) {
AccessControlStorage storage $ = _getAccessControlStorage();
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 {
AccessControlStorage storage $ = _getAccessControlStorage();
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) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (!hasRole(role, account)) {
$._roles[role].hasRole[account] = true;
emit RoleGranted(role, account, _msgSender());
return true;
} else {
return false;
}
}
/**
* @dev Attempts to revoke `role` from `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) {
AccessControlStorage storage $ = _getAccessControlStorage();
if (hasRole(role, account)) {
$._roles[role].hasRole[account] = false;
emit RoleRevoked(role, account, _msgSender());
return true;
} else {
return false;
}
}
}
Initializable.sol 238 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reinitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Pointer to storage slot. Allows integrators to override it with a custom storage location.
*
* NOTE: Consider following the ERC-7201 formula to derive storage locations.
*/
function _initializableStorageSlot() internal pure virtual returns (bytes32) {
return INITIALIZABLE_STORAGE;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
bytes32 slot = _initializableStorageSlot();
assembly {
$.slot := slot
}
}
}
ContextUpgradeable.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
PausableUpgradeable.sol 133 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {ContextUpgradeable} from "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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 PausableUpgradeable is Initializable, ContextUpgradeable {
/// @custom:storage-location erc7201:openzeppelin.storage.Pausable
struct PausableStorage {
bool _paused;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Pausable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant PausableStorageLocation = 0xcd5ed15c6e187e77e9aee88184c21f4f2182ab5827cb3b7e07fbedcd63f03300;
function _getPausableStorage() private pure returns (PausableStorage storage $) {
assembly {
$.slot := PausableStorageLocation
}
}
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
function __Pausable_init() internal onlyInitializing {
}
function __Pausable_init_unchained() internal onlyInitializing {
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
PausableStorage storage $ = _getPausableStorage();
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 {
PausableStorage storage $ = _getPausableStorage();
$._paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
PausableStorage storage $ = _getPausableStorage();
$._paused = false;
emit Unpaused(_msgSender());
}
}
ReentrancyGuardUpgradeable.sol 108 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @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 ReentrancyGuardUpgradeable is Initializable {
// 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;
/// @custom:storage-location erc7201:openzeppelin.storage.ReentrancyGuard
struct ReentrancyGuardStorage {
uint256 _status;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.ReentrancyGuard")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant ReentrancyGuardStorageLocation = 0x9b779b17422d0df92223018b32b4d1fa46e071723d6817e2486d003becc55f00;
function _getReentrancyGuardStorage() private pure returns (ReentrancyGuardStorage storage $) {
assembly {
$.slot := ReentrancyGuardStorageLocation
}
}
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
$._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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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 {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
// 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) {
ReentrancyGuardStorage storage $ = _getReentrancyGuardStorage();
return $._status == ENTERED;
}
}
EIP712Upgradeable.sol 210 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.20;
import {MessageHashUtils} from "@openzeppelin/contracts/utils/cryptography/MessageHashUtils.sol";
import {IERC5267} from "@openzeppelin/contracts/interfaces/IERC5267.sol";
import {Initializable} from "../../proxy/utils/Initializable.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.
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267 {
bytes32 private constant TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:storage-location erc7201:openzeppelin.storage.EIP712
struct EIP712Storage {
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 _hashedVersion;
string _name;
string _version;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.EIP712")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant EIP712StorageLocation = 0xa16a46d94261c7517cc8ff89f61c0ce93598e3c849801011dee649a6a557d100;
function _getEIP712Storage() private pure returns (EIP712Storage storage $) {
assembly {
$.slot := EIP712StorageLocation
}
}
/**
* @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].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
EIP712Storage storage $ = _getEIP712Storage();
$._name = name;
$._version = version;
// Reset prior values in storage if upgrading
$._hashedName = 0;
$._hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @inheritdoc IERC5267
*/
function eip712Domain()
public
view
virtual
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
EIP712Storage storage $ = _getEIP712Storage();
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require($._hashedName == 0 && $._hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal view virtual returns (string memory) {
EIP712Storage storage $ = _getEIP712Storage();
return $._version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = $._hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
EIP712Storage storage $ = _getEIP712Storage();
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = $._hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
}
ERC165Upgradeable.sol 33 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
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;
}
IERC1967.sol 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*/
interface IERC1967 {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
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
);
}
draft-IERC1822.sol 20 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.20;
/**
* @dev ERC-1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
ERC1967Utils.sol 177 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/ERC1967/ERC1967Utils.sol)
pragma solidity ^0.8.22;
import {IBeacon} from "../beacon/IBeacon.sol";
import {IERC1967} from "../../interfaces/IERC1967.sol";
import {Address} from "../../utils/Address.sol";
import {StorageSlot} from "../../utils/StorageSlot.sol";
/**
* @dev This library provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[ERC-1967] slots.
*/
library ERC1967Utils {
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev The `implementation` of the proxy is invalid.
*/
error ERC1967InvalidImplementation(address implementation);
/**
* @dev The `admin` of the proxy is invalid.
*/
error ERC1967InvalidAdmin(address admin);
/**
* @dev The `beacon` of the proxy is invalid.
*/
error ERC1967InvalidBeacon(address beacon);
/**
* @dev An upgrade function sees `msg.value > 0` that may be lost.
*/
error ERC1967NonPayable();
/**
* @dev Returns the current implementation address.
*/
function getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
if (newImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(newImplementation);
}
StorageSlot.getAddressSlot(IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Performs implementation upgrade with additional setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-Upgraded} event.
*/
function upgradeToAndCall(address newImplementation, bytes memory data) internal {
_setImplementation(newImplementation);
emit IERC1967.Upgraded(newImplementation);
if (data.length > 0) {
Address.functionDelegateCall(newImplementation, data);
} else {
_checkNonPayable();
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*
* TIP: To get this value clients can read directly from the storage slot shown below (specified by ERC-1967) using
* the https://eth.wiki/json-rpc/API#eth_getstorageat[`eth_getStorageAt`] RPC call.
* `0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103`
*/
function getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the ERC-1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
if (newAdmin == address(0)) {
revert ERC1967InvalidAdmin(address(0));
}
StorageSlot.getAddressSlot(ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {IERC1967-AdminChanged} event.
*/
function changeAdmin(address newAdmin) internal {
emit IERC1967.AdminChanged(getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is the keccak-256 hash of "eip1967.proxy.beacon" subtracted by 1.
*/
// solhint-disable-next-line private-vars-leading-underscore
bytes32 internal constant BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the ERC-1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
if (newBeacon.code.length == 0) {
revert ERC1967InvalidBeacon(newBeacon);
}
StorageSlot.getAddressSlot(BEACON_SLOT).value = newBeacon;
address beaconImplementation = IBeacon(newBeacon).implementation();
if (beaconImplementation.code.length == 0) {
revert ERC1967InvalidImplementation(beaconImplementation);
}
}
/**
* @dev Change the beacon and trigger a setup call if data is nonempty.
* This function is payable only if the setup call is performed, otherwise `msg.value` is rejected
* to avoid stuck value in the contract.
*
* Emits an {IERC1967-BeaconUpgraded} event.
*
* CAUTION: Invoking this function has no effect on an instance of {BeaconProxy} since v5, since
* it uses an immutable beacon without looking at the value of the ERC-1967 beacon slot for
* efficiency.
*/
function upgradeBeaconToAndCall(address newBeacon, bytes memory data) internal {
_setBeacon(newBeacon);
emit IERC1967.BeaconUpgraded(newBeacon);
if (data.length > 0) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
} else {
_checkNonPayable();
}
}
/**
* @dev Reverts if `msg.value` is not zero. It can be used to avoid `msg.value` stuck in the contract
* if an upgrade doesn't perform an initialization call.
*/
function _checkNonPayable() private {
if (msg.value > 0) {
revert ERC1967NonPayable();
}
}
}
IBeacon.sol 16 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.20;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {UpgradeableBeacon} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
UUPSUpgradeable.sol 147 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.22;
import {IERC1822Proxiable} from "../../interfaces/draft-IERC1822.sol";
import {ERC1967Utils} from "../ERC1967/ERC1967Utils.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*/
abstract contract UUPSUpgradeable is IERC1822Proxiable {
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable
address private immutable __self = address(this);
/**
* @dev The version of the upgrade interface of the contract. If this getter is missing, both `upgradeTo(address)`
* and `upgradeToAndCall(address,bytes)` are present, and `upgradeTo` must be used if no function should be called,
* while `upgradeToAndCall` will invoke the `receive` function if the second argument is the empty byte string.
* If the getter returns `"5.0.0"`, only `upgradeToAndCall(address,bytes)` is present, and the second argument must
* be the empty byte string if no function should be called, making it impossible to invoke the `receive` function
* during an upgrade.
*/
string public constant UPGRADE_INTERFACE_VERSION = "5.0.0";
/**
* @dev The call is from an unauthorized context.
*/
error UUPSUnauthorizedCallContext();
/**
* @dev The storage `slot` is unsupported as a UUID.
*/
error UUPSUnsupportedProxiableUUID(bytes32 slot);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC-1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC-1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
_checkProxy();
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
_checkNotDelegated();
_;
}
/**
* @dev Implementation of the ERC-1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual notDelegated returns (bytes32) {
return ERC1967Utils.IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data);
}
/**
* @dev Reverts if the execution is not performed via delegatecall or the execution
* context is not of a proxy with an ERC-1967 compliant implementation pointing to self.
* See {_onlyProxy}.
*/
function _checkProxy() internal view virtual {
if (
address(this) == __self || // Must be called through delegatecall
ERC1967Utils.getImplementation() != __self // Must be called through an active proxy
) {
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Reverts if the execution is performed via delegatecall.
* See {notDelegated}.
*/
function _checkNotDelegated() internal view virtual {
if (address(this) != __self) {
// Must not be called through delegatecall
revert UUPSUnauthorizedCallContext();
}
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev Performs an implementation upgrade with a security check for UUPS proxies, and additional setup call.
*
* As a security check, {proxiableUUID} is invoked in the new implementation, and the return value
* is expected to be the implementation slot in ERC-1967.
*
* Emits an {IERC1967-Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data) private {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (bytes32 slot) {
if (slot != ERC1967Utils.IMPLEMENTATION_SLOT) {
revert UUPSUnsupportedProxiableUUID(slot);
}
ERC1967Utils.upgradeToAndCall(newImplementation, data);
} catch {
// The implementation is not UUPS
revert ERC1967Utils.ERC1967InvalidImplementation(newImplementation);
}
}
}
Address.sol 150 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (utils/Address.sol)
pragma solidity ^0.8.20;
import {Errors} from "./Errors.sol";
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert Errors.InsufficientBalance(address(this).balance, amount);
}
(bool success, bytes memory returndata) = recipient.call{value: amount}("");
if (!success) {
_revert(returndata);
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {Errors.FailedCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert Errors.InsufficientBalance(address(this).balance, value);
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {Errors.FailedCall}) in case
* of an unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {Errors.FailedCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {Errors.FailedCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly ("memory-safe") {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert Errors.FailedCall();
}
}
}
Errors.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Errors.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of common custom errors used in multiple contracts
*
* IMPORTANT: Backwards compatibility is not guaranteed in future versions of the library.
* It is recommended to avoid relying on the error API for critical functionality.
*
* _Available since v5.1._
*/
library Errors {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error InsufficientBalance(uint256 balance, uint256 needed);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedCall();
/**
* @dev The deployment failed.
*/
error FailedDeployment();
/**
* @dev A necessary precompile is missing.
*/
error MissingPrecompile(address);
}
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)
}
}
}
StorageSlot.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.20;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC-1967 implementation slot:
* ```solidity
* contract ERC1967 {
* // Define the slot. Alternatively, use the SlotDerivation library to derive the slot.
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(newImplementation.code.length > 0);
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* TIP: Consider using this library along with {SlotDerivation}.
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct Int256Slot {
int256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `Int256Slot` with member `value` located at `slot`.
*/
function getInt256Slot(bytes32 slot) internal pure returns (Int256Slot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns a `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
/**
* @dev Returns a `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
assembly ("memory-safe") {
r.slot := store.slot
}
}
}
Strings.sol 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)))
}
}
}
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);
}
}
}
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)
}
}
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Math.sol 685 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
SafeCast.sol 1162 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
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);
}
}
}
Errors.sol 65 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/// @title Shared Errors
/// @notice Common error definitions used across multiple contracts
library Errors {
// Generic errors (deprecated - use specific errors below)
error InvalidAddress();
error TransferFailed();
error InvalidAmount();
error InsufficientBalance();
error ArrayLengthMismatch();
error Unauthorized();
// Specific amount errors
error WithdrawAmountZero();
error WithdrawAmountExceedsTreasury();
error CommitAmountZero();
error CommitAmountTooLowForFlatFee();
error PackPriceBelowMinimum();
error PackPriceAboveMaximum();
error PayoutExceedsOrderAmount();
error OrderAmountBelowBucketMin();
error OrderAmountAboveBucketMax();
error PayoutAmountBelowBucketMin();
error PayoutAmountAboveBucketMax();
// Specific balance errors
error InsufficientTreasuryBalance();
// Specific address errors
error CosignerAddressZero();
error NotActiveCosigner();
error ReceiverAddressZero();
error CosignerAddressZeroInCommit();
error CosignerNotActive();
error PackSignerMismatch();
error PackSignerNotCosigner();
error MarketplaceAddressZero();
error CommitSignerMismatch();
error CommitSignerNotCosigner();
error FulfillmentSignerMismatch();
error FulfillmentSignerNotCosigner();
error FundsReceiverAddressZero();
// Specific authorization errors
error OnlyCosignerCanFulfill();
// Packs contract-specific errors
error AlreadyCosigner();
error AlreadyFulfilled();
error InvalidCommitOwner();
error InvalidBuckets();
error InvalidReward();
error InvalidPackPrice();
error InvalidCommitId();
error WithdrawalFailed();
error InvalidCommitCancellableTime();
error InvalidNftFulfillmentExpiryTime();
error CommitIsCancelled();
error CommitNotCancellable();
error InvalidFundsReceiverManager();
error BucketSelectionFailed();
error InvalidProtocolFee();
}
MEAccessControlUpgradeable.sol 126 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
/**
* @title MEAccessControlUpgradeable
* @dev Contract that inherits from OpenZeppelin's AccessControlUpgradeable and exposes role management
* functions at the top level for improved developer experience.
*/
contract MEAccessControlUpgradeable is AccessControlUpgradeable {
bytes32 public constant OPS_ROLE = keccak256("OPS_ROLE");
bytes32 public constant RESCUE_ROLE = keccak256("RESCUE_ROLE");
error InvalidOwner();
function __MEAccessControl_init() internal {
__AccessControl_init();
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
_grantRole(OPS_ROLE, msg.sender);
_grantRole(RESCUE_ROLE, msg.sender);
}
/// @notice Transfers admin rights to a new address. Admin functions are intentionally not paused
/// @param newAdmin Address of the new admin
function transferAdmin(
address newAdmin
) public onlyRole(DEFAULT_ADMIN_ROLE) {
if (newAdmin == address(0)) revert InvalidOwner();
// Grant new admin the default admin role
_grantRole(DEFAULT_ADMIN_ROLE, newAdmin);
_grantRole(OPS_ROLE, newAdmin);
// Revoke old admin's roles
_revokeRole(DEFAULT_ADMIN_ROLE, msg.sender);
_revokeRole(OPS_ROLE, msg.sender);
}
/// @notice Adds a new operations user
/// @param user Address to grant operations role to
function addOpsUser(address user) public onlyRole(DEFAULT_ADMIN_ROLE) {
_grantRole(OPS_ROLE, user);
}
/// @notice Removes an operations user
/// @param user Address to revoke operations role from
function removeOpsUser(address user) public onlyRole(DEFAULT_ADMIN_ROLE) {
_revokeRole(OPS_ROLE, user);
}
/// @notice Adds a new rescue user
/// @param user Address to grant rescue role to
function addRescueUser(address user) public onlyRole(DEFAULT_ADMIN_ROLE) {
_grantRole(RESCUE_ROLE, user);
}
/// @notice Removes a rescue user
/// @param user Address to revoke rescue role from
function removeRescueUser(
address user
) public onlyRole(DEFAULT_ADMIN_ROLE) {
_revokeRole(RESCUE_ROLE, user);
}
/**
* @notice Explicitly re-expose the inherited functions to make them more discoverable
* in developer tools and documentation.
*/
// Just uncomment any methods you want to make obviously available:
/**
* @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 Makes `hasRole` visible at the top level of our contract.
* @param role The role to check
* @param account The account to check the role for
* @return bool True if account has the role
*/
// function hasRole(bytes32 role, address account) public view override returns (bool) {
// return super.hasRole(role, account);
// }
/**
* @dev Makes `getRoleAdmin` visible at the top level of our contract.
* @param role The role to get the admin role for
* @return bytes32 The admin role
*/
// function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
// return super.getRoleAdmin(role);
// }
/**
* @dev Makes `grantRole` visible at the top level of our contract.
* @param role The role to grant
* @param account The account to grant the role to
*/
// function grantRole(bytes32 role, address account) public override {
// super.grantRole(role, account);
// }
/**
* @dev Makes `revokeRole` visible at the top level of our contract.
* @param role The role to revoke
* @param account The account to revoke the role from
*/
// function revokeRole(bytes32 role, address account) public override {
// super.revokeRole(role, account);
// }
/**
* @dev Makes `renounceRole` visible at the top level of our contract.
* @param role The role to renounce
* @param callerConfirmation The confirmation address (must be the sender)
*/
// function renounceRole(bytes32 role, address callerConfirmation) public override {
// super.renounceRole(role, callerConfirmation);
// }
}
AbstractSignatureVerifierUpgradeable.sol 30 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
abstract contract AbstractSignatureVerifierUpgradeable is EIP712Upgradeable {
using ECDSA for bytes32;
function __AbstractSignatureVerifier_init(
string memory name,
string memory version
) internal onlyInitializing {
__EIP712_init(name, version);
}
function _verify(
bytes32 digest,
bytes memory signature
) internal view virtual returns (address) {
return ECDSA.recover(digest, signature);
}
function verify(
bytes32 digest,
bytes memory signature
) public view virtual returns (address) {
return _verify(digest, signature);
}
}
PacksSignatureVerifierUpgradeable.sol 142 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "./AbstractSignatureVerifierUpgradeable.sol";
contract PacksSignatureVerifierUpgradeable is
AbstractSignatureVerifierUpgradeable
{
struct BucketData {
uint256 oddsBps;
uint256 minValue;
uint256 maxValue;
}
struct CommitData {
uint256 id;
address receiver;
address cosigner;
uint256 seed;
uint256 counter;
uint256 packPrice;
BucketData[] buckets;
bytes32 packHash;
}
enum PackType {
NFT,
RWA
}
enum FulfillmentOption {
NFT,
Payout
}
bytes32 private constant _TYPE_HASH =
keccak256(
"CommitData(uint256 id,address receiver,address cosigner,uint256 seed,uint256 counter,uint256 packPrice,BucketData[] buckets,bytes32 packHash)"
);
function __PacksSignatureVerifier_init(
string memory name,
string memory version
) internal onlyInitializing {
__AbstractSignatureVerifier_init(name, version);
}
/// @notice Hashes a commit
/// @param commit Commit to hash
/// @return Hash of the commit
function hashCommit(CommitData memory commit) public view returns (bytes32) {
return _hashCommit(commit);
}
/// @dev Internal function to hash a commit
/// @param commit Commit to hash
/// @return Hash of the commit
function _hashCommit(CommitData memory commit) internal view returns (bytes32) {
return _hashTypedDataV4(
keccak256(
abi.encode(
keccak256(
"CommitData(uint256 id,address receiver,address cosigner,uint256 seed,uint256 counter,uint256 packPrice,BucketData[] buckets,bytes32 packHash)"
),
commit.id,
commit.receiver,
commit.cosigner,
commit.seed,
commit.counter,
commit.packPrice,
commit.buckets,
commit.packHash
)
)
);
}
/// @notice Hashes a pack commit
/// @param packType Pack type
/// @param packPrice Pack price in ether
/// @param buckets Buckets used in the pack
/// @return Hash of the pack
function hashPack(PackType packType, uint256 packPrice, BucketData[] memory buckets) public pure returns (bytes32) {
return keccak256(abi.encode(packType, packPrice, buckets));
}
/// @notice Hashes a fulfillment
/// @param digest The commit digest
/// @param marketplace Marketplace address
/// @param orderAmount Order amount
/// @param orderData Order data
/// @param token Token address
/// @param tokenId Token id
/// @param payoutAmount ETH value on payout
/// @param choice The receiver's choice
/// @return Hash of the fulfillment
function hashFulfillment(
bytes32 digest,
address marketplace,
uint256 orderAmount,
bytes memory orderData,
address token,
uint256 tokenId,
uint256 payoutAmount,
FulfillmentOption choice
) public pure returns (bytes32) {
return keccak256(abi.encode(digest, marketplace, orderAmount, orderData, token, tokenId, payoutAmount, choice));
}
/// @notice Verifies the signature for a given Commit, returning the address of the signer.
/// @dev Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs.
/// @param commit A commit.
/// @param signature An EIP712 signature of the given commit.
function verifyCommit(CommitData memory commit, bytes memory signature) public view returns (address) {
return _verifyCommit(commit, signature);
}
/// @dev Internal function to verify a commit
/// @param commit Commit to verify
/// @param signature Signature to verify
/// @return Address of the signer
function _verifyCommit(CommitData memory commit, bytes memory signature) internal view returns (address) {
bytes32 digest = _hashCommit(commit);
return _verifyHash(digest, signature);
}
/// @notice Verifies the signature for a given hash, returning the address of the signer.
/// @dev Will revert if the signature is invalid. Does not verify that the signer is authorized to mint NFTs.
/// @param hash A hash.
/// @param signature An EIP712 signature of the given hash.
function verifyHash(bytes32 hash, bytes memory signature) public pure returns (address) {
return _verifyHash(hash, signature);
}
/// @dev Internal function to verify a hash
/// @param hash Hash to verify
/// @param signature Signature to verify
/// @return Address of the signer
function _verifyHash(bytes32 hash, bytes memory signature) internal pure returns (address) {
return ECDSA.recover(hash, signature);
}
}
TokenRescuer.sol 151 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;
import {IERC20} from "forge-std/interfaces/IERC20.sol";
import {IERC721} from "forge-std/interfaces/IERC721.sol";
import {IERC1155} from "forge-std/interfaces/IERC1155.sol";
import {Errors} from "./Errors.sol";
abstract contract TokenRescuer {
event ERC20BatchRescued(address[] tokens, address[] to, uint256[] amounts);
event ERC721BatchRescued(
address[] tokens,
address[] to,
uint256[] tokenIds
);
event ERC1155BatchRescued(
address[] tokens,
address[] to,
uint256[] tokenIds,
uint256[] amounts
);
event ETHRescued(address to, uint256 amount);
/**
* @notice Rescues multiple ERC20 tokens from the contract
* @param tokens The addresses of the ERC20 tokens to rescue
* @param to The addresses to send the tokens to
* @param amounts The amounts of tokens to rescue
*/
function _rescueERC20Batch(
address[] memory tokens,
address[] memory to,
uint256[] memory amounts
) internal {
if (tokens.length == 0)
revert Errors.InvalidAmount();
if (tokens.length != to.length || tokens.length != amounts.length)
revert Errors.ArrayLengthMismatch();
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i] == address(0)) revert Errors.InvalidAddress();
if (to[i] == address(0)) revert Errors.InvalidAddress();
if (amounts[i] == 0)
revert Errors.InvalidAmount();
uint256 balance = IERC20(tokens[i]).balanceOf(address(this));
if (balance < amounts[i]) revert Errors.InsufficientBalance();
if (!IERC20(tokens[i]).transfer(to[i], amounts[i]))
revert Errors.TransferFailed();
}
emit ERC20BatchRescued(tokens, to, amounts);
}
/**
* @notice Rescues multiple ERC721 tokens from the contract
* @param tokens The addresses of the ERC721 tokens to rescue
* @param to The addresses to send the tokens to
* @param tokenIds The IDs of the tokens to rescue
*/
function _rescueERC721Batch(
address[] memory tokens,
address[] memory to,
uint256[] memory tokenIds
) internal {
if (tokens.length == 0)
revert Errors.InvalidAmount();
if (tokens.length != to.length || tokens.length != tokenIds.length)
revert Errors.ArrayLengthMismatch();
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i] == address(0)) revert Errors.InvalidAddress();
if (to[i] == address(0)) revert Errors.InvalidAddress();
IERC721(tokens[i]).safeTransferFrom(
address(this),
to[i],
tokenIds[i]
);
}
emit ERC721BatchRescued(tokens, to, tokenIds);
}
/**
* @notice Rescues multiple ERC1155 tokens from the contract
* @param tokens The addresses of the ERC1155 tokens to rescue
* @param to The addresses to send the tokens to
* @param tokenIds The IDs of the tokens to rescue
* @param amounts The amounts of each token to rescue
*/
function _rescueERC1155Batch(
address[] memory tokens,
address[] memory to,
uint256[] memory tokenIds,
uint256[] memory amounts
) internal {
if (tokens.length == 0)
revert Errors.InvalidAmount();
if (
tokens.length != to.length ||
tokens.length != tokenIds.length ||
tokens.length != amounts.length
) revert Errors.ArrayLengthMismatch();
for (uint256 i = 0; i < tokens.length; i++) {
if (tokens[i] == address(0)) revert Errors.InvalidAddress();
if (to[i] == address(0)) revert Errors.InvalidAddress();
if (amounts[i] == 0)
revert Errors.InvalidAmount();
// Balance check for ERC1155
uint256 balance = IERC1155(tokens[i]).balanceOf(
address(this),
tokenIds[i]
);
if (balance < amounts[i]) revert Errors.InsufficientBalance();
uint256[] memory singleTokenId = new uint256[](1);
uint256[] memory singleAmount = new uint256[](1);
singleTokenId[0] = tokenIds[i];
singleAmount[0] = amounts[i];
IERC1155(tokens[i]).safeBatchTransferFrom(
address(this),
to[i],
singleTokenId,
singleAmount,
""
);
}
emit ERC1155BatchRescued(tokens, to, tokenIds, amounts);
}
/**
* @notice Rescues ETH from the contract
* @param to The address to send the ETH to
* @param amount The amount of ETH to rescue
*/
function _rescueETH(address to, uint256 amount) internal {
if (to == address(0)) revert Errors.InvalidAddress();
if (amount == 0) revert Errors.InvalidAmount();
if (address(this).balance < amount)
revert Errors.InsufficientBalance();
(bool success, ) = to.call{value: amount}("");
if (!success) revert Errors.TransferFailed();
emit ETHRescued(to, amount);
}
}
IPRNG.sol 17 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
/// @title IPRNG
/// @notice Interface for the PRNG contract that provides pseudo-random number generation
interface IPRNG {
/// @notice Base points for percentage calculations (100.00%)
function BASE_POINTS() external view returns (uint256);
/// @notice Maximum CRC32 hash value adjusted to prevent modulo bias
function MAX_CRC32_HASH_VALUE() external view returns (uint32);
/// @notice Generates a pseudo-random number between 0 and BASE_POINTS
/// @param signature The input signature bytes to use as entropy source
/// @return A pseudo-random number between 0 and BASE_POINTS (0-10000)
function rng(bytes calldata signature) external view returns (uint32);
}
Packs.sol 229 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {Errors} from "../common/Errors.sol";
import "./base/PacksCommit.sol";
import "./base/PacksFulfill.sol";
import "./base/PacksAdmin.sol";
contract Packs is
PacksAdmin,
PacksCommit,
PacksFulfill
{
// ============================================================
// MODIFIERS
// ============================================================
modifier onlyCommitOwnerOrCosigner(uint256 commitId_) {
if (packs[commitId_].receiver != msg.sender && packs[commitId_].cosigner != msg.sender) {
revert Errors.InvalidCommitOwner();
}
_;
}
// ============================================================
// CONSTRUCTOR
// ============================================================
constructor(uint256 protocolFee_,uint256 flatFee_,address fundsReceiver_, address prng_, address fundsReceiverManager_) initializer {
__MEAccessControl_init();
__Pausable_init();
__PacksSignatureVerifier_init("Packs", "1");
__ReentrancyGuard_init();
uint256 existingBalance = address(this).balance;
if (existingBalance > 0) {
_depositTreasury(existingBalance);
}
_setProtocolFee(protocolFee_);
_setFlatFee(flatFee_);
_setFundsReceiver(fundsReceiver_);
PRNG = IPRNG(prng_);
_grantRole(FUNDS_RECEIVER_MANAGER_ROLE, fundsReceiverManager_);
// Initialize reward limits
minReward = 0.01 ether;
maxReward = 5 ether;
minPackPrice = 0.01 ether;
maxPackPrice = 0.25 ether;
// Initialize expiries
commitCancellableTime = 1 hours;
nftFulfillmentExpiryTime = 10 minutes;
}
// ============================================================
// CORE BUSINESS LOGIC
// ============================================================
function commit(
address receiver_,
address cosigner_,
uint256 seed_,
PackType packType_,
BucketData[] memory buckets_,
bytes memory signature_
) external payable whenNotPaused returns (uint256) {
return _commit(receiver_, cosigner_, seed_, packType_, buckets_, signature_);
}
function fulfill(
uint256 commitId_,
address marketplace_,
bytes calldata orderData_,
uint256 orderAmount_,
address token_,
uint256 tokenId_,
uint256 payoutAmount_,
bytes calldata commitSignature_,
bytes calldata fulfillmentSignature_,
FulfillmentOption choice_
) public payable whenNotPaused {
_fulfill(
commitId_,
marketplace_,
orderData_,
orderAmount_,
token_,
tokenId_,
payoutAmount_,
commitSignature_,
fulfillmentSignature_,
choice_
);
}
function fulfillByDigest(
bytes32 commitDigest_,
address marketplace_,
bytes calldata orderData_,
uint256 orderAmount_,
address token_,
uint256 tokenId_,
uint256 payoutAmount_,
bytes calldata commitSignature_,
bytes calldata fulfillmentSignature_,
FulfillmentOption choice_
) external payable whenNotPaused {
return fulfill(
commitIdByDigest[commitDigest_],
marketplace_,
orderData_,
orderAmount_,
token_,
tokenId_,
payoutAmount_,
commitSignature_,
fulfillmentSignature_,
choice_
);
}
function cancel(uint256 commitId_) external nonReentrant onlyCommitOwnerOrCosigner(commitId_) {
_cancel(commitId_);
}
// ============================================================
// TREASURY MANAGEMENT
// ============================================================
function withdrawTreasury(uint256 amount) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
_withdrawTreasury(amount);
}
function emergencyWithdraw() external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) {
_emergencyWithdraw();
}
receive() external payable {
_depositTreasury(msg.value);
}
// ============================================================
// ADMIN CONFIGURATION
// ============================================================
function addCosigner(address cosigner_) external onlyRole(DEFAULT_ADMIN_ROLE) {
_addCosigner(cosigner_);
}
function removeCosigner(address cosigner_) external onlyRole(DEFAULT_ADMIN_ROLE) {
_removeCosigner(cosigner_);
}
function setCommitCancellableTime(uint256 commitCancellableTime_) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateCommitCancellableTime(commitCancellableTime_);
}
function setNftFulfillmentExpiryTime(uint256 nftFulfillmentExpiryTime_) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateNftFulfillmentExpiryTime(nftFulfillmentExpiryTime_);
}
function setMinReward(uint256 minReward_) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateMinReward(minReward_);
}
function setMaxReward(uint256 maxReward_) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateMaxReward(maxReward_);
}
function setMinPackPrice(uint256 minPackPrice_) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateMinPackPrice(minPackPrice_);
}
function setMaxPackPrice(uint256 maxPackPrice_) external onlyRole(DEFAULT_ADMIN_ROLE) {
_updateMaxPackPrice(maxPackPrice_);
}
function setProtocolFee(uint256 protocolFee_) external onlyRole(OPS_ROLE) {
_setProtocolFee(protocolFee_);
}
function setFlatFee(uint256 flatFee_) external onlyRole(OPS_ROLE) {
_setFlatFee(flatFee_);
}
function setFundsReceiver(address fundsReceiver_) external onlyRole(FUNDS_RECEIVER_MANAGER_ROLE) {
_setFundsReceiver(fundsReceiver_);
}
function transferFundsReceiverManager(address newFundsReceiverManager_)
external
onlyRole(FUNDS_RECEIVER_MANAGER_ROLE)
{
if (newFundsReceiverManager_ == address(0)) {
revert Errors.InvalidFundsReceiverManager();
}
_transferFundsReceiverManager(newFundsReceiverManager_);
}
function pause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_pause();
}
function unpause() external onlyRole(DEFAULT_ADMIN_ROLE) {
_unpause();
}
// ============================================================
// VIEW FUNCTIONS & UTILITIES
// ============================================================
function getPacksLength() external view returns (uint256) {
return packs.length;
}
// ============================================================
// INTERNAL OVERRIDES
// ============================================================
function _transferFundsReceiverManager(address newFundsReceiverManager_) internal override {
_revokeRole(FUNDS_RECEIVER_MANAGER_ROLE, msg.sender);
_grantRole(FUNDS_RECEIVER_MANAGER_ROLE, newFundsReceiverManager_);
emit FundsReceiverManagerTransferred(msg.sender, newFundsReceiverManager_);
}
}
PacksInitializable.sol 69 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {Packs} from "./Packs.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts/proxy/utils/UUPSUpgradeable.sol";
import {IPRNG} from "../common/interfaces/IPRNG.sol";
contract PacksInitializable is Packs, UUPSUpgradeable {
error InvalidZeroAddress();
/// @dev Disables initializers for the implementation contract.
constructor() Packs(0, 0, address(0x2), address(0x3), address(0x4)) {
_disableInitializers();
}
/// @notice Initializes the contract and handles any pre-existing balance
/// @dev Sets up EIP712 domain separator and deposits any ETH sent during deployment
function initialize(
uint256 protocolFee_,
uint256 flatFee_,
address initialOwner_,
address fundsReceiver_,
address prng_,
address fundsReceiverManager_
) public initializer {
if (initialOwner_ == address(0)) revert InvalidZeroAddress();
__ReentrancyGuard_init();
__MEAccessControl_init();
__Pausable_init();
__PacksSignatureVerifier_init("Packs", "1");
uint256 existingBalance = address(this).balance;
if (existingBalance > 0) {
_depositTreasury(existingBalance);
}
_setProtocolFee(protocolFee_);
_setFlatFee(flatFee_);
_setFundsReceiver(fundsReceiver_);
PRNG = IPRNG(prng_);
_grantRole(FUNDS_RECEIVER_MANAGER_ROLE, fundsReceiverManager_);
// Initialize reward limits
minReward = 0.01 ether;
maxReward = 5 ether;
minPackPrice = 0.01 ether;
maxPackPrice = 0.25 ether;
// Initialize expiries
commitCancellableTime = 1 days;
nftFulfillmentExpiryTime = 10 minutes;
// Grant roles to initial owner
_grantRole(DEFAULT_ADMIN_ROLE, initialOwner_);
_grantRole(OPS_ROLE, initialOwner_);
_grantRole(RESCUE_ROLE, initialOwner_);
}
/// @dev Overriden to prevent unauthorized upgrades.
function _authorizeUpgrade(
address newImplementation
) internal override onlyRole(DEFAULT_ADMIN_ROLE) {
if (newImplementation == address(0))
revert InvalidZeroAddress();
}
}
PacksAdmin.sol 238 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "./PacksStorage.sol";
import {MEAccessControlUpgradeable} from "../../common/MEAccessControlUpgradeable.sol";
import {ReentrancyGuardUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import {PausableUpgradeable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import {Errors} from "../../common/Errors.sol";
import {TokenRescuer} from "../../common/TokenRescuer.sol";
/// @title PacksAdmin
/// @notice Handles admin configuration, treasury management, pause controls, and token rescue for Packs contract
/// @dev Abstract contract with admin helpers - storage accessed from PacksStorage
abstract contract PacksAdmin is MEAccessControlUpgradeable, ReentrancyGuardUpgradeable, PausableUpgradeable, PacksStorage, TokenRescuer {
// ============================================================
// EVENTS
// ============================================================
event CosignerAdded(address indexed cosigner);
event CosignerRemoved(address indexed cosigner);
event MaxRewardUpdated(uint256 oldMaxReward, uint256 newMaxReward);
event MaxPackPriceUpdated(uint256 oldMaxPackPrice, uint256 newMaxPackPrice);
event MinRewardUpdated(uint256 oldMinReward, uint256 newMinReward);
event MinPackPriceUpdated(uint256 oldMinPackPrice, uint256 newMinPackPrice);
event CommitCancellableTimeUpdated(uint256 oldCommitCancellableTime, uint256 newCommitCancellableTime);
event NftFulfillmentExpiryTimeUpdated(uint256 oldNftFulfillmentExpiryTime, uint256 newNftFulfillmentExpiryTime);
event FundsReceiverUpdated(address indexed oldFundsReceiver, address indexed newFundsReceiver);
event FundsReceiverManagerTransferred(
address indexed oldFundsReceiverManager, address indexed newFundsReceiverManager
);
event ProtocolFeeUpdated(uint256 oldProtocolFee, uint256 newProtocolFee);
event FlatFeeUpdated(uint256 oldFlatFee, uint256 newFlatFee);
event TreasuryWithdrawal(address indexed sender, uint256 amount, address fundsReceiver);
event EmergencyWithdrawal(address indexed sender, uint256 amount, address fundsReceiver);
// ============================================================
// ADMIN CONFIGURATION
// ============================================================
// ---------- Cosigner Management ----------
function _addCosigner(address cosigner_) internal {
if (cosigner_ == address(0)) revert Errors.CosignerAddressZero();
if (isCosigner[cosigner_]) revert Errors.AlreadyCosigner();
isCosigner[cosigner_] = true;
emit CosignerAdded(cosigner_);
}
function _removeCosigner(address cosigner_) internal {
if (!isCosigner[cosigner_]) revert Errors.NotActiveCosigner();
isCosigner[cosigner_] = false;
emit CosignerRemoved(cosigner_);
}
// ---------- Time Parameters ----------
function _updateCommitCancellableTime(uint256 commitCancellableTime_) internal {
if (commitCancellableTime_ < MIN_COMMIT_CANCELLABLE_TIME) {
revert Errors.InvalidCommitCancellableTime();
}
uint256 oldCommitCancellableTime = commitCancellableTime;
commitCancellableTime = commitCancellableTime_;
emit CommitCancellableTimeUpdated(oldCommitCancellableTime, commitCancellableTime_);
}
function _updateNftFulfillmentExpiryTime(uint256 nftFulfillmentExpiryTime_) internal {
if (nftFulfillmentExpiryTime_ < MIN_NFT_FULFILLMENT_EXPIRY_TIME) {
revert Errors.InvalidNftFulfillmentExpiryTime();
}
uint256 oldNftFulfillmentExpiryTime = nftFulfillmentExpiryTime;
nftFulfillmentExpiryTime = nftFulfillmentExpiryTime_;
emit NftFulfillmentExpiryTimeUpdated(oldNftFulfillmentExpiryTime, nftFulfillmentExpiryTime_);
}
// ---------- Reward Limits ----------
function _updateMinReward(uint256 minReward_) internal {
if (minReward_ == 0) revert Errors.InvalidReward();
if (minReward_ > maxReward) revert Errors.InvalidReward();
uint256 oldMinReward = minReward;
minReward = minReward_;
emit MinRewardUpdated(oldMinReward, minReward_);
}
function _updateMaxReward(uint256 maxReward_) internal {
if (maxReward_ == 0) revert Errors.InvalidReward();
if (maxReward_ < minReward) revert Errors.InvalidReward();
uint256 oldMaxReward = maxReward;
maxReward = maxReward_;
emit MaxRewardUpdated(oldMaxReward, maxReward_);
}
// ---------- Pack Price Limits ----------
function _updateMinPackPrice(uint256 minPackPrice_) internal {
if (minPackPrice_ == 0) revert Errors.InvalidPackPrice();
if (minPackPrice_ > maxPackPrice) revert Errors.InvalidPackPrice();
uint256 oldMinPackPrice = minPackPrice;
minPackPrice = minPackPrice_;
emit MinPackPriceUpdated(oldMinPackPrice, minPackPrice_);
}
function _updateMaxPackPrice(uint256 maxPackPrice_) internal {
if (maxPackPrice_ == 0) revert Errors.InvalidPackPrice();
if (maxPackPrice_ < minPackPrice) revert Errors.InvalidPackPrice();
uint256 oldMaxPackPrice = maxPackPrice;
maxPackPrice = maxPackPrice_;
emit MaxPackPriceUpdated(oldMaxPackPrice, maxPackPrice_);
}
// ---------- Fees ----------
function _setProtocolFee(uint256 protocolFee_) internal {
if (protocolFee_ > BASE_POINTS) revert Errors.InvalidProtocolFee();
uint256 oldProtocolFee = protocolFee;
protocolFee = protocolFee_;
emit ProtocolFeeUpdated(oldProtocolFee, protocolFee_);
}
function _setFlatFee(uint256 flatFee_) internal {
uint256 oldFlatFee = flatFee;
flatFee = flatFee_;
emit FlatFeeUpdated(oldFlatFee, flatFee_);
}
// ---------- Funds Receiver ----------
function _setFundsReceiver(address fundsReceiver_) internal virtual {
if (fundsReceiver_ == address(0)) revert Errors.FundsReceiverAddressZero();
if (hasRole(FUNDS_RECEIVER_MANAGER_ROLE, fundsReceiver_)) {
revert Errors.InvalidFundsReceiverManager();
}
address oldFundsReceiver = fundsReceiver;
fundsReceiver = payable(fundsReceiver_);
emit FundsReceiverUpdated(oldFundsReceiver, fundsReceiver_);
}
// ============================================================
// TREASURY LOGIC
// ============================================================
function _withdrawTreasury(uint256 amount) internal {
if (amount == 0) revert Errors.WithdrawAmountZero();
if (amount > treasuryBalance) revert Errors.WithdrawAmountExceedsTreasury();
treasuryBalance -= amount;
(bool success,) = payable(fundsReceiver).call{value: amount}("");
if (!success) revert Errors.WithdrawalFailed();
emit TreasuryWithdrawal(msg.sender, amount, fundsReceiver);
}
function _emergencyWithdraw() internal virtual {
treasuryBalance = 0;
commitBalance = 0;
protocolBalance = 0;
uint256 currentBalance = address(this).balance;
_rescueETH(fundsReceiver, currentBalance);
// Pause must be called by inheriting contract that has PausableUpgradeable
_pause();
emit EmergencyWithdrawal(msg.sender, currentBalance, fundsReceiver);
}
function _transferFundsReceiverManager(address newFundsReceiverManager_) internal virtual;
// ============================================================
// RESCUE FUNCTIONS (Token Recovery)
// ============================================================
function rescueERC20(address token, address to, uint256 amount) external {
_checkRole(RESCUE_ROLE, msg.sender);
address[] memory tokens = new address[](1);
address[] memory tos = new address[](1);
uint256[] memory amounts = new uint256[](1);
tokens[0] = token;
tos[0] = to;
amounts[0] = amount;
_rescueERC20Batch(tokens, tos, amounts);
}
function rescueERC721(address token, address to, uint256 tokenId) external {
_checkRole(RESCUE_ROLE, msg.sender);
address[] memory tokens = new address[](1);
address[] memory tos = new address[](1);
uint256[] memory tokenIds = new uint256[](1);
tokens[0] = token;
tos[0] = to;
tokenIds[0] = tokenId;
_rescueERC721Batch(tokens, tos, tokenIds);
}
function rescueERC1155(address token, address to, uint256 tokenId, uint256 amount) external {
_checkRole(RESCUE_ROLE, msg.sender);
address[] memory tokens = new address[](1);
address[] memory tos = new address[](1);
uint256[] memory tokenIds = new uint256[](1);
uint256[] memory amounts = new uint256[](1);
tokens[0] = token;
tos[0] = to;
tokenIds[0] = tokenId;
amounts[0] = amount;
_rescueERC1155Batch(tokens, tos, tokenIds, amounts);
}
function rescueERC20Batch(address[] calldata tokens, address[] calldata tos, uint256[] calldata amounts)
external
{
_checkRole(RESCUE_ROLE, msg.sender);
_rescueERC20Batch(tokens, tos, amounts);
}
function rescueERC721Batch(address[] calldata tokens, address[] calldata tos, uint256[] calldata tokenIds)
external
{
_checkRole(RESCUE_ROLE, msg.sender);
_rescueERC721Batch(tokens, tos, tokenIds);
}
function rescueERC1155Batch(
address[] calldata tokens,
address[] calldata tos,
uint256[] calldata tokenIds,
uint256[] calldata amounts
) external {
_checkRole(RESCUE_ROLE, msg.sender);
_rescueERC1155Batch(tokens, tos, tokenIds, amounts);
}
}
PacksCommit.sol 223 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "./PacksStorage.sol";
import {Errors} from "../../common/Errors.sol";
/// @title PacksCommit
/// @notice Handles commit flow logic for Packs contract
/// @dev Abstract contract with commit helpers - storage accessed from PacksStorage
abstract contract PacksCommit is PacksStorage {
// ============================================================
// EVENTS
// ============================================================
event Commit(
address indexed sender,
uint256 indexed commitId,
address indexed receiver,
address cosigner,
uint256 seed,
uint256 counter,
uint256 packPrice,
bytes32 packHash,
bytes32 digest,
uint256 protocolFee,
uint256 flatFee
);
event CommitCancelled(uint256 indexed commitId, bytes32 digest);
event CancellationRefundFailed(uint256 indexed commitId, address indexed receiver, uint256 amount, bytes32 digest);
// ============================================================
// COMMIT LOGIC
// ============================================================
/// @notice Calculate contribution amount with custom fee rate
function calculateContributionWithoutFee(
uint256 amount,
uint256 feeRate
) public pure returns (uint256) {
return (amount * BASE_POINTS) / (BASE_POINTS + feeRate);
}
function _commit(
address receiver_,
address cosigner_,
uint256 seed_,
PackType packType_,
BucketData[] memory buckets_,
bytes memory signature_
) internal returns (uint256) {
uint256 packPrice = _validateAndCalculatePackPrice(msg.value);
_validateCommitAddresses(receiver_, cosigner_);
_validateBuckets(buckets_, packPrice);
bytes32 packHash = _verifyPackSignature(packType_, packPrice, buckets_, signature_, cosigner_);
uint256 commitId = _createCommit(receiver_, cosigner_, seed_, packPrice, buckets_, packHash);
_processCommitFees(commitId, packPrice);
_setCommitExpiryTimes(commitId);
bytes32 digest = hashCommit(packs[commitId]);
commitIdByDigest[digest] = commitId;
emit Commit(
msg.sender, commitId, receiver_, cosigner_, seed_,
packs[commitId].counter, packPrice, packHash, digest,
feesPaid[commitId], flatFee
);
return commitId;
}
function _validateAndCalculatePackPrice(uint256 totalAmount) internal view returns (uint256) {
if (totalAmount == 0) revert Errors.CommitAmountZero();
if (totalAmount <= flatFee) revert Errors.CommitAmountTooLowForFlatFee();
uint256 packPrice = calculateContributionWithoutFee(totalAmount, protocolFee) - flatFee;
if (packPrice < minPackPrice) revert Errors.PackPriceBelowMinimum();
if (packPrice > maxPackPrice) revert Errors.PackPriceAboveMaximum();
return packPrice;
}
function _validateCommitAddresses(address receiver_, address cosigner_) internal view {
if (receiver_ == address(0)) revert Errors.ReceiverAddressZero();
if (cosigner_ == address(0)) revert Errors.CosignerAddressZeroInCommit();
if (!isCosigner[cosigner_]) revert Errors.CosignerNotActive();
}
function _validateBuckets(BucketData[] memory buckets_, uint256 packPrice) internal view {
if (buckets_.length < MIN_BUCKETS) revert Errors.InvalidBuckets();
if (buckets_.length > MAX_BUCKETS) revert Errors.InvalidBuckets();
uint256 totalOdds = 0;
for (uint256 i = 0; i < buckets_.length; i++) {
_validateBucketValues(buckets_[i], packPrice);
_validateBucketOdds(buckets_[i]);
if (i < buckets_.length - 1 && buckets_[i].maxValue > buckets_[i + 1].minValue) {
revert Errors.InvalidBuckets();
}
totalOdds += buckets_[i].oddsBps;
}
if (totalOdds != BASE_POINTS) revert Errors.InvalidBuckets();
}
function _validateBucketValues(BucketData memory bucket, uint256 packPrice) internal view {
if (bucket.minValue == 0) revert Errors.InvalidReward();
if (bucket.maxValue == 0) revert Errors.InvalidReward();
if (bucket.minValue > bucket.maxValue) revert Errors.InvalidReward();
if (bucket.minValue < minReward) revert Errors.InvalidReward();
if (bucket.maxValue > maxReward) revert Errors.InvalidReward();
}
function _validateBucketOdds(BucketData memory bucket) internal pure {
if (bucket.oddsBps == 0) revert Errors.InvalidBuckets();
if (bucket.oddsBps > 10000) revert Errors.InvalidBuckets();
}
function _verifyPackSignature(
PackType packType_,
uint256 packPrice,
BucketData[] memory buckets_,
bytes memory signature_,
address expectedCosigner
) internal view returns (bytes32) {
bytes32 packHash = hashPack(packType_, packPrice, buckets_);
address signer = verifyHash(packHash, signature_);
if (signer != expectedCosigner) revert Errors.PackSignerMismatch();
if (!isCosigner[signer]) revert Errors.PackSignerNotCosigner();
return packHash;
}
function _createCommit(
address receiver_,
address cosigner_,
uint256 seed_,
uint256 packPrice,
BucketData[] memory buckets_,
bytes32 packHash
) internal returns (uint256) {
uint256 commitId = packs.length;
uint256 userCounter = packCount[receiver_]++;
packs.push(CommitData({
id: commitId,
receiver: receiver_,
cosigner: cosigner_,
seed: seed_,
counter: userCounter,
packPrice: packPrice,
buckets: buckets_,
packHash: packHash
}));
return commitId;
}
function _processCommitFees(uint256 commitId, uint256 packPrice) internal {
feesPaid[commitId] = msg.value - packPrice;
protocolBalance += feesPaid[commitId];
_handleFlatFeePayment();
commitBalance += packPrice;
}
function _setCommitExpiryTimes(uint256 commitId) internal {
commitCancellableAt[commitId] = block.timestamp + commitCancellableTime;
nftFulfillmentExpiresAt[commitId] = block.timestamp + nftFulfillmentExpiryTime;
}
function _handleFlatFeePayment() internal {
if (flatFee > 0 && fundsReceiver != address(0)) {
(bool success, ) = fundsReceiver.call{value: flatFee}("");
if (!success) {
treasuryBalance += flatFee;
}
} else if (flatFee > 0) {
treasuryBalance += flatFee;
}
}
// ============================================================
// CANCEL LOGIC
// ============================================================
function _cancel(uint256 commitId_) internal {
_validateCancellationRequest(commitId_);
isCancelled[commitId_] = true;
CommitData memory commitData = packs[commitId_];
uint256 totalRefund = _calculateAndUpdateRefund(commitId_, commitData.packPrice);
_processRefund(commitId_, commitData.receiver, totalRefund, commitData);
emit CommitCancelled(commitId_, hashCommit(commitData));
}
function _validateCancellationRequest(uint256 commitId_) internal view {
if (commitId_ >= packs.length) revert Errors.InvalidCommitId();
if (isFulfilled[commitId_]) revert Errors.AlreadyFulfilled();
if (isCancelled[commitId_]) revert Errors.CommitIsCancelled();
if (block.timestamp < commitCancellableAt[commitId_]) {
revert Errors.CommitNotCancellable();
}
}
function _calculateAndUpdateRefund(uint256 commitId_, uint256 packPrice) internal returns (uint256 totalRefund) {
commitBalance -= packPrice;
uint256 protocolFeesPaid = feesPaid[commitId_];
protocolBalance -= protocolFeesPaid;
totalRefund = packPrice + protocolFeesPaid;
}
function _processRefund(uint256 commitId_, address receiver, uint256 amount, CommitData memory commitData) internal {
(bool success,) = payable(receiver).call{value: amount}("");
if (!success) {
treasuryBalance += amount;
emit CancellationRefundFailed(commitId_, receiver, amount, hashCommit(commitData));
}
}
}
PacksFulfill.sol 241 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import "./PacksStorage.sol";
import {Errors} from "../../common/Errors.sol";
/// @title PacksFulfill
/// @notice Handles fulfillment flow logic for Packs contract
/// @dev Abstract contract with fulfillment helpers - storage accessed from PacksStorage
abstract contract PacksFulfill is PacksStorage {
// ============================================================
// EVENTS
// ============================================================
event Fulfillment(
address indexed sender,
uint256 indexed commitId,
uint256 rng,
uint256 odds,
uint256 bucketIndex,
uint256 payout,
address token,
uint256 tokenId,
uint256 amount,
address receiver,
FulfillmentOption choice,
FulfillmentOption fulfillmentType,
bytes32 digest
);
event FulfillmentPayoutFailed(uint256 indexed commitId, address indexed receiver, uint256 amount, bytes32 digest);
event TreasuryDeposit(address indexed sender, uint256 amount);
// ============================================================
// FULFILLMENT LOGIC
// ============================================================
function _fulfill(
uint256 commitId_,
address marketplace_,
bytes calldata orderData_,
uint256 orderAmount_,
address token_,
uint256 tokenId_,
uint256 payoutAmount_,
bytes calldata commitSignature_,
bytes calldata fulfillmentSignature_,
FulfillmentOption choice_
) internal {
CommitData memory commitData = _validateFulfillmentRequest(commitId_, marketplace_, orderAmount_, payoutAmount_);
(uint256 rng, bytes32 digest) = _verifyFulfillmentSignatures(
commitData, commitSignature_, fulfillmentSignature_, marketplace_,
orderData_, orderAmount_, token_, tokenId_, payoutAmount_, choice_
);
(uint256 bucketIndex, BucketData memory bucket) = _determineOutcomeAndValidate(
rng, commitData.buckets, orderAmount_, payoutAmount_
);
FulfillmentOption fulfillmentType = _determineFulfillmentType(commitId_, choice_);
_markFulfilledAndUpdateBalances(commitId_, commitData.packPrice);
_executeFulfillment(
commitId_, commitData, marketplace_, orderData_, orderAmount_,
token_, tokenId_, payoutAmount_, rng, bucket, bucketIndex,
choice_, fulfillmentType, digest
);
}
function _validateFulfillmentRequest(
uint256 commitId_,
address marketplace_,
uint256 orderAmount_,
uint256 payoutAmount_
) internal returns (CommitData memory) {
if (commitId_ >= packs.length) revert Errors.InvalidCommitId();
if (msg.sender != packs[commitId_].cosigner) revert Errors.OnlyCosignerCanFulfill();
if (marketplace_ == address(0)) revert Errors.MarketplaceAddressZero();
if (msg.value > 0) _depositTreasury(msg.value);
if (orderAmount_ > treasuryBalance) revert Errors.InsufficientTreasuryBalance();
if (isFulfilled[commitId_]) revert Errors.AlreadyFulfilled();
if (isCancelled[commitId_]) revert Errors.CommitIsCancelled();
if (payoutAmount_ > orderAmount_) revert Errors.PayoutExceedsOrderAmount();
return packs[commitId_];
}
function _verifyFulfillmentSignatures(
CommitData memory commitData,
bytes calldata commitSignature_,
bytes calldata fulfillmentSignature_,
address marketplace_,
bytes calldata orderData_,
uint256 orderAmount_,
address token_,
uint256 tokenId_,
uint256 payoutAmount_,
FulfillmentOption choice_
) internal view returns (uint256 rng, bytes32 digest) {
address commitCosigner = verifyCommit(commitData, commitSignature_);
if (commitCosigner != commitData.cosigner) revert Errors.CommitSignerMismatch();
if (!isCosigner[commitCosigner]) revert Errors.CommitSignerNotCosigner();
rng = PRNG.rng(commitSignature_);
digest = hashCommit(commitData);
bytes32 fulfillmentHash = hashFulfillment(
digest, marketplace_, orderAmount_, orderData_,
token_, tokenId_, payoutAmount_, choice_
);
address fulfillmentCosigner = verifyHash(fulfillmentHash, fulfillmentSignature_);
if (fulfillmentCosigner != commitData.cosigner) revert Errors.FulfillmentSignerMismatch();
if (!isCosigner[fulfillmentCosigner]) revert Errors.FulfillmentSignerNotCosigner();
}
function _determineOutcomeAndValidate(
uint256 rng,
BucketData[] memory buckets,
uint256 orderAmount_,
uint256 payoutAmount_
) internal pure returns (uint256 bucketIndex, BucketData memory bucket) {
bucketIndex = _getBucketIndex(rng, buckets);
bucket = buckets[bucketIndex];
if (orderAmount_ < bucket.minValue) revert Errors.OrderAmountBelowBucketMin();
if (orderAmount_ > bucket.maxValue) revert Errors.OrderAmountAboveBucketMax();
if (payoutAmount_ < bucket.minValue) revert Errors.PayoutAmountBelowBucketMin();
if (payoutAmount_ > bucket.maxValue) revert Errors.PayoutAmountAboveBucketMax();
}
function _getBucketIndex(uint256 rng, BucketData[] memory buckets) internal pure returns (uint256) {
uint256 cumulativeOdds = 0;
for (uint256 i = 0; i < buckets.length; i++) {
cumulativeOdds += buckets[i].oddsBps;
if (rng < cumulativeOdds) {
return i;
}
}
revert Errors.BucketSelectionFailed();
}
function _determineFulfillmentType(uint256 commitId_, FulfillmentOption choice_) internal view returns (FulfillmentOption) {
if (choice_ == FulfillmentOption.NFT && block.timestamp > nftFulfillmentExpiresAt[commitId_]) {
return FulfillmentOption.Payout;
}
return choice_;
}
function _markFulfilledAndUpdateBalances(uint256 commitId_, uint256 packPrice) internal {
isFulfilled[commitId_] = true;
commitBalance -= packPrice;
treasuryBalance += packPrice;
uint256 protocolFeesPaid = feesPaid[commitId_];
protocolBalance -= protocolFeesPaid;
treasuryBalance += protocolFeesPaid;
}
function _executeFulfillment(
uint256 commitId_,
CommitData memory commitData,
address marketplace_,
bytes calldata orderData_,
uint256 orderAmount_,
address token_,
uint256 tokenId_,
uint256 payoutAmount_,
uint256 rng,
BucketData memory bucket,
uint256 bucketIndex,
FulfillmentOption choice_,
FulfillmentOption fulfillmentType,
bytes32 digest
) internal {
if (fulfillmentType == FulfillmentOption.NFT) {
_executeNFTFulfillment(commitId_, commitData, marketplace_, orderData_, orderAmount_,
token_, tokenId_, rng, bucket, bucketIndex, choice_, fulfillmentType, digest);
} else {
_executePayoutFulfillment(commitId_, commitData, payoutAmount_, rng, bucket,
bucketIndex, choice_, fulfillmentType, digest);
}
}
function _executeNFTFulfillment(
uint256 commitId_,
CommitData memory commitData,
address marketplace_,
bytes calldata orderData_,
uint256 orderAmount_,
address token_,
uint256 tokenId_,
uint256 rng,
BucketData memory bucket,
uint256 bucketIndex,
FulfillmentOption choice_,
FulfillmentOption fulfillmentType,
bytes32 digest
) internal {
(bool success,) = marketplace_.call{value: orderAmount_}(orderData_);
if (success) {
treasuryBalance -= orderAmount_;
emit Fulfillment(msg.sender, commitId_, rng, bucket.oddsBps, bucketIndex,
0, token_, tokenId_, orderAmount_, commitData.receiver, choice_, fulfillmentType, digest);
} else {
(bool fallbackSuccess,) = commitData.receiver.call{value: orderAmount_}("");
if (fallbackSuccess) {
treasuryBalance -= orderAmount_;
} else {
emit FulfillmentPayoutFailed(commitData.id, commitData.receiver, orderAmount_, digest);
}
emit Fulfillment(msg.sender, commitId_, rng, bucket.oddsBps, bucketIndex,
orderAmount_, address(0), 0, 0, commitData.receiver, choice_, fulfillmentType, digest);
}
}
function _executePayoutFulfillment(
uint256 commitId_,
CommitData memory commitData,
uint256 payoutAmount_,
uint256 rng,
BucketData memory bucket,
uint256 bucketIndex,
FulfillmentOption choice_,
FulfillmentOption fulfillmentType,
bytes32 digest
) internal {
(bool success,) = commitData.receiver.call{value: payoutAmount_}("");
if (success) {
treasuryBalance -= payoutAmount_;
} else {
emit FulfillmentPayoutFailed(commitData.id, commitData.receiver, payoutAmount_, digest);
}
emit Fulfillment(msg.sender, commitId_, rng, bucket.oddsBps, bucketIndex,
payoutAmount_, address(0), 0, 0, commitData.receiver, choice_, fulfillmentType, digest);
}
function _depositTreasury(uint256 amount) internal {
treasuryBalance += amount;
emit TreasuryDeposit(msg.sender, amount);
}
}
PacksStorage.sol 59 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.28;
import {PacksSignatureVerifierUpgradeable} from "../../common/SignatureVerifier/PacksSignatureVerifierUpgradeable.sol";
import {IPRNG} from "../../common/interfaces/IPRNG.sol";
/* Do not remove any storage variables from this contract. Always add new variables to the end. */
/// @title PacksStorage
/// @notice Storage layout for Packs contract
/// @dev All storage variables and events for Packs
abstract contract PacksStorage is PacksSignatureVerifierUpgradeable {
// ============================================================
// STORAGE
// ============================================================
IPRNG public PRNG;
address payable public fundsReceiver;
CommitData[] public packs;
mapping(bytes32 commitDigest => uint256 commitId) public commitIdByDigest;
uint256 public treasuryBalance;
uint256 public commitBalance;
uint256 public constant MIN_COMMIT_CANCELLABLE_TIME = 1 hours;
uint256 public commitCancellableTime;
mapping(uint256 commitId => uint256 cancellableAt) public commitCancellableAt;
uint256 public constant MIN_NFT_FULFILLMENT_EXPIRY_TIME = 30 seconds;
uint256 public nftFulfillmentExpiryTime;
mapping(uint256 commitId => uint256 expiresAt) public nftFulfillmentExpiresAt;
bytes32 public constant FUNDS_RECEIVER_MANAGER_ROLE = keccak256("FUNDS_RECEIVER_MANAGER_ROLE");
mapping(address cosigner => bool active) public isCosigner;
mapping(address receiver => uint256 counter) public packCount;
mapping(uint256 commitId => bool fulfilled) public isFulfilled;
mapping(uint256 commitId => bool cancelled) public isCancelled;
uint256 public minReward;
uint256 public maxReward;
uint256 public minPackPrice;
uint256 public maxPackPrice;
uint256 public minPackRewardMultiplier; // deprecated. These slots are unused but have to remain here.
uint256 public maxPackRewardMultiplier; // deprecated. These slots are unused but have to remain here.
uint256 public constant MIN_BUCKETS = 1;
uint256 public constant MAX_BUCKETS = 6;
uint256 public constant BASE_POINTS = 10000;
uint256 public protocolFee = 0;
uint256 public protocolBalance = 0;
mapping(uint256 commitId => uint256 protocolFee) public feesPaid;
uint256 public flatFee = 0;
}
Read Contract
BASE_POINTS 0xb5ab1c5d → uint256
DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
FUNDS_RECEIVER_MANAGER_ROLE 0x84d76f5e → bytes32
MAX_BUCKETS 0x15aaea17 → uint256
MIN_BUCKETS 0x09d2e766 → uint256
MIN_COMMIT_CANCELLABLE_TIME 0x1c39d42b → uint256
MIN_NFT_FULFILLMENT_EXPIRY_TIME 0xf57f6784 → uint256
OPS_ROLE 0x0f3ba023 → bytes32
PRNG 0x564ef91d → address
RESCUE_ROLE 0xb1a9f809 → bytes32
UPGRADE_INTERFACE_VERSION 0xad3cb1cc → string
calculateContributionWithoutFee 0x38635dd6 → uint256
commitBalance 0xaf156d4b → uint256
commitCancellableAt 0x0900804d → uint256
commitCancellableTime 0x622edc20 → uint256
commitIdByDigest 0x920a78a8 → uint256
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
feesPaid 0x798af41f → uint256
flatFee 0xd9eb5947 → uint256
fundsReceiver 0x23c7e09c → address
getPacksLength 0xab664c48 → uint256
getRoleAdmin 0x248a9ca3 → bytes32
hasRole 0x91d14854 → bool
hashCommit 0xe3ae29c8 → bytes32
hashFulfillment 0x4b359e04 → bytes32
hashPack 0xced7b8e5 → bytes32
isCancelled 0xcdf92c27 → bool
isCosigner 0xaec2259f → bool
isFulfilled 0x09149020 → bool
maxPackPrice 0x2e6b86cb → uint256
maxPackRewardMultiplier 0xd4cbb9d2 → uint256
maxReward 0x66a78e6c → uint256
minPackPrice 0xb2fb7c2d → uint256
minPackRewardMultiplier 0x183dd403 → uint256
minReward 0xba16d600 → uint256
nftFulfillmentExpiresAt 0x8b2d141d → uint256
nftFulfillmentExpiryTime 0xca29195c → uint256
packCount 0x474bf3b5 → uint256
packs 0xb84c1392 → uint256, address, address, uint256, uint256, uint256, bytes32
paused 0x5c975abb → bool
protocolBalance 0x61e98db8 → uint256
protocolFee 0xb0e21e8a → uint256
proxiableUUID 0x52d1902d → bytes32
supportsInterface 0x01ffc9a7 → bool
treasuryBalance 0x313dab20 → uint256
verify 0x258ae582 → address
verifyCommit 0x0e89c439 → address
verifyHash 0x2749deb1 → address
Write Contract 36 functions
These functions modify contract state and require a wallet transaction to execute.
addCosigner 0x6dbf1655
address cosigner_
addOpsUser 0xc0a3f329
address user
addRescueUser 0x4c2adcb0
address user
cancel 0x40e58ee5
uint256 commitId_
commit 0x69ff5638
address receiver_
address cosigner_
uint256 seed_
uint8 packType_
tuple[] buckets_
bytes signature_
returns: uint256
emergencyWithdraw 0xdb2e21bc
No parameters
fulfill 0x92826eda
uint256 commitId_
address marketplace_
bytes orderData_
uint256 orderAmount_
address token_
uint256 tokenId_
uint256 payoutAmount_
bytes commitSignature_
bytes fulfillmentSignature_
uint8 choice_
fulfillByDigest 0x017baf80
bytes32 commitDigest_
address marketplace_
bytes orderData_
uint256 orderAmount_
address token_
uint256 tokenId_
uint256 payoutAmount_
bytes commitSignature_
bytes fulfillmentSignature_
uint8 choice_
grantRole 0x2f2ff15d
bytes32 role
address account
initialize 0x10e51e14
uint256 protocolFee_
uint256 flatFee_
address initialOwner_
address fundsReceiver_
address prng_
address fundsReceiverManager_
pause 0x8456cb59
No parameters
removeCosigner 0xd371f924
address cosigner_
removeOpsUser 0xfb1c11f3
address user
removeRescueUser 0xfb74f6a7
address user
renounceRole 0x36568abe
bytes32 role
address callerConfirmation
rescueERC1155 0x6bd80353
address token
address to
uint256 tokenId
uint256 amount
rescueERC1155Batch 0x787c3b38
address[] tokens
address[] tos
uint256[] tokenIds
uint256[] amounts
rescueERC20 0xb2118a8d
address token
address to
uint256 amount
rescueERC20Batch 0x1c9eeebf
address[] tokens
address[] tos
uint256[] amounts
rescueERC721 0x7df325e1
address token
address to
uint256 tokenId
rescueERC721Batch 0xb28c8ac3
address[] tokens
address[] tos
uint256[] tokenIds
revokeRole 0xd547741f
bytes32 role
address account
setCommitCancellableTime 0x778822e3
uint256 commitCancellableTime_
setFlatFee 0x23fa495a
uint256 flatFee_
setFundsReceiver 0x141edd58
address fundsReceiver_
setMaxPackPrice 0x688b308b
uint256 maxPackPrice_
setMaxReward 0x25c33e13
uint256 maxReward_
setMinPackPrice 0xe9b6302c
uint256 minPackPrice_
setMinReward 0xb6a1cb2b
uint256 minReward_
setNftFulfillmentExpiryTime 0xa41c9d5a
uint256 nftFulfillmentExpiryTime_
setProtocolFee 0x787dce3d
uint256 protocolFee_
transferAdmin 0x75829def
address newAdmin
transferFundsReceiverManager 0xeb97d8d1
address newFundsReceiverManager_
unpause 0x3f4ba83a
No parameters
upgradeToAndCall 0x4f1ef286
address newImplementation
bytes data
withdrawTreasury 0x11f1fc99
uint256 amount
Recent Transactions
No transactions found for this address