Address Contract Verified
Address
0x38E65890F1070b40d357313ec893D73bcA46Be56
Balance
1.0857 ETH
Nonce
1
Code Size
24267 bytes
Creator
0xeDb7c032...b187 at tx 0x17a1ecc6...5f62a8
Indexed Transactions
0
Contract Bytecode
24267 bytes
0x6080604052600436101561001257600080fd5b60003560e01c8063014635461461039757806301ffc9a71461039257806306d254da1461038d57806306fdde0314610388578063081812fc14610383578063095ea7b31461037e578063098144d4146103795780630d705df6146103745780630e910d391461036f57806318160ddd1461036a57806323b872dd146103655780632a55205a146103605780632ed56f361461035b5780632f745c591461035657806335a83013146103515780633a7cb0861461034c5780633ccfd60b1461034757806342842e0e14610342578063438b63001461033d578063455d9ac4146103385780634f6ccce7146103335780634f808dc21461032e5780635077ee24146103295780635ceeb3ec146103245780635f5168361461031f5780636221d13c1461031a5780636352211e14610315578063665155c01461031057806370a082311461030b578063715018a614610306578063738cba9a1461030157806378491b1b146102fc5780637cb64759146102f75780637fd67d49146102f2578063816403a1146102ed578063881c632c146102e85780638da5cb5b146102e3578063916358a3146102de57806393803fdf146102d957806395d89b41146102d45780639df742d7146102cf5780639e05d240146102ca578063a22cb465146102c5578063a9fc664e146102c0578063b0153d5e146102bb578063b40a5627146102b6578063b88d4fde146102b1578063c87b56dd146102ac578063cac92669146102a7578063d5abeb01146102a2578063d8d472d81461029d578063e985e9c514610298578063f2fde38b14610293578063f9da32241461028e578063fafe3a20146102895763fdca172e1461028457600080fd5b61278d565b61267e565b612519565b61247f565b612441565b61240c565b6123e5565b612355565b6121b7565b612150565b612043565b611e71565b611db0565b611cc4565b611c58565b611ae1565b611a5c565b611a07565b6118ca565b6118a1565b6117cb565b611735565b61166d565b6115c7565b61143d565b611363565b611302565b6112db565b6112b1565b611293565b61126d565b6111f7565b6110b6565b610fae565b610ef6565b610ed8565b610d2e565b610cb7565b610c8f565b610b80565b610ad9565b610a1b565b6109de565b610913565b6108b5565b61088c565b610842565b610815565b6107ed565b6107d2565b6106b3565b610683565b6105c6565b6104df565b6103ed565b6103ac565b60009103126103a757565b600080fd5b346103a75760003660031901126103a757602060405173721c002b0059009a671d00ad1700c9748146cd1b8152f35b6001600160e01b03198116036103a757565b346103a75760203660031901126103a75761043b60043561040d816103db565b63ffffffff60e01b1663152a902d60e11b811490811561043f575b5060405190151581529081906020820190565b0390f35b63780e9d6360e01b811491508115610459575b5038610428565b632b435fdb60e21b8114915081156104bd575b811561047a575b5038610452565b6380ac58cd60e01b8114915081156104ac575b811561049b575b5038610473565b6301ffc9a760e01b14905038610494565b635b5e139f60e01b8114915061048d565b63503e914d60e11b8114915061046c565b6001600160a01b038116036103a757565b346103a75760203660031901126103a7576004356104fc816104ce565b6006546001600160a01b039190610516908316331461369e565b16801561053357604980546001600160a01b031916919091179055005b60405162461bcd60e51b815260206004820152600f60248201526e496e76616c6964206164647265737360881b6044820152606490fd5b60005b83811061057d5750506000910152565b818101518382015260200161056d565b906020916105a68151809281855285808601910161056a565b601f01601f1916010190565b9060206105c392818152019061058d565b90565b346103a757600080600319360112610680576040518180546105e781612c68565b80845290600190818116908115610658575060011461061d575b61043b84610611818803826120ce565b604051918291826105b2565b93508180526020938483205b828410610645575050508161043b936106119282010193610601565b8054858501870152928501928101610629565b61043b96506106119450602092508593915060ff191682840152151560051b82010193610601565b80fd5b346103a75760203660031901126103a75760206106a1600435615653565b6040516001600160a01b039091168152f35b346103a75760403660031901126103a7576004356106d0816104ce565b6024356106dc816155c2565b6001600160a01b038181169084168114610783573314908115610771575b501561070b5761070991615c34565b005b60405162461bcd60e51b815260206004820152603860248201527f4552433732313a20617070726f76652063616c6c6572206973206e6f74206f776044820152771b995c881b9bdc88185c1c1c9bdd995908199bdc88185b1b60421b6064820152608490fd5b61077d915033906151a7565b386106fa565b60405162461bcd60e51b815260206004820152602160248201527f4552433732313a20617070726f76616c20746f2063757272656e74206f776e656044820152603960f91b6064820152608490fd5b346103a75760003660031901126103a75760206106a1612b88565b346103a75760003660031901126103a7576040805163657711f560e11b815260016020820152f35b346103a75760003660031901126103a7576020610830614757565b6040516001600160601b039091168152f35b346103a75760003660031901126103a7576020600254604051908152f35b60609060031901126103a757600435610878816104ce565b90602435610885816104ce565b9060443590565b346103a75761070961089d36610860565b916108b06108ab8433615800565b6156d6565b615a9e565b346103a75760403660031901126103a75760018060a01b03604954166127106108e560475460a01c602435614a54565b604080516001600160a01b03949094168452919004602083015290f35b6001600160601b038116036103a757565b346103a75760203660031901126103a75760043561093081610902565b61094560018060a01b0360065416331461369e565b6127106001600160601b03821611610999576107099061097466ffffffffffffff604b5460a01c164210614e27565b604880546001600160a01b031660a09290921b6001600160a01b031916919091179055565b60405162461bcd60e51b815260206004820152601c60248201527f446973636f756e742070657263656e7461676520746f6f2068696768000000006044820152606490fd5b346103a75760403660031901126103a7576020610a09600435610a00816104ce565b60243590615341565b604051908152f35b801515036103a757565b346103a75760203660031901126103a757600435610a3881610a11565b610a4d60018060a01b0360065416331461369e565b6041805460ff60401b191691151560401b60ff60401b16919091179055005b9181601f840112156103a7578235916001600160401b0383116103a7576020808501948460051b0101116103a757565b6020908160408183019282815285518094520193019160005b828110610ac3575050505090565b8351151585529381019392810192600101610ab5565b346103a75760203660031901126103a7576004356001600160401b0381116103a757610b09903690600401610a6c565b90610b13826137aa565b91610b2160405193846120ce565b808352601f19610b30826137aa565b0136602085013760005b818110610b4f576040518061043b8682610a9c565b80610b67610b61610b7b938587614973565b35614ba3565b610b7182876139c9565b90151590526139a4565b610b3a565b346103a75760003660031901126103a757610ba660018060a01b0360065416331461369e565b610bae613c10565b60405466ffffffffffffff8160601c1642119081610c7d575b50610c70575b603f54610bdb811515614f85565b610be56000603f55565b610c20610c19610c11610c0b610c03604d5462ffffff9060601c1690565b62ffffff1690565b84614a54565b612710900490565b8092613bee565b9080610c54575b5080610c38575b6107096001603855565b604a54610c4e91906001600160a01b0316614c39565b38610c2e565b604b54610c6a91906001600160a01b0316614c39565b38610c27565b610c78614a80565b610bcd565b6001600160601b031615905038610bc7565b346103a757610709610ca036610860565b9060405192610cae846120b3565b6000845261573c565b346103a7576020806003193601126103a757610cdd600435610cd8816104ce565b614c9a565b906040519181839283018184528251809152816040850193019160005b828110610d0957505050500390f35b835185528695509381019392810192600101610cfa565b63ffffffff8116036103a757565b60203660031901126103a757600435610d4681610d20565b610d4e613c10565b604b54610e3e610e0a66ffffffffffffff92610d71848260a01c16421015613b03565b610de960405491610da263ffffffff96878560b81c1694610d96868a8c161115613b3d565b60601c16421115613b78565b610dc8610dc0610db460495460a01c90565b6001600160601b031690565b341015613bb4565b610dd332331461390d565b610ddb614757565b956002549160d81c16613bee565b93848210610ec357610e05906001600160601b03163411613bb4565b613bfb565b6040805463ffffffff60b81b191660b883901b63ffffffff60b81b16179055923390346001600160601b03169085906140b0565b604054610e589060b81c63ffffffff165b63ffffffff1690565b11610eb6575b610e666147d7565b6040805163ffffffff9092168252346020830152429082015233907f025ecfc771110b33a5a72dd787c154336f05caa0447910a403028333139b75ec9080606081015b0390a26107096001603855565b610ebe614630565b610e5e565b610e05906001600160601b0316341015613bb4565b346103a75760203660031901126103a7576020610a09600435615250565b346103a75760203660031901126103a757600435610f1381610902565b610f2860018060a01b0360065416331461369e565b63ffffffff610f4381604b5460d81c168260025416906136e9565b60405460b81c821691161115610f5c57610709906130f1565b60405162461bcd60e51b8152602060048201526019602482015278115b9bdd59da081dda5b9b9a5b99c8189a591cc8195e1a5cdd603a1b6044820152606490fd5b66ffffffffffffff8116036103a757565b346103a75760203660031901126103a757600435610fcb81610f9d565b610fe060018060a01b0360065416331461369e565b66ffffffffffffff610ffa81604b5460a01c164210614e84565b80604c5460a01c1690821610611075576110139061316a565b61070961104a61102f604b5466ffffffffffffff9060a01c1690565b604c546110449060d81c63ffffffff16610e4f565b90613509565b6040805466ffffffffffffff60601b191660609290921b66ffffffffffffff60601b16919091179055565b60405162461bcd60e51b815260206004820152601960248201527814dd185c9d0818d85b9b9bdd081899481899599bdc99481053603a1b6044820152606490fd5b346103a7576003196020368201126103a7576004356001600160401b03918282116103a7576102e09082360301126103a757600080516020615e76833981519152549160ff8360401c16159216801590816111ef575b60011490816111e5575b1590816111dc575b506111ca57600080516020615e76833981519152805467ffffffffffffffff1916600117905561115690826111a5575b600401613529565b61115c57005b600080516020615e76833981519152805460ff60401b19169055604051600181527fc7f505b2f371ae2175ee4913f4499e1f2633a7b5936321eed1cdaeb6115181d290602090a1005b600080516020615e76833981519152805460ff60401b1916600160401b17905561114e565b60405163f92ee8a960e01b8152600490fd5b9050153861111e565b303b159150611116565b83915061110c565b346103a75760203660031901126103a757600435611214816157c7565b156112315760005260426020526020604060002054604051908152f35b60405162461bcd60e51b8152602060048201526014602482015273151bdad95b88191bd95cc81b9bdd08195e1a5cdd60621b6044820152606490fd5b346103a75760003660031901126103a757602060ff60055460a81c166040519015158152f35b346103a75760203660031901126103a75760206106a16004356155c2565b346103a75760003660031901126103a757602066ffffffffffffff60405460601c16604051908152f35b346103a75760203660031901126103a7576020610a096004356112fd816104ce565b61550d565b346103a7576000806003193601126106805760065481906001600160a01b0381169061132f33831461369e565b6001600160a01b0319166006557f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b346103a75760203660031901126103a75760043561138081610d20565b61139560018060a01b0360065416331461369e565b6113ae66ffffffffffffff604b5460a01c164210614e84565b63ffffffff80604c5460d81c1690821611156113cd576110139061319f565b60405162461bcd60e51b815260206004820152601660248201527526bab9ba1034b731b932b0b9b290323ab930ba34b7b760511b6044820152606490fd5b62ffffff8116036103a757565b60409060031901126103a7576004356114308161140b565b906024356105c3816104ce565b346103a75761144b36611418565b9061146160018060a01b0360065416331461369e565b604b546114819060a01c66ffffffffffffff165b66ffffffffffffff1690565b421015806115a6575b6115675760405466ffffffffffffff8160601c1642119081611555575b50611548575b6002546114fe62ffffff6114f3610e4f600060405460018060601b03811661151f575b50604b546114ee9060d81c63ffffffff1663ffffffff8816906136e9565b6136e9565b9316928311156136ff565b60005b82811061150a57005b80611519600192840186614fbc565b01611501565b611542915063ffffffff61153860415463ffffffff1690565b9160d81c166136e9565b386114d0565b611550614a80565b6114ad565b6001600160601b0316159050386114a7565b60405162461bcd60e51b815260206004820152601360248201527241756374696f6e20696e2070726f677265737360681b6044820152606490fd5b0390fd5b506040546115bf9060601c66ffffffffffffff16611475565b42111561148a565b346103a75760203660031901126103a7576115ed60018060a01b0360065416331461369e565b600435604655005b60409060031901126103a75760043561160d81610d20565b906024356105c381610d20565b60208082019080835283518092528060408094019401926000905b83821061164457505050505090565b845180516001600160a01b03168752830151868401529485019493820193600190910190611635565b346103a75761167b366115f5565b63ffffffff8091169161168d836137aa565b90604061169c815193846120ce565b848352601f196116ab866137aa565b0160005b81811061171157505060005b8481168681101561170457906116f96116ff926116e86116e36116de8589614a3c565b6119f1565b614be2565b6116f282896139c9565b52866139c9565b50613bfb565b6116bb565b82518061043b878261161a565b602090835161171f81612080565b60008152826000818301528288010152016116af565b346103a75760203660031901126103a75760043561175281610902565b61176760018060a01b0360065416331461369e565b66ffffffffffffff604c5460a01c164210156117865761070990613116565b60405162461bcd60e51b815260206004820152601e60248201527f416c6c6f776c697374206d696e7420616c7265616479207374617274656400006044820152606490fd5b346103a75760203660031901126103a7576004356117e881610f9d565b6117fd60018060a01b0360065416331461369e565b66ffffffffffffff9081604c5460a01c1642101561186a5761183f61070992611835611475604b5466ffffffffffffff9060a01c1690565b9083161115614eca565b604c805466ffffffffffffff60a01b191660a09290921b66ffffffffffffff60a01b16919091179055565b60405162461bcd60e51b815260206004820152600f60248201526e1053081b5a5b9d081cdd185c9d1959608a1b6044820152606490fd5b346103a75760003660031901126103a7576006546040516001600160a01b039091168152602090f35b346103a7576020806003193601126103a7576001600160401b036004358181116103a757366023820112156103a75780600401359182116103a757602490368284830101116103a75761192860018060a01b0360065416331461369e565b61193c83611937604554612c68565b612cf5565b600093601f841160011461197d5750928293600093611970575b505050600019600383901b1c191660019190911b17604555005b0101359050388080611956565b6045600052601f19841694600080516020615e56833981519152939181905b8782106119d757505084600196106119bb575b50505050811b01604555005b60001960f88660031b161c1992010135169055388080806119af565b80600184978683959689010135815501960192019061199c565b63ffffffff166000526039602052604060002090565b346103a75760203660031901126103a75763ffffffff600435611a2981610d20565b16600090815260396020908152604091829020805460019091015483516001600160a01b03909216825291810191909152f35b346103a75760008060031936011261068057604051816001805490611a8082612c68565b808552918181169081156106585750600114611aa65761043b84610611818803826120ce565b80945082526020938483205b828410611ace575050508161043b936106119282010193610601565b8054858501870152928501928101611ab2565b60403660031901126103a7576004356001600160401b0381116103a757611b0f610709913690600401610a6c565b611ba9611ba460243592611b22846104ce565b611b46611b3e611475604c5466ffffffffffffff9060a01c1690565b421015613736565b604b5494611b6166ffffffffffffff8760a01c164210613773565b6046546040516001600160601b0319606088901b1660208201908152601482529192611b9f929091611b946034826120ce565b5190209336916137c1565b613948565b61380f565b6001600160a01b0381166000908152603a6020526040902054611bcf9060ff1615613847565b611bf06002549263ffffffff611be48561387d565b9160d81c161015613898565b611c12611bff604a5460a01c90565b346001600160601b0390911611156138d1565b611c1d32331461390d565b6001600160a01b0381166000908152603a60205260409020611c4690805460ff19166001179055565b611c5334603f5401603f55565b614fbc565b346103a75760203660031901126103a7577f6787c7f9a80aa0f5ceddab2c54f1f5169c0b88e75dd5e19d5e858a64144c7dbc6020600435611c9881610a11565b611ca061514f565b151560055460ff60a81b8260a81b169060ff60a81b191617600555604051908152a1005b346103a75760403660031901126103a757600435611ce1816104ce565b602435611ced81610a11565b6001600160a01b03821691338314611d6f5781611d2c611d3d9233600052600460205260406000209060018060a01b0316600052602052604060002090565b9060ff801983541691151516179055565b604051901515815233907f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c3190602090a3005b60405162461bcd60e51b815260206004820152601960248201527822a9219b99189d1030b8383937bb32903a379031b0b63632b960391b6044820152606490fd5b346103a75760203660031901126103a757600435611dcd816104ce565b611dd561514f565b6001600160a01b038082169190821515823b1581611e69575b50611e575760407fcc5dc080ff977b3c3a211fa63ab74f90f658f5ba9d3236e92c8f59570f442aac9161070994611e23612b88565b8351921682526020820152a1600580546001600160a81b031916600883901b610100600160a81b0316176001179055612bd3565b6040516332483afb60e01b8152600490fd5b905038611dee565b610ea97f3ab706acce053a4246886a2268a3fe0f7bac19ed2df0f36286da4936a0654c7a611e9e366115f5565b9290611ea8613c10565b611fcd604b549466ffffffffffffff611ec8818860a01c16421015613b03565b60405490611eea63ffffffff91828460b81c1693610d96858588161115613b3d565b611ef53415156144ff565b611f0032331461390d565b6001611f0b866119f1565b8054611f33903390611f2d906001600160a01b03165b6001600160a01b031690565b14614539565b018054926001600160601b03611f63611f5234831660a088901c614574565b9b8561153860025463ffffffff1690565b9184611f6d614757565b9316116120205780611f839216908b1611613bb4565b6001600160f01b03831660a08a901b6001600160a01b031916179055604054611fb49060981c63ffffffff16610e4f565b90851614908115612014575b50612007575b858361458d565b611fd56147d7565b6040805163ffffffff90921682526001600160601b039094166020820152429381019390935233929081906060820190565b61200f614630565b611fc6565b60019150161538611fc0565b61203e9150612034610db460495460a01c90565b908b161015613bb4565b611f83565b346103a75760003660031901126103a757602063ffffffff60405460b81c16604051908152f35b634e487b7160e01b600052604160045260246000fd5b604081019081106001600160401b0382111761209b57604052565b61206a565b6001600160401b03811161209b57604052565b602081019081106001600160401b0382111761209b57604052565b90601f801991011681019081106001600160401b0382111761209b57604052565b604051906120fc82612080565b565b6001600160401b03811161209b57601f01601f191660200190565b929192612125826120fe565b9161213360405193846120ce565b8294818452818301116103a7578281602093846000960137010152565b346103a75760803660031901126103a75760043561216d816104ce565b602435612179816104ce565b606435916001600160401b0383116103a757366023840112156103a7576121ad610709933690602481600401359101612119565b916044359161573c565b346103a75760203660031901126103a7576004356121d4816157c7565b1561231e576000908072184f03e93ff9f4daa797ed6e38ed64bf6a1f0160401b8181811015612310575b50506d04ee2d6d415b85acef810000000080831015612301575b50662386f26fc10000808310156122f2575b506305f5e100808310156122e3575b50612710808310156122d4575b5060648210156122c4575b600a809210156122ba575b60019081602161226d828701614df5565b95860101905b612284575b61043b61061186614d3d565b600019019083906f181899199a1a9b1b9c1cb0b131b232b360811b8282061a8353049182156122b557919082612273565b612278565b916001019161225c565b9190606460029104910191612251565b60049193920491019138612246565b60089193920491019138612239565b6010919392049101913861222a565b60209193920491019138612218565b6040945004915038806121fe565b60405162461bcd60e51b815260206004820152600f60248201526e151bdad95b881b9bdd08199bdd5b99608a1b6044820152606490fd5b346103a75760203660031901126103a75760043561237281610902565b61238760018060a01b0360065416331461369e565b6127106001600160601b038216116123a2576107099061313b565b60405162461bcd60e51b815260206004820152601b60248201527a0a4def2c2d8e8f240e0cae4c6cadce8c2ceca40e8dede40d0d2ced602b1b6044820152606490fd5b346103a75760003660031901126103a757602063ffffffff604b5460d81c16604051908152f35b346103a75760203660031901126103a757602061243360043561242e81610902565b61468a565b63ffffffff60405191168152f35b346103a75760403660031901126103a7576020612475600435612463816104ce565b60243590612470826104ce565b6151a7565b6040519015158152f35b346103a75760203660031901126103a75760043561249c816104ce565b6006546001600160a01b03906124b5908216331461369e565b8116156124c55761070990615dec565b60405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608490fd5b346103a75760203660031901126103a75760043561253681610d20565b61254b60018060a01b0360065416331461369e565b604b549063ffffffff80821692612568828260d81c168510614f09565b6002549066ffffffffffffff9060a01c81164210156125b85750926125939161070994161115614f45565b604b805463ffffffff60d81b191660d89290921b63ffffffff60d81b16919091179055565b60405494919290606086901c1642116126235760405162461bcd60e51b815260206004820152602a60248201527f43616e6e6f74206368616e6765206d6178537570706c7920647572696e67207460448201526934329030bab1ba34b7b760b11b6064820152608490fd5b610709946125939361266a92610e4f926001600160601b031615612671575b6040546126639060d81c63ffffffff165b60415463ffffffff165b906136e9565b9116614a3c565b1115614f45565b612679614a80565b612642565b61268736611418565b9062ffffff604054916126a766ffffffffffffff8460601c1642116139e2565b6041546126b99060401c60ff16613a20565b16906126c6821515613a61565b6126d132331461390d565b6001600160601b031615612780575b60025491612728612720610e4f61270361265360405463ffffffff9060d81c1690565b604b546114ee9060d81c63ffffffff1663ffffffff8916906136e9565b8311156136ff565b612740610db461273a60495460a01c90565b84613aa6565b9261274d84341015613ac2565b60005b83811061276b5761070961276686603f5461388b565b603f55565b8061277a600192840185614fbc565b01612750565b612788614a80565b6126e0565b346103a75760603660031901126103a7576001600160401b036004358181116103a7576127be903690600401610a6c565b90916024359081116103a7576127d8903690600401610a6c565b92906127e56044356104ce565b6127ed613c10565b60405461280766ffffffffffffff8260601c1642116148fd565b61281284151561493d565b6001600160601b031615612b7b575b6000938493855b81811061285a57868061283f576107096001603855565b612854906044356001600160a01b0316614c39565b80610c2e565b6128706116de61286b838589614973565b613195565b805461288a903390611f2d906001600160a01b0316611f21565b60018101549760029061289f828b1615614983565b60009060a08b901c60018c1615612b6157878b106129a2575b60019261295396959492612919926128d760405460018060601b031690565b906128e984888060601b038416613bee565b6000918181111561299a576128fe9250613bee565b925b15612958575b506129148454604435614fbc565b61388b565b9a61294a61293461292f60415463ffffffff1690565b614a27565b63ffffffff1663ffffffff196041541617604155565b179101556139a4565b612828565b61276661298c610db461297a6129949461297460485460a01c90565b90613aa6565b6127106001600160601b039091160490565b603f5461388b565b38612906565b505092612900565b6129ad8b898b614973565b6047546040516331a9108f60e11b8152913560048301819052916001600160a01b0391821691906020908181602481875afa928315612b2d5785918994612b32575b5083163314928315612a79575b5050509050612a0c575b506128b8565b600193509a61295396959492612a3e8d612a39612919959f612a30612a3491614ba3565b1590565b6149eb565b614bc3565b604054612a6b90612a6590610db49061297a906001600160601b031660485460a01c612974565b926139a4565b9c9250929495965092612a06565b604c549294612ae394508593612a9990611f21906001600160a01b031681565b604051632e7cda1d60e21b81523360048201526001600160a01b039384166024820152929091166044830152606482019290925260006084820152928391908290819060a4820190565b03915afa918215612b2d578692612b00575b5050803883816129fc565b612b1f9250803d10612b26575b612b1781836120ce565b8101906149d6565b3880612af5565b503d612b0d565b612bc7565b612b53919450833d8511612b5a575b612b4b81836120ce565b8101906149c1565b92386129ef565b503d612b41565b60019250612b75906129539695949261388b565b9a61294a565b612b83614a80565b612821565b600554600881901c6001600160a01b031691908215612ba45750565b60ff1615612bae57565b73721c002b0059009a671d00ad1700c9748146cd1b9150565b6040513d6000823e3d90fd5b6001600160a01b0381169081612be7575050565b3b612bf0575b50565b803b156103a7576000809160446040518094819363fb2de5d760e01b83523060048401526102d160248401525af115612bed576120fc906120a0565b903590601e19813603018212156103a757018035906001600160401b0382116103a7576020019181360383136103a757565b356105c3816104ce565b90600182811c92168015612c98575b6020831014612c8257565b634e487b7160e01b600052602260045260246000fd5b91607f1691612c77565b601f8111612cae575050565b60009081805260208220906020601f850160051c83019410612ceb575b601f0160051c01915b828110612ce057505050565b818155600101612cd4565b9092508290612ccb565b601f8111612d01575050565b6000906045825260208220906020601f850160051c83019410612d3f575b601f0160051c01915b828110612d3457505050565b818155600101612d28565b9092508290612d1f565b90601f8211612d56575050565b60019160009083825260208220906020601f850160051c83019410612d96575b601f0160051c01915b828110612d8c5750505050565b8181558301612d7f565b9092508290612d76565b601f8111612dac575050565b6000906043825260208220906020601f850160051c83019410612dea575b601f0160051c01915b828110612ddf57505050565b818155600101612dd3565b9092508290612dca565b601f8111612e00575050565b6000906044825260208220906020601f850160051c83019410612e3e575b601f0160051c01915b828110612e3357505050565b818155600101612e27565b9092508290612e1e565b91906001600160401b03811161209b57612e6c81612e67604354612c68565b612da0565b6000601f8211600114612ea657819293600092612e9b575b50508160011b916000199060031b1c191617604355565b013590503880612e84565b6043600052601f198216937f9690ad99d6ce244efa8a0f6c2d04036d3b33a9474db32a71b71135c69510279391805b868110612f0d5750836001959610612ef3575b505050811b01604355565b0135600019600384901b60f8161c19169055388080612ee8565b90926020600181928686013581550194019101612ed5565b91906001600160401b03811161209b57612f4981612f44604454612c68565b612df4565b6000601f8211600114612f8357819293600092612f78575b50508160011b916000199060031b1c191617604455565b013590503880612f61565b6044600052601f198216937f9b22d3d61959b4d3528b1d8ba932c96fbe302b36a1aad1d95cab54f9e0a135ea91805b868110612fea5750836001959610612fd0575b505050811b01604455565b0135600019600384901b60f8161c19169055388080612fc5565b90926020600181928686013581550194019101612fb2565b91906001600160401b03811161209b5761302181611937604554612c68565b6000601f821160011461305b57819293600092613050575b50508160011b916000199060031b1c191617604555565b013590503880613039565b6045600052601f19821693600080516020615e5683398151915291805b8681106130b05750836001959610613096575b505050811b01604555565b0135600019600384901b60f8161c1916905538808061308b565b90926020600181928686013581550194019101613078565b80546001600160a01b0319166001600160a01b03909216919091179055565b356105c381610902565b604980546001600160a01b031660a09290921b6001600160a01b031916919091179055565b604a80546001600160a01b031660a09290921b6001600160a01b031916919091179055565b604780546001600160a01b031660a09290921b6001600160a01b031916919091179055565b356105c381610f9d565b604b805466ffffffffffffff60a01b191660a09290921b66ffffffffffffff60a01b16919091179055565b356105c381610d20565b604c805463ffffffff60d81b191660d89290921b63ffffffff60d81b16919091179055565b6040805463ffffffff60d81b191660d89290921b63ffffffff60d81b16919091179055565b356105c38161140b565b356105c381610a11565b6134d46102c06120fc9261321a6132148280612c2c565b90612e48565b61323061322a6020830183612c2c565b90612f25565b6132466132406040830183612c2c565b90613002565b606081013560465561327f61325d60808301612c5e565b604780546001600160a01b0319166001600160a01b0392909216919091179055565b61329361328e60a083016130e7565b61313b565b6132c46132a260c08301612c5e565b604880546001600160a01b0319166001600160a01b0392909216919091179055565b6132d361097460e083016130e7565b6133056132e36101008301612c5e565b604980546001600160a01b0319166001600160a01b0392909216919091179055565b61331a61331561012083016130e7565b6130f1565b61334c61332a6101408301612c5e565b604a80546001600160a01b0319166001600160a01b0392909216919091179055565b61336161335c61016083016130e7565b613116565b6133936133716101808301612c5e565b604b80546001600160a01b0319166001600160a01b0392909216919091179055565b6133a86133a36101a08301613160565b61316a565b6133b86125936101c08301613195565b6133ea6133c86101e08301612c5e565b604c80546001600160a01b0319166001600160a01b0392909216919091179055565b6133fa61183f6102008301613160565b61340f61340a6102208301613195565b61319f565b61343561341f6102408301613195565b63ffffffff1663ffffffff19604d541617604d55565b6134666134456102608301613195565b63ffffffff60201b604d549160201b169063ffffffff60201b191617604d55565b61349b6134766102808301613195565b604d805463ffffffff60401b191660409290921b63ffffffff60401b16919091179055565b6134ce6134ab6102a083016131e9565b604d805462ffffff60601b191660609290921b62ffffff60601b16919091179055565b016131f3565b604d805460ff60781b191691151560781b60ff60781b16919091179055565b634e487b7160e01b600052601160045260246000fd5b91909166ffffffffffffff8080941691160191821161352457565b6134f3565b6135338180612c2c565b9061355b60209261355361354985870187612c2c565b9490923691612119565b923691612119565b916135646153fb565b61356c6153fb565b8151906001600160401b03821161209b576000926135938361358e8654612c68565b612ca2565b81601f84116001146136105750918084926135e99796946135cd9692613605575b50508160011b916000199060031b1c191617905561542a565b6135e46135df611f2160c08401612c5e565b615dd8565b6131fd565b6120fc61104a61102f604b5466ffffffffffffff9060a01c1690565b0151905038806135b4565b600080529190601f1984167f290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e5639386905b8282106136865750509260019285926135e99998966135cd98961061366d575b505050811b01905561542a565b015160001960f88460031b161c19169055388080613660565b80600186978294978701518155019601940190613640565b156136a557565b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b63ffffffff918216908216039190821161352457565b1561370657565b60405162461bcd60e51b8152602060048201526008602482015267546f6f206d616e7960c01b6044820152606490fd5b1561373d57565b60405162461bcd60e51b815260206004820152600e60248201526d1053081b9bdd081cdd185c9d195960921b6044820152606490fd5b1561377a57565b60405162461bcd60e51b8152602060048201526008602482015267105308195b99195960c21b6044820152606490fd5b6001600160401b03811161209b5760051b60200190565b92916137cc826137aa565b916137da60405193846120ce565b829481845260208094019160051b81019283116103a757905b8282106138005750505050565b813581529083019083016137f3565b1561381657565b60405162461bcd60e51b8152602060048201526009602482015268139bdd081bdb88105360ba1b6044820152606490fd5b1561384e57565b60405162461bcd60e51b815260206004820152600760248201526610db185a5b595960ca1b6044820152606490fd5b906001820180921161352457565b9190820180921161352457565b1561389f57565b60405162461bcd60e51b815260206004820152600a602482015269135a5b9d1959081bdd5d60b21b6044820152606490fd5b156138d857565b60405162461bcd60e51b815260206004820152600d60248201526c496e76616c69642066756e647360981b6044820152606490fd5b1561391457565b60405162461bcd60e51b815260206004820152600c60248201526b4e6f20636f6e74726163747360a01b6044820152606490fd5b929091906000915b845183101561399c5761396383866139c9565b519060008282101561398a57506000526020526139846040600020926139a4565b91613950565b60409161398493825260205220612a65565b915092501490565b60001981146135245760010190565b634e487b7160e01b600052603260045260246000fd5b80518210156139dd5760209160051b010190565b6139b3565b156139e957565b60405162461bcd60e51b815260206004820152600f60248201526e41756374696f6e206f6e676f696e6760881b6044820152606490fd5b15613a2757565b60405162461bcd60e51b8152602060048201526012602482015271141d589b1a58c81b9bdd08185b1b1bddd95960721b6044820152606490fd5b15613a6857565b60405162461bcd60e51b81526020600482015260166024820152754d757374206d696e74206174206c65617374206f6e6560501b6044820152606490fd5b6001600160601b03918216908216029081169190820361352457565b15613ac957565b60405162461bcd60e51b8152602060048201526012602482015271496e73756666696369656e742066756e647360701b6044820152606490fd5b15613b0a57565b60405162461bcd60e51b815260206004820152600b60248201526a139bdd081cdd185c9d195960aa1b6044820152606490fd5b15613b4457565b60405162461bcd60e51b815260206004820152600c60248201526b42616420657374696d61746560a01b6044820152606490fd5b15613b7f57565b60405162461bcd60e51b815260206004820152600d60248201526c105d58dd1a5bdb88195b991959609a1b6044820152606490fd5b15613bbb57565b60405162461bcd60e51b815260206004820152600b60248201526a42696420746f6f206c6f7760a81b6044820152606490fd5b9190820391821161352457565b63ffffffff8091169081146135245760010190565b600260385414613c21576002603855565b604051633ee5aeb560e01b8152600490fd5b6040805463ffffffff60981b191660989290921b63ffffffff60981b16919091179055565b906020600191613c70838060a01b03825116856130c8565b0151910155565b6040805460a085901b6001600160a01b03191694600194938587179363ffffffff936001600160601b039093169290919060981c84161561407c57838116801515908161405d575b501561404b57965b613ce2610db4610db489613cda8c6119f1565b015460a01c90565b831115613e5257505084906000915b613df0575b5015613d4b5750604884901b63ffffffff60481b161792613d47919083613d4063ffffffff60281b1982613d29856119f1565b01541663ffffffff60281b8560281b1617926119f1565b01556119f1565b0155565b8385613d6a610e4f83613d62613d4798979a6119f1565b015460481c90565b9263ffffffff60281b9183613db463ffffffff60481b9a858460281b16908c8960481b1617179a63ffffffff60481b1983613da4866119f1565b015416908960481b1617926119f1565b0155831615613de457613d409063ffffffff60281b1983613dd4866119f1565b015416908560281b1617926119f1565b5050506116de81613c33565b828716151580613e37575b15613e3257613e18610e4f87613e108a6119f1565b015460281c90565b83811615613e2857965085613cf1565b5050508338613cf6565b613cf6565b5080613e4c610db4610db489613cda8c6119f1565b10613dfb565b90939296918680600092613e71610e4f895463ffffffff9060981c1690565b915b613fe7575b505050600014613f3e5750508154613d47939291859160981c63ffffffff1690613ea185613c33565b602882901b63ffffffff60281b16179682613ebb836119f1565b0154935463ffffffff60481b198516604887901b63ffffffff60481b16908117959092909160b81c63ffffffff1690613f11610e4f613f03604b5463ffffffff9060d81c1690565b60025463ffffffff1661265d565b91161015613f25575b5050613d40906119f1565b600163ffffffff60481b011916179250613d4038613f1a565b613d4794935081969250613f59610e4f87613e1081956119f1565b9263ffffffff60281b9783613fa58163ffffffff60481b958c8960281b1690878660481b161717179a63ffffffff60281b1983613f95866119f1565b015416908960281b1617926119f1565b01558316613fb6575b5050506119f1565b613fdd9063ffffffff60481b1983613fcd866119f1565b015416908560481b1617926119f1565b0155388381613fae565b9091948a81168015158061402f575b1561402757831461401a57610e4f86613d62614011936119f1565b94919082613e73565b9492505050863880613e78565b509491613e78565b5082614044610db4610db48a613cda876119f1565b1015613ff6565b50805460981c63ffffffff1696613cc7565b9050614074610e4f845463ffffffff9060b81c1690565b101538613cbf565b5050505091506120fc9250806140946140ab92613c33565b61409c6120ef565b926000845260208401526119f1565b613c58565b604080546001600160a01b031960a086901b1695946001938488179363ffffffff936001600160601b039093169290919060981c8416156144dc5783811680151590816144bd575b50156144ab57975b614113610db4610db488613cda8d6119f1565b8311156142c957505083906000915b61425c575b50156141b65750604885901b63ffffffff60481b1617938161416c63ffffffff60281b1982614155856119f1565b01541663ffffffff60281b8660281b1617926119f1565b01555b6001600160a01b038316156141ab57506140ab906120fc936141a16141926120ef565b6001600160a01b039095168552565b60208401526119f1565b9150613d47906119f1565b9094806141ca610e4f85613d6281956119f1565b9263ffffffff60281b918361421463ffffffff60481b9a858460281b16908c8960481b1617179a63ffffffff60481b1983614204866119f1565b015416908a60481b1617926119f1565b015583161561424b576142449063ffffffff60281b1983614234866119f1565b015416908660281b1617926119f1565b015561416f565b50505061425782613c33565b61416f565b90919293968381161515806142ae575b156142a457614281610e4f89613e10846119f1565b90848216156142965750969392919084614122565b979493925050508238614127565b9693929190614127565b50816142c3610db4610db48b613cda866119f1565b1061426c565b909392979185806000926142e8610e4f895463ffffffff9060981c1690565b915b614447575b5050506000146143a2575050815483919060981c63ffffffff169061431386613c33565b602882901b63ffffffff60281b1617968261432d836119f1565b0154935463ffffffff60481b198516604888901b63ffffffff60481b16908117959092909160b81c63ffffffff1690614375610e4f613f03604b5463ffffffff9060d81c1690565b91161015614389575b5050614244906119f1565b600163ffffffff60481b0119161792506142443861437e565b909692508391506143b9610e4f83613e108a6119f1565b9263ffffffff60281b97836144058163ffffffff60481b958c8960281b1690878660481b161717179a63ffffffff60281b19836143f5866119f1565b015416908a60281b1617926119f1565b01558316614416575b50505061416f565b61443d9063ffffffff60481b198361442d866119f1565b015416908660481b1617926119f1565b015538818161440e565b9091948b81168015158061448f575b1561448757831461447a57610e4f86613d62614471936119f1565b949190826142ea565b94925050508538806142ef565b5094916142ef565b50826144a4610db4610db48a613cda876119f1565b1015614456565b50805460981c63ffffffff1697614100565b90506144d4610e4f845463ffffffff9060b81c1690565b1015386140f8565b505050506120fc94508291506144f46140ab93613c33565b6141a16141926120ef565b1561450657565b60405162461bcd60e51b815260206004820152600b60248201526a139bc8115512081cd95b9d60aa1b6044820152606490fd5b1561454057565b60405162461bcd60e51b815260206004820152600c60248201526b139bdd081e5bdd5c88189a5960a21b6044820152606490fd5b6001600160601b03918216908216019190821161352457565b6120fc92600161459c836119f1565b015463ffffffff90818160281c16918160481c1691806145fc575b50816145c5575b5050613c77565b6001906145f39063ffffffff60281b19836145df866119f1565b0154169063ffffffff60281b1617926119f1565b015538806145be565b600161462863ffffffff60481b1982614614856119f1565b01541663ffffffff60481b851617926119f1565b0155386145b7565b63ffffffff8060405460981c1690811561468657816120fc92600052603960205260016146678119826040600020015416926119f1565b0155600161467b8260405460981c166119f1565b015460281c16613c33565b5050565b9061469e60405463ffffffff9060981c1690565b63ffffffff928382161561474f576001906146c2610db4610db484613cda876119f1565b6001600160601b03909116908111156147485781949293945b6146e6575b50505090565b9091939284811615158061472d575b156147265761470a610e4f84613e10846119f1565b908582161561471e575092939190816146db565b9394506146e0565b92936146e0565b5081614742610db4610db486613cda866119f1565b106146f5565b5090925050565b506000925050565b63ffffffff61477681604b5460d81c1661265d60025463ffffffff1690565b816040549116828260b81c161015806147b0575b156147a5576001613cda6105c393610db49360981c166119f1565b505060495460a01c90565b50818160981c16151561478a565b66ffffffffffffff918216908216039190821161352457565b60405460601c66ffffffffffffff1666ffffffffffffff6000828216428111156148f65761480791504290613bee565b905b604d549263ffffffff92838560201c1611614825575b50505050565b61484761484161102f604b5466ffffffffffffff9060a01c1690565b826147be565b838560401c16808483161061485e575b505061481f565b8061104a956148819716946148738685613509565b16116148e3575b5050613509565b7fc2b459809119087ca9d2bc10dea53a51b7d848b1a11075db037bdca58292c3e86148d56148bb60405466ffffffffffffff9060601c1690565b60405166ffffffffffffff90911681529081906020820190565b0390a1388080808080614857565b6148ee9293506147be565b90388061487a565b5090614809565b1561490457565b60405162461bcd60e51b8152602060048201526011602482015270105d58dd1a5bdb881b9bdd08195b991959607a1b6044820152606490fd5b1561494457565b60405162461bcd60e51b81526020600482015260076024820152664e6f206269647360c81b6044820152606490fd5b91908110156139dd5760051b0190565b1561498a57565b60405162461bcd60e51b815260206004820152600f60248201526e105b1c9958591e4818db185a5b5959608a1b6044820152606490fd5b908160209103126103a757516105c3816104ce565b908160209103126103a757516105c381610a11565b156149f257565b60405162461bcd60e51b815260206004820152600d60248201526c111a5cd8dbdd5b9d081d5cd959609a1b6044820152606490fd5b90600163ffffffff8093160191821161352457565b91909163ffffffff8080941691160191821161352457565b8181029291811591840414171561352457565b6001600160601b03908116612710039190821161352457565b614ab3614a9260025463ffffffff1690565b63ffffffff60201b6041549160201b169063ffffffff60201b191617604155565b6120fc61276661298c610c11614b68614ae9614ad8604b5463ffffffff9060d81c1690565b60415460201c63ffffffff1661265d565b60405463ffffffff919060b81c82168183168110614b855750614b0b906131c4565b614b4e614b2c610db46001613cda6116de60405463ffffffff9060981c1690565b604080546001600160601b0319166001600160601b0392909216919091179055565b6040546001600160601b0381169160d89190911c16614a54565b614b7f610db4614b7a60485460a01c90565b614a67565b90614a54565b614b8f91506131c4565b614b9e614b2c60495460a01c90565b614b4e565b8060081c9060048210156139dd5760ff600191161b90603b015416151590565b8060081c60048110156139dd5760ff600191603b0192161b8154179055565b90604051614bef81612080565b82546001600160a01b031681526001909201546020830152565b3d15614c34573d90614c1a826120fe565b91614c2860405193846120ce565b82523d6000602084013e565b606090565b6000918291829182916001600160a01b03165af1614c55614c09565b5015614c5d57565b60405162461bcd60e51b8152602060048201526015602482015274115d1a195c881d1c985b9cd9995c8819985a5b1959605a1b6044820152606490fd5b90614ca48261550d565b8015614d0b57614cb3816137aa565b90614cc160405192836120ce565b808252601f19614cd0826137aa565b0136602084013760005b818110614ce8575090925050565b80614cf6614d069287615341565b614d0082866139c9565b526139a4565b614cda565b509050604051614d1a816120b3565b60008152600036813790565b90614d396020928281519485920161056a565b0190565b9060405191826000604554614d5181612c68565b600191808316908115614dcd5750600114614d84575b5050614d76906120fc93614d26565b03601f1981018452836120ce565b60456000908152602093509091600080516020615e568339815191525b838310614db75750505082010182614d76614d67565b8054898401860152889550918401918101614da1565b614d7694506120fc969350602092915060ff1916828601528015150284010191819450614d67565b90614dff826120fe565b614e0c60405191826120ce565b8281528092614e1d601f19916120fe565b0190602036910137565b15614e2e57565b60405162461bcd60e51b815260206004820152602860248201527f43616e6e6f742073657420646973636f756e742061667465722061756374696f6044820152676e2073746172747360c01b6064820152608490fd5b15614e8b57565b60405162461bcd60e51b8152602060048201526017602482015276105d58dd1a5bdb88185b1c9958591e481cdd185c9d1959604a1b6044820152606490fd5b15614ed157565b60405162461bcd60e51b815260206004820152601060248201526f20a61030b33a32b91030bab1ba34b7b760811b6044820152606490fd5b15614f1057565b60405162461bcd60e51b815260206004820152600d60248201526c4f6e6c7920646563726561736560981b6044820152606490fd5b15614f4c57565b60405162461bcd60e51b81526020600482015260116024820152706d6178537570706c7920746f6f206c6f7760781b6044820152606490fd5b15614f8c57565b60405162461bcd60e51b81526020600482015260086024820152674e6f2066756e647360c01b6044820152606490fd5b6001600160a01b038116801561509557614fd5836157c7565b615050578290614fe582846158f9565b614fee836158bc565b60007fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8180a461501e82826158f9565b604d5460781c60ff1661502f575050565b61503c61504d91836150d9565b916000526042602052604060002090565b55565b60405162461bcd60e51b815260206004820152601c60248201527f4552433732313a20746f6b656e20616c7265616479206d696e746564000000006044820152606490fd5b606460405162461bcd60e51b815260206004820152602060248201527f4552433732313a206d696e7420746f20746865207a65726f20616464726573736044820152fd5b6040805160208101928352606093841b6001600160601b031916918101919091524360001981014060548301526001198101406074830152600319014060948201524460b48201524190921b60d483015260c882529061010081016001600160401b0381118282101761209b5760405251902090565b6006546001600160a01b0316330361516357565b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2043616c6c6572206973206e6f7420746865206f776e65726044820152fd5b6001600160a01b039081166000908152600460209081526040808320858516845290915290205460ff1692919083156151de575050565b60ff60055460a81c166151ef575050565b80919293506151fc612b88565b1691161490565b60809060208152602c60208201527f455243373231456e756d657261626c653a20676c6f62616c20696e646578206f60408201526b7574206f6620626f756e647360a01b60608201520190565b9060025490818310156152c157600092835b8381106152825760405162461bcd60e51b8152806115a260048201615203565b61528b816157c7565b61529e575b615299906139a4565b615262565b938181146152ba576152b2615299916139a4565b949050615290565b5090915050565b60405162461bcd60e51b8152806115a260048201615203565b60809060208152602b60208201527f455243373231456e756d657261626c653a206f776e657220696e646578206f7560408201526a74206f6620626f756e647360a81b60608201520190565b6002548110156139dd57600260005260206000200190600090565b9061534b8261550d565b8110156153e2576000908192600254935b84811061537c5760405162461bcd60e51b8152806115a2600482016152da565b6153a0611f2161538b83615326565b905460039190911b1c6001600160a01b031690565b6001600160a01b038316146153be575b6153b9906139a4565b61535c565b928281036153ce57505050905090565b6153da6153b9916139a4565b9390506153b0565b60405162461bcd60e51b8152806115a2600482016152da565b60ff600080516020615e768339815191525460401c161561541857565b604051631afcd79f60e31b8152600490fd5b9081516001600160401b03811161209b576001906154518161544c8454612c68565b612d49565b602080601f831160011461548c575081929394600092615481575b5050600019600383901b1c191690821b179055565b01519050388061546c565b6001600052601f198316959091907fb10e2d527612073b26eecdfd717e6a320cf44b4afac2b0732d9fcbe2b7fa0cf6926000905b8882106154f657505083859697106154dd575b505050811b019055565b015160001960f88460031b161c191690553880806154d3565b8087859682949686015181550195019301906154c0565b6001600160a01b0316801561556a57600254600091825b8281106155315750505090565b615540611f2161538b83615326565b8214615555575b615550906139a4565b615524565b92615562615550916139a4565b939050615547565b60405162461bcd60e51b815260206004820152602a60248201527f4552433732313a2062616c616e636520717565727920666f7220746865207a65604482015269726f206164647265737360b01b6064820152608490fd5b6155cb816157c7565b156155fc576002548110156139dd576002600052600080516020615e3683398151915201546001600160a01b031690565b60405162461bcd60e51b815260206004820152602960248201527f4552433732313a206f776e657220717565727920666f72206e6f6e657869737460448201526832b73a103a37b5b2b760b91b6064820152608490fd5b61565c816157c7565b1561567c576000908152600360205260409020546001600160a01b031690565b60405162461bcd60e51b815260206004820152602c60248201527f4552433732313a20617070726f76656420717565727920666f72206e6f6e657860448201526b34b9ba32b73a103a37b5b2b760a11b6064820152608490fd5b156156dd57565b60405162461bcd60e51b815260206004820152603160248201527f4552433732313a207472616e736665722063616c6c6572206973206e6f74206f6044820152701ddb995c881b9bdc88185c1c1c9bdd9959607a1b6064820152608490fd5b906157609392916157506108ab8433615800565b61575b838383615a9e565b615cce565b1561576757565b60405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527131b2b4bb32b91034b6b83632b6b2b73a32b960711b6064820152608490fd5b600254811090816157d6575090565b90156139dd576002600052600080516020615e3683398151915201546001600160a01b0316151590565b615809826157c7565b1561586257615817826155c2565b6001600160a01b03828116828216811494909190851561584a575b505050821561584057505090565b6105c392506151a7565b6158579192939550615653565b161491388080615832565b60405162461bcd60e51b815260206004820152602c60248201527f4552433732313a206f70657261746f7220717565727920666f72206e6f6e657860448201526b34b9ba32b73a103a37b5b2b760a11b6064820152608490fd5b60025490600160401b82101561209b5760018201806002558210156139dd5760026000526120fc91600080516020615e36833981519152016130c8565b60005b6001908181101561481f578084018411613524576001600160a01b03831661593057604051635cbd944160e01b8152600490fd5b016158fc565b909160005b600190818110156159b157808301808411613524576001600160a01b03868116159086161580806159aa575b1561597e57604051635cbd944160e01b8152600490fd5b1561598c575b50500161593b565b15615998575b80615984565b6159a4908686336159b8565b38615992565b5081615967565b5050505050565b9092916001600160a01b0391826159cd612b88565b16806159dc575b505050505050565b8033146159d457803b156103a7576000948460849481604051998a98899763657711f560e11b895216600488015216602486015216604484015260648301525afa8015612b2d57615a32575b80808080806159d4565b80615a3f615a45926120a0565b8061039c565b38615a28565b60005b600190818110156159b1578085018511613524576001600160a01b03838116159081615a93575b5015615a8d57604051635cbd944160e01b8152600490fd5b01615a4e565b905084161538615a75565b9190615aa9826155c2565b6001600160a01b0380851694918116859003615b89578216938415615b38576120fc948491615ad9838686615936565b615ae283615be0565b615b0e85615aef85615326565b90919082549060031b9160018060a01b03809116831b921b1916179055565b7fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef600080a4615a4b565b60405162461bcd60e51b8152602060048201526024808201527f4552433732313a207472616e7366657220746f20746865207a65726f206164646044820152637265737360e01b6064820152608490fd5b60405162461bcd60e51b815260206004820152602960248201527f4552433732313a207472616e73666572206f6620746f6b656e2074686174206960448201526839903737ba1037bbb760b91b6064820152608490fd5b600081815260036020526040812080546001600160a01b03191690556001600160a01b03615c0d836155c2565b167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b9258280a4565b816000526003602052615c4b8160406000206130c8565b6001600160a01b0380615c5d846155c2565b169116907f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925600080a4565b908160209103126103a757516105c3816103db565b6001600160a01b0391821681529116602082015260408101919091526080606082018190526105c39291019061058d565b92909190823b15615dcf57615d01926020926000604051809681958294630a85bd0160e11b9a8b85523360048601615c9d565b03926001600160a01b03165af160009181615d9f575b50615d9157615d24614c09565b80519081615d8c5760405162461bcd60e51b815260206004820152603260248201527f4552433732313a207472616e7366657220746f206e6f6e20455243373231526560448201527131b2b4bb32b91034b6b83632b6b2b73a32b960711b6064820152608490fd5b602001fd5b6001600160e01b0319161490565b615dc191925060203d8111615dc8575b615db981836120ce565b810190615c88565b9038615d17565b503d615daf565b50505050600190565b6120fc90615de46153fb565b615dec6153fb565b600680546001600160a01b039283166001600160a01b0319821681179092559091167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a356fe405787fa12a823e0f2b7631cc41b3ba8828b3321ca811111fa75cd3aa3bb5acea80a8fcc11760162f08bb091d2c9389d07f2b73d0e996161dfac6f1043b5fc0bf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00a264697066735822122049b3469e8c64981da27432685c06a04be9e9de24e5a9d2a6db2f920579946ba164736f6c63430008140033
Verified Source Code Full Match
Compiler: v0.8.20+commit.a1b79de6
EVM: paris
Optimization: Yes (50 runs)
OwnablePermissions.sol 8 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
abstract contract OwnablePermissions is Context {
function _requireCallerIsContractOwner() internal view virtual;
}
ICreatorToken.sol 9 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorToken {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
function getTransferValidationFunction() external view returns (bytes4 functionSignature, bool isViewFunction);
}
ICreatorTokenLegacy.sol 8 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ICreatorTokenLegacy {
event TransferValidatorUpdated(address oldValidator, address newValidator);
function getTransferValidator() external view returns (address validator);
function setTransferValidator(address validator) external;
}
ITransferValidator.sol 17 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidator {
function applyCollectionTransferPolicy(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId) external view;
function validateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount) external;
function beforeAuthorizedTransfer(address operator, address token, uint256 tokenId) external;
function afterAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransfer(address operator, address token) external;
function afterAuthorizedTransfer(address token) external;
function beforeAuthorizedTransfer(address token, uint256 tokenId) external;
function beforeAuthorizedTransferWithAmount(address token, uint256 tokenId, uint256 amount) external;
function afterAuthorizedTransferWithAmount(address token, uint256 tokenId) external;
}
ITransferValidatorSetTokenType.sol 6 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface ITransferValidatorSetTokenType {
function setTokenTypeOfCollection(address collection, uint16 tokenType) external;
}
AutomaticValidatorTransferApproval.sol 33 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../access/OwnablePermissions.sol";
/**
* @title AutomaticValidatorTransferApproval
* @author Limit Break, Inc.
* @notice Base contract mix-in that provides boilerplate code giving the contract owner the
* option to automatically approve a 721-C transfer validator implementation for transfers.
*/
abstract contract AutomaticValidatorTransferApproval is OwnablePermissions {
/// @dev Emitted when the automatic approval flag is modified by the creator.
event AutomaticApprovalOfTransferValidatorSet(bool autoApproved);
/// @dev If true, the collection's transfer validator is automatically approved to transfer holder's tokens.
bool public autoApproveTransfersFromValidator;
/**
* @notice Sets if the transfer validator is automatically approved as an operator for all token owners.
*
* @dev Throws when the caller is not the contract owner.
*
* @param autoApprove If true, the collection's transfer validator will be automatically approved to
* transfer holder's tokens.
*/
function setAutomaticApprovalOfTransfersFromValidator(bool autoApprove) external {
_requireCallerIsContractOwner();
autoApproveTransfersFromValidator = autoApprove;
emit AutomaticApprovalOfTransferValidatorSet(autoApprove);
}
}
CreatorTokenBase.sol 192 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "../access/OwnablePermissions.sol";
import "../interfaces/ICreatorToken.sol";
import "../interfaces/ICreatorTokenLegacy.sol";
import "../interfaces/ITransferValidator.sol";
import "./TransferValidation.sol";
import "../interfaces/ITransferValidatorSetTokenType.sol";
/**
* @title CreatorTokenBase
* @author Limit Break, Inc.
* @notice CreatorTokenBaseV3 is an abstract contract that provides basic functionality for managing token
* transfer policies through an implementation of ICreatorTokenTransferValidator/ICreatorTokenTransferValidatorV2/ICreatorTokenTransferValidatorV3.
* This contract is intended to be used as a base for creator-specific token contracts, enabling customizable transfer
* restrictions and security policies.
*
* <h4>Features:</h4>
* <ul>Ownable: This contract can have an owner who can set and update the transfer validator.</ul>
* <ul>TransferValidation: Implements the basic token transfer validation interface.</ul>
*
* <h4>Benefits:</h4>
* <ul>Provides a flexible and modular way to implement custom token transfer restrictions and security policies.</ul>
* <ul>Allows creators to enforce policies such as account and codehash blacklists, whitelists, and graylists.</ul>
* <ul>Can be easily integrated into other token contracts as a base contract.</ul>
*
* <h4>Intended Usage:</h4>
* <ul>Use as a base contract for creator token implementations that require advanced transfer restrictions and
* security policies.</ul>
* <ul>Set and update the ICreatorTokenTransferValidator implementation contract to enforce desired policies for the
* creator token.</ul>
*
* <h4>Compatibility:</h4>
* <ul>Backward and Forward Compatible - V1/V2/V3 Creator Token Base will work with V1/V2/V3 Transfer Validators.</ul>
*/
abstract contract CreatorTokenBase is OwnablePermissions, TransferValidation, ICreatorToken {
/// @dev Thrown when setting a transfer validator address that has no deployed code.
error CreatorTokenBase__InvalidTransferValidatorContract();
/// @dev The default transfer validator that will be used if no transfer validator has been set by the creator.
address public constant DEFAULT_TRANSFER_VALIDATOR = address(0x721C002B0059009a671D00aD1700c9748146cd1B);
/// @dev Used to determine if the default transfer validator is applied.
/// @dev Set to true when the creator sets a transfer validator address.
bool private isValidatorInitialized;
/// @dev Address of the transfer validator to apply to transactions.
address private transferValidator;
constructor() {
_emitDefaultTransferValidator();
_registerTokenType(DEFAULT_TRANSFER_VALIDATOR);
}
/**
* @notice Sets the transfer validator for the token contract.
*
* @dev Throws when provided validator contract is not the zero address and does not have code.
* @dev Throws when the caller is not the contract owner.
*
* @dev <h4>Postconditions:</h4>
* 1. The transferValidator address is updated.
* 2. The `TransferValidatorUpdated` event is emitted.
*
* @param transferValidator_ The address of the transfer validator contract.
*/
function setTransferValidator(address transferValidator_) public {
_requireCallerIsContractOwner();
bool isValidTransferValidator = transferValidator_.code.length > 0;
if(transferValidator_ != address(0) && !isValidTransferValidator) {
revert CreatorTokenBase__InvalidTransferValidatorContract();
}
emit TransferValidatorUpdated(address(getTransferValidator()), transferValidator_);
isValidatorInitialized = true;
transferValidator = transferValidator_;
_registerTokenType(transferValidator_);
}
/**
* @notice Returns the transfer validator contract address for this token contract.
*/
function getTransferValidator() public view override returns (address validator) {
validator = transferValidator;
if (validator == address(0)) {
if (!isValidatorInitialized) {
validator = DEFAULT_TRANSFER_VALIDATOR;
}
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 /*value*/) internal virtual override {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(caller, from, to, tokenId);
}
}
/**
* @dev Pre-validates a token transfer, reverting if the transfer is not allowed by this token's security policy.
* Inheriting contracts are responsible for overriding the _beforeTokenTransfer function, or its equivalent
* and calling _validateBeforeTransfer so that checks can be properly applied during token transfers.
*
* @dev Be aware that if the msg.sender is the transfer validator, the transfer is automatically permitted, as the
* transfer validator is expected to pre-validate the transfer.
*
* @dev Used for ERC20 and ERC1155 token transfers which have an amount value to validate in the transfer validator.
* @dev The `tokenId` for ERC20 tokens should be set to `0`.
*
* @dev Throws when the transfer doesn't comply with the collection's transfer policy, if the transferValidator is
* set to a non-zero address.
*
* @param caller The address of the caller.
* @param from The address of the sender.
* @param to The address of the receiver.
* @param tokenId The token id being transferred.
* @param amount The amount of token being transferred.
*/
function _preValidateTransfer(
address caller,
address from,
address to,
uint256 tokenId,
uint256 amount,
uint256 /*value*/) internal virtual override {
address validator = getTransferValidator();
if (validator != address(0)) {
if (msg.sender == validator) {
return;
}
ITransferValidator(validator).validateTransfer(caller, from, to, tokenId, amount);
}
}
function _tokenType() internal virtual pure returns(uint16);
function _registerTokenType(address validator) internal {
if (validator != address(0)) {
uint256 validatorCodeSize;
assembly {
validatorCodeSize := extcodesize(validator)
}
if(validatorCodeSize > 0) {
try ITransferValidatorSetTokenType(validator).setTokenTypeOfCollection(address(this), _tokenType()) {
} catch { }
}
}
}
/**
* @dev Used during contract deployment for constructable and cloneable creator tokens
* @dev to emit the `TransferValidatorUpdated` event signaling the validator for the contract
* @dev is the default transfer validator.
*/
function _emitDefaultTransferValidator() internal {
emit TransferValidatorUpdated(address(0), DEFAULT_TRANSFER_VALIDATOR);
}
}
TransferValidation.sol 125 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@openzeppelin/contracts/utils/Context.sol";
/**
* @title TransferValidation
* @author Limit Break, Inc.
* @notice A mix-in that can be combined with ERC-721 contracts to provide more granular hooks.
* Openzeppelin's ERC721 contract only provides hooks for before and after transfer. This allows
* developers to validate or customize transfers within the context of a mint, a burn, or a transfer.
*/
abstract contract TransferValidation is Context {
/// @dev Thrown when the from and to address are both the zero address.
error ShouldNotMintToBurnAddress();
/*************************************************************************/
/* Transfers Without Amounts */
/*************************************************************************/
/// @dev Inheriting contracts should call this function in the _beforeTokenTransfer function to get more granular hooks.
function _validateBeforeTransfer(address from, address to, uint256 tokenId) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_preValidateMint(_msgSender(), to, tokenId, msg.value);
} else if(toZeroAddress) {
_preValidateBurn(_msgSender(), from, tokenId, msg.value);
} else {
_preValidateTransfer(_msgSender(), from, to, tokenId, msg.value);
}
}
/// @dev Inheriting contracts should call this function in the _afterTokenTransfer function to get more granular hooks.
function _validateAfterTransfer(address from, address to, uint256 tokenId) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_postValidateMint(_msgSender(), to, tokenId, msg.value);
} else if(toZeroAddress) {
_postValidateBurn(_msgSender(), from, tokenId, msg.value);
} else {
_postValidateTransfer(_msgSender(), from, to, tokenId, msg.value);
}
}
/// @dev Optional validation hook that fires before a mint
function _preValidateMint(address caller, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a mint
function _postValidateMint(address caller, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a burn
function _preValidateBurn(address caller, address from, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a burn
function _postValidateBurn(address caller, address from, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a transfer
function _preValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a transfer
function _postValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 value) internal virtual {}
/*************************************************************************/
/* Transfers With Amounts */
/*************************************************************************/
/// @dev Inheriting contracts should call this function in the _beforeTokenTransfer function to get more granular hooks.
function _validateBeforeTransfer(address from, address to, uint256 tokenId, uint256 amount) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_preValidateMint(_msgSender(), to, tokenId, amount, msg.value);
} else if(toZeroAddress) {
_preValidateBurn(_msgSender(), from, tokenId, amount, msg.value);
} else {
_preValidateTransfer(_msgSender(), from, to, tokenId, amount, msg.value);
}
}
/// @dev Inheriting contracts should call this function in the _afterTokenTransfer function to get more granular hooks.
function _validateAfterTransfer(address from, address to, uint256 tokenId, uint256 amount) internal virtual {
bool fromZeroAddress = from == address(0);
bool toZeroAddress = to == address(0);
if(fromZeroAddress && toZeroAddress) {
revert ShouldNotMintToBurnAddress();
} else if(fromZeroAddress) {
_postValidateMint(_msgSender(), to, tokenId, amount, msg.value);
} else if(toZeroAddress) {
_postValidateBurn(_msgSender(), from, tokenId, amount, msg.value);
} else {
_postValidateTransfer(_msgSender(), from, to, tokenId, amount, msg.value);
}
}
/// @dev Optional validation hook that fires before a mint
function _preValidateMint(address caller, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a mint
function _postValidateMint(address caller, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a burn
function _preValidateBurn(address caller, address from, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a burn
function _postValidateBurn(address caller, address from, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires before a transfer
function _preValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
/// @dev Optional validation hook that fires after a transfer
function _postValidateTransfer(address caller, address from, address to, uint256 tokenId, uint256 amount, uint256 value) internal virtual {}
}
Constants.sol 62 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @dev Constant bytes32 value of 0x000...000
bytes32 constant ZERO_BYTES32 = bytes32(0);
/// @dev Constant value of 0
uint256 constant ZERO = 0;
/// @dev Constant value of 1
uint256 constant ONE = 1;
/// @dev Constant value representing an open order in storage
uint8 constant ORDER_STATE_OPEN = 0;
/// @dev Constant value representing a filled order in storage
uint8 constant ORDER_STATE_FILLED = 1;
/// @dev Constant value representing a cancelled order in storage
uint8 constant ORDER_STATE_CANCELLED = 2;
/// @dev Constant value representing the ERC721 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC721 = 721;
/// @dev Constant value representing the ERC1155 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC1155 = 1155;
/// @dev Constant value representing the ERC20 token type for signatures and transfer hooks
uint256 constant TOKEN_TYPE_ERC20 = 20;
/// @dev Constant value to mask the upper bits of a signature that uses a packed `vs` value to extract `s`
bytes32 constant UPPER_BIT_MASK = 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
/// @dev EIP-712 typehash used for validating signature based stored approvals
bytes32 constant UPDATE_APPROVAL_TYPEHASH =
keccak256("UpdateApprovalBySignature(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 approvalExpiration,uint256 sigDeadline,uint256 masterNonce)");
/// @dev EIP-712 typehash used for validating a single use permit without additional data
bytes32 constant SINGLE_USE_PERMIT_TYPEHASH =
keccak256("PermitTransferFrom(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 expiration,uint256 masterNonce)");
/// @dev EIP-712 typehash used for validating a single use permit with additional data
string constant SINGLE_USE_PERMIT_TRANSFER_ADVANCED_TYPEHASH_STUB =
"PermitTransferFromWithAdditionalData(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 nonce,address operator,uint256 expiration,uint256 masterNonce,";
/// @dev EIP-712 typehash used for validating an order permit that updates storage as it fills
string constant PERMIT_ORDER_ADVANCED_TYPEHASH_STUB =
"PermitOrderWithAdditionalData(uint256 tokenType,address token,uint256 id,uint256 amount,uint256 salt,address operator,uint256 expiration,uint256 masterNonce,";
/// @dev Pausable flag for stored approval transfers of ERC721 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC721 = 1 << 0;
/// @dev Pausable flag for stored approval transfers of ERC1155 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC1155 = 1 << 1;
/// @dev Pausable flag for stored approval transfers of ERC20 assets
uint256 constant PAUSABLE_APPROVAL_TRANSFER_FROM_ERC20 = 1 << 2;
/// @dev Pausable flag for single use permit transfers of ERC721 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC721 = 1 << 3;
/// @dev Pausable flag for single use permit transfers of ERC1155 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC1155 = 1 << 4;
/// @dev Pausable flag for single use permit transfers of ERC20 assets
uint256 constant PAUSABLE_PERMITTED_TRANSFER_FROM_ERC20 = 1 << 5;
/// @dev Pausable flag for order fill transfers of ERC1155 assets
uint256 constant PAUSABLE_ORDER_TRANSFER_FROM_ERC1155 = 1 << 6;
/// @dev Pausable flag for order fill transfers of ERC20 assets
uint256 constant PAUSABLE_ORDER_TRANSFER_FROM_ERC20 = 1 << 7;
Initializable.sol 228 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.20;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Storage of the initializable contract.
*
* It's implemented on a custom ERC-7201 namespace to reduce the risk of storage collisions
* when using with upgradeable contracts.
*
* @custom:storage-location erc7201:openzeppelin.storage.Initializable
*/
struct InitializableStorage {
/**
* @dev Indicates that the contract has been initialized.
*/
uint64 _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool _initializing;
}
// keccak256(abi.encode(uint256(keccak256("openzeppelin.storage.Initializable")) - 1)) & ~bytes32(uint256(0xff))
bytes32 private constant INITIALIZABLE_STORAGE = 0xf0c57e16840df040f15088dc2f81fe391c3923bec73e23a9662efc9c229c6a00;
/**
* @dev The contract is already initialized.
*/
error InvalidInitialization();
/**
* @dev The contract is not initializing.
*/
error NotInitializing();
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint64 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that in the context of a constructor an `initializer` may be invoked any
* number of times. This behavior in the constructor can be useful during testing and is not expected to be used in
* production.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
// Cache values to avoid duplicated sloads
bool isTopLevelCall = !$._initializing;
uint64 initialized = $._initialized;
// Allowed calls:
// - initialSetup: the contract is not in the initializing state and no previous version was
// initialized
// - construction: the contract is initialized at version 1 (no reininitialization) and the
// current contract is just being deployed
bool initialSetup = initialized == 0 && isTopLevelCall;
bool construction = initialized == 1 && address(this).code.length == 0;
if (!initialSetup && !construction) {
revert InvalidInitialization();
}
$._initialized = 1;
if (isTopLevelCall) {
$._initializing = true;
}
_;
if (isTopLevelCall) {
$._initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: Setting the version to 2**64 - 1 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint64 version) {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing || $._initialized >= version) {
revert InvalidInitialization();
}
$._initialized = version;
$._initializing = true;
_;
$._initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
_checkInitializing();
_;
}
/**
* @dev Reverts if the contract is not in an initializing state. See {onlyInitializing}.
*/
function _checkInitializing() internal view virtual {
if (!_isInitializing()) {
revert NotInitializing();
}
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
// solhint-disable-next-line var-name-mixedcase
InitializableStorage storage $ = _getInitializableStorage();
if ($._initializing) {
revert InvalidInitialization();
}
if ($._initialized != type(uint64).max) {
$._initialized = type(uint64).max;
emit Initialized(type(uint64).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint64) {
return _getInitializableStorage()._initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _getInitializableStorage()._initializing;
}
/**
* @dev Returns a pointer to the storage namespace.
*/
// solhint-disable-next-line var-name-mixedcase
function _getInitializableStorage() private pure returns (InitializableStorage storage $) {
assembly {
$.slot := INITIALIZABLE_STORAGE
}
}
}
ContextUpgradeable.sol 34 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
ERC165Upgradeable.sol 33 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "@openzeppelin/contracts/utils/introspection/IERC165.sol";
import {Initializable} from "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165Upgradeable is Initializable, IERC165 {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
IERC721.sol 135 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.20;
import {IERC165} from "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC-721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC-721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or
* {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon
* a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC-721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the address zero.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
IERC721Receiver.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.20;
/**
* @title ERC-721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC-721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be
* reverted.
*
* The selector can be obtained in Solidity with `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
IERC721Enumerable.sol 29 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
IERC721Metadata.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.20;
import {IERC721} from "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
}
Panic.sol 57 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
ReentrancyGuard.sol 87 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)
pragma solidity ^0.8.20;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
* consider using {ReentrancyGuardTransient} instead.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant NOT_ENTERED = 1;
uint256 private constant ENTERED = 2;
uint256 private _status;
/**
* @dev Unauthorized reentrant call.
*/
error ReentrancyGuardReentrantCall();
constructor() {
_status = NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be NOT_ENTERED
if (_status == ENTERED) {
revert ReentrancyGuardReentrantCall();
}
// Any calls to nonReentrant after this point will fail
_status = ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == ENTERED;
}
}
Strings.sol 116 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
assembly ("memory-safe") {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
assembly ("memory-safe") {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its checksummed ASCII `string` hexadecimal
* representation, according to EIP-55.
*/
function toChecksumHexString(address addr) internal pure returns (string memory) {
bytes memory buffer = bytes(toHexString(addr));
// hash the hex part of buffer (skip length + 2 bytes, length 40)
uint256 hashValue;
assembly ("memory-safe") {
hashValue := shr(96, keccak256(add(buffer, 0x22), 40))
}
for (uint256 i = 41; i > 1; --i) {
// possible values for buffer[i] are 48 (0) to 57 (9) and 97 (a) to 102 (f)
if (hashValue & 0xf > 7 && uint8(buffer[i]) > 96) {
// case shift by xoring with 0x20
buffer[i] ^= 0x20;
}
hashValue >>= 4;
}
return string(buffer);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
Hashes.sol 31 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/Hashes.sol)
pragma solidity ^0.8.20;
/**
* @dev Library of standard hash functions.
*
* _Available since v5.1._
*/
library Hashes {
/**
* @dev Commutative Keccak256 hash of a sorted pair of bytes32. Frequently used when working with merkle proofs.
*
* NOTE: Equivalent to the `standardNodeHash` in our https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
*/
function commutativeKeccak256(bytes32 a, bytes32 b) internal pure returns (bytes32) {
return a < b ? _efficientKeccak256(a, b) : _efficientKeccak256(b, a);
}
/**
* @dev Implementation of keccak256(abi.encode(a, b)) that doesn't allocate or expand memory.
*/
function _efficientKeccak256(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly ("memory-safe") {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
MerkleProof.sol 514 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/cryptography/MerkleProof.sol)
// This file was procedurally generated from scripts/generate/templates/MerkleProof.js.
pragma solidity ^0.8.20;
import {Hashes} from "./Hashes.sol";
/**
* @dev These functions deal with verification of Merkle Tree proofs.
*
* The tree and the proofs can be generated using our
* https://github.com/OpenZeppelin/merkle-tree[JavaScript library].
* You will find a quickstart guide in the readme.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the Merkle tree could be reinterpreted as a leaf value.
* OpenZeppelin's JavaScript library generates Merkle trees that are safe
* against this attack out of the box.
*
* IMPORTANT: Consider memory side-effects when using custom hashing functions
* that access memory in an unsafe way.
*
* NOTE: This library supports proof verification for merkle trees built using
* custom _commutative_ hashing functions (i.e. `H(a, b) == H(b, a)`). Proving
* leaf inclusion in trees built using non-commutative hashing functions requires
* additional logic that is not supported by this library.
*/
library MerkleProof {
/**
*@dev The multiproof provided is not valid.
*/
error MerkleProofInvalidMultiproof();
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with the default hashing function.
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProof(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in memory with a custom hashing function.
*/
function processProof(
bytes32[] memory proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function verifyCalldata(bytes32[] calldata proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
return processProofCalldata(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with the default hashing function.
*/
function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = Hashes.commutativeKeccak256(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function verifyCalldata(
bytes32[] calldata proof,
bytes32 root,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processProofCalldata(proof, leaf, hasher) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leaves & pre-images are assumed to be sorted.
*
* This version handles proofs in calldata with a custom hashing function.
*/
function processProofCalldata(
bytes32[] calldata proof,
bytes32 leaf,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
computedHash = hasher(computedHash, proof[i]);
}
return computedHash;
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProof(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProof}.
*/
function multiProofVerify(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProof(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in memory with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProof(
bytes32[] memory proof,
bool[] memory proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves
) internal pure returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with the default hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves
) internal pure returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = Hashes.commutativeKeccak256(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
/**
* @dev Returns true if the `leaves` can be simultaneously proven to be a part of a Merkle tree defined by
* `root`, according to `proof` and `proofFlags` as described in {processMultiProof}.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. See {processMultiProof} for details.
*
* NOTE: Consider the case where `root == proof[0] && leaves.length == 0` as it will return `true`.
* The `leaves` must be validated independently. See {processMultiProofCalldata}.
*/
function multiProofVerifyCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32 root,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bool) {
return processMultiProofCalldata(proof, proofFlags, leaves, hasher) == root;
}
/**
* @dev Returns the root of a tree reconstructed from `leaves` and sibling nodes in `proof`. The reconstruction
* proceeds by incrementally reconstructing all inner nodes by combining a leaf/inner node with either another
* leaf/inner node or a proof sibling node, depending on whether each `proofFlags` item is true or false
* respectively.
*
* This version handles multiproofs in calldata with a custom hashing function.
*
* CAUTION: Not all Merkle trees admit multiproofs. To use multiproofs, it is sufficient to ensure that: 1) the tree
* is complete (but not necessarily perfect), 2) the leaves to be proven are in the opposite order they are in the
* tree (i.e., as seen from right to left starting at the deepest layer and continuing at the next layer).
*
* NOTE: The _empty set_ (i.e. the case where `proof.length == 1 && leaves.length == 0`) is considered a no-op,
* and therefore a valid multiproof (i.e. it returns `proof[0]`). Consider disallowing this case if you're not
* validating the leaves elsewhere.
*/
function processMultiProofCalldata(
bytes32[] calldata proof,
bool[] calldata proofFlags,
bytes32[] memory leaves,
function(bytes32, bytes32) view returns (bytes32) hasher
) internal view returns (bytes32 merkleRoot) {
// This function rebuilds the root hash by traversing the tree up from the leaves. The root is rebuilt by
// consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the
// `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of
// the Merkle tree.
uint256 leavesLen = leaves.length;
uint256 proofFlagsLen = proofFlags.length;
// Check proof validity.
if (leavesLen + proof.length != proofFlagsLen + 1) {
revert MerkleProofInvalidMultiproof();
}
// The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using
// `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop".
bytes32[] memory hashes = new bytes32[](proofFlagsLen);
uint256 leafPos = 0;
uint256 hashPos = 0;
uint256 proofPos = 0;
// At each step, we compute the next hash using two values:
// - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we
// get the next hash.
// - depending on the flag, either another value from the "main queue" (merging branches) or an element from the
// `proof` array.
for (uint256 i = 0; i < proofFlagsLen; i++) {
bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++];
bytes32 b = proofFlags[i]
? (leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++])
: proof[proofPos++];
hashes[i] = hasher(a, b);
}
if (proofFlagsLen > 0) {
if (proofPos != proof.length) {
revert MerkleProofInvalidMultiproof();
}
unchecked {
return hashes[proofFlagsLen - 1];
}
} else if (leavesLen > 0) {
return leaves[0];
} else {
return proof[0];
}
}
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Math.sol 685 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2²⁵⁶ + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= prod1) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 exp;
unchecked {
exp = 128 * SafeCast.toUint(value > (1 << 128) - 1);
value >>= exp;
result += exp;
exp = 64 * SafeCast.toUint(value > (1 << 64) - 1);
value >>= exp;
result += exp;
exp = 32 * SafeCast.toUint(value > (1 << 32) - 1);
value >>= exp;
result += exp;
exp = 16 * SafeCast.toUint(value > (1 << 16) - 1);
value >>= exp;
result += exp;
exp = 8 * SafeCast.toUint(value > (1 << 8) - 1);
value >>= exp;
result += exp;
exp = 4 * SafeCast.toUint(value > (1 << 4) - 1);
value >>= exp;
result += exp;
exp = 2 * SafeCast.toUint(value > (1 << 2) - 1);
value >>= exp;
result += exp;
result += SafeCast.toUint(value > 1);
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
uint256 isGt;
unchecked {
isGt = SafeCast.toUint(value > (1 << 128) - 1);
value >>= isGt * 128;
result += isGt * 16;
isGt = SafeCast.toUint(value > (1 << 64) - 1);
value >>= isGt * 64;
result += isGt * 8;
isGt = SafeCast.toUint(value > (1 << 32) - 1);
value >>= isGt * 32;
result += isGt * 4;
isGt = SafeCast.toUint(value > (1 << 16) - 1);
value >>= isGt * 16;
result += isGt * 2;
result += SafeCast.toUint(value > (1 << 8) - 1);
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
SafeCast.sol 1162 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
SignedMath.sol 68 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, int256 a, int256 b) internal pure returns (int256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * int256(SafeCast.toUint(condition)));
}
}
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// Formula from the "Bit Twiddling Hacks" by Sean Eron Anderson.
// Since `n` is a signed integer, the generated bytecode will use the SAR opcode to perform the right shift,
// taking advantage of the most significant (or "sign" bit) in two's complement representation.
// This opcode adds new most significant bits set to the value of the previous most significant bit. As a result,
// the mask will either be `bytes32(0)` (if n is positive) or `~bytes32(0)` (if n is negative).
int256 mask = n >> 255;
// A `bytes32(0)` mask leaves the input unchanged, while a `~bytes32(0)` mask complements it.
return uint256((n + mask) ^ mask);
}
}
}
GmStudioRankedAuction.sol 1317 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "./helpers/OwnableUpgradeable.sol";
import "./helpers/ERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
interface IERC2981 {
/**
* @notice Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information.
* @param salePrice - the sale price of the NFT asset specified by `tokenId`.
* @return receiver - address of who should be sent the royalty payment.
* @return royaltyAmount - the royalty payment amount for `salePrice`.
*/
function royaltyInfo(
uint256 tokenId,
uint256 salePrice
) external view returns (address receiver, uint256 royaltyAmount);
}
interface IDelegateRegistry {
/**
* @notice Checks if a delegate has been granted permission for an ERC721 token.
* @param delegate The address of the delegate.
* @param vault The address of the vault (original owner).
* @param contract_ The address of the ERC721 contract.
* @param tokenId The ID of the token.
* @param role The role assigned to the delegate.
* @return True if the delegate has permission, false otherwise.
*/
function checkDelegateForERC721(
address delegate,
address vault,
address contract_,
uint256 tokenId,
bytes32 role
) external view returns (bool);
}
/// @title GmStudioRankedAuction
/// @notice A ranked auction contract for gmDAO NFTs with allowlist and discount functionalities.
contract GmStudioRankedAuction is
ERC721EnumerableUpgradeable,
OwnableUpgradeable,
IERC2981,
ReentrancyGuard
{
// Mapping of bid IDs to BidNode structs representing the bids.
mapping(uint32 => BidNode) public bidNodes;
// Tracks whether an address has claimed their allowlist mint.
mapping(address => bool) private _addressToAllowlistClaimed;
// Bitmap to track used gmDAO tokens for discounts (supports up to 1024 tokens).
uint256[4] private _gmDaoDiscountFlags;
// Ether amount available for withdrawal by the owner.
uint256 private _withdrawable;
// The final clearing price after the auction ends.
uint96 private finalClearingPrice;
// Timestamp when the auction ends.
uint56 public auctionEndTimeStamp;
// ID of the lowest winning bid (tail of the winning bids linked list).
uint32 private winningTail;
// Counter for generating unique bid IDs.
uint32 public bidCount;
// Number of winning bids in the auction.
uint32 private numberOfWinningBids;
// Number of winning bids that claimed an NFT
uint32 private numberOfClaimedWinningBids;
// Amount minted before auction
uint32 private mintedBeforeAuction;
// Bool for public mint
bool private allowPublic;
// Mapping from token ID to seed
mapping(uint256 => bytes32) private _tokenSeeds;
/// @notice Struct representing the project configuration and parameters.
struct Project {
string name; // Name of the project/token
string symbol; // symbol of the project/token
string tokenBase; // Base URI for token metadata
bytes32 merkleRoot; // Merkle root for the allowlist (used for allowlist minting)
address gmV3Contract; // Address of the gmV3Contract (for gmDAO tokens)
uint96 royalty; // Royalty percentage (in basis points, out of 10000)
address payable ownerAddress; // Address of the contract owner
uint96 gmDiscount; // Discount percentage for gmDAO token holders (in basis points, out of 10000)
address payable royaltyAddress; // Address to receive royalty payments
uint96 minBid; // Minimum bid amount (in wei)
address payable artistAddress; // Address of the artist
uint96 allowListPrice; // Price for allowlist minting (in wei)
address payable gmDaoAddress; // gmDAO address
uint56 auctionStartTimeStamp; // Auction start time (UNIX timestamp in seconds)
uint32 maxSupply; // Maximum number of tokens to mint
address delegateRegistry; // Address of delegate registry
uint56 allowListStartTimeStamp; // Allowlist minting start time (UNIX timestamp in seconds)
uint32 auctionDuration; // Duration of the auction (in seconds)
uint32 auctionExtension; // Time added when a bid is placed near the end (in seconds)
uint32 auctionExtenderTimeFrame; // Timeframe near the end during which bids extend the auction (in seconds)
uint32 maxAuctionExtension; // Maximum total time the auction can be extended (in seconds)
uint24 gmDaoShare; // Share of proceeds for gmDAO (in basis points, out of 10000)
bool needsSeed; // Whether to generate seeds for tokens
}
/**
* @notice Struct representing a bid in the auction.
* @dev Contains bidder address and packed data for:
* - 96 bits: amount
* - 32 bits: next
* - 32 bits: prev
* - bit 0: isWinning
* - bit 1: isClaimed
* (Total = 96+32+32+2 bits used, fits in 256 bits).
*/
struct BidNode {
address bidder; // 20 bytes
uint256 data; // Packed data for amount, next, prev, flags
}
// Instance of the project configuration.
Project private project;
// Event emitted when a bid is submitted.
event BidSubmitted(
address indexed bidder,
uint32 bidId,
uint256 amount,
uint256 timestamp
);
// Event emitted when a bid is updated.
event BidUpdated(
address indexed bidder,
uint32 bidId,
uint256 newAmount,
uint256 timestamp
);
// Event emitted when the auction is extended.
event AuctionExtended(uint256 newEndTime);
/**
* @notice Initializes the project with the provided project data.
* @dev This function initializes the ERC721 and Ownable contracts, sets up the project data, and calculates the auction end timestamp.
* @param _p The project data struct containing all configuration parameters.
*/
function initProject(Project calldata _p) public initializer {
// Initialize the ERC721 contract with the project name and symbol.
__ERC721_init(_p.name, _p.symbol);
// Initialize the Ownable contract with the owner's address.
__Ownable_init(_p.ownerAddress);
// Store the project data.
project = _p;
// Calculate the auction end timestamp based on the start time and duration.
auctionEndTimeStamp =
project.auctionStartTimeStamp +
project.auctionDuration;
}
/**
* @notice Mint tokens to a specified address (owner only).
* @dev Allows the owner to mint a specified number of tokens to a given address, subject to certain conditions.
* @param count The number of tokens to mint.
* @param a The address to receive the minted tokens.
*/
function ownerMint(uint24 count, address a) external onlyOwner {
// If the auction is currently in progress, the owner cannot mint.
if (
block.timestamp >= project.auctionStartTimeStamp &&
block.timestamp <= auctionEndTimeStamp
) {
revert("Auction in progress");
}
// If the auction has ended but not yet finalized, finalize it.
if (block.timestamp > auctionEndTimeStamp && finalClearingPrice == 0) {
_finalizeAuction();
}
uint256 totalSupply = _owners.length;
uint32 unclaimedWinningBids = 0;
// If the auction has been finalized, calculate unclaimed winning bids.
if (finalClearingPrice != 0) {
unclaimedWinningBids =
numberOfWinningBids -
numberOfClaimedWinningBids;
}
// Calculate the number of tokens available for the owner to mint.
uint32 availableForOwner = project.maxSupply -
uint32(totalSupply) -
unclaimedWinningBids;
// Ensure the owner does not mint more tokens than allowed.
require(count <= availableForOwner, "Too many");
// Mint the specified number of tokens to the address 'a'.
for (uint256 i; i < count; ) {
unchecked {
uint256 tokenId = totalSupply + i;
_mint(a, tokenId);
i++;
}
}
}
/**
* @notice Mint a token to an allowlisted address if conditions are met.
* @dev Mints a token to the specified address 'a' if they are on the allowlist and haven't already claimed.
* @param proof The Merkle proof verifying the address is on the allowlist.
* @param a The address to mint the token to.
*/
function allowListMint(
bytes32[] calldata proof,
address a
) external payable {
// Ensure the allowlist minting has started.
require(
block.timestamp >= project.allowListStartTimeStamp,
"AL not started"
);
// Ensure the allowlist minting has not ended.
require(block.timestamp < project.auctionStartTimeStamp, "AL ended");
// Verify that the address 'a' is on the allowlist using the Merkle proof.
require(
MerkleProof.verify(
proof,
project.merkleRoot,
keccak256(abi.encodePacked(a))
),
"Not on AL"
);
// Ensure the address hasn't already claimed their allowlist mint.
require(_addressToAllowlistClaimed[a] == false, "Claimed");
uint256 totalSupply = _owners.length;
// Ensure the total supply doesn't exceed the maximum supply.
require(totalSupply + 1 <= project.maxSupply, "Minted out");
// Ensure the correct amount of Ether is provided.
require(project.allowListPrice <= msg.value, "Invalid funds");
// Prevent contracts from minting.
require(msg.sender == tx.origin, "No contracts");
unchecked {
uint256 tokenId = totalSupply;
// Mark the address as having claimed their allowlist mint.
_addressToAllowlistClaimed[a] = true;
// Add the funds to the withdrawable balance.
_withdrawable += msg.value;
// Mint the token to address 'a'.
_mint(a, tokenId);
}
}
function publicMint(uint24 count, address a) external payable {
require(block.timestamp > auctionEndTimeStamp, "Auction ongoing");
require(allowPublic, "Public not allowed");
require(count > 0, "Must mint at least one");
require(msg.sender == tx.origin, "No contracts");
if (finalClearingPrice == 0) {
_finalizeAuction();
}
uint256 totalSupply = _owners.length;
// Calculate the number of unclaimed winning bids.
uint32 unclaimedWinningBids = numberOfWinningBids -
numberOfClaimedWinningBids;
// Calculate the number of tokens available for public minting.
uint32 availableForPublic = project.maxSupply -
uint32(totalSupply) -
unclaimedWinningBids;
// Ensure the public does not mint more tokens than allowed.
require(count <= availableForPublic, "Too many");
// Ensure the correct amount of Ether is provided.
uint256 totalPrice = count * project.minBid;
require(msg.value >= totalPrice, "Insufficient funds");
// Mint the specified number of tokens to the address 'a'.
for (uint256 i; i < count; ) {
unchecked {
uint256 tokenId = totalSupply + i;
_mint(a, tokenId);
i++;
}
}
// Add funds to withdrawable balance
_withdrawable += totalPrice;
}
/**
* @notice Places a new bid into the auction.
* @dev Users can place multiple bids. The bid is inserted into the ordered linked list of bids.
* @param estimatedNodePositionId The estimated position in the linked list for optimization.
*/
function placeBid(
uint32 estimatedNodePositionId
) external payable nonReentrant {
// Ensure the auction has started.
require(
block.timestamp >= project.auctionStartTimeStamp,
"Not started"
);
// Ensure the estimated node position is valid.
require(estimatedNodePositionId <= bidCount, "Bad estimate");
// Ensure the auction has not ended.
require(block.timestamp <= auctionEndTimeStamp, "Auction ended");
// Ensure the bid amount meets the minimum bid requirement.
require(msg.value >= project.minBid, "Bid too low");
// Prevent contracts from placing bids.
require(msg.sender == tx.origin, "No contracts");
// Get the cutoff bid amount required to be a winning bid.
uint96 cutoffAmount = getCutoffBidAmount();
// Calculate the maximum number of winning bids.
uint256 maxWinners = project.maxSupply - _owners.length;
if (bidCount >= maxWinners) {
// If the list of bids is full, the new bid must be strictly greater than the cutoff amount.
require(msg.value > cutoffAmount, "Bid too low");
} else {
// If the list is not full, the bid must be at least the cutoff amount (minimum bid).
require(msg.value >= cutoffAmount, "Bid too low");
}
// Generate a new bid ID.
uint32 newBidId = ++bidCount;
// Insert the new bid into the ordered linked list.
_insertNode(
estimatedNodePositionId,
newBidId,
uint96(msg.value),
msg.sender
);
// If the number of bids exceeds the maximum number of winners, adjust the winning tail.
if (bidCount > maxWinners) {
_adjustWinningTail();
}
// Extend the auction if the bid was placed near the end.
_extendAuctionIfNeeded();
// Emit an event for the new bid.
emit BidSubmitted(msg.sender, newBidId, msg.value, block.timestamp);
}
/**
* @notice Inserts a bid node into the ordered linked list of bids.
* @dev The list is ordered by bid amount in descending order.
* @param estimatedNodeId The estimated node position for optimization.
* @param newNodeId The ID of the new bid node.
* @param bid The amount of the bid.
* @param bidder The address of the bidder.
*/
function _insertNode(
uint32 estimatedNodeId,
uint32 newNodeId,
uint96 bid,
address bidder
) internal {
// isNewNode = true when first creating the node;
// but we reuse the same storage slot if the node already existed
// (though that generally doesn't happen for a brand new bidId).
bool isNewNode = (bidder != address(0));
// Data packing structure (256 bits):
// bits [160..255]: bid amount (96 bits)
// bits [72..103]: next (32 bits)
// bits [40..71]: prev (32 bits)
// bit 0: isWinning
// bit 1: isClaimed
// The rest bits [2..39] remain unused.
uint256 newNodeData = (uint256(bid) << 160) |
(uint256(0) << 72) | // next
(uint256(0) << 40) | // prev
uint256(1); // isWinning=1, isClaimed=0
if (winningTail == 0) {
// Initialize the list with the new node
winningTail = newNodeId;
bidNodes[newNodeId] = BidNode({bidder: bidder, data: newNodeData});
return;
}
uint32 currentId = (estimatedNodeId != 0 && estimatedNodeId <= bidCount)
? estimatedNodeId
: winningTail;
uint96 currentAmount = uint96(bidNodes[currentId].data >> 160);
// Traverse the list to find the correct position for the new bid
if (bid > currentAmount) {
// Traverse backward to find the insertion point
bool isHead = false;
while (
currentId != 0 &&
(uint96(bidNodes[currentId].data >> 160) < bid)
) {
uint32 prevId = uint32(bidNodes[currentId].data >> 40);
if (prevId == 0) {
isHead = true;
break;
}
currentId = prevId;
}
if (isHead) {
// Inserting at the head of the list
uint32 headId = currentId;
// newNode.next = headId
newNodeData |= uint256(headId) << 72;
// newNode.prev = 0
newNodeData |= uint256(0) << 40;
// Update the previous head's prev pointer to point to the new node
uint256 headData = bidNodes[headId].data;
headData =
(headData & ~((uint256(0xFFFFFFFF) << 40))) |
(uint256(newNodeId) << 40); // head.prev = newNodeId
bidNodes[headId].data = headData;
} else {
// Inserting between currentId and its next node
uint32 nextId = uint32(bidNodes[currentId].data >> 72);
// Set new node's prev and next pointers
newNodeData |= uint256(nextId) << 72; // newNode.next
newNodeData |= uint256(currentId) << 40; // newNode.prev
// Update currentId's next pointer to newNodeId
uint256 currentNodeData = bidNodes[currentId].data;
currentNodeData =
(currentNodeData & ~((uint256(0xFFFFFFFF) << 72))) |
(uint256(newNodeId) << 72);
bidNodes[currentId].data = currentNodeData;
// Update next node's prev pointer to newNodeId if nextId != 0
if (nextId != 0) {
uint256 nextNodeData = bidNodes[nextId].data;
nextNodeData =
(nextNodeData & ~((uint256(0xFFFFFFFF) << 40))) |
(uint256(newNodeId) << 40);
bidNodes[nextId].data = nextNodeData;
} else {
// If nextId is zero, update the winningTail to the new node
winningTail = newNodeId;
}
}
} else {
// Traverse forward to find the insertion point
bool isWinningTail = false;
while (
currentId != 0 &&
(uint96(bidNodes[currentId].data >> 160) >= bid)
) {
if (currentId == winningTail) {
isWinningTail = true;
break;
}
uint32 nextId = uint32(bidNodes[currentId].data >> 72);
currentId = nextId;
}
if (isWinningTail) {
// Inserting at the tail of the list
uint32 oldTail = winningTail;
winningTail = newNodeId;
// newNode.next = 0
newNodeData |= uint256(0) << 72;
// newNode.prev = oldTail
newNodeData |= uint256(oldTail) << 40;
uint256 oldTailData = bidNodes[oldTail].data;
// Update the old tail's next pointer to point to the new node
oldTailData =
(oldTailData & ~((uint256(0xFFFFFFFF) << 72))) |
(uint256(newNodeId) << 72);
// If the max number of winners is reached, clear the isWinning flag
if (bidCount >= (project.maxSupply - uint32(_owners.length))) {
oldTailData &= ~uint256(1); // Clear isWinning flag
}
bidNodes[oldTail].data = oldTailData;
} else {
// Inserting between two nodes
uint32 prevId = uint32(bidNodes[currentId].data >> 40);
// newNode.next = currentId
newNodeData |= uint256(currentId) << 72;
// newNode.prev = prevId
newNodeData |= uint256(prevId) << 40;
// Update current node's prev pointer to new node
uint256 currentNodeData = bidNodes[currentId].data;
currentNodeData =
(currentNodeData & ~((uint256(0xFFFFFFFF) << 40))) |
(uint256(newNodeId) << 40);
bidNodes[currentId].data = currentNodeData;
// Update previous node's next pointer to new node if prevId != 0
if (prevId != 0) {
uint256 prevNodeData = bidNodes[prevId].data;
prevNodeData =
(prevNodeData & ~((uint256(0xFFFFFFFF) << 72))) |
(uint256(newNodeId) << 72);
bidNodes[prevId].data = prevNodeData;
}
}
}
// Insert the new node into the mapping
if (isNewNode) {
bidNodes[newNodeId] = BidNode({bidder: bidder, data: newNodeData});
} else {
bidNodes[newNodeId].data = newNodeData;
}
}
/**
* @notice Updates an existing bid by increasing the bid amount.
* @dev Users can only increase their bids. The bid is re-inserted into the ordered linked list if necessary.
* @param bidId The ID of the bid to update.
* @param estimatedNodePositionId The estimated node ID for reordering.
*/
function updateBid(
uint32 bidId,
uint32 estimatedNodePositionId
) external payable nonReentrant {
// Ensure the auction has started.
require(
block.timestamp >= project.auctionStartTimeStamp,
"Not started"
);
// Ensure the estimated node position is valid.
require(estimatedNodePositionId <= bidCount, "Bad estimate");
// Ensure the auction has not ended.
require(block.timestamp <= auctionEndTimeStamp, "Auction ended");
// Ensure the caller is increasing the bid amount.
require(msg.value > 0, "No ETH sent");
// Prevent contracts from updating bids.
require(msg.sender == tx.origin, "No contracts");
BidNode storage node = bidNodes[bidId];
require(node.bidder == msg.sender, "Not your bid");
// Decode the current data
uint256 nodeData = node.data;
uint96 currentAmount = uint96(nodeData >> 160);
uint96 newAmount = currentAmount + uint96(msg.value);
// Compute the cutoff amount and max winners
uint32 maxWinners = project.maxSupply - uint32(_owners.length);
uint96 cutoffAmount = getCutoffBidAmount();
// Check if the updated bid meets the required conditions
if (bidCount >= maxWinners) {
require(newAmount > cutoffAmount, "Bid too low");
} else {
require(newAmount >= project.minBid, "Bid too low");
}
bool wasWinning = (nodeData & uint256(1)) != 0;
// Update the bid amount (preserve 'isWinning' + 'isClaimed' bits)
// bit[0]: isWinning, bit[1]: isClaimed
// We only want to replace the amount bits [160..255].
// So we mask out the old amount, then set the new amount:
uint256 flagsMask = nodeData &
0x000000FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
// This keeps bits [0..159] intact, which includes isWinning, isClaimed, prev, next
// Then we put newAmount in bits [160..255].
node.data = flagsMask | (uint256(newAmount) << 160);
// If previously not winning or we updated the tail, re-check tail
if (bidId == winningTail || !wasWinning) {
_adjustWinningTail();
}
// Adjust the position of the node in the linked list if necessary
_adjustNodePosition(bidId, newAmount, estimatedNodePositionId);
// Extend auction if needed
_extendAuctionIfNeeded();
emit BidUpdated(msg.sender, bidId, newAmount, block.timestamp);
}
/**
* @notice Adjusts the position of a bid node after updating its amount.
* @dev Detaches the node and re-inserts it into the correct position in the ordered linked list.
* @param bidId The ID of the bid node to adjust.
* @param newAmount The new bid amount.
* @param estimatedNodePositionId The estimated node position for optimization.
*/
function _adjustNodePosition(
uint32 bidId,
uint96 newAmount,
uint32 estimatedNodePositionId
) internal {
_detachNode(bidId);
_insertNode(estimatedNodePositionId, bidId, newAmount, address(0));
}
/**
* @notice Detaches a bid node from the linked list.
* @dev Updates the previous and next nodes to bypass the detached node.
* @param bidId The ID of the bid node to detach.
*/
function _detachNode(uint32 bidId) internal {
uint256 nodeData = bidNodes[bidId].data;
uint32 prevId = uint32(nodeData >> 40);
uint32 nextId = uint32(nodeData >> 72);
// Update previous node's next pointer
if (prevId != 0) {
uint256 prevData = bidNodes[prevId].data;
bidNodes[prevId].data =
(prevData & ~(uint256(0xFFFFFFFF) << 72)) |
(uint256(nextId) << 72);
}
// Update next node's prev pointer
if (nextId != 0) {
uint256 nextData = bidNodes[nextId].data;
bidNodes[nextId].data =
(nextData & ~(uint256(0xFFFFFFFF) << 40)) |
(uint256(prevId) << 40);
}
}
/**
* @notice Adjusts the winning tail of the linked list when necessary.
* @dev Updates the 'isWinning' flag of the old winning tail and moves the winning tail to the previous node.
*/
function _adjustWinningTail() internal {
if (winningTail == 0) return;
// Clear the `isWinning` flag for the old winningTail
uint256 oldTailData = bidNodes[winningTail].data;
// bit[0] = isWinning -> set to 0
bidNodes[winningTail].data = oldTailData & ~uint256(1);
// Update the winningTail to the previous node
winningTail = uint32(bidNodes[winningTail].data >> 40); // Get `prev`
}
/**
* @notice Returns the estimated node ID for a given bid amount.
* @dev Navigates the linked list to find the appropriate position for the bid.
* @param bid The amount of the bid for which to find the estimated position.
* @return The estimated node ID.
*/
function getEstimatedNodeId(uint96 bid) external view returns (uint32) {
uint32 currentId = winningTail;
if (currentId == 0) return 0;
uint96 currentAmount = uint96(bidNodes[currentId].data >> 160);
if (bid > currentAmount) {
while (
currentId != 0 &&
(uint96(bidNodes[currentId].data >> 160) < bid)
) {
uint32 prevId = uint32(bidNodes[currentId].data >> 40);
if (prevId == 0) {
break;
}
currentId = prevId;
}
return currentId;
} else {
return winningTail;
}
}
/**
* @notice Returns the cutoff bid amount required to be a winning bid.
* @dev Determines the bid amount of the `winningTail` or the minimum bid if the auction is undersubscribed.
* @return cutoffAmount The minimum amount required to be a winning bid.
*/
function getCutoffBidAmount() public view returns (uint96 cutoffAmount) {
uint32 maxWinners = project.maxSupply - uint32(_owners.length);
if (bidCount >= maxWinners && winningTail != 0) {
// If there are enough bids to fill all available tokens, return the `winningTail` amount
uint256 tailData = bidNodes[winningTail].data;
return uint96(tailData >> 160);
} else {
// If there are fewer bids than tokens, any bid can win
return project.minBid;
}
}
/**
* @notice Internal function to extend the auction if a bid is placed near the end.
* @dev Extends the auction end time by 'auctionExtension' if within 'auctionExtenderTimeFrame', up to 'maxAuctionExtension'.
*/
function _extendAuctionIfNeeded() internal {
uint256 timeRemaining = auctionEndTimeStamp > block.timestamp
? auctionEndTimeStamp - block.timestamp
: 0;
if (timeRemaining < project.auctionExtenderTimeFrame) {
uint56 totalExtendedTime = auctionEndTimeStamp -
(project.auctionStartTimeStamp + project.auctionDuration);
if (totalExtendedTime < project.maxAuctionExtension) {
uint56 extensionTime = project.auctionExtension;
// Adjust extension time if it exceeds maxAuctionExtension
if (
totalExtendedTime + extensionTime >
project.maxAuctionExtension
) {
extensionTime =
project.maxAuctionExtension -
totalExtendedTime;
}
auctionEndTimeStamp += extensionTime;
emit AuctionExtended(auctionEndTimeStamp);
}
}
}
/**
* @notice Allows users to claim their NFTs and refunds after the auction ends.
* Now it sets `isClaimed` = 1 instead of deleting the bid node.
* @param bidIds The array of bid IDs to claim.
* @param gmDaoTokenIds The array of gmDAO token IDs for discount eligibility.
* @param a The address to receive the NFTs and refunds.
*/
function claim(
uint32[] calldata bidIds,
uint256[] calldata gmDaoTokenIds,
address a
) external nonReentrant {
require(block.timestamp > auctionEndTimeStamp, "Auction not ended");
require(bidIds.length > 0, "No bids");
if (finalClearingPrice == 0) {
_finalizeAuction();
}
uint256 totalRefund = 0;
uint256 gmTokenIndex = 0; // Tracks which gmDAO token to use for discounts
for (uint256 i = 0; i < bidIds.length; i++) {
uint32 bidId = bidIds[i];
BidNode storage node = bidNodes[bidId];
require(node.bidder == msg.sender, "Not your bid");
uint256 nodeData = node.data;
bool isWinning = ((nodeData & uint256(1)) != 0);
bool isAlreadyClaimed = ((nodeData & uint256(2)) != 0); // bit[1] = isClaimed
require(!isAlreadyClaimed, "Already claimed");
uint256 bidAmount = uint96(nodeData >> 160);
uint256 discount = 0;
if (isWinning) {
// Winning bid: apply discount logic
if (gmTokenIndex < gmDaoTokenIds.length) {
uint256 gmDaoTokenId = gmDaoTokenIds[gmTokenIndex];
address gmTokenOwner = ERC721Upgradeable(
project.gmV3Contract
).ownerOf(gmDaoTokenId);
// Check ownership or delegation
if (
gmTokenOwner == msg.sender || // Direct ownership
IDelegateRegistry(project.delegateRegistry)
.checkDelegateForERC721(
msg.sender,
gmTokenOwner,
address(project.gmV3Contract),
gmDaoTokenId,
""
)
) {
require(
!_isDiscountUsed(gmDaoTokenId),
"Discount used"
);
_setDiscountUsed(gmDaoTokenId); // Mark discount as used
discount =
(finalClearingPrice * project.gmDiscount) /
10000;
gmTokenIndex++;
}
}
uint256 effectivePrice = finalClearingPrice - discount;
uint256 refundAmount = bidAmount > effectivePrice
? bidAmount - effectivePrice
: 0;
// Add unused discount portion back to withdrawable if discount was not used
if (discount == 0) {
_withdrawable +=
(finalClearingPrice * project.gmDiscount) /
10000;
}
// Mint the NFT to address 'a'.
_mint(a, _owners.length);
totalRefund += refundAmount;
numberOfClaimedWinningBids += 1;
} else {
// Losing bid: full refund
totalRefund += bidAmount;
}
// Set isClaimed = 1 (bit[1])
// preserve the rest of nodeData, just set bit 1:
node.data = nodeData | uint256(2); // set bit[1]
// Instead of deleting the node, we keep it with isClaimed = true
}
// Transfer any refunds to the address 'a'.
if (totalRefund > 0) {
_safeTransferEther(payable(a), totalRefund);
}
}
/**
* @notice Finalizes the auction by determining the final clearing price and the number of winning bids.
* @dev Calculates the final clearing price based on the bids and marks the auction as finalized.
*/
function _finalizeAuction() internal {
mintedBeforeAuction = uint32(_owners.length);
uint32 maxAvailableTokens = uint32(
project.maxSupply - mintedBeforeAuction
);
if (bidCount >= maxAvailableTokens) {
numberOfWinningBids = maxAvailableTokens;
finalClearingPrice = uint96(bidNodes[winningTail].data >> 160);
} else {
numberOfWinningBids = uint32(bidCount);
finalClearingPrice = project.minBid;
}
// Calculate instant withdrawable amount
uint256 totalProceeds = numberOfWinningBids *
uint256(finalClearingPrice);
uint256 instantWithdrawable = (totalProceeds *
(10000 - project.gmDiscount)) / 10000;
// Reserve the discount portion
_withdrawable += instantWithdrawable; // Add to withdrawable funds
}
/**
* @notice Checks if a gmDAO token has been used for a discount.
* @param tokenId The gmDAO token ID to check.
* @return True if the token has been used, false otherwise.
*/
function _isDiscountUsed(uint256 tokenId) internal view returns (bool) {
uint256 index = tokenId / 256; // Determine which uint256 to use
uint256 bit = 1 << (tokenId % 256); // Determine the specific bit within the uint256
return (_gmDaoDiscountFlags[index] & bit) != 0;
}
/**
* @notice Marks a gmDAO token as used for a discount.
* @param tokenId The gmDAO token ID to mark.
*/
function _setDiscountUsed(uint256 tokenId) internal {
uint256 index = tokenId / 256;
uint256 bit = 1 << (tokenId % 256);
_gmDaoDiscountFlags[index] |= bit;
}
/**
* @notice Public function returning an array of booleans indicating whether each gmDAO token’s discount was used.
* @param gmDaoTokenIds The array of gmDAO token IDs to check.
* @return A boolean array parallel to gmDaoTokenIds where `true` means discount was used.
*/
function areDiscountsUsed(
uint256[] calldata gmDaoTokenIds
) external view returns (bool[] memory) {
bool[] memory used = new bool[](gmDaoTokenIds.length);
for (uint256 i = 0; i < gmDaoTokenIds.length; i++) {
used[i] = _isDiscountUsed(gmDaoTokenIds[i]);
}
return used;
}
/**
* @notice Public function that returns an array of BidNode data starting from `startId` of length `count`.
* @dev If you pass (0, 5), you'll get bidNodes[0..4].
* Watch out for existence: if a node was never created or is out of range, it might just contain default values.
* @param startId The starting bid ID
* @param count How many nodes to fetch
*/
function getBidNodes(
uint32 startId,
uint32 count
) external view returns (BidNode[] memory) {
BidNode[] memory result = new BidNode[](count);
for (uint32 i = 0; i < count; i++) {
uint32 bidId = startId + i;
result[i] = bidNodes[bidId];
}
return result;
}
/**
* @notice Internal function to safely transfer Ether.
* @param to The recipient address.
* @param amount The amount of Ether to transfer.
*/
function _safeTransferEther(address payable to, uint256 amount) internal {
(bool sent, ) = to.call{value: amount}("");
require(sent, "Ether transfer failed");
}
/**
* @notice Returns a list of token IDs owned by the specified address.
* @param _owner The address to query.
* @return An array of token IDs owned by the address.
*/
function walletOfOwner(
address _owner
) public view returns (uint256[] memory) {
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) return new uint256[](0);
uint256[] memory tokensId = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokensId[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokensId;
}
/**
* @notice Returns the royalty information for a given token ID and sale price.
* @dev This function is required by the ERC2981 standard.
* @param _salePrice The sale price of the token.
* @return receiver The address to receive the royalties.
* @return royaltyAmount The amount of royalties owed.
*/
function royaltyInfo(
uint256,
uint256 _salePrice
) external view override returns (address receiver, uint256 royaltyAmount) {
receiver = project.royaltyAddress;
royaltyAmount = (_salePrice * project.royalty) / 10000;
}
/**
* @notice Returns the metadata of the token with the given ID.
* @dev It returns a JSON object which conforms to the ERC721 metadata standard.
* @param _tokenId The ID of the token to retrieve metadata for.
* @return A JSON object that contains the metadata of the given token.
*/
function tokenURI(
uint256 _tokenId
) public view override returns (string memory) {
require(_exists(_tokenId), "Token not found");
return string.concat(project.tokenBase, Strings.toString(_tokenId));
}
/**
* @notice Returns the maximum supply of tokens.
* @return The maximum supply of tokens.
*/
function maxSupply() public view returns (uint32) {
return project.maxSupply;
}
/**
* @notice Allows the owner to set the metadata base URL for the project.
* @dev Only callable by the owner.
* @param _tokenBase String representing the base URL for tokens.
*/
function setTokenBase(string calldata _tokenBase) public onlyOwner {
project.tokenBase = _tokenBase;
}
/**
* @notice Sets the address to receive royalties.
* @param _royaltyAddress The new royalty recipient address.
*/
function setRoyaltyAddress(
address payable _royaltyAddress
) public onlyOwner {
require(_royaltyAddress != address(0), "Invalid address");
project.royaltyAddress = _royaltyAddress;
}
/**
* @notice Sets the royalty percentage.
* @param _royalty The new royalty percentage (out of 10000).
*/
function setRoyalty(uint96 _royalty) public onlyOwner {
require(_royalty <= 10000, "Royalty percentage too high");
project.royalty = _royalty;
}
/**
* @notice Allows the owner to set the Merkle root for the allowlist.
* @dev Only callable by the owner.
* @param _merkleRoot The new Merkle root.
*/
function setMerkleRoot(bytes32 _merkleRoot) external onlyOwner {
project.merkleRoot = _merkleRoot;
}
/**
* @notice Allows the owner to set the gmDAO token holder discount percentage.
* @dev Only callable by the owner and not after the auction has started.
* The discount cannot exceed 10000 (100%).
* @param _gmDiscount The new discount percentage (in basis points out of 10000).
*/
function setGmDiscount(uint96 _gmDiscount) external onlyOwner {
require(_gmDiscount <= 10000, "Discount percentage too high");
// Disallow after auction start
require(
block.timestamp < project.auctionStartTimeStamp,
"Cannot set discount after auction starts"
);
project.gmDiscount = _gmDiscount;
}
/**
* @notice Allows the owner to set the minimum bid amount.
* @dev Only callable by the owner before we have enough winning bids.
* @param _minBid The new minimum bid amount (in wei).
*/
function setMinBid(uint96 _minBid) external onlyOwner {
// If we already have enough winning bids, disallow change.
uint32 maxWinners = project.maxSupply - uint32(_owners.length);
require(bidCount < maxWinners, "Enough winning bids exist");
project.minBid = _minBid;
}
/**
* @notice Allows the owner to set the allowlist minting price.
* @dev Only callable by the owner before the allowlist minting starts.
* @param _allowListPrice The new price for allowlist minting (in wei).
*/
function setALPrice(uint96 _allowListPrice) external onlyOwner {
require(
block.timestamp < project.allowListStartTimeStamp,
"Allowlist mint already started"
);
project.allowListPrice = _allowListPrice;
}
/**
* @notice Allows the owner to set the auction start timestamp.
* @dev Only callable by the owner if the auction hasn't started yet.
* @param _auctionStartTimeStamp The new auction start timestamp (UNIX time in seconds).
*/
function setAuctionStart(uint56 _auctionStartTimeStamp) external onlyOwner {
require(
block.timestamp < project.auctionStartTimeStamp,
"Auction already started"
);
require(
_auctionStartTimeStamp >= project.allowListStartTimeStamp,
"Start cannot be before AL"
);
project.auctionStartTimeStamp = _auctionStartTimeStamp;
// Recalculate the auction end timestamp
auctionEndTimeStamp =
project.auctionStartTimeStamp +
project.auctionDuration;
}
/**
* @notice Allows the owner to increase the auction duration.
* @dev Only callable by the owner before the auction starts. Can only increase the auctionDuration.
* @param _auctionDuration The new auction duration in seconds.
*/
function setAuctionDuration(uint32 _auctionDuration) external onlyOwner {
require(
block.timestamp < project.auctionStartTimeStamp,
"Auction already started"
);
require(
_auctionDuration > project.auctionDuration,
"Must increase duration"
);
project.auctionDuration = _auctionDuration;
// Recalculate the auction end timestamp
auctionEndTimeStamp =
project.auctionStartTimeStamp +
project.auctionDuration;
}
/**
* @notice Allows the owner to set the allowlist minting start timestamp.
* @dev Only callable by the owner if the allowlist minting hasn't started yet. Must be before the auction start time.
* @param _allowListStartTimeStamp The new allowlist minting start timestamp (UNIX time in seconds).
*/
function setALStart(uint56 _allowListStartTimeStamp) external onlyOwner {
require(
block.timestamp < project.allowListStartTimeStamp,
"AL mint started"
);
require(
_allowListStartTimeStamp <= project.auctionStartTimeStamp,
"AL after auction"
);
project.allowListStartTimeStamp = _allowListStartTimeStamp;
}
/**
* @notice Allows the owner to decrease the maximum supply of tokens.
* @dev Only callable by the owner. Can only decrease the maxSupply, and cannot set it lower than the current total supply + unclaimed winning bids.
* @param _maxSupply The new maximum supply of tokens.
*/
function setMaxSupply(uint32 _maxSupply) external onlyOwner {
require(_maxSupply < project.maxSupply, "Only decrease");
uint256 totalSupply = _owners.length;
// Check the current auction status
if (block.timestamp < project.auctionStartTimeStamp) {
// Before auction starts
require(_maxSupply >= uint32(totalSupply), "maxSupply too low");
} else if (
block.timestamp >= project.auctionStartTimeStamp &&
block.timestamp <= auctionEndTimeStamp
) {
// During the auction
revert("Cannot change maxSupply during the auction");
} else {
// After auction ends
if (finalClearingPrice == 0) {
// Auction not finalized, finalize it
_finalizeAuction();
}
// After finalization, calculate unclaimed winning bids
uint32 unclaimedWinningBids = numberOfWinningBids -
numberOfClaimedWinningBids;
uint32 minimumMaxSupply = uint32(totalSupply) +
unclaimedWinningBids;
require(_maxSupply >= minimumMaxSupply, "maxSupply too low");
}
project.maxSupply = _maxSupply;
}
/**
* @notice Allows the owner to set whether public mint should be open.
* @dev Only callable by the owner.
* @param _allowPublic Public open or closed.
*/
function setAllowPublic(bool _allowPublic) external onlyOwner {
allowPublic = _allowPublic;
}
/**
* @notice Allows the contract owner to withdraw accumulated Ether.
* @dev Can withdraw allowlist funds at any time and auction funds after the auction ends.
* Ensures funds cannot be withdrawn more than once.
*/
function withdraw() external onlyOwner nonReentrant {
// Finalize the auction if it's ended but not yet finalized
if (block.timestamp > auctionEndTimeStamp && finalClearingPrice == 0) {
_finalizeAuction();
}
uint256 amountToWithdraw = _withdrawable;
require(amountToWithdraw > 0, "No funds");
// Reset withdrawable amount to prevent re-entrancy
_withdrawable = 0;
// Calculate gmDAO's share (in basis points out of 10000)
uint256 gmDaoAmount = (amountToWithdraw * project.gmDaoShare) / 10000;
// Calculate artist's share as the remaining amount
uint256 artistAmount = amountToWithdraw - gmDaoAmount;
// Transfer gmDAO's share to the gmDAO address
if (gmDaoAmount > 0) {
_safeTransferEther(project.gmDaoAddress, gmDaoAmount);
}
// Transfer the artist's share to the artist's address
if (artistAmount > 0) {
_safeTransferEther(project.artistAddress, artistAmount);
}
}
/**
* @notice Modifier to check if a token exists.
* @param tokenId The token ID to check.
*/
modifier tokenExists(uint256 tokenId) {
require(_exists(tokenId), "Token does not exist");
_;
}
/**
* @notice Creates a seed for a token based on various blockchain parameters.
* @param tokenId The ID of the token.
* @param receiver The address of the receiver.
* @return The generated seed.
*/
function _createSeed(
uint256 tokenId,
address receiver
) private view returns (bytes32) {
unchecked {
return
keccak256(
abi.encodePacked(
tokenId,
receiver,
blockhash(block.number - 1),
blockhash(block.number - 2),
blockhash(block.number - 4),
block.prevrandao,
block.coinbase
)
);
}
}
...
// [truncated — 51944 bytes total]
Address.sol 12 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
}
ERC721C.sol 140 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@limitbreak/creator-token-standards/src/utils/AutomaticValidatorTransferApproval.sol";
import "@limitbreak/creator-token-standards/src/utils/CreatorTokenBase.sol";
import "./ERC721Upgradeable.sol";
import "@limitbreak/creator-token-standards/src/interfaces/ITransferValidatorSetTokenType.sol";
import {TOKEN_TYPE_ERC721} from "@limitbreak/permit-c/src/Constants.sol";
/**
* @title ERC721C
* @author Limit Break, Inc.
* @notice Extends OpenZeppelin's ERC721 implementation with Creator Token functionality, which
* allows the contract owner to update the transfer validation logic by managing a security policy in
* an external transfer validation security policy registry. See {CreatorTokenTransferValidator}.
*/
abstract contract ERC721C is
ERC721Upgradeable,
CreatorTokenBase,
AutomaticValidatorTransferApproval
{
/**
* @dev Override _msgData to resolve conflict between base classes.
*/
function _msgData()
internal
view
virtual
override(Context, ContextUpgradeable)
returns (bytes calldata)
{
return super._msgData(); // You can choose either ContextUpgradeable._msgData() or OwnableUpgradeable._msgData().
}
/**
* @dev Override _msgSender to resolve conflict between base classes.
*/
function _msgSender()
internal
view
virtual
override(Context, ContextUpgradeable)
returns (address)
{
return super._msgSender(); // You can choose ContextUpgradeable._msgSender() or OwnableUpgradeable._msgSender().
}
function _contextSuffixLength()
internal
view
virtual
override(ContextUpgradeable, Context)
returns (uint256)
{
return 0;
}
/**
* @notice Overrides behavior of isApprovedFor all such that if an operator is not explicitly approved
* for all, the contract owner can optionally auto-approve the 721-C transfer validator for transfers.
*/
function isApprovedForAll(
address owner,
address operator
) public view virtual override returns (bool isApproved) {
isApproved = super.isApprovedForAll(owner, operator);
if (!isApproved) {
if (autoApproveTransfersFromValidator) {
isApproved = operator == address(getTransferValidator());
}
}
}
/**
* @notice Indicates whether the contract implements the specified interface.
* @dev Overrides supportsInterface in ERC165.
* @param interfaceId The interface id
* @return true if the contract implements the specified interface, false otherwise
*/
function supportsInterface(
bytes4 interfaceId
) public view virtual override returns (bool) {
return
interfaceId == type(ICreatorToken).interfaceId ||
interfaceId == type(ICreatorTokenLegacy).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @notice Returns the function selector for the transfer validator's validation function to be called
* @notice for transaction simulation.
*/
function getTransferValidationFunction()
external
pure
returns (bytes4 functionSignature, bool isViewFunction)
{
functionSignature = bytes4(
keccak256("validateTransfer(address,address,address,uint256)")
);
isViewFunction = true;
}
/// @dev Ties the _beforeTokenTransfer hook to transfer validation logic.
function _beforeTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual override {
super._beforeTokenTransfer(from, to, firstTokenId, batchSize);
for (uint256 i = 0; i < batchSize; ) {
_validateBeforeTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
/// @dev Ties the _afterTokenTransfer hook to transfer validation logic.
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual override {
super._afterTokenTransfer(from, to, firstTokenId, batchSize);
for (uint256 i = 0; i < batchSize; ) {
_validateAfterTransfer(from, to, firstTokenId + i);
unchecked {
++i;
}
}
}
function _tokenType() internal pure override returns (uint16) {
return uint16(TOKEN_TYPE_ERC721);
}
}
ERC721EnumerableUpgradeable.sol 83 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
/* import "./ERC721Upgradeable.sol"; */
import "./ERC721C.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account but rips out the core of the gas-wasting processing that comes from OpenZeppelin.
*/
abstract contract ERC721EnumerableUpgradeable is ERC721C, IERC721Enumerable {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(
bytes4 interfaceId
) public view virtual override(ERC721C, IERC165) returns (bool) {
return
interfaceId == type(IERC721Enumerable).interfaceId || // ERC721 Enumerable
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _owners.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(
uint256 index
) public view virtual override returns (uint256) {
require(
index < totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
uint256 tokenId;
uint256 count = 0;
// Iterate over normal token range
for (tokenId = 0; tokenId < _owners.length; tokenId++) {
if (_exists(tokenId)) {
if (count == index) {
return tokenId;
}
count++;
}
}
revert("ERC721Enumerable: global index out of bounds");
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(
address owner,
uint256 index
) public view virtual override returns (uint256 tokenId) {
require(
index < balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
uint256 count;
for (uint256 i = 0; i < _owners.length; i++) {
if (owner == _owners[i]) {
if (count == index) return i;
// Token ID for normal tokens
else count++;
}
}
revert("ERC721Enumerable: owner index out of bounds");
}
}
ERC721Upgradeable.sol 438 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
import "./Address.sol";
/**
* @dev Implementation of the {IERC721} interface.
* This is an upgradeable version of the ERC721 contract.
*/
abstract contract ERC721Upgradeable is
ContextUpgradeable,
ERC165Upgradeable,
IERC721,
IERC721Metadata
{
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
// Mapping from token ID to owner address
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
* @param name_ The name of the token.
* @param symbol_ The symbol of the token.
*/
function __ERC721_init(
string memory name_,
string memory symbol_
) internal onlyInitializing {
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(
string memory name_,
string memory symbol_
) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(
bytes4 interfaceId
) public view virtual override(ERC165Upgradeable, 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: balance query for the zero address"
);
uint256 count;
for (uint256 i; i < _owners.length; ++i) {
if (owner == _owners[i]) ++count;
}
return count;
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(
uint256 tokenId
) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: owner query for nonexistent token");
return _owners[tokenId];
}
/**
* @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 {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(
uint256 tokenId
) public view virtual override returns (address) {
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(
address operator,
bool approved
) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_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: transfer caller is not owner nor 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: transfer caller is not owner nor 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 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 tokenId < _owners.length && _owners[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) {
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, 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);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, 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(
ERC721Upgradeable.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId);
}
/**
* @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 {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both 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 {}
function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
) internal virtual {}
}
OwnableUpgradeable.sol 95 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.20;
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init(address _ownerOnInit) internal onlyInitializing {
__Ownable_init_unchained(_ownerOnInit);
}
function __Ownable_init_unchained(
address _ownerOnInit
) internal onlyInitializing {
_transferOwnership(_ownerOnInit);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
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);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
Read Contract
DEFAULT_TRANSFER_VALIDATOR 0x01463546 → address
areDiscountsUsed 0x3a7cb086 → bool[]
auctionEndTimeStamp 0x665155c0 → uint56
autoApproveTransfersFromValidator 0x6221d13c → bool
balanceOf 0x70a08231 → uint256
bidCount 0xb40a5627 → uint32
bidNodes 0x93803fdf → address, uint256
getApproved 0x081812fc → address
getBidNodes 0x7fd67d49 → tuple[]
getCutoffBidAmount 0x0e910d39 → uint96
getEstimatedNodeId 0xd8d472d8 → uint32
getTransferValidationFunction 0x0d705df6 → bytes4, bool
getTransferValidator 0x098144d4 → address
isApprovedForAll 0xe985e9c5 → bool
maxSupply 0xd5abeb01 → uint32
name 0x06fdde03 → string
owner 0x8da5cb5b → address
ownerOf 0x6352211e → address
royaltyInfo 0x2a55205a → address, uint256
supportsInterface 0x01ffc9a7 → bool
symbol 0x95d89b41 → string
tokenByIndex 0x4f6ccce7 → uint256
tokenOfOwnerByIndex 0x2f745c59 → uint256
tokenSeed 0x5f516836 → bytes32
tokenURI 0xc87b56dd → string
totalSupply 0x18160ddd → uint256
walletOfOwner 0x438b6300 → uint256[]
Write Contract 29 functions
These functions modify contract state and require a wallet transaction to execute.
allowListMint 0x9df742d7
bytes32[] proof
address a
approve 0x095ea7b3
address to
uint256 tokenId
claim 0xfdca172e
uint32[] bidIds
uint256[] gmDaoTokenIds
address a
initProject 0xb2bc931d
tuple _p
ownerMint 0x78491b1b
uint24 count
address a
placeBid 0x455d9ac4
uint32 estimatedNodePositionId
publicMint 0xfafe3a20
uint24 count
address a
renounceOwnership 0x715018a6
No parameters
safeTransferFrom 0x42842e0e
address from
address to
uint256 tokenId
safeTransferFrom 0xb88d4fde
address from
address to
uint256 tokenId
bytes _data
setALPrice 0x816403a1
uint96 _allowListPrice
setALStart 0x881c632c
uint56 _allowListStartTimeStamp
setAllowPublic 0x35a83013
bool _allowPublic
setApprovalForAll 0xa22cb465
address operator
bool approved
setAuctionDuration 0x738cba9a
uint32 _auctionDuration
setAuctionStart 0x5077ee24
uint56 _auctionStartTimeStamp
setAutomaticApprovalOfTransfersFromValidator 0x9e05d240
bool autoApprove
setGmDiscount 0x2ed56f36
uint96 _gmDiscount
setMaxSupply 0xf9da3224
uint32 _maxSupply
setMerkleRoot 0x7cb64759
bytes32 _merkleRoot
setMinBid 0x4f808dc2
uint96 _minBid
setRoyalty 0xcac92669
uint96 _royalty
setRoyaltyAddress 0x06d254da
address _royaltyAddress
setTokenBase 0x916358a3
string _tokenBase
setTransferValidator 0xa9fc664e
address transferValidator_
transferFrom 0x23b872dd
address from
address to
uint256 tokenId
transferOwnership 0xf2fde38b
address newOwner
updateBid 0xb0153d5e
uint32 bidId
uint32 estimatedNodePositionId
withdraw 0x3ccfd60b
No parameters
Token Balances (1)
View Transfers →Recent Transactions
No transactions found for this address