Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xAA97C94962A70d8bc6B9e2b1829d74Ed0CE51F16
Balance 0.028010 ETH
Nonce 1
Code Size 19636 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

19636 bytes
0x6080806040526004361015610066575b50361561003e577fdeab4c30000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f491fe534000000000000000000000000000000000000000000000000000000005f5260045ffd5b5f3560e01c90816301ffc9a7146133d457508063038592051461317157806306fdde03146130cf578063081812fc146130b1578063088baaef14612a3e578063095ea7b3146128945780630db542561461278157806314032cfe14612571578063150b7a02146124e85780631dd96792146120b357806323b872dd146120965780632dbf9be614611d5a57806334b25029146118b75780633d46b819146117ee5780634126614d1461178857806342842e0e1461175b578063486c4b7f1461171a5780634d8af09e146116b45780634dfccf62146114315780635e78ffd71461132d5780636352211e146112fe57806365cd69a11461127757806370a08231146111cf578063715018a61461116957806384b0196e146110555780638da5cb5b1461102f5780639548087914610e1157806395d89b4114610d475780639941803214610c40578063a22cb46514610b73578063b45a3c0e14610b0a578063b88d4fde14610a8a578063c87b56dd14610a53578063d24177a814610875578063e985e9c51461081c578063ea1294581461042e578063f2fde38b146103455763f84e791d14610214575f61000f565b6060600319360112610341576102286134c2565b6102306134d8565b610238613c01565b6001600160a01b03821615610319576001600160a01b038116156102f1576102aa906012549261026784613a4d565b60125583813b6102e35761027a91614115565b7f032bc66be43dbccb7487781d168eb7bda224628a3b2c3388bdf69b532a3a16116020604051858152a182614213565b6102b43482614637565b604435907f14e519d8030c1e5bdd1754357afb1c9ab286d3de2b482b65f00ebecf604080555f80a36001600a55005b6102ec91614033565b61027a565b7ffbd849c6000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fd92e233d000000000000000000000000000000000000000000000000000000005f5260045ffd5b5f80fd5b34610341576020600319360112610341576001600160a01b036103666134c2565b61036e614657565b1680156103c4576001600160a01b036006548273ffffffffffffffffffffffffffffffffffffffff19821617600655167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e05f80a3005b608460405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f64647265737300000000000000000000000000000000000000000000000000006064820152fd5b346103415761043c366134ee565b9096959193929461044b613c01565b61045487613c56565b6001600160a01b03851615610319578142116107f45760408051602081018981526001600160a01b038088169383019390935260608201899052918716608082015260a081018a90523360c082015260e08101939093526104c38361010081015b03601f19810185528461343f565b875f52600960205260405f20925190209282549160428360a01c9560405160208101917f5fd4fde1cb878824d6e96eec97296c9e818ad783a10b7c9ede6e7f27eca7b06b83528c60408301528860608301526003608083015260a082015260a0815261053060c08261343f565b51902061053b614969565b90604051917f1901000000000000000000000000000000000000000000000000000000000000835260028301526022820152208092036107cc576105959261058d6001600160a01b0393928493614a85565b949094614aba565b169116036107a4576bffffffffffffffffffffffff82146107775760016105e392016001600160a01b0373ffffffffffffffffffffffffffffffffffffffff1983549260a01b169116179055565b604051606082901b7fffffffffffffffffffffffffffffffffffffffff0000000000000000000000001660208201908152603482018590529061063381605481015b03601f19810183528261343f565b51902090845f52601160205260405f20825f5260205260ff60405f2054161561074f576106a46001600160a01b0392865f52601060205260405f20815f526020525f6001604082208281550155865f52601160205260405f20815f5260205260405f2060ff19815416905586613e4e565b1691823b15610341576040517f42842e0e0000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b039290921660248301526044820152905f908290606490829084905af1801561074457610734575b507fed5cde06b8fd39942af9650caf18ecdd41df6dbb8d7a30385fa440e4bbc03cf75f80a36001600a55005b5f61073e9161343f565b82610708565b6040513d5f823e3d90fd5b7ff070cb6f000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b7f8baa579f000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f8b56642d000000000000000000000000000000000000000000000000000000005f5260045ffd5b7f0819bdcd000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610341576040600319360112610341576108356134c2565b6001600160a01b036108456134d8565b91165f5260056020526001600160a01b0360405f2091165f52602052602060ff60405f2054166040519015158152f35b6101006003193601126103415761088a6134c2565b6108926134d8565b60443560643567ffffffffffffffff8111610341576108b590369060040161357e565b60849291923567ffffffffffffffff8111610341576108d890369060040161357e565b60a49291923567ffffffffffffffff8111610341576108fb90369060040161357e565b93909260c43567ffffffffffffffff81116103415761091e90369060040161357e565b979096610929613c01565b6001600160a01b038b1615610319576001600160a01b038a16156102f157848314801590610a49575b610a21578034036109f9576109b66109bc9a7f032bc66be43dbccb7487781d168eb7bda224628a3b2c3388bdf69b532a3a161160206012549e8f9061099682613a4d565b60125581813b6109eb576109a991614115565b604051908152a18c614213565b8a613f07565b60e435907f14e519d8030c1e5bdd1754357afb1c9ab286d3de2b482b65f00ebecf604080555f80a36001600a55005b6109f491614033565b6109a9565b7f42c0a68f000000000000000000000000000000000000000000000000000000005f5260045ffd5b7fa24a13a6000000000000000000000000000000000000000000000000000000005f5260045ffd5b5088871415610952565b3461034157602060031936011261034157610a86610a72600435613ac9565b604051918291602083526020830190613559565b0390f35b3461034157608060031936011261034157610aa36134c2565b50610aac6134d8565b5060643567ffffffffffffffff811161034157610acd90369060040161347e565b50610ae2610add60443533613fc9565b613966565b7f8574adcf000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461034157602060031936011261034157610b3b6004355f5260026020526001600160a01b0360405f205416151590565b15610b4b57602060405160018152f35b7fb1d04f08000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461034157604060031936011261034157610b8c6134c2565b60243590811515809203610341576001600160a01b031690813314610bfc57335f52600560205260405f20825f5260205260405f2060ff1981541660ff83161790556040519081527f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c3160203392a3005b606460405162461bcd60e51b815260206004820152601960248201527f4552433732313a20617070726f766520746f2063616c6c6572000000000000006044820152fd5b34610341576020600319360112610341576004356040517f6352211e0000000000000000000000000000000000000000000000000000000081528160048201526020816024816001600160a01b037f000000000000000000000000aa97c94962a70d8bc6b9e2b1829d74ed0ce51f16165afa908115610744575f91610d18575b506001600160a01b0333911603610cf0575f52600960205260206001600160a01b0360405f205416604051908152f35b7f30cd7471000000000000000000000000000000000000000000000000000000005f5260045ffd5b610d3a915060203d602011610d40575b610d32818361343f565b8101906139ed565b82610cc0565b503d610d28565b34610341575f600319360112610341576040515f600154610d678161374b565b8084529060018116908115610ded5750600114610d8f575b610a8683610a728185038261343f565b60015f9081527fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6939250905b808210610dd357509091508101602001610a72610d7f565b919260018160209254838588010152019101909291610dbb565b60ff191660208086019190915291151560051b84019091019150610a729050610d7f565b346103415760206003193601126103415760043567ffffffffffffffff811161034157610e4290369060040161347e565b610e4a614657565b60ff6014541661100757805167ffffffffffffffff8111610fda57610e7060135461374b565b601f8111610f43575b50602091601f8211600114610ec557610ea7925f9183610eba575b50505f198260011b9260031b1c19161790565b6013555b6014805460ff19166001179055005b015190508380610e94565b601f1982169260135f527f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a090915f5b858110610f2b57508360019510610f13575b505050811b01601355610eab565b01515f1960f88460031b161c19169055828080610f05565b91926020600181928685015181550194019201610ef3565b610fac9060135f52601f830160051c7f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a090019060208410610fb2575b601f0160051c7f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a09001906139d7565b82610e79565b7f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a0909150610f7e565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7fe8cba6d8000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610341575f6003193601126103415760206001600160a01b0360065416604051908152f35b34610341575f6003193601126103415761110d6110917f425647530000000000000000000000000000000000000000000000000000000461471c565b6110ba7f310000000000000000000000000000000000000000000000000000000000000161478e565b602061111b604051926110cd838561343f565b5f84525f3681376040519586957f0f00000000000000000000000000000000000000000000000000000000000000875260e08588015260e0870190613559565b908582036040870152613559565b4660608501523060808501525f60a085015283810360c08501528180845192838152019301915f5b82811061115257505050500390f35b835185528695509381019392810192600101611143565b34610341575f60031936011261034157611181614657565b5f6001600160a01b0360065473ffffffffffffffffffffffffffffffffffffffff198116600655167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a3005b34610341576020600319360112610341576001600160a01b036111f06134c2565b16801561120d575f526003602052602060405f2054604051908152f35b608460405162461bcd60e51b815260206004820152602960248201527f4552433732313a2061646472657373207a65726f206973206e6f74206120766160448201527f6c6964206f776e657200000000000000000000000000000000000000000000006064820152fd5b60406003193601126103415760043561128e613c01565b61129781613c56565b34156112d6576112a73482614637565b602435907f0131d4fe789c9eeb7c2dd7e32aa9393d395bef62f1f67e0ba2a76d33c6dcf5ee5f80a36001600a55005b7f1f2a2005000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461034157602060031936011261034157602061131c600435613aa6565b6001600160a01b0360405191168152f35b346103415761133b366135e9565b939291611346613c01565b6001600160a01b03841615610319576001600160a01b038316156102f1576001600160a01b03811615611409576113ca6113d0936012549561138787613a4d565b60125586813b6113fb5761139a91614115565b7f032bc66be43dbccb7487781d168eb7bda224628a3b2c3388bdf69b532a3a16116020604051888152a185614213565b836144a0565b7f14e519d8030c1e5bdd1754357afb1c9ab286d3de2b482b65f00ebecf604080555f80a36001600a55005b61140491614033565b61139a565b7f6b093aad000000000000000000000000000000000000000000000000000000005f5260045ffd5b346103415760e06003193601126103415760043560443567ffffffffffffffff81116103415761146590369060040161347e565b90606435608435906001600160a01b0382168092036103415760a4359360c43561148d613c01565b61149685613c56565b8315610319578042116107f4576040519060208201908682528460408401528560608401528760808401523360a084015260c083015260c082526114db60e08361343f565b855f52600960205260405f20915190209181549060428260a01c9460405160208101917f5fd4fde1cb878824d6e96eec97296c9e818ad783a10b7c9ede6e7f27eca7b06b83528a60408301528760608301526001608083015260a082015260a0815261154860c08261343f565b519020611553614969565b90604051917f1901000000000000000000000000000000000000000000000000000000000000835260028301526022820152209081602435036107cc576115a89261058d6001600160a01b0393928493614a85565b169116036107a4576bffffffffffffffffffffffff82146107775760016115f692016001600160a01b0373ffffffffffffffffffffffffffffffffffffffff1983549260a01b169116179055565b825f52600b60205260405f20549181831061168c575f8281949261161c8395849561373e565b878452600b60205260408420555af16116336138e6565b5015611664577fed5cde06b8fd39942af9650caf18ecdd41df6dbb8d7a30385fa440e4bbc03cf75f80a36001600a55005b7f6d963f88000000000000000000000000000000000000000000000000000000005f5260045ffd5b7faaa0d009000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610341576116c23661363b565b9291906116cd613c01565b6116d683613c56565b6001600160a01b03821615610319576116ef91836144a0565b7f0131d4fe789c9eeb7c2dd7e32aa9393d395bef62f1f67e0ba2a76d33c6dcf5ee5f80a36001600a55005b34610341576117283661363b565b929190611733613c01565b61173c83613c56565b6001600160a01b038216156103195780156112d6576116ef918361428a565b3461034157610ae2610add61176f366135af565b9150505f60405161178160208261343f565b5233613fc9565b3461034157611796366135e9565b9392916117a1613c01565b6001600160a01b03841615610319576001600160a01b038316156102f1576001600160a01b038116156114095781156112d6576117e86113d0936012549561138787613a4d565b8361428a565b34610341576020600319360112610341576004356040517f6352211e0000000000000000000000000000000000000000000000000000000081528160048201526020816024816001600160a01b037f000000000000000000000000aa97c94962a70d8bc6b9e2b1829d74ed0ce51f16165afa908115610744575f91611898575b506001600160a01b0333911603610cf0575f526009602052602060405f205460a01c604051908152f35b6118b1915060203d602011610d4057610d32818361343f565b8261186e565b34610341576020600319360112610341576004356001600160a01b037f000000000000000000000000aa97c94962a70d8bc6b9e2b1829d74ed0ce51f16166040517f6352211e000000000000000000000000000000000000000000000000000000008152826004820152602081602481855afa5f9181611d39575b5061195f577fb1d04f08000000000000000000000000000000000000000000000000000000005f5260045ffd5b6001600160a01b031615610b4b576020602491604051928380927f6352211e0000000000000000000000000000000000000000000000000000000082528660048301525afa908115610744575f91611d1a575b506001600160a01b0333911603610cf057805f52600b60205260405f2054815f52600d60205260405f209182546119e881613a0c565b936119f6604051958661343f565b818552601f19611a0583613a0c565b015f5b818110611cee5750505f5b828110611c6757505050805f52600f60205260405f205f915f918054925b838110611c145750601f19611a5e611a4886613a0c565b95611a56604051978861343f565b808752613a0c565b015f5b818110611be85750505f905f5b848110611b3b57878787604051928392606084019084526060602085015281518091526020608085019201905f5b818110611b02575050508281036040840152602080835192838152019201905f5b818110611acb575050500390f35b919350916020604082611af46001948851602080916001600160a01b0381511684520151910152565b019401910191849392611abd565b91939450916020604082611b2c6001948851602080916001600160a01b0381511684520151910152565b01940191019185949392611a9c565b600190845f9997989952601160205260405f20611b588285613a24565b90549060031b1c5f5260205260ff60405f205416611b7b575b0196959496611a6e565b845f52601060205260405f20611b918285613a24565b90549060031b1c5f52602052611be260405f2094611bae81613a4d565b958460405191611bbd83613423565b6001600160a01b03815416835201546020820152611bdb828c613a39565b5289613a39565b50611b71565b6040519697959660209190611bfc81613423565b5f81525f8382015282828a0101520196959496611a61565b825f9795969752601160205260405f20611c2e8284613a24565b90549060031b1c5f5260205260ff60405f205416611c53575b60010195949395611a31565b94611c5f600191613a4d565b959050611c47565b806001600160a01b03611c806001938599979899613a24565b90549060031b1c16865f52600c60205260405f206001600160a01b0380611ca78588613a24565b90549060031b1c16165f5260205260405f205460405191611cc783613423565b82526020820152611cd88287613a39565b52611ce38186613a39565b500194939294611a13565b6040519596949560209190611d0281613423565b5f81525f838201528282880101520195949395611a08565b611d33915060203d602011610d4057610d32818361343f565b826119b2565b611d5391925060203d602011610d4057610d32818361343f565b9084611932565b346103415760c06003193601126103415760043560443567ffffffffffffffff811161034157611d8e90369060040161347e565b60643567ffffffffffffffff811161034157611dae90369060040161347e565b916084359160a435611dbe613c01565b611ddc835f5260026020526001600160a01b0360405f205416151590565b15610b4b57611dea83613aa6565b6001600160a01b0333911603610cf0578042116107f45760405190611e4582602081019286845260a06040830152611e2560c083018a613559565b9088606084015233608084015260a083015203601f19810184528361343f565b835f52600960205260405f20915190209181549060428260a01c9460405160208101917f5fd4fde1cb878824d6e96eec97296c9e818ad783a10b7c9ede6e7f27eca7b06b83528860408301528760608301526005608083015260a082015260a08152611eb260c08261343f565b519020611ebd614969565b90604051917f1901000000000000000000000000000000000000000000000000000000000000835260028301526022820152209081602435036107cc57611f129261058d6001600160a01b0393928493614a85565b169116036107a4576bffffffffffffffffffffffff8214610777576001611f6092016001600160a01b0373ffffffffffffffffffffffffffffffffffffffff1983549260a01b169116179055565b805f52601560205260405f20835167ffffffffffffffff8111610fda57611f87825461374b565b601f811161205b575b50602094601f8211600114611ffa57611fc19293949582915f92611fef5750505f198260011b9260031b1c19161790565b90555b7fe6b029312a4fe660620d9aac173bc78279912103135fdd45fcb95684efee4bd65f80a36001600a55005b015190508680610e94565b601f19821695835f52805f20915f5b8881106120435750836001959697981061202b575b505050811b019055611fc4565b01515f1960f88460031b161c1916905585808061201e565b91926020600181928685015181550194019201612009565b61208690835f5260205f20601f840160051c8101916020851061208c575b601f0160051c01906139d7565b85611f90565b9091508190612079565b3461034157610ae2610add6120aa366135af565b91505033613fc9565b346103415760a06003193601126103415760043560443567ffffffffffffffff8111610341576120e790369060040161347e565b606435906084356120f6613c01565b6120ff84613c56565b8042116107f45760405190602082019085825284604084015233606084015260808301526080825261213260a08361343f565b845f52600960205260405f20915190209181549060428260a01c9460405160208101917f5fd4fde1cb878824d6e96eec97296c9e818ad783a10b7c9ede6e7f27eca7b06b83528960408301528760608301526004608083015260a082015260a0815261219f60c08261343f565b5190206121aa614969565b90604051917f1901000000000000000000000000000000000000000000000000000000000000835260028301526022820152209081602435036107cc576121ff9261058d6001600160a01b0393928493614a85565b169116036107a4576bffffffffffffffffffffffff821461077757600161224d92016001600160a01b0373ffffffffffffffffffffffffffffffffffffffff1983549260a01b169116179055565b815f52600b6020525f6040812055815f52600d60205260405f205f5b81548110156122dd57806001600160a01b0361228760019385613a24565b90549060031b1c16855f52600c60205260405f206001600160a01b0382165f526020525f6040812055855f52600e6020526001600160a01b0360405f2091165f5260205260405f2060ff19815416905501612269565b5050815f52600d60205260405f2080545f8255806124ce575b5050815f52600f60205260405f20915f5b8354811015612365578061231d60019286613a24565b90549060031b1c835f52601060205260405f20815f526020525f83604082208281550155835f52601160205260405f20905f5260205260405f2060ff19815416905501612307565b50805f52600f60205260405f208054905f8155816124b0575b505061238981613aa6565b50805f6001600160a01b0361239d83613aa6565b83835260046020526040832073ffffffffffffffffffffffffffffffffffffffff198154169055168082526003602052604082205f19815401905582825260026020526040822073ffffffffffffffffffffffffffffffffffffffff1981541690557fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8280a4805f52601560205260405f20612439815461374b565b908161246d575b50507fbf7ca02baa2417b74691f2f4e439006ba9753eee8ab5e7c15eaf673a8c1f0dcd5f80a36001600a55005b81601f5f93116001146124845750555b8280612440565b818352602083206124a091601f0160051c8101906001016139d7565b808252816020812091555561247d565b5f5260205f20908101905b8181101561237e575f81556001016124bb565b6124e1915f5260205f20908101906139d7565b82806122f6565b34610341576080600319360112610341576125016134c2565b5061250a6134d8565b5060643567ffffffffffffffff8111610341573660238201121561034157806004013567ffffffffffffffff811161034157369101602401116103415760206040517f150b7a02000000000000000000000000000000000000000000000000000000008152f35b346103415760c06003193601126103415760043560443567ffffffffffffffff8111610341576125a590369060040161347e565b90606435916001600160a01b038316809303610341576084359260a435916125cb613c01565b6125d484613c56565b8242116107f45760405192602084019085825283604086015286606086015233608086015260a085015260a0845261260d60c08561343f565b845f52600960205260405f20935190209083549060428260a01c9360405160208101917f5fd4fde1cb878824d6e96eec97296c9e818ad783a10b7c9ede6e7f27eca7b06b83528960408301528660608301525f608083015260a082015260a0815261267960c08261343f565b519020612684614969565b90604051917f1901000000000000000000000000000000000000000000000000000000000000835260028301526022820152209081602435036107cc576126d99261058d6001600160a01b0393928493614a85565b169116036107a4576bffffffffffffffffffffffff81146107775782546001600160a01b031660019190910160a01b73ffffffffffffffffffffffffffffffffffffffff191617825580158015612759575b5050507f984cbcf51cba481417bc4c1f7faacf7392a4cbcd6c7fb7888b24ed2e50a0be775f80a36001600a55005b6102f15773ffffffffffffffffffffffffffffffffffffffff1982541617905582808061272b565b60e06003193601126103415760043560243560443567ffffffffffffffff8111610341576127b390369060040161357e565b9060643567ffffffffffffffff8111610341576127d490369060040161357e565b9060843567ffffffffffffffff8111610341576127f590369060040161357e565b92909160a43567ffffffffffffffff81116103415761281890369060040161357e565b969095612823613c01565b61282c8a613c56565b88340361286c5761283d988a613f07565b60c435907f0131d4fe789c9eeb7c2dd7e32aa9393d395bef62f1f67e0ba2a76d33c6dcf5ee5f80a36001600a55005b7fcfb73638000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610341576040600319360112610341576128ad6134c2565b602435906001600160a01b03806128c384613aa6565b169116908082146129d4578033149081156129aa575b501561294057815f52600460205260405f208173ffffffffffffffffffffffffffffffffffffffff198254161790556001600160a01b0361291983613aa6565b167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9255f80a4005b608460405162461bcd60e51b815260206004820152603d60248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f7420746f60448201527f6b656e206f776e6572206f7220617070726f76656420666f7220616c6c0000006064820152fd5b90505f52600560205260405f206001600160a01b0333165f5260205260ff60405f205416836128d9565b608460405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e6560448201527f72000000000000000000000000000000000000000000000000000000000000006064820152fd5b34610341576101606003193601126103415760043560443567ffffffffffffffff811161034157612a7390369060040161347e565b9060643560843567ffffffffffffffff811161034157612a9790369060040161357e565b909160a43567ffffffffffffffff811161034157612ab990369060040161357e565b909360c43567ffffffffffffffff811161034157612adb90369060040161357e565b94909260e43567ffffffffffffffff811161034157612afe90369060040161357e565b93909761010435966001600160a01b0388169081890361034157610124359c61014435612b328e612b2d613c01565b613c56565b8315610319578042116107f4578688148015906130a7575b61307f578d8f898f918f9487938f8f908d988f8e906040519b8c9960208b019b8d8d5260408c015260608b0161014090526101608b0190612b8a9261385c565b90898203601f190160808b0152612ba0926138a9565b90878203601f190160a0890152612bb69261385c565b90858203601f190160c0870152612bcc926138a9565b918960e08501526101008401523361012084015261014083015203601f1981018452612bf8908461343f565b815f52600960205260405f2092519020928254918260a01c946040519060208201927f5fd4fde1cb878824d6e96eec97296c9e818ad783a10b7c9ede6e7f27eca7b06b84526040830152866060830152608082016006905260a082015260a08152612c6460c08261343f565b519020612c6f614969565b90604051917f1901000000000000000000000000000000000000000000000000000000000000835260028301526022820152604290209081602435036107cc57612cc79261058d6001600160a01b0393928493614a85565b169116036107a4576bffffffffffffffffffffffff8214610777576001612d1592016001600160a01b0373ffffffffffffffffffffffffffffffffffffffff1983549260a01b169116179055565b80613034575b50505f5b848110612ed15750505050505f5b848110612d615787877fed5cde06b8fd39942af9650caf18ecdd41df6dbb8d7a30385fa440e4bbc03cf75f80a36001600a55005b612d74612d6f828786613915565b613952565b610625612dc7612d8584868b613915565b3560405192839160208301958690917fffffffffffffffffffffffffffffffffffffffff00000000000000000000000060349360601b16825260148201520190565b519020875f52601160205260405f20815f5260205260ff60405f2054161561074f57612e2f90885f52601060205260405f20815f526020525f6001604082208281550155885f52601160205260405f20815f5260205260405f2060ff19815416905588613e4e565b6001600160a01b03612e45612d6f838887613915565b1690612e52818489613915565b3591803b15610341576040517f42842e0e0000000000000000000000000000000000000000000000000000000081523060048201526001600160a01b038716602482015260448101939093525f908390606490829084905af191821561074457600192612ec1575b5001612d2d565b5f612ecb9161343f565b89612eba565b8a5f52600c60205260405f206001600160a01b03612ef3612d6f848988613915565b165f5260205260405f205490612f0a818685613915565b35821061300c57612f29600192612f22838887613915565b359061373e565b8c5f52600c60205260405f206001600160a01b03612f4b612d6f858b8a613915565b165f5260205260405f20558b5f52600c60205260405f206001600160a01b03612f78612d6f848a89613915565b165f5260205260405f205415612fbc575b612fb66001600160a01b03612fa2612d6f848a89613915565b168a612faf848988613915565b3591613df7565b01612d1f565b8b5f52600e60205260405f206001600160a01b03612fde612d6f848a89613915565b165f5260205260405f2060ff198154169055613007613001612d6f838988613915565b8d613cf4565b612f89565b7fe4455cae000000000000000000000000000000000000000000000000000000005f5260045ffd5b8b5f52600b60205260405f20549181831061168c575f828194928f61305b8496859661373e565b908452600b60205260408420555af16130726138e6565b5015611664578b80612d1b565b7f469224f0000000000000000000000000000000000000000000000000000000005f5260045ffd5b50888c1415612b4a565b3461034157602060031936011261034157602061131c60043561381e565b34610341575f600319360112610341576040515f5f546130ee8161374b565b8084529060018116908115610ded575060011461311557610a8683610a728185038261343f565b5f8080527f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563939250905b80821061315757509091508101602001610a72610d7f565b91926001816020925483858801015201910190929161313f565b346103415761317f366134ee565b9096959192939461318e613c01565b61319787613c56565b6001600160a01b03841615610319578142116107f45760408051602081018981526001600160a01b03808a169383019390935260608201889052918616608082015260a081018a90523360c082015260e08101939093526131fc8361010081016104b5565b875f52600960205260405f20925190209282549160428360a01c9560405160208101917f5fd4fde1cb878824d6e96eec97296c9e818ad783a10b7c9ede6e7f27eca7b06b83528c60408301528860608301526002608083015260a082015260a0815261326960c08261343f565b519020613274614969565b90604051917f1901000000000000000000000000000000000000000000000000000000000000835260028301526022820152208092036107cc576132c69261058d6001600160a01b0393928493614a85565b169116036107a4576bffffffffffffffffffffffff821461077757600161331492016001600160a01b0373ffffffffffffffffffffffffffffffffffffffff1983549260a01b169116179055565b835f52600c60205260405f206001600160a01b0384165f5260205260405f205482811061300c5761337a93613351846001600160a01b039361373e565b5f878152600c6020908152604080832086861684529091529020819055156133a5575b16613df7565b7fed5cde06b8fd39942af9650caf18ecdd41df6dbb8d7a30385fa440e4bbc03cf75f80a36001600a55005b855f52600e60205260405f208282165f5260205260405f2060ff1981541690556133cf8187613cf4565b613374565b3461034157602060031936011261034157600435907fffffffff00000000000000000000000000000000000000000000000000000000821682036103415761341d602092613669565b15158152f35b6040810190811067ffffffffffffffff821117610fda57604052565b90601f601f19910116810190811067ffffffffffffffff821117610fda57604052565b67ffffffffffffffff8111610fda57601f01601f191660200190565b81601f820112156103415760208135910161349882613462565b926134a6604051948561343f565b8284528282011161034157815f92602092838601378301015290565b600435906001600160a01b038216820361034157565b602435906001600160a01b038216820361034157565b6101006003198201126103415760043591602435916044359067ffffffffffffffff8211610341576135229160040161347e565b906064356001600160a01b038116810361034157906084359060a4356001600160a01b0381168103610341579060c4359060e43590565b90601f19601f602080948051918291828752018686015e5f8582860101520116010190565b9181601f840112156103415782359167ffffffffffffffff8311610341576020808501948460051b01011161034157565b6003196060910112610341576004356001600160a01b038116810361034157906024356001600160a01b0381168103610341579060443590565b60031960a0910112610341576004356001600160a01b038116810361034157906024356001600160a01b038116810361034157906044356001600160a01b038116810361034157906064359060843590565b600319608091011261034157600435906024356001600160a01b038116810361034157906044359060643590565b7fffffffff00000000000000000000000000000000000000000000000000000000167fb45a3c0e000000000000000000000000000000000000000000000000000000008114613738577f80ac58cd00000000000000000000000000000000000000000000000000000000811490811561370e575b81156136e7575090565b7f01ffc9a70000000000000000000000000000000000000000000000000000000091501490565b7f5b5e139f00000000000000000000000000000000000000000000000000000000811491506136dd565b50600190565b9190820391821161077757565b90600182811c92168015613792575b602083101461376557565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602260045260245ffd5b91607f169161375a565b5f92918154916137ab8361374b565b808352926001811690811561380057506001146137c757505050565b5f9081526020812093945091925b8383106137e6575060209250010190565b6001816020929493945483858701015201910191906137d5565b9050602094955060ff1991509291921683830152151560051b010190565b61384461383f825f5260026020526001600160a01b0360405f205416151590565b613a5b565b5f5260046020526001600160a01b0360405f20541690565b916020908281520191905f905b8082106138765750505090565b9091928335906001600160a01b038216820361034157602080916001600160a01b03600194168152019401920190613869565b90918281527f07ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff83116103415760209260051b809284830137010190565b3d15613910573d906138f782613462565b91613905604051938461343f565b82523d5f602084013e565b606090565b91908110156139255760051b0190565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b356001600160a01b03811681036103415790565b1561396d57565b608460405162461bcd60e51b815260206004820152602d60248201527f4552433732313a2063616c6c6572206973206e6f7420746f6b656e206f776e6560448201527f72206f7220617070726f766564000000000000000000000000000000000000006064820152fd5b8181106139e2575050565b5f81556001016139d7565b9081602091031261034157516001600160a01b03811681036103415790565b67ffffffffffffffff8111610fda5760051b60200190565b8054821015613925575f5260205f2001905f90565b80518210156139255760209160051b010190565b5f1981146107775760010190565b15613a6257565b606460405162461bcd60e51b815260206004820152601860248201527f4552433732313a20696e76616c696420746f6b656e20494400000000000000006044820152fd5b5f5260026020526001600160a01b0360405f205416613ac6811515613a5b565b90565b613ae7815f5260026020526001600160a01b0360405f205416151590565b15610b4b575f526015602052613b09613b1060405f206040519283809261379c565b038261343f565b8051613ac65750613b2260135461374b565b613b4e577f8714d516000000000000000000000000000000000000000000000000000000005f5260045ffd5b604051601354815f613b5f8361374b565b8083529260018116908115613be25750600114613b83575b613ac69250038261343f565b5060135f90815290917f66de8ffda797e3de9c05e8fc57b3bf0ec28a930d40b0d285d93c06501cf6a0905b818310613bc6575050906020613ac692820101613b77565b6020919350806001915483858801015201910190918392613bae565b60209250613ac694915060ff191682840152151560051b820101613b77565b6002600a5414613c12576002600a55565b606460405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152fd5b604051907f6352211e00000000000000000000000000000000000000000000000000000000825260048201526020816024816001600160a01b037f000000000000000000000000aa97c94962a70d8bc6b9e2b1829d74ed0ce51f16165afa908115610744575f91613cd5575b506001600160a01b0333911603610cf057565b613cee915060203d602011610d4057610d32818361343f565b5f613cc2565b5f52600d60205260405f2080545f5b818110613d11575b50505050565b6001600160a01b03613d238285613a24565b90549060031b1c166001600160a01b03851614613d4257600101613d03565b909192505f19820191821161077757613d786001600160a01b03613d69613d979486613a24565b90549060031b1c169184613a24565b9091906001600160a01b038084549260031b9316831b921b1916179055565b80548015613dca575f190190613dad8282613a24565b6001600160a01b0382549160031b1b19169055555f808080613d0b565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603160045260245ffd5b613e4c926001600160a01b03604051937fa9059cbb000000000000000000000000000000000000000000000000000000006020860152166024840152604483015260448252613e4760648361343f565b6146af565b565b5f52600f60205260405f2080545f5b818110613e6a5750505050565b83613e758285613a24565b90549060031b1c14613e8957600101613e5d565b9192505f19810190811161077757613eb5613ea7613ecb9285613a24565b90549060031b1c9284613a24565b81939154905f199060031b92831b921b19161790565b905580548015613dca575f190190613ee38282613a24565b5f1982549160031b1b19169055555f808080613d0b565b9190820180921161077757565b97969491939290989598828214801590613fbf575b61307f5780613fa0575b505f5b818110613f735750505050505f5b818110613f4657505050505050565b80613f6d613f5a612d6f600194868b613915565b613f65838789613915565b3590886144a0565b01613f37565b80613f9a613f87612d6f600194868a613915565b613f92838789613915565b35908c61428a565b01613f29565b885f52600b602052613fb760405f20918254613efa565b90555f613f26565b5086861415613f1c565b906001600160a01b0380613fdc83613aa6565b16921690828214928315614010575b508215613ff757505090565b6001600160a01b0391925061400b9061381e565b161490565b9092505f52600560205260405f20815f5260205260ff60405f205416915f613feb565b614058916040519161404660208461343f565b5f83526140538282614115565b6147c5565b1561405f57565b60405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e74657200000000000000000000000000006064820152608490fd5b156140d157565b606460405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e746564000000006044820152fd5b6001600160a01b031680156141cf5761414b614145835f5260026020526001600160a01b0360405f205416151590565b156140ca565b61416c614145835f5260026020526001600160a01b0360405f205416151590565b805f52600360205260405f2060018154019055815f52600260205260405f208173ffffffffffffffffffffffffffffffffffffffff198254161790555f7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8180a4565b606460405162461bcd60e51b815260206004820152602060248201527f4552433732313a206d696e7420746f20746865207a65726f20616464726573736044820152fd5b90815f5260096020526001600160a01b0360405f205416614262575f918252600960205260409091206001600160a01b0390911674010000000000000000000000000000000000000000179055565b7f0dc149f0000000000000000000000000000000000000000000000000000000005f5260045ffd5b916001600160a01b03821691835f52600e60205260405f20835f5260205260ff60405f20541615614445575b50604051907f70a08231000000000000000000000000000000000000000000000000000000008252306004830152602082602481865afa918215610744575f9261440f575b506040517f23b872dd00000000000000000000000000000000000000000000000000000000602082015233602482015230604482015260648101919091526143509061434a8160848101610625565b836146af565b604051907f70a08231000000000000000000000000000000000000000000000000000000008252306004830152602082602481865afa918215610744575f926143db575b50808211156143d2576143a69161373e565b915b82156112d6575f52600c60205260405f20905f526020526143ce60405f20918254613efa565b9055565b50505f916143a8565b9091506020813d602011614407575b816143f76020938361343f565b810103126103415751905f614394565b3d91506143ea565b9091506020813d60201161443d575b8161442b6020938361343f565b810103126103415751906106256142fb565b3d915061441e565b835f52600d60205260405f209081549168010000000000000000831015610fda5782613d7891600161447995018155613a24565b825f52600e60205260405f20825f5260205260405f20600160ff198254161790555f6142b6565b9060405160208101906144e88161062587868690917fffffffffffffffffffffffffffffffffffffffff00000000000000000000000060349360601b16825260148201520190565b51902091805f52601160205260405f20835f5260205260ff60405f205416156145d8575b6001906001600160a01b036040519361452485613423565b169384845260208401918683525f52601060205260405f20905f526020526001600160a01b038060405f209451161673ffffffffffffffffffffffffffffffffffffffff1984541617835551910155803b15610341576040517f42842e0e00000000000000000000000000000000000000000000000000000000815233600482015230602482015260448101929092525f908290606490829084905af18015610744576145ce5750565b5f613e4c9161343f565b805f52600f60205260405f209081549168010000000000000000831015610fda5761460e613eb584879360018097018155613a24565b9055805f52601160205260405f20845f5260205260405f208260ff19825416179055905061450c565b8115614653575f52600b6020526143ce60405f20918254613efa565b5050565b6001600160a01b0360065416330361466b57565b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b905f602091828151910182855af115610744575f513d61471357506001600160a01b0381163b155b6146de5750565b6001600160a01b03907f5274afe7000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b600114156146d7565b60ff811461477b5760ff811690601f8211614753576040519161474060408461343f565b6020808452838101919036833783525290565b7fb3512b0c000000000000000000000000000000000000000000000000000000005f5260045ffd5b50604051613ac681613b0981600761379c565b60ff81146147b25760ff811690601f8211614753576040519161474060408461343f565b50604051613ac681613b0981600861379c565b91823b156149615761482b926020925f6001600160a01b036040518097819682957f150b7a020000000000000000000000000000000000000000000000000000000084523360048501528560248501526044840152608060648401526084830190613559565b0393165af15f9181614904575b506148bd576148456138e6565b805190816148b85760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527f63656976657220696d706c656d656e74657200000000000000000000000000006064820152608490fd5b602001fd5b7fffffffff00000000000000000000000000000000000000000000000000000000167f150b7a02000000000000000000000000000000000000000000000000000000001490565b9091506020813d602011614959575b816149206020938361343f565b8101031261034157517fffffffff000000000000000000000000000000000000000000000000000000008116810361034157905f614838565b3d9150614913565b505050600190565b6001600160a01b037f000000000000000000000000aa97c94962a70d8bc6b9e2b1829d74ed0ce51f1616301480614a5c575b156149c4577fd76e190072257624c180ac9d8c90e22c1f5ac1c23cd19fb80311e8499950daef90565b60405160208101907f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f82527f3e455176595285ae386f74ae90f07472477268078fcb23db4a561bcb66eca44360408201527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260a08152614a5660c08261343f565b51902090565b507f0000000000000000000000000000000000000000000000000000000000000001461461499b565b9060418151145f14614ab157614aad91602082015190606060408401519301515f1a90614c03565b9091565b50505f90600290565b6005811015614bd65780614acb5750565b60018103614b1757606460405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152fd5b60028103614b6357606460405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152fd5b600314614b6c57565b608460405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c60448201527f75650000000000000000000000000000000000000000000000000000000000006064820152fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b7f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08411614c73576020935f9360ff60809460405194855216868401526040830152606082015282805260015afa15610744575f516001600160a01b03811615614c6b57905f90565b505f90600190565b505050505f9060039056fea26469706673582212206a546929f68d001befb9309d5615f0815ec5934ca629c25c58157059a57b391a64736f6c634300081e0033

Verified Source Code Full Match

Compiler: v0.8.30+commit.73712a01 EVM: prague Optimization: Yes (10000 runs)
Ownable.sol 83 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        _checkOwner();
        _;
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if the sender is not the owner.
     */
    function _checkOwner() internal view virtual {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

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

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
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
        );
}
ReentrancyGuard.sol 77 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be _NOT_ENTERED
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == _ENTERED;
    }
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address to, uint256 value) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 value) external returns (bool);
}
SafeERC20.sol 198 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.2.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

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

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
ERC721.sol 506 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.2) (token/ERC721/ERC721.sol)

pragma solidity ^0.8.0;

import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";

/**
 * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
 * the Metadata extension, but not including the Enumerable extension, which is available separately as
 * {ERC721Enumerable}.
 */
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
    using Address for address;
    using Strings for uint256;

    // Token name
    string private _name;

    // Token symbol
    string private _symbol;

    // Mapping from token ID to owner address
    mapping(uint256 => address) private _owners;

    // Mapping owner address to token count
    mapping(address => uint256) private _balances;

    // Mapping from token ID to approved address
    mapping(uint256 => address) private _tokenApprovals;

    // Mapping from owner to operator approvals
    mapping(address => mapping(address => bool)) private _operatorApprovals;

    /**
     * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
        return
            interfaceId == type(IERC721).interfaceId ||
            interfaceId == type(IERC721Metadata).interfaceId ||
            super.supportsInterface(interfaceId);
    }

    /**
     * @dev See {IERC721-balanceOf}.
     */
    function balanceOf(address owner) public view virtual override returns (uint256) {
        require(owner != address(0), "ERC721: address zero is not a valid owner");
        return _balances[owner];
    }

    /**
     * @dev See {IERC721-ownerOf}.
     */
    function ownerOf(uint256 tokenId) public view virtual override returns (address) {
        address owner = _ownerOf(tokenId);
        require(owner != address(0), "ERC721: invalid token ID");
        return owner;
    }

    /**
     * @dev See {IERC721Metadata-name}.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev See {IERC721Metadata-symbol}.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev See {IERC721Metadata-tokenURI}.
     */
    function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
        _requireMinted(tokenId);

        string memory baseURI = _baseURI();
        return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
    }

    /**
     * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
     * token will be the concatenation of the `baseURI` and the `tokenId`. Empty
     * by default, can be overridden in child contracts.
     */
    function _baseURI() internal view virtual returns (string memory) {
        return "";
    }

    /**
     * @dev See {IERC721-approve}.
     */
    function approve(address to, uint256 tokenId) public virtual override {
        address owner = ERC721.ownerOf(tokenId);
        require(to != owner, "ERC721: approval to current owner");

        require(
            _msgSender() == owner || isApprovedForAll(owner, _msgSender()),
            "ERC721: approve caller is not token owner or approved for all"
        );

        _approve(to, tokenId);
    }

    /**
     * @dev See {IERC721-getApproved}.
     */
    function getApproved(uint256 tokenId) public view virtual override returns (address) {
        _requireMinted(tokenId);

        return _tokenApprovals[tokenId];
    }

    /**
     * @dev See {IERC721-setApprovalForAll}.
     */
    function setApprovalForAll(address operator, bool approved) public virtual override {
        _setApprovalForAll(_msgSender(), operator, approved);
    }

    /**
     * @dev See {IERC721-isApprovedForAll}.
     */
    function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
        return _operatorApprovals[owner][operator];
    }

    /**
     * @dev See {IERC721-transferFrom}.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        //solhint-disable-next-line max-line-length
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");

        _transfer(from, to, tokenId);
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) public virtual override {
        safeTransferFrom(from, to, tokenId, "");
    }

    /**
     * @dev See {IERC721-safeTransferFrom}.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) public virtual override {
        require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: caller is not token owner or approved");
        _safeTransfer(from, to, tokenId, data);
    }

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * `data` is additional data, it has no specified format and it is sent in call to `to`.
     *
     * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
     * implement alternative mechanisms to perform token transfer, such as signature-based.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeTransfer(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal virtual {
        _transfer(from, to, tokenId);
        require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
    }

    /**
     * @dev Returns the owner of the `tokenId`. Does NOT revert if token doesn't exist
     */
    function _ownerOf(uint256 tokenId) internal view virtual returns (address) {
        return _owners[tokenId];
    }

    /**
     * @dev Returns whether `tokenId` exists.
     *
     * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
     *
     * Tokens start existing when they are minted (`_mint`),
     * and stop existing when they are burned (`_burn`).
     */
    function _exists(uint256 tokenId) internal view virtual returns (bool) {
        return _ownerOf(tokenId) != address(0);
    }

    /**
     * @dev Returns whether `spender` is allowed to manage `tokenId`.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
        address owner = ERC721.ownerOf(tokenId);
        return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender);
    }

    /**
     * @dev Safely mints `tokenId` and transfers it to `to`.
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function _safeMint(address to, uint256 tokenId) internal virtual {
        _safeMint(to, tokenId, "");
    }

    /**
     * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
     * forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
     */
    function _safeMint(
        address to,
        uint256 tokenId,
        bytes memory data
    ) internal virtual {
        _mint(to, tokenId);
        require(
            _checkOnERC721Received(address(0), to, tokenId, data),
            "ERC721: transfer to non ERC721Receiver implementer"
        );
    }

    /**
     * @dev Mints `tokenId` and transfers it to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
     *
     * Requirements:
     *
     * - `tokenId` must not exist.
     * - `to` cannot be the zero address.
     *
     * Emits a {Transfer} event.
     */
    function _mint(address to, uint256 tokenId) internal virtual {
        require(to != address(0), "ERC721: mint to the zero address");
        require(!_exists(tokenId), "ERC721: token already minted");

        _beforeTokenTransfer(address(0), to, tokenId, 1);

        // Check that tokenId was not minted by `_beforeTokenTransfer` hook
        require(!_exists(tokenId), "ERC721: token already minted");

        unchecked {
            // Will not overflow unless all 2**256 token ids are minted to the same owner.
            // Given that tokens are minted one by one, it is impossible in practice that
            // this ever happens. Might change if we allow batch minting.
            // The ERC fails to describe this case.
            _balances[to] += 1;
        }

        _owners[tokenId] = to;

        emit Transfer(address(0), to, tokenId);

        _afterTokenTransfer(address(0), to, tokenId, 1);
    }

    /**
     * @dev Destroys `tokenId`.
     * The approval is cleared when the token is burned.
     * This is an internal function that does not check if the sender is authorized to operate on the token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     *
     * Emits a {Transfer} event.
     */
    function _burn(uint256 tokenId) internal virtual {
        address owner = ERC721.ownerOf(tokenId);

        _beforeTokenTransfer(owner, address(0), tokenId, 1);

        // Update ownership in case tokenId was transferred by `_beforeTokenTransfer` hook
        owner = ERC721.ownerOf(tokenId);

        // Clear approvals
        delete _tokenApprovals[tokenId];

        unchecked {
            // Cannot overflow, as that would require more tokens to be burned/transferred
            // out than the owner initially received through minting and transferring in.
            _balances[owner] -= 1;
        }
        delete _owners[tokenId];

        emit Transfer(owner, address(0), tokenId);

        _afterTokenTransfer(owner, address(0), tokenId, 1);
    }

    /**
     * @dev Transfers `tokenId` from `from` to `to`.
     *  As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     *
     * Emits a {Transfer} event.
     */
    function _transfer(
        address from,
        address to,
        uint256 tokenId
    ) internal virtual {
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
        require(to != address(0), "ERC721: transfer to the zero address");

        _beforeTokenTransfer(from, to, tokenId, 1);

        // Check that tokenId was not transferred by `_beforeTokenTransfer` hook
        require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");

        // Clear approvals from the previous owner
        delete _tokenApprovals[tokenId];

        unchecked {
            // `_balances[from]` cannot overflow for the same reason as described in `_burn`:
            // `from`'s balance is the number of token held, which is at least one before the current
            // transfer.
            // `_balances[to]` could overflow in the conditions described in `_mint`. That would require
            // all 2**256 token ids to be minted, which in practice is impossible.
            _balances[from] -= 1;
            _balances[to] += 1;
        }
        _owners[tokenId] = to;

        emit Transfer(from, to, tokenId);

        _afterTokenTransfer(from, to, tokenId, 1);
    }

    /**
     * @dev Approve `to` to operate on `tokenId`
     *
     * Emits an {Approval} event.
     */
    function _approve(address to, uint256 tokenId) internal virtual {
        _tokenApprovals[tokenId] = to;
        emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
    }

    /**
     * @dev Approve `operator` to operate on all of `owner` tokens
     *
     * Emits an {ApprovalForAll} event.
     */
    function _setApprovalForAll(
        address owner,
        address operator,
        bool approved
    ) internal virtual {
        require(owner != operator, "ERC721: approve to caller");
        _operatorApprovals[owner][operator] = approved;
        emit ApprovalForAll(owner, operator, approved);
    }

    /**
     * @dev Reverts if the `tokenId` has not been minted yet.
     */
    function _requireMinted(uint256 tokenId) internal view virtual {
        require(_exists(tokenId), "ERC721: invalid token ID");
    }

    /**
     * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
     * The call is not executed if the target address is not a contract.
     *
     * @param from address representing the previous owner of the given token ID
     * @param to target address that will receive the tokens
     * @param tokenId uint256 ID of the token to be transferred
     * @param data bytes optional data to send along with the call
     * @return bool whether the call correctly returned the expected magic value
     */
    function _checkOnERC721Received(
        address from,
        address to,
        uint256 tokenId,
        bytes memory data
    ) private returns (bool) {
        if (to.isContract()) {
            try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, data) returns (bytes4 retval) {
                return retval == IERC721Receiver.onERC721Received.selector;
            } catch (bytes memory reason) {
                if (reason.length == 0) {
                    revert("ERC721: transfer to non ERC721Receiver implementer");
                } else {
                    /// @solidity memory-safe-assembly
                    assembly {
                        revert(add(32, reason), mload(reason))
                    }
                }
            }
        } else {
            return true;
        }
    }

    /**
     * @dev Hook that is called before any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens will be transferred to `to`.
     * - When `from` is zero, the tokens will be minted for `to`.
     * - When `to` is zero, ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual {}

    /**
     * @dev Hook that is called after any token transfer. This includes minting and burning. If {ERC721Consecutive} is
     * used, the hook may be called as part of a consecutive (batch) mint, as indicated by `batchSize` greater than 1.
     *
     * Calling conditions:
     *
     * - When `from` and `to` are both non-zero, ``from``'s tokens were transferred to `to`.
     * - When `from` is zero, the tokens were minted for `to`.
     * - When `to` is zero, ``from``'s tokens were burned.
     * - `from` and `to` are never both zero.
     * - `batchSize` is non-zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 firstTokenId,
        uint256 batchSize
    ) internal virtual {}

    /**
     * @dev Unsafe write access to the balances, used by extensions that "mint" tokens using an {ownerOf} override.
     *
     * WARNING: Anyone calling this MUST ensure that the balances remain consistent with the ownership. The invariant
     * being that for any address `a` the value returned by `balanceOf(a)` must be equal to the number of tokens such
     * that `ownerOf(tokenId)` is `a`.
     */
    // solhint-disable-next-line func-name-mixedcase
    function __unsafe_increaseBalance(address account, uint256 amount) internal {
        _balances[account] += amount;
    }
}
IERC721.sol 145 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC721/IERC721.sol)

pragma solidity ^0.8.0;

import "../../utils/introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId,
        bytes calldata data
    ) external;

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
     * or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
     * understand this adds an external call which potentially creates a reentrancy vulnerability.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address from,
        address to,
        uint256 tokenId
    ) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);
}
IERC721Receiver.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

/**
 * @title ERC721 token receiver interface
 * @dev Interface for any contract that wants to support safeTransfers
 * from ERC721 asset contracts.
 */
interface IERC721Receiver {
    /**
     * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
     * by `operator` from `from`, this function is called.
     *
     * It must return its Solidity selector to confirm the token transfer.
     * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
     *
     * The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
     */
    function onERC721Received(
        address operator,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external returns (bytes4);
}
IERC721Metadata.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {
    /**
     * @dev Returns the token collection name.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}
Address.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @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://diligence.consensys.net/posts/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.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @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, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * 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.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @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`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResultFromTarget(target, success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
     * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
     *
     * _Available since v4.8._
     */
    function verifyCallResultFromTarget(
        address target,
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        if (success) {
            if (returndata.length == 0) {
                // only check isContract if the call was successful and the return data is empty
                // otherwise we already know that it was a contract
                require(isContract(target), "Address: call to non-contract");
            }
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    /**
     * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason or using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            _revert(returndata, errorMessage);
        }
    }

    function _revert(bytes memory returndata, string memory errorMessage) 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
            /// @solidity memory-safe-assembly
            assembly {
                let returndata_size := mload(returndata)
                revert(add(32, returndata), returndata_size)
            }
        } else {
            revert(errorMessage);
        }
    }
}
Context.sol 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

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

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }
}
ShortStrings.sol 122 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ShortStrings.sol)

pragma solidity ^0.8.20;

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

// | string  | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA   |
// | length  | 0x                                                              BB |
type ShortString is bytes32;

/**
 * @dev This library provides functions to convert short memory strings
 * into a `ShortString` type that can be used as an immutable variable.
 *
 * Strings of arbitrary length can be optimized using this library if
 * they are short enough (up to 31 bytes) by packing them with their
 * length (1 byte) in a single EVM word (32 bytes). Additionally, a
 * fallback mechanism can be used for every other case.
 *
 * Usage example:
 *
 * ```solidity
 * contract Named {
 *     using ShortStrings for *;
 *
 *     ShortString private immutable _name;
 *     string private _nameFallback;
 *
 *     constructor(string memory contractName) {
 *         _name = contractName.toShortStringWithFallback(_nameFallback);
 *     }
 *
 *     function name() external view returns (string memory) {
 *         return _name.toStringWithFallback(_nameFallback);
 *     }
 * }
 * ```
 */
library ShortStrings {
    // Used as an identifier for strings longer than 31 bytes.
    bytes32 private constant FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;

    error StringTooLong(string str);
    error InvalidShortString();

    /**
     * @dev Encode a string of at most 31 chars into a `ShortString`.
     *
     * This will trigger a `StringTooLong` error is the input string is too long.
     */
    function toShortString(string memory str) internal pure returns (ShortString) {
        bytes memory bstr = bytes(str);
        if (bstr.length > 31) {
            revert StringTooLong(str);
        }
        return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
    }

    /**
     * @dev Decode a `ShortString` back to a "normal" string.
     */
    function toString(ShortString sstr) internal pure returns (string memory) {
        uint256 len = byteLength(sstr);
        // using `new string(len)` would work locally but is not memory safe.
        string memory str = new string(32);
        assembly ("memory-safe") {
            mstore(str, len)
            mstore(add(str, 0x20), sstr)
        }
        return str;
    }

    /**
     * @dev Return the length of a `ShortString`.
     */
    function byteLength(ShortString sstr) internal pure returns (uint256) {
        uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
        if (result > 31) {
            revert InvalidShortString();
        }
        return result;
    }

    /**
     * @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
     */
    function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
        if (bytes(value).length < 32) {
            return toShortString(value);
        } else {
            StorageSlot.getStringSlot(store).value = value;
            return ShortString.wrap(FALLBACK_SENTINEL);
        }
    }

    /**
     * @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
     */
    function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return toString(value);
        } else {
            return store;
        }
    }

    /**
     * @dev Return the length of a string that was encoded to `ShortString` or written to storage using
     * {setWithFallback}.
     *
     * WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
     * actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
     */
    function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
        if (ShortString.unwrap(value) != FALLBACK_SENTINEL) {
            return byteLength(value);
        } else {
            return bytes(store).length;
        }
    }
}
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 70 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @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;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @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) {
        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] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        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);
    }
}
ECDSA.sol 213 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @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,
        InvalidSignatureV // Deprecated in v4.8
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode 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 {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]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        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.
            /// @solidity memory-safe-assembly
            assembly {
                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);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode 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 {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        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[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        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.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // 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);
        }

        // 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);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @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) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}
EIP712.sol 160 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/EIP712.sol)

pragma solidity ^0.8.20;

import {MessageHashUtils} from "./MessageHashUtils.sol";
import {ShortStrings, ShortString} from "../ShortStrings.sol";
import {IERC5267} from "../../interfaces/IERC5267.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP-712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding scheme specified in the EIP requires a domain separator and a hash of the typed structured data, whose
 * encoding is very generic and therefore its implementation in Solidity is not feasible, thus this contract
 * does not implement the encoding itself. Protocols need to implement the type-specific encoding they need in order to
 * produce the hash of their typed data using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP-712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
 * separator of the implementation contract. This will cause the {_domainSeparatorV4} function to always rebuild the
 * separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
 *
 * @custom:oz-upgrades-unsafe-allow state-variable-immutable
 */
abstract contract EIP712 is IERC5267 {
    using ShortStrings for *;

    bytes32 private constant TYPE_HASH =
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");

    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _cachedDomainSeparator;
    uint256 private immutable _cachedChainId;
    address private immutable _cachedThis;

    bytes32 private immutable _hashedName;
    bytes32 private immutable _hashedVersion;

    ShortString private immutable _name;
    ShortString private immutable _version;
    string private _nameFallback;
    string private _versionFallback;

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP-712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        _name = name.toShortStringWithFallback(_nameFallback);
        _version = version.toShortStringWithFallback(_versionFallback);
        _hashedName = keccak256(bytes(name));
        _hashedVersion = keccak256(bytes(version));

        _cachedChainId = block.chainid;
        _cachedDomainSeparator = _buildDomainSeparator();
        _cachedThis = address(this);
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
            return _cachedDomainSeparator;
        } else {
            return _buildDomainSeparator();
        }
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return MessageHashUtils.toTypedDataHash(_domainSeparatorV4(), structHash);
    }

    /**
     * @dev See {IERC-5267}.
     */
    function eip712Domain()
        public
        view
        virtual
        returns (
            bytes1 fields,
            string memory name,
            string memory version,
            uint256 chainId,
            address verifyingContract,
            bytes32 salt,
            uint256[] memory extensions
        )
    {
        return (
            hex"0f", // 01111
            _EIP712Name(),
            _EIP712Version(),
            block.chainid,
            address(this),
            bytes32(0),
            new uint256[](0)
        );
    }

    /**
     * @dev The name parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _name which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Name() internal view returns (string memory) {
        return _name.toStringWithFallback(_nameFallback);
    }

    /**
     * @dev The version parameter for the EIP712 domain.
     *
     * NOTE: By default this function reads _version which is an immutable value.
     * It only reads from storage if necessary (in case the value is too large to fit in a ShortString).
     */
    // solhint-disable-next-line func-name-mixedcase
    function _EIP712Version() internal view returns (string memory) {
        return _version.toStringWithFallback(_versionFallback);
    }
}
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)
        }
    }
}
ERC165.sol 29 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 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);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * 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[EIP 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 345 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

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

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return 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 up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

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

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 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.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            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^256 / 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^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            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^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

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

    /**
     * @notice 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) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice 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 + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 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 + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * 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 + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * 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;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                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 log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}
BVGS.sol 365 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.30;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./Withdrawals.sol";
import "./SignatureVerification.sol";

/* ───────────────────────────── ERC-5192 / Soulbound standard ──────────────────────────────── */
interface IERC5192 {

    /// Emitted exactly once when a token becomes locked (non-transferable).
    event Locked(uint256 tokenId);

    /// Emitted if a token ever becomes unlocked (not used, but declared for ERC-5192 compliance).
    event Unlocked(uint256 tokenId);

    /// MUST always return true for every existing BVGS NFT.
    function locked(uint256 tokenId) external view returns (bool);
}

/**
 * @title BVGS
 * @dev Core soul-bound ERC-721 contract for BVGS NFT creation and bagging flows 
 *      Implements ERC-5192 (soulbound standard) for non-transferability.
 *      Inherits the Withdrawals smart contract which inherits Deposits and SignatureVerification contracts.
 */
contract BVGS is ERC721, Ownable, Withdrawals, IERC5192 {

    /// @dev Next token ID to mint (auto-incremented per mint.
    uint256 private _nextId;
    
    /* ─────────── Custom errors ───────── */
    error ZeroTokenAddress();
    error ArrayLengthMismatch();
    error EthValueMismatch();
    error DefaultURIAlreadySet();
    error NoURI();
    error TransfersDisabled();
    error UseDepositETH();
    error FallbackNotAllowed();


    /* ───────────────────────── Metadata storage ────────────────────────── */
    string  private _defaultMetadataURI;
    bool    private _defaultURISet;
    mapping(uint256 => string) private _tokenMetadataURIs;

    /// Emitted whenever a per-token metadata URI is set/updated.
    event TokenMetadataURISet(uint256 indexed tokenId, bytes32 indexed referenceId);
    event Bagged(uint256 indexed tokenId, bytes32 indexed referenceId);


    /* ─────────────────────────── Constructor ───────────────────────────── */

    /**
     * @dev Deploys the contract and initializes the EIP-712 domain used for
     *      signature authorization in SignatureVerification.
     */
    constructor()
        ERC721("bvgs", "BVGS")
        SignatureVerification(address(this))
    {}


    /* ─────────── Bagging callback (burn underlying ERC-721) ───────────── */
    function _burnBagNFT(uint256 tokenId) internal override {
        _burn(tokenId);
    }


    /* ───────────────────────── Minting + bagging flows ───────────────────────── */

    /**
     * @notice Mint a new BVGS NFT and deposit ETH.
     * @param to The address that will receive the newly minted BVGS NFT.
     * @param bvgsPublicKey The public key used for on-chain signature verification.
     * @param referenceId An external reference ID for off-chain tracking of this deposit.
     * 
     * Requirements:
     * - `to` must not be the zero address.
     * - `bvgsPublicKey` must not be the zero address.
     * - `msg.value` > 0 to deposit ETH.
     */
    function bagETH(
        address to,
        address bvgsPublicKey,
        bytes32 referenceId
    ) external payable nonReentrant {
        if (to == address(0))            revert ZeroAddress();
        if (bvgsPublicKey == address(0)) revert ZeroKey();

        uint256 tokenId = _nextId++; 

        if (to.code.length == 0) {       
            _mint(to, tokenId);
        } else {                          
            _safeMint(to, tokenId);
        }

        emit Locked(tokenId);

        initialize(tokenId, bvgsPublicKey);
        _depositETH(tokenId, msg.value);

        emit Bagged(tokenId, referenceId);
    }

    /**
     * @notice Mint a new BVGS NFT and deposit ERC20 tokens.
     * @param to The recipient of the newly minted BVGS NFT.
     * @param bvgsPublicKey The public key used for off-chain signature verification.
     * @param tokenAddress The ERC20 token contract address to deposit.
     * @param amount The amount of ERC20 tokens to deposit.
     * @param referenceId An external reference ID for off-chain tracking.
     * 
     * Requirements:
     * - `to` and `bvgsPublicKey` must not be the zero address.
     * - `tokenAddress` must not be the zero address.
     * - `amount` must be greater than zero.
     */
    function bagERC20(
        address to,
        address bvgsPublicKey,
        address tokenAddress,
        uint256 amount,
        bytes32 referenceId
    ) external nonReentrant {
        if (to == address(0))            revert ZeroAddress();
        if (bvgsPublicKey == address(0)) revert ZeroKey();
        if (tokenAddress == address(0))  revert ZeroTokenAddress();
        if (amount == 0)                 revert ZeroAmount();

        uint256 tokenId = _nextId++; 

        if (to.code.length == 0) {    
            _mint(to, tokenId);
        } else {                         
            _safeMint(to, tokenId);
        }

        emit Locked(tokenId);

        initialize(tokenId, bvgsPublicKey);
        _depositERC20(tokenId, tokenAddress, amount);

        emit Bagged(tokenId, referenceId);
    }

    /**
     * @notice Mint a new BVGS NFT and deposit a single ERC721.
     * @param to The recipient of the newly minted BVGS NFT.
     * @param bvgsPublicKey The public key used for off-chain signature verification.
     * @param nftContract The ERC721 contract address to deposit.
     * @param externalNftTokenId The token ID of the ERC721 to deposit.
     * @param referenceId An external reference ID for off-chain tracking.
     * 
     * Requirements:
     * - `to`, `bvgsPublicKey`, and `nftContract` must not be the zero address.
     */
    function bagERC721(
        address to,
        address bvgsPublicKey,
        address nftContract,
        uint256 externalNftTokenId,
        bytes32 referenceId
    ) external nonReentrant {
        if (to == address(0))            revert ZeroAddress();
        if (bvgsPublicKey == address(0)) revert ZeroKey();
        if (nftContract == address(0))   revert ZeroTokenAddress();

        uint256 tokenId = _nextId++; 

        if (to.code.length == 0) {      
            _mint(to, tokenId);
        } else {                          
            _safeMint(to, tokenId);
        }

        emit Locked(tokenId);

        initialize(tokenId, bvgsPublicKey);
        _depositERC721(tokenId, nftContract, externalNftTokenId);

        emit Bagged(tokenId, referenceId);
    }

    /**
     * @notice Mint a new BVGS NFT and perform a batch deposit of ETH, ERC20s, and ERC721s.
     * @param to The recipient of the newly minted BVGS NFT.
     * @param bvgsPublicKey The public key used for off-chain signature verification.
     * @param amountETH The amount of ETH to deposit.
     * @param tokenAddresses ERC20 token contract addresses to deposit.
     * @param tokenAmounts Corresponding amounts of each ERC20 to deposit.
     * @param nftContracts ERC721 contract addresses to deposit.
     * @param nftTokenIds Corresponding token IDs of each ERC721 to deposit.
     * @param referenceId An external reference ID for off-chain tracking.
     * 
     * Requirements:
     * - `to` and `bvgsPublicKey` must not be zero addresses.
     * - `tokenAddresses.length == tokenAmounts.length`.
     * - `nftContracts.length == nftTokenIds.length`.
     * - `msg.value == amountETH`.
     */
    function bagBatch(
        address to,
        address bvgsPublicKey,
        uint256 amountETH,
        address[] calldata tokenAddresses,
        uint256[] calldata tokenAmounts,
        address[] calldata nftContracts,
        uint256[] calldata nftTokenIds,
        bytes32 referenceId
    ) external payable nonReentrant {
        if (to == address(0))            revert ZeroAddress();
        if (bvgsPublicKey == address(0)) revert ZeroKey();
        if (
            tokenAddresses.length != tokenAmounts.length ||
            nftContracts.length  != nftTokenIds.length
        ) revert ArrayLengthMismatch();
        if (msg.value != amountETH) revert EthValueMismatch();

        uint256 tokenId = _nextId++; 

        if (to.code.length == 0) {        
            _mint(to, tokenId);
        } else {                         
            _safeMint(to, tokenId);
        }

        emit Locked(tokenId);

        initialize(tokenId, bvgsPublicKey);
        _batchDeposit(
            tokenId,
            amountETH,
            tokenAddresses,
            tokenAmounts,
            nftContracts,
            nftTokenIds
        );

        emit Bagged(tokenId, referenceId);
    }


    /* ──────────────────────── Default metadata management ──────────────────────── */

    /**
     * @notice Sets the default metadata URI for all BVGS NFTs (only once).
     * @param newDefaultURI The base metadata URI to use for tokens without custom URIs.
     * @dev Can only be called by the contract owner, and only once.
     *      
     * Requirements:
     * - `_defaultURISet` must be false.
     */
    function setDefaultMetadataURI(string memory newDefaultURI)
        external onlyOwner
    {
        if (_defaultURISet) revert DefaultURIAlreadySet();
        _defaultMetadataURI = newDefaultURI;
        _defaultURISet      = true;
    }


    /* ───────────────────────── Token-gated + EIP-712 secured metadata management ────────────────────────── */

    /**
     * @notice Sets or updates a custom metadata URI for a specific BVGS NFT.
     * @param tokenId The ID of the BVGS NFT to update.
     * @param messageHash The EIP-712 digest that was signed.
     * @param signature The EIP-712 signature by the active BVGS key.
     * @param newMetadataURI The new metadata URI to assign.
     * @param referenceId An external reference ID for off-chain tracking.
     * @param signatureExpiry UNIX timestamp until which the signature is valid.
     * 
     * Requirements:
     * - `tokenId` must exist and caller must be its owner.
     * - `signature` must be valid and unexpired.
     */
    function setTokenMetadataURI(
        uint256 tokenId,
        bytes32 messageHash,
        bytes memory signature,
        string memory newMetadataURI,
        bytes32 referenceId,
        uint256 signatureExpiry
    ) external nonReentrant {
        if (!_exists(tokenId))                revert NonexistentToken();
        if (ownerOf(tokenId) != msg.sender)   revert NotOwner();
        if (block.timestamp > signatureExpiry) revert SignatureExpired();

        bytes memory data = abi.encode(
            tokenId, newMetadataURI, referenceId, msg.sender, signatureExpiry
        );
        verifySignature(
            tokenId, messageHash, signature,
            address(0), OperationType.SET_TOKEN_URI, data
        );

        _tokenMetadataURIs[tokenId] = newMetadataURI;
        emit TokenMetadataURISet(tokenId, referenceId);
    }

    /**
     * @notice Returns the metadata URI for a BVGS NFT.
     * @param tokenId The ID of the token to query.
     * @return The custom URI if set; otherwise the default URI.
     * @dev Reverts if neither custom nor default URI is available.
     */
    function tokenURI(uint256 tokenId)
        public view override(ERC721)
        returns (string memory)
    {
        if (!_exists(tokenId)) revert NonexistentToken();
        string memory custom = _tokenMetadataURIs[tokenId];
        if (bytes(custom).length > 0) return custom;
        if (bytes(_defaultMetadataURI).length > 0) return _defaultMetadataURI;
        revert NoURI();
    }


    /* ────────────────────── Soul-bound mechanics (ERC-5192) ────────────── */

    /**
     * @notice Always returns true for existing BVGS NFTs (soul‐bound).
     * @param tokenId The ID of the BVGS NFT.
     * @return Always true.
     * @dev Reverts if token does not exist.
     */
    function locked(uint256 tokenId) external view override returns (bool) {
        if (!_exists(tokenId)) revert NonexistentToken();
        return true;
    }

    /// Disable any transfer—soul‐bound enforcement.
    function _transfer(address, address, uint256) internal pure override {
        revert TransfersDisabled();
    }


    /* ─────────────────── ERC-721 standard overrides ────────────────────── */

    /// Clears custom metadata on burn.
    function _burn(uint256 tokenId)
        internal override(ERC721)
    {
        super._burn(tokenId);
        delete _tokenMetadataURIs[tokenId];
    }

    function supportsInterface(bytes4 interfaceId)
        public view override(ERC721)
        returns (bool)
    {
        if (interfaceId == 0xb45a3c0e) return true; // IERC5192
        return super.supportsInterface(interfaceId);
    }


    /* ───────────────────────── Fallback handlers ───────────────────────── */
    receive() external payable { revert UseDepositETH(); }
    fallback() external payable { revert FallbackNotAllowed(); }
}
Deposits.sol 282 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.30;

import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./SignatureVerification.sol";   

/**
 * @title Deposits
 * @dev Internal ETH/ERC20/ERC721 deposit and bookkeeping logic.
 *      Inherits SignatureVerification for key access and ReentrancyGuard for safety.
 */
abstract contract Deposits is SignatureVerification, IERC721Receiver, ReentrancyGuard {
    using SafeERC20 for IERC20;

    /* ───────── Events ───────── */
    event Deposited (uint256 indexed tokenId, bytes32 indexed referenceId);


    /* ───────── Errors ───────── */
    error NonexistentToken();
    error ZeroAddress();
    error ZeroAmount();
    error MismatchedInputs();
    error ETHMismatch();


    /* ───────── Storage ───────── */
    mapping(uint256 => uint256) internal _baggedETH;

    // ERC-20
    mapping(uint256 => mapping(address => uint256))   internal _erc20Balances;
    mapping(uint256 => address[])                     internal _erc20TokenAddresses;
    mapping(uint256 => mapping(address => bool))      internal _erc20Known;

    // ERC-721
    struct BaggedNFT { address nftContract; uint256 nftTokenId; }
    mapping(uint256 => bytes32[])                     internal _nftKeys;
    mapping(uint256 => mapping(bytes32 => BaggedNFT)) internal _nftData;
    mapping(uint256 => mapping(bytes32 => bool))      internal _nftKnown;


    /* ───────── Guards ───────── */
    function _requireOwnsBag(uint256 tokenId) internal view {
        if (_erc721.ownerOf(tokenId) != msg.sender) revert NotOwner();
    }
    function _requireExists(uint256 tokenId) internal view {
        address owner;
        try _erc721.ownerOf(tokenId) returns (address o) { owner = o; } catch { revert NonexistentToken(); }
        if (owner == address(0)) revert NonexistentToken();
    }


    /* ───────── IERC721Receiver ───────── */
    function onERC721Received(address, address, uint256, bytes calldata)
        public pure override returns (bytes4)
    { return this.onERC721Received.selector; }


    /* ══════════════════  USER-FACING DEPOSIT WRAPPERS  ══════════════════ */
    
    /*
    * @notice Deposit ETH into a BVGS NFT.
    * @param tokenId    The ID of the BVGS NFT.
    * @param referenceId External reference ID for off-chain tracking.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `msg.value` must be > 0.
    */
    function depositETH(uint256 tokenId, bytes32 referenceId)
        external payable nonReentrant
    {
        _requireOwnsBag(tokenId);
        if (msg.value == 0) revert ZeroAmount();

        _depositETH(tokenId, msg.value);
        emit Deposited(tokenId, referenceId);
    }

    /*
    * @notice Deposit ERC-20 tokens into a BVGS NFT.
    * @param tokenId      The ID of the BVGS NFT.
    * @param tokenAddress The ERC-20 token contract address.
    * @param amount       The amount of tokens to deposit.
    * @param referenceId  External reference ID for off-chain tracking.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `tokenAddress` must not be the zero address.
    * - `amount` must be greater than zero.
    */
    function depositERC20(
        uint256 tokenId,
        address tokenAddress,
        uint256 amount,
        bytes32 referenceId
    ) external nonReentrant {
        _requireOwnsBag(tokenId);
        if (tokenAddress == address(0)) revert ZeroAddress();
        if (amount == 0)           revert ZeroAmount();

        _depositERC20(tokenId, tokenAddress, amount);
        emit Deposited(tokenId, referenceId);
    }

    /*
    * @notice Deposit an ERC-721 NFT into a BVGS NFT.
    * @param tokenId      The ID of the BVGS NFT.
    * @param nftContract  The ERC-721 contract address.
    * @param nftTokenId   The token ID of the ERC-721 to deposit.
    * @param referenceId  External reference ID for off-chain tracking.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `nftContract` must not be the zero address.
    */
    function depositERC721(
        uint256 tokenId,
        address nftContract,
        uint256 nftTokenId,
        bytes32 referenceId
    ) external nonReentrant {
        _requireOwnsBag(tokenId);
        if (nftContract == address(0)) revert ZeroAddress();

        _depositERC721(tokenId, nftContract, nftTokenId);
        emit Deposited(tokenId, referenceId);
    }

    /*
    * @notice Batch-deposit ETH, multiple ERC-20s, and multiple ERC-721s in one call.
    * @param tokenId         The ID of the BVGS NFT.
    * @param amountETH       The ETH amount to deposit.
    * @param tokenAddresses  The list of ERC-20 token addresses.
    * @param tokenAmounts    The corresponding ERC-20 token amounts.
    * @param nftContracts    The list of ERC-721 contract addresses.
    * @param nftTokenIds     The corresponding ERC-721 token IDs.
    * @param referenceId     External reference ID for off-chain tracking.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `tokenAddresses.length` must equal `tokenAmounts.length`.
    * - `nftContracts.length` must equal `nftTokenIds.length`.
    * - `msg.value` must equal `amountETH`.
    */
    function batchDeposit(
        uint256 tokenId,
        uint256 amountETH,
        address[] calldata tokenAddresses,
        uint256[] calldata tokenAmounts,
        address[] calldata nftContracts,
        uint256[] calldata nftTokenIds,
        bytes32 referenceId
    ) external payable nonReentrant {
        _requireOwnsBag(tokenId);
        if (msg.value != amountETH) revert ETHMismatch();

        _batchDeposit(tokenId, amountETH, tokenAddresses, tokenAmounts, nftContracts, nftTokenIds);

        emit Deposited(tokenId, referenceId);
    }


    /* ══════════════════  INTERNAL DEPOSIT HELPERS  ══════════════════ */

    function _depositETH(uint256 tokenId, uint256 amountETH) internal {
        if (amountETH == 0) return;
        _baggedETH[tokenId] += amountETH;
    }

    function _depositERC20(
        uint256 tokenId,
        address tokenAddress,
        uint256 amount
    ) internal {
        IERC20 t = IERC20(tokenAddress);

        // Register token if new
        if (!_erc20Known[tokenId][tokenAddress]) {
            _erc20TokenAddresses[tokenId].push(tokenAddress);
            _erc20Known[tokenId][tokenAddress] = true;
        }

        // Pull tokens
        uint256 beforeBal = t.balanceOf(address(this));
        t.safeTransferFrom(msg.sender, address(this), amount);
        uint256 afterBal  = t.balanceOf(address(this));

        // Book the delta
        // Ensures assets booked match assets received regardless of input
        uint256 delta = afterBal > beforeBal ? afterBal - beforeBal : 0;
        
        if (delta == 0) revert ZeroAmount();
        
        _erc20Balances[tokenId][tokenAddress] += delta;
    }

    function _depositERC721(
        uint256 tokenId,
        address nftContract,
        uint256 nftTokenId
    ) internal {

        // Register NFT 
        bytes32 key = keccak256(abi.encodePacked(nftContract, nftTokenId));
        if (!_nftKnown[tokenId][key]) {
            _nftKeys[tokenId].push(key);
            _nftKnown[tokenId][key] = true;
        }
        _nftData[tokenId][key] = BaggedNFT(nftContract, nftTokenId);

        // Pull token
        IERC721(nftContract).safeTransferFrom(msg.sender, address(this), nftTokenId);
    }

    function _batchDeposit(
        uint256 tokenId,
        uint256 amountETH,
        address[] calldata tokenAddresses,
        uint256[] calldata tokenAmounts,
        address[] calldata nftContracts,
        uint256[] calldata nftTokenIds
    ) internal {
        if (tokenAddresses.length != tokenAmounts.length || nftContracts.length != nftTokenIds.length) revert MismatchedInputs();
        if (amountETH > 0) _baggedETH[tokenId] += amountETH;

        uint256 erc20Count = tokenAddresses.length;
        for (uint256 i; i < erc20Count; ) {
            _depositERC20(tokenId, tokenAddresses[i], tokenAmounts[i]);
            unchecked { ++i; }
        }

        uint256 nftCount = nftContracts.length;
        for (uint256 i; i < nftCount; ) {
            _depositERC721(tokenId, nftContracts[i], nftTokenIds[i]);
            unchecked { ++i; }
        }
    }


    /* ══════════════════  INTERNAL BOOK-KEEPING UTILITIES  ══════════════════ */

    /*
    * @dev Remove an ERC20 token address from the bag’s tracking array using swap & pop.
    * @param tokenId The BVGS NFT ID.
    * @param tokenAddress The ERC20 token address to remove.
    */
    function _removeERC20Token(uint256 tokenId, address tokenAddress) internal {
        address[] storage tokenAddresses = _erc20TokenAddresses[tokenId];
        uint256 len = tokenAddresses.length;
        for (uint256 i; i < len; ) {
            if (tokenAddresses[i] == tokenAddress) {
                tokenAddresses[i] = tokenAddresses[len - 1];
                tokenAddresses.pop();
                break;
            }
            unchecked { ++i; } 
        }
    }

    /*
    * @dev Remove an ERC721 key from the bag’s tracking array using swap & pop.
    * @param tokenId The BVGS NFT ID.
    * @param key The keccak256(nftContract, tokenId) to remove.
    */
    function _removeNFTKey(uint256 tokenId, bytes32 key) internal {
        bytes32[] storage keys = _nftKeys[tokenId];
        uint256 len = keys.length;
        for (uint256 i = 0; i < len; ) {
            if (keys[i] == key) {
                keys[i] = keys[len - 1];
                keys.pop();
                break;
            }
            unchecked { ++i; }
        }
    }   
}
SignatureVerification.sol 191 lines
// SPDX-License-Identifier: BUSL-1.1
// Copyright © 2025 BVGS. All Rights Reserved.
// You may use, modify, and share this code for NON-COMMERCIAL purposes only.
// Commercial use requires written permission from BVGS.
pragma solidity ^0.8.30;

import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/utils/cryptography/EIP712.sol";

/**
 * @title SignatureVerification
 * @notice Provides signature-based authorization for Bagging contract operations using EIP‑712.
 * @dev Each BVGS NFT references an active BVGS public key that must sign operations.
 *      The contract stores a nonce to prevent replay attacks.
 */
contract SignatureVerification is EIP712 {
    using ECDSA for bytes32;

    /// @notice Enumerates the possible operations that require BVGS key authorization.
    enum OperationType {
        ROTATE_KEY,
        UNBAG_ETH,
        UNBAG_ERC20,
        UNBAG_NFT,
        BURN_BAG,
        SET_TOKEN_URI,
        BATCH_UNBAG
    }

    /// @dev Gas-cheap pointer to the BVGS ERC-721 (set once in constructor).
    ERC721 immutable _erc721;  

    /**
     * @dev Stores authorization data for each BVGS NFT.
     * @param nonce Monotonically increasing value to prevent signature replay.
     * @param activeBvgsPublicKey The public key currently authorized to sign operations for this BVGS NFT.
     */
    struct TokenAuth {
        address activeBvgsPublicKey;      
        uint96  nonce;                  
    }

    /// @dev Mapping from BVGS NFT token ID to its TokenAuth.
    mapping(uint256 => TokenAuth) private _tokenAuth;


    /* ─────────────────── Errors ────────────────────── */
    error NotOwner();
    error InvalidMessageHash();
    error InvalidSignature();
    error AlreadyInitialized();
    error ZeroKey();


    /* ─────────────────── EIP-712 setup ───────────────────── */

    /**
     * @dev Typehash for the operation, including tokenId, nonce, opType (as uint8),
     *      and a bytes32 hash of the data.
     */
    bytes32 private constant OPERATION_TYPEHASH =
        keccak256("Operation(uint256 tokenId,uint256 nonce,uint8 opType,bytes32 dataHash)");


    /**
     * @notice Constructor that sets the reference to the ERC721 contract for BVGS NFT ownership checks.
     * @param erc721Address The address of the ERC721 contract that mints/owns the BVGS NFTs.
     */
    constructor(address erc721Address) EIP712("BVGS", "1") {
        _erc721 = ERC721(erc721Address);
    }

    /**
     * @notice Initializes the BVGS NFT data with a public key and nonce.
     * @dev Intended to be called once upon minting a new BVGS NFT.
     * @param tokenId The ID of the BVGS NFT being initialized.
     * @param bvgsPublicKey The public key that will sign operations for this BVGS NFT.
     */
    function initialize(uint256 tokenId, address bvgsPublicKey) internal {
        if (_tokenAuth[tokenId].activeBvgsPublicKey != address(0)) {
            revert AlreadyInitialized();
        }   

        _tokenAuth[tokenId].activeBvgsPublicKey = bvgsPublicKey; 
        _tokenAuth[tokenId].nonce               = 1;            
    }

    /**
     * @notice Modifier that checks the caller is the owner of the specified token.
     * @param tokenId The ID of the BVGS NFT to check ownership against.
     */
    modifier onlyTokenOwner(uint256 tokenId) {
        if (_erc721.ownerOf(tokenId) != msg.sender) revert NotOwner();
        _;
    }

    /**
     * @notice Verifies an EIP‑712 signature for a specific operation.
     * @param tokenId The ID of the BVGS NFT.
     * @param messageHash The EIP‑712 digest that was signed.
     * @param signature The BVGS NFT private key signature to verify.
     * @param newBvgsPublicKey The new BVGS NFT public key (if rotating the key).
     * @param opType The operation being authorized.
     * @param data Encoded parameters for the specific operation.
     *
     * Requirements:
     * - The EIP-712 message digest must match `messageHash`.
     * - The signature must be valid for the current, active BVGS NFT public key.
     * - On successful verification, the nonce increments.
     * - If `opType` is `ROTATE_KEY`, the BVGS NFT public key is updated to `newBvgsPublicKey`.
     */
    function verifySignature(
        uint256 tokenId,
        bytes32 messageHash,
        bytes memory signature,
        address newBvgsPublicKey,
        OperationType opType,
        bytes memory data
    ) internal {
        TokenAuth storage tokenAuth = _tokenAuth[tokenId];

        // Compute the hash of the operation data.
        bytes32 dataHash = keccak256(data);
        bytes32 structHash = keccak256(
            abi.encode(
                OPERATION_TYPEHASH,
                tokenId,
                tokenAuth.nonce,
                uint8(opType),
                dataHash
            )
        );
        bytes32 expectedHash = _hashTypedDataV4(structHash);

        if (messageHash != expectedHash) {
            revert InvalidMessageHash();
        }

        address signer = expectedHash.recover(signature);
        if (signer != tokenAuth.activeBvgsPublicKey) {
            revert InvalidSignature();
        }

        // Increment nonce after successful verification.
        tokenAuth.nonce++;

        // If rotating the key, update the active BVGS public key.
        if (opType == OperationType.ROTATE_KEY && newBvgsPublicKey != address(0)) {
            if (newBvgsPublicKey == address(0)) revert ZeroKey();
            tokenAuth.activeBvgsPublicKey = newBvgsPublicKey;
        }
    }


    /* ─────────────────── Token-gated view functions ────────────────────── */

    /**
     * @notice Retrieves the current BVGS public key for the given BVGS NFT.
     * @param tokenId The ID of the BVGS NFT.
     * @return The currently active BVGS public key.
     *
     * Requirements:
     * - Caller must be the owner of `tokenId`.
     */
    function getActiveBvgsPublicKeyForToken(uint256 tokenId)
        external
        view
        onlyTokenOwner(tokenId)
        returns (address)
    {
        return _tokenAuth[tokenId].activeBvgsPublicKey;
    }

    /**
     * @notice Retrieves the current nonce for the given BVGS NFT.
     * @param tokenId The ID of the BVGS NFT.
     * @return The current nonce used for signature verification.
     *
     * Requirements:
     * - Caller must be the owner of `tokenId`.
     */
    function getNonce(uint256 tokenId)
        external
        view
        onlyTokenOwner(tokenId)
        returns (uint256)
    {
        return uint256(_tokenAuth[tokenId].nonce); 
    }
}
Withdrawals.sol 435 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.30;

import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "./Deposits.sol";

/**
 * @title Withdrawals
 * @dev Signature-gated unbag, burn, key-rotation, plus view helpers.
 *      Inherits Deposits for storage & deposit helpers, and
 *      SignatureVerification for EIP-712 auth.
 */
abstract contract Withdrawals is Deposits {
    using SafeERC20 for IERC20;


    /* ───────── Events ───────── */
    event Unbagged  (uint256 indexed tokenId, bytes32 indexed referenceId);
    event BagBurned (uint256 indexed tokenId, bytes32 indexed referenceId);
    event KeyRotated(uint256 indexed tokenId, bytes32 indexed referenceId);


    /* ───────── Errors ───────── */
    error SignatureExpired();
    error NoETHBagged();
    error InsufficientTokenBalance();
    error NFTNotFound();
    error EthTransferFailed();


    /* ══════════════════  USER-FACING UNBAGGING METHODS  ══════════════════ */

    /*
    * @notice Withdraw ETH from a bag, authorized via EIP-712 signature.
    * @param tokenId         The ID of the BVGS NFT.
    * @param messageHash     The EIP-712 digest that was signed.
    * @param signature       The EIP-712 signature by the active BVGS key.
    * @param amountETH       The amount of ETH to withdraw.
    * @param recipient       The address receiving the ETH.
    * @param referenceId     External reference ID for off-chain tracking.
    * @param signatureExpiry UNIX timestamp after which the signature is invalid.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `recipient` must not be the zero address.
    * - `block.timestamp` must be ≤ `signatureExpiry`.
    * - bag must have ≥ `amountETH` ETH
    */
    function unbagETH(
        uint256 tokenId,
        bytes32 messageHash,
        bytes memory signature,
        uint256 amountETH,
        address recipient,
        bytes32 referenceId,
        uint256 signatureExpiry
    ) external nonReentrant {
        _requireOwnsBag(tokenId);
        if (recipient == address(0)) revert ZeroAddress();
        if (block.timestamp > signatureExpiry)  revert SignatureExpired();

        // 1) Verify
        bytes memory data = abi.encode(tokenId, amountETH, recipient, referenceId, msg.sender, signatureExpiry);
        verifySignature(tokenId, messageHash, signature, address(0), OperationType.UNBAG_ETH, data);

        // 2) Effects
        uint256 currentBal = _baggedETH[tokenId];
        if (currentBal < amountETH) revert NoETHBagged();
        _baggedETH[tokenId] = currentBal - amountETH;

        // 3) Interaction
        (bool success, ) = payable(recipient).call{value: amountETH}("");
        if (!success) revert EthTransferFailed();

        emit Unbagged(tokenId, referenceId);
    }

    /*
    * @notice Withdraw an ERC-20 token from a bag, authorized via EIP-712 signature.
    * @param tokenId         The ID of the BVGS NFT.
    * @param messageHash     The EIP-712 digest that was signed.
    * @param signature       The EIP-712 signature by the active BVGS key.
    * @param tokenAddress    The ERC-20 token address to withdraw.
    * @param amount          The amount of tokens to withdraw.
    * @param recipient       The address receiving the tokens.
    * @param referenceId     External reference ID for off-chain tracking.
    * @param signatureExpiry UNIX timestamp after which the signature is invalid.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `recipient` must not be the zero address.
    * - `block.timestamp` must be ≤ `signatureExpiry`.
    * - bag must have ≥ `amount` balance of `tokenAddress`.
    */
    function unbagERC20(
        uint256 tokenId,
        bytes32 messageHash,
        bytes memory signature,
        address tokenAddress,
        uint256 amount,
        address recipient,
        bytes32 referenceId,
        uint256 signatureExpiry
    ) external nonReentrant {
        _requireOwnsBag(tokenId);
        if (recipient == address(0)) revert ZeroAddress();
        if (block.timestamp > signatureExpiry)  revert SignatureExpired();

        // 1) Verify
        bytes memory data = abi.encode(tokenId, tokenAddress, amount, recipient, referenceId, msg.sender, signatureExpiry);
        verifySignature(tokenId, messageHash, signature, address(0), OperationType.UNBAG_ERC20, data);

        // 2) Effects
        uint256 balance = _erc20Balances[tokenId][tokenAddress];
        if (balance < amount) revert InsufficientTokenBalance();
        _erc20Balances[tokenId][tokenAddress] = balance - amount;

        if (_erc20Balances[tokenId][tokenAddress] == 0) {
            delete _erc20Known[tokenId][tokenAddress];
            _removeERC20Token(tokenId, tokenAddress);
        }

        // 3) Interaction
        IERC20(tokenAddress).safeTransfer(recipient, amount);

        emit Unbagged(tokenId, referenceId);
    }

    /*
    * @notice Withdraw an ERC-721 token from a bag, authorized via EIP-712 signature.
    * @param tokenId         The ID of the BVGS NFT.
    * @param messageHash     The EIP-712 digest that was signed.
    * @param signature       The EIP-712 signature by the active BVGS key.
    * @param nftContract     The ERC-721 contract address.
    * @param nftTokenId      The token ID of the ERC-721 to withdraw.
    * @param recipient       The address receiving the NFT.
    * @param referenceId     External reference ID for off-chain tracking.
    * @param signatureExpiry UNIX timestamp after which the signature is invalid.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `recipient` must not be the zero address.
    * - `block.timestamp` must be ≤ `signatureExpiry`.
    * - The specified NFT must be bagged in this bag.
    */
    function unbagERC721(
        uint256 tokenId,
        bytes32 messageHash,
        bytes memory signature,
        address nftContract,
        uint256 nftTokenId,
        address recipient,
        bytes32 referenceId,
        uint256 signatureExpiry
    ) external nonReentrant {
        _requireOwnsBag(tokenId);
        if (recipient == address(0)) revert ZeroAddress();
        if (block.timestamp > signatureExpiry)  revert SignatureExpired();

        // 1) Verify
        bytes memory data = abi.encode(tokenId, nftContract, nftTokenId, recipient, referenceId, msg.sender, signatureExpiry);
        verifySignature(tokenId, messageHash, signature, address(0), OperationType.UNBAG_NFT, data);

        bytes32 key = keccak256(abi.encodePacked(nftContract, nftTokenId));
        if (!_nftKnown[tokenId][key]) revert NFTNotFound();

        // 2) Effects
        delete _nftData[tokenId][key];
        _nftKnown[tokenId][key] = false;
        _removeNFTKey(tokenId, key);

        // 3) Interaction
        IERC721(nftContract).safeTransferFrom(address(this), recipient, nftTokenId);

        emit Unbagged(tokenId, referenceId);
    }

    /*
    * @notice Batch withdrawal of ETH, ERC-20s, and ERC-721s with a single signature.
    * @param tokenId         The ID of the BVGS NFT.
    * @param messageHash     The EIP-712 digest that was signed.
    * @param signature       The EIP-712 signature by the active BVGS key.
    * @param amountETH       The amount of ETH to withdraw.
    * @param tokenAddresses  The list of ERC-20 token addresses.
    * @param tokenAmounts    The corresponding amounts of each ERC-20.
    * @param nftContracts    The list of ERC-721 contract addresses.
    * @param nftTokenIds     The corresponding ERC-721 token IDs.
    * @param recipient       The address receiving all assets.
    * @param referenceId     External reference ID for off-chain tracking.
    * @param signatureExpiry UNIX timestamp after which the signature is invalid.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `recipient` must not be the zero address.
    * - `block.timestamp` must be ≤ `signatureExpiry`.
    * - `tokenAddresses.length` must equal `tokenAmounts.length`.
    * - `nftContracts.length` must equal `nftTokenIds.length`.
    * - bag must have ≥ `amountETH` ETH and sufficient balances for each asset.
    */
    function batchUnbag(
        uint256 tokenId,
        bytes32 messageHash,
        bytes memory signature,
        uint256 amountETH,
        address[] calldata tokenAddresses,
        uint256[] calldata tokenAmounts,
        address[] calldata nftContracts,
        uint256[] calldata nftTokenIds,
        address recipient,
        bytes32 referenceId,
        uint256 signatureExpiry
    ) external nonReentrant {
        _requireOwnsBag(tokenId);
        if (recipient == address(0)) revert ZeroAddress();
        if (block.timestamp > signatureExpiry) revert SignatureExpired();
        if (tokenAddresses.length != tokenAmounts.length ||
            nftContracts.length != nftTokenIds.length
        ) revert MismatchedInputs();

        // 1) Verify
        bytes memory data = abi.encode(
            tokenId, amountETH, tokenAddresses, tokenAmounts, nftContracts, nftTokenIds, recipient, referenceId, msg.sender, signatureExpiry
        );
        verifySignature(tokenId, messageHash, signature, address(0), OperationType.BATCH_UNBAG, data);

        // 2/3) Effects + Interactions for each asset type
        if (amountETH > 0) {
            uint256 currentBal = _baggedETH[tokenId];
            if (currentBal < amountETH) revert NoETHBagged();
            _baggedETH[tokenId] = currentBal - amountETH;
            (bool success, ) = payable(recipient).call{value: amountETH}("");
            if (!success) revert EthTransferFailed();
        }

        // — ERC-20s —
        for (uint256 i; i < tokenAddresses.length; ) {
            uint256 balance = _erc20Balances[tokenId][tokenAddresses[i]];
            if (balance < tokenAmounts[i]) revert InsufficientTokenBalance();
            _erc20Balances[tokenId][tokenAddresses[i]] = balance - tokenAmounts[i];

            if (_erc20Balances[tokenId][tokenAddresses[i]] == 0) {
                delete _erc20Known[tokenId][tokenAddresses[i]];
                _removeERC20Token(tokenId, tokenAddresses[i]);
            }

            IERC20(tokenAddresses[i]).safeTransfer(recipient, tokenAmounts[i]);
            unchecked { ++i; }
        }

        // — ERC-721s —
        for (uint256 i; i < nftContracts.length; ) {
            bytes32 key = keccak256(abi.encodePacked(nftContracts[i], nftTokenIds[i]));
            if (!_nftKnown[tokenId][key]) revert NFTNotFound();

            delete _nftData[tokenId][key];
            _nftKnown[tokenId][key] = false;
            _removeNFTKey(tokenId, key);

            IERC721(nftContracts[i]).safeTransferFrom(address(this), recipient, nftTokenIds[i]);
            unchecked { ++i; }
        }

        emit Unbagged(tokenId, referenceId);
    }


    /* ══════════════════  Key-rotation  ══════════════════ */

    /*
    * @notice Rotate the off-chain authorization key for a bag.
    * @param tokenId         The ID of the BVGS NFT.
    * @param messageHash     The EIP-712 digest that was signed.
    * @param signature       The EIP-712 signature by the active BVGS key.
    * @param newPublicKey    The new authorized BVGS public key.
    * @param referenceId     External reference ID for off-chain tracking.
    * @param signatureExpiry UNIX timestamp after which the signature is invalid.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `block.timestamp` must be ≤ `signatureExpiry`.
    */
    function rotateBvgsKey(
        uint256 tokenId,
        bytes32 messageHash,
        bytes memory signature,
        address newPublicKey,
        bytes32 referenceId,
        uint256 signatureExpiry
    ) external nonReentrant {
        _requireOwnsBag(tokenId);
        if (block.timestamp > signatureExpiry) revert SignatureExpired();

        bytes memory data = abi.encode(
            tokenId, newPublicKey, referenceId, msg.sender, signatureExpiry
        );
        verifySignature(
            tokenId, messageHash, signature,
            newPublicKey, OperationType.ROTATE_KEY, data
        );
        emit KeyRotated(tokenId, referenceId);
    }


   /* ══════════════════  Burn  ══════════════════ */

    /* abstract hook for BVGS to burn its own ERC-721 */
    function _burnBagNFT(uint256 id) internal virtual;

    /*
    * @notice Authenticated burn of a bag, clearing all assets and burning the NFT.
    * @param tokenId         The ID of the BVGS NFT.
    * @param messageHash     The EIP-712 digest that was signed.
    * @param signature       The EIP-712 signature by the active BVGS key.
    * @param referenceId     External reference ID for off-chain tracking.
    * @param signatureExpiry UNIX timestamp after which the signature is invalid.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    * - `block.timestamp` must be ≤ `signatureExpiry`.
    */
    function burnBag(
        uint256 tokenId,
        bytes32 messageHash,
        bytes memory signature,
        bytes32 referenceId,
        uint256 signatureExpiry
    ) external nonReentrant {
        _requireOwnsBag(tokenId);
        if (block.timestamp > signatureExpiry) revert SignatureExpired();

        bytes memory data = abi.encode(
            tokenId, referenceId, msg.sender, signatureExpiry
        );
        verifySignature(
            tokenId, messageHash, signature,
            address(0), OperationType.BURN_BAG, data
        );

        _finalizeBurn(tokenId);
        emit BagBurned(tokenId, referenceId);
    }

    /**
    * @dev Internal helper called by `burnBag`.
    *      - Wipes all ETH / ERC20 / ERC721 bookkeeping for the vault.
    *      - Delegates the actual ERC-721 burn to `_burnBagNFT` (implemented in BVGS).
    */
    function _finalizeBurn(uint256 tokenId) internal {
        /* ---- ETH ---- */
        delete _baggedETH[tokenId];

        /* ---- ERC-20 balances ---- */
        address[] storage toks = _erc20TokenAddresses[tokenId];
        for (uint256 i; i < toks.length; ) {
            address t = toks[i];
            delete _erc20Balances[tokenId][t];
            delete _erc20Known[tokenId][t];
            unchecked { ++i; }
        }
        delete _erc20TokenAddresses[tokenId];

        /* ---- ERC-721 bookkeeping ---- */
        bytes32[] storage keys = _nftKeys[tokenId];
        for (uint256 i; i < keys.length;) {
            bytes32 k = keys[i];
            delete _nftData[tokenId][k];
            delete _nftKnown[tokenId][k];
            unchecked { ++i; }
        }
        delete _nftKeys[tokenId];

        /* ---- finally burn the NFT itself ---- */
        _burnBagNFT(tokenId);
    }


    /* ══════════════════  View helper  ══════════════════ */

    /*
    * @notice Returns the full contents of a bag: ETH, ERC-20 balances, and ERC-721s.
    * @param tokenId The ID of the BVGS NFT.
    * @return bagETH      The ETH amount held.
    * @return erc20Tokens Array of (tokenAddress, balance) for each ERC-20.
    * @return nfts        Array of BaggedNFT structs representing each ERC-721.
    *
    * Requirements:
    * - `tokenId` must exist and caller must be its owner.
    */
    struct BaggedERC20 { address tokenAddress; uint256 balance; }

    function getFullBag(uint256 tokenId)
        external view
        returns (
            uint256 bagETH,
            BaggedERC20[] memory erc20Tokens,
            BaggedNFT[]  memory nftContracts
        )
    {
        _requireExists(tokenId);
        if (_erc721.ownerOf(tokenId) != msg.sender) revert NotOwner();

        bagETH = _baggedETH[tokenId];

        // ERC-20s
        address[] storage tokenAddresses = _erc20TokenAddresses[tokenId];
        erc20Tokens = new BaggedERC20[](tokenAddresses.length);
        for (uint256 i; i < tokenAddresses.length; ) {
            erc20Tokens[i] = BaggedERC20({
                tokenAddress: tokenAddresses[i],
                balance: _erc20Balances[tokenId][tokenAddresses[i]]
            });
            unchecked { ++i; }
        }

        // ERC-721s
        bytes32[] storage nftList = _nftKeys[tokenId];
        uint256 count;
        for (uint256 i; i < nftList.length; ) {
            if (_nftKnown[tokenId][nftList[i]]) count++;
            unchecked { ++i; }
        }
        nftContracts = new BaggedNFT[](count);
        uint256 idx;
        for (uint256 i; i < nftList.length; ) {
            if (_nftKnown[tokenId][nftList[i]]) {
                nftContracts[idx++] = _nftData[tokenId][nftList[i]];
            }
            unchecked { ++i; }
        }
    }

}

Read Contract

balanceOf 0x70a08231 → uint256
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
getActiveBvgsPublicKeyForToken 0x99418032 → address
getApproved 0x081812fc → address
getFullBag 0x34b25029 → uint256, tuple[], tuple[]
getNonce 0x3d46b819 → uint256
isApprovedForAll 0xe985e9c5 → bool
locked 0xb45a3c0e → bool
name 0x06fdde03 → string
onERC721Received 0x150b7a02 → bytes4
owner 0x8da5cb5b → address
ownerOf 0x6352211e → address
supportsInterface 0x01ffc9a7 → bool
symbol 0x95d89b41 → string
tokenURI 0xc87b56dd → string

Write Contract 23 functions

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

approve 0x095ea7b3
address to
uint256 tokenId
bagBatch 0xd24177a8
address to
address bvgsPublicKey
uint256 amountETH
address[] tokenAddresses
uint256[] tokenAmounts
address[] nftContracts
uint256[] nftTokenIds
bytes32 referenceId
bagERC20 0x4126614d
address to
address bvgsPublicKey
address tokenAddress
uint256 amount
bytes32 referenceId
bagERC721 0x5e78ffd7
address to
address bvgsPublicKey
address nftContract
uint256 externalNftTokenId
bytes32 referenceId
bagETH 0xf84e791d
address to
address bvgsPublicKey
bytes32 referenceId
batchDeposit 0x0db54256
uint256 tokenId
uint256 amountETH
address[] tokenAddresses
uint256[] tokenAmounts
address[] nftContracts
uint256[] nftTokenIds
bytes32 referenceId
batchUnbag 0x088baaef
uint256 tokenId
bytes32 messageHash
bytes signature
uint256 amountETH
address[] tokenAddresses
uint256[] tokenAmounts
address[] nftContracts
uint256[] nftTokenIds
address recipient
bytes32 referenceId
uint256 signatureExpiry
burnBag 0x1dd96792
uint256 tokenId
bytes32 messageHash
bytes signature
bytes32 referenceId
uint256 signatureExpiry
depositERC20 0x486c4b7f
uint256 tokenId
address tokenAddress
uint256 amount
bytes32 referenceId
depositERC721 0x4d8af09e
uint256 tokenId
address nftContract
uint256 nftTokenId
bytes32 referenceId
depositETH 0x65cd69a1
uint256 tokenId
bytes32 referenceId
renounceOwnership 0x715018a6
No parameters
rotateBvgsKey 0x14032cfe
uint256 tokenId
bytes32 messageHash
bytes signature
address newPublicKey
bytes32 referenceId
uint256 signatureExpiry
safeTransferFrom 0x42842e0e
address from
address to
uint256 tokenId
safeTransferFrom 0xb88d4fde
address from
address to
uint256 tokenId
bytes data
setApprovalForAll 0xa22cb465
address operator
bool approved
setDefaultMetadataURI 0x95480879
string newDefaultURI
setTokenMetadataURI 0x2dbf9be6
uint256 tokenId
bytes32 messageHash
bytes signature
string newMetadataURI
bytes32 referenceId
uint256 signatureExpiry
transferFrom 0x23b872dd
address from
address to
uint256 tokenId
transferOwnership 0xf2fde38b
address newOwner
unbagERC20 0x03859205
uint256 tokenId
bytes32 messageHash
bytes signature
address tokenAddress
uint256 amount
address recipient
bytes32 referenceId
uint256 signatureExpiry
unbagERC721 0xea129458
uint256 tokenId
bytes32 messageHash
bytes signature
address nftContract
uint256 nftTokenId
address recipient
bytes32 referenceId
uint256 signatureExpiry
unbagETH 0x4dfccf62
uint256 tokenId
bytes32 messageHash
bytes signature
uint256 amountETH
address recipient
bytes32 referenceId
uint256 signatureExpiry

Token Balances (1)

View Transfers →
wstETH 0

Recent Transactions

No transactions found for this address