Address Contract Partially Verified
Address
0x18d04735d18495B5336e00CD092c5d17c9e5a0B4
Balance
0 ETH
Nonce
1
Code Size
24125 bytes
Creator
0x45faf792...4705 at tx 0x78b4744d...0c51ef
Indexed Transactions
0
Contract Bytecode
24125 bytes
0x6080604052600436101561001257600080fd5b60003560e01c80630804a4ee146102b25780630be4f422146102ad5780630c9c0c8d146102a8578063129458f4146102a3578063174768911461029e5780631c2916c014610299578063238ac9331461029457806327b02fce1461028f57806328f89c3a1461028a5780632eb4a7ab146102855780632ebfe12a146102805780632ec0f3591461027b578063350868651461027657806338bf282e1461027157806359bb61991461026c578063617e1b171461026757806366503315146102625780636c70bee91461025d578063715018a61461025857806371c53455146102535780637b12ae831461024e57806389ff17f2146102495780638da5cb5b14610244578063907d13401461023f578063925f9e841461023a57806392d3c7a414610235578063933e059714610230578063aad2b7231461022b578063af50330914610226578063b8ceaef214610221578063c718dbda1461021c578063cd3efe0614610217578063d6a95f3914610212578063d81af72514610212578063d8ae136a1461020d578063e829558814610208578063e9ec2e9914610203578063ec732959146101fe578063ee990783146101f9578063f19ea903146101f4578063f2fde38b146101ef5763f5d4e4f1146101ea57600080fd5b612300565b61226f565b612230565b612218565b6121dd565b6121bf565b612193565b611cfc565b611ce3565b611cc5565b611c86565b611c33565b611ac7565b61196a565b61190e565b6118c1565b61181e565b6117af565b611786565b611693565b6114d5565b611398565b61133a565b6111b1565b6110e6565b6110c1565b6110a8565b61103b565b610f42565b610e13565b610d01565b610b61565b610b1f565b610850565b6107f5565b610704565b610412565b610377565b61034d565b61032f565b6102c7565b60009103126102c257565b600080fd5b346102c25760008060031936011261032c577f8dea8703c3cf94703383ce38a9c894669dccd4ca8e65ddb43267aa0248711450805460ff1916600117905533815260f160205260408120541561031a5780f35b6040516304e3fa1560e01b8152600490fd5b80fd5b346102c25760003660031901126102c2576020606654604051908152f35b346102c25760203660031901126102c257604061036b6004356124b2565b82519182526020820152f35b346102c25760203660031901126102c25760043560005260f1602052602060ff604060002054166040519015158152f35b600319906020818301126102c257600435916001600160401b0383116102c25782610220920301126102c25760040190565b634e487b7160e01b600052602160045260246000fd5b600e11156103fa57565b6103da565b91906020830192600e8210156103fa5752565b346102c25761043761042b610426366103a8565b6125df565b604051918291826103ff565b0390f35b634e487b7160e01b600052604160045260246000fd5b606081019081106001600160401b0382111761046c57604052565b61043b565b604081019081106001600160401b0382111761046c57604052565b60a081019081106001600160401b0382111761046c57604052565b60e081019081106001600160401b0382111761046c57604052565b60c081019081106001600160401b0382111761046c57604052565b608081019081106001600160401b0382111761046c57604052565b6001600160401b03811161046c57604052565b90601f801991011681019081106001600160401b0382111761046c57604052565b60405190610539826104a7565b565b60405190610539826104c2565b6040519061053982610451565b6040519061053982610471565b6040519061030082018281106001600160401b0382111761046c57604052565b6001600160401b03811161046c5760051b60200190565b600211156102c257565b6001600160a01b038116036102c257565b3590610539826105a3565b91908260609103126102c2576040516105d781610451565b604080829480356105e781610599565b845260208101356105f7816105a3565b60208501520135910152565b6001600160781b038116036102c257565b9060a06003198301126102c25760405161062d81610451565b60608193600435835260231901126102c25760405161064b81610451565b60243561065781610599565b8152604435610665816105a3565b60208201526064356040820152602082015260406084359161068683610603565b0152565b91909160a0818403126102c257604060808151926106a784610451565b6106b9849682358652602083016105bf565b602085015201359161068683610603565b9190604051926106d984610451565b8390606081019283116102c257905b8282106106f457505050565b81358152602091820191016106e8565b346102c2576020806003193601126102c257600435906001600160401b0382116102c257366023830112156102c25781600401359161074283610582565b916040610752604051948561050b565b84845260208401906024610120809702850101933685116102c257602401915b8483106107845761078286612c0a565b005b823603908782126102c257608083519261079d84610471565b6107a7368761068a565b8452609f1901126102c2578251906107be82610471565b3660bf860112156102c257889286926107da3660a089016106ca565b81526101008701358482015283820152815201920191610772565b346102c25760003660031901126102c25760f3546040516001600160a01b039091168152602090f35b600319906020818301126102c257600435916001600160401b0383116102c257826101e0920301126102c25760040190565b346102c25760206108686108633661081e565b613144565b6040519015158152f35b61ffff8116036102c257565b359061053982610872565b68ffffffffffffffffff8116036102c257565b359061053982610889565b600311156102c257565b3590610539826108a7565b6001600160401b038116036102c257565b3590610539826108bc565b9080601f830112156102c257604051916108f1836104dd565b8290608081019283116102c257905b82821061090d5750505090565b8135815260209182019101610900565b6001600160401b03811161046c57601f01601f191660200190565b9291926109448261091d565b91610952604051938461050b565b8294818452818301116102c2578281602093846000960137010152565b9080601f830112156102c25781602061098a93359101610938565b90565b9190610100838203126102c257604051906109a78261048c565b81936109b382826108d8565b83526080810135602084015260a081013560408401526001600160401b039160c08201358381116102c257816109ea91840161096f565b606085015260e08201359283116102c257608092610a08920161096f565b910152565b81601f820112156102c257803591602091610a2784610582565b93610a35604051958661050b565b808552838086019160051b830101928084116102c257848301915b848310610a605750505050505090565b82356001600160401b0381116102c2578691610a818484809489010161098d565b815201920191610a50565b91909160e0818403126102c257610aa161052c565b92610aab8261087e565b8452610ab96020830161089c565b6020850152610aca604083016108b1565b6040850152610adb606083016108cd565b6060850152610aec608083016105b4565b608085015260a082013560a085015260c08201356001600160401b0381116102c257610b189201610a0d565b60c0830152565b346102c25760203660031901126102c2576004356001600160401b0381116102c257610b59610b546020923690600401610a8c565b61334f565b604051908152f35b346102c25760003660031901126102c2576020606554604051908152f35b91908260409103126102c257604051610b9781610471565b6020808294803584520135910152565b9080601f830112156102c25760405191610bc083610471565b8290604081019283116102c257905b828210610bdc5750505090565b8135815260209182019101610bcf565b91906080838203126102c2576020610a0860405192610c0a84610471565b60408496610c188382610ba7565b865201610ba7565b9080601f830112156102c2578135916020610c3a84610582565b93604093610c4b604051968761050b565b81865260208087019260061b850101938185116102c257602001915b848310610c775750505050505090565b838691610c848486610b7f565b815201920191610c67565b6101009060231901126102c257602490565b9080601f830112156102c2576020908235610cbb81610582565b93610cc9604051958661050b565b81855260208086019260051b8201019283116102c257602001905b828210610cf2575050505090565b81358152908301908301610ce4565b346102c257600319610140368201126102c257600435906001600160401b03908183116102c2576102009083360301126102c257610d3d61053b565b9180600401358281116102c257610d5a906004369184010161096f565b8352610d693660248301610b7f565b6020840152610d7b3660648301610bec565b6040840152610d8d3660e48301610bec565b6060840152610da0366101648301610bec565b60808401526101e4810135908282116102c2576004610dc29236920101610c20565b60a0830152610dd036610c8f565b610124359182116102c25761043792610dfb610df3610e01943690600401610ca1565b923690613406565b906141e3565b60405190151581529081906020820190565b346102c2576003196060368201126102c2576001600160401b03906024356004356044358481116102c25780600401610200823603958601126102c257610e586142cd565b60009583875260bd60205260408720858852602052604087209582359060221901811215610f3e5783016004810135918211610f3e57602401928136038413610f3e5786610f236101e4600f93610ed7610f2c96610f38997f3d09e10d1c966d01c4a2c14d0ac9af253486aa5e99b6cffe9019c4d43eb1fb239d6134a1565b6024810135600185015560448101356002850155610efb606482016003860161356f565b610f0b60e482016007860161356f565b610f1c6101648201600b860161356f565b01856135c1565b929091016135f6565b60405193849384613756565b0390a180f35b8780fd5b346102c25760403660031901126102c257600435610f5f816105a3565b610faf602435610f6e816105a3565b60005492610f9360ff8560081c16158095819661102d575b811561100d575b5061381b565b83610fa6600160ff196000541617600055565b610ff45761387e565b610fb557005b610fc561ff001960005416600055565b604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb384740249890602090a1005b61100861010061ff00196000541617600055565b61387e565b303b1591508161101f575b5038610f8d565b6001915060ff161438611018565b600160ff8216109150610f86565b346102c25760403660031901126102c2576020610b596024356004356139a6565b9060206003198301126102c2576004356001600160401b03928382116102c257806023830112156102c25781600401359384116102c25760248460051b830101116102c2576024019190565b346102c2576020610b596110bb3661105c565b90613a5b565b346102c25760a03660031901126102c25761043761042b6110e136610614565b613aaf565b346102c25760003660031901126102c2576020606754604051908152f35b919082519283825260005b848110611130575050826000602080949584010152601f8019910116010190565b60208183018101518483018201520161110f565b61010060c061098a936020845260018060a01b03808251166020860152806020830151166040860152604082015116606085015260608101516001600160781b03809116608086015260808201511660a085015260a08101518285015201519160e0808201520190611104565b346102c25760008060031936011261032c5760c0606091604051906111d5826104a7565b808252806020830152806040830152808483015280608083015260a0820152015261043760018060a01b03611208613c07565b6112a561121361052c565b6001600160a01b037f000000000000000000000000b0124f5d0e906d3652d0b58f03e315ec42a57e9a8516168152926001600160a01b037f000000000000000000000000ccb9212144d35c3f0fd7e3905f46c8fd1a23901382161660208501527f0000000000000000000000009b3a451982cdec83d833f0495d7bf766430dd978166001600160a01b03166040840152565b6001600160781b037f00000000000000000000000000000000000000000000000000000000000000191660608301526001600160781b037f00000000000000000000000000000000000000000000000000000000000000191660808301527f0000000000000000000000000000000000000000000000000000000000000e1060a083015260c082015260405191829182611144565b346102c25760008060031936011261032c576113546142cd565b603380546001600160a01b0319811690915581906001600160a01b03167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b346102c25760a03660031901126102c2576020610b596113b736610614565b613c28565b6000915b600283106113cd57505050565b6001908251815260208091019201920191906113c0565b9060406020610539936113f88482516113bc565b01519101906113bc565b90602091828152815192611423610200948583850152610220840190611104565b9160a08285015194611445604096604085019060208091805184520151910152565b611457604082015160808501906113e4565b61146a60608201516101008501906113e4565b61147d60808201516101808501906113e4565b015194601f19828503019101528080855193848152019401926000905b8382106114a957505050505090565b90919293948382826114c86001948a5160208091805184520151910152565b019601949392019061149a565b346102c2576040806003193601126102c2578051906114f3826104c2565b60608252606060a0602093611506613cc2565b85820152611512613cdb565b8482015261151e613cdb565b8382015261152a613cdb565b60808201520152600090600435825260bd835280822060243583528352808220815192611556846104c2565b82519080835461156581612f2b565b8085529160019180831690811561162657506001146115f2575b505050916104379582611599600f946115e396038261050b565b86526115a760018301612f65565b908601526115b760038201612fb6565b848601526115c760078201612fb6565b60608601526115d8600b8201612fb6565b608086015201612fdd565b60a08301525191829182611402565b92508483528783205b8284106116135750505081018501858261159961157f565b80548585018a01529288019281016115fb565b60ff19168a870152505050151560051b820186019050858261159961157f565b9060406003198301126102c2576004356001600160401b03928382116102c257806023830112156102c25781600401359384116102c257602484830101116102c257602401919060243590565b346102c2576116a136611646565b91906116ac836145c2565b929193905061173e61173661171460405160208101903360601b825289603482015260006054820152603581526116e281610451565b5190207f19457468657265756d205369676e6564204d6573736167653a0a333200000000600052601c52603c60002090565b60f3546001600160a01b03908116959094611730913691610938565b90615b50565b919091615b92565b16036117745761174d916147d5565b7f88961649b3b00b15da12dbae1c3f418d46c3f3bda07ead6727468fb7652115fe600080a2005b604051630bdb98d360e41b8152600490fd5b346102c25760003660031901126102c2576033546040516001600160a01b039091168152602090f35b346102c25760203660031901126102c2576004356117cc816145c2565b904210611803576117dc916147d5565b7fb1913e330f49ea507fdfb64d9316412d7f5b9f632b4a1e66b64558359570c6a9600080a2005b60405162de3d5b60e11b8152600490fd5b801515036102c257565b346102c2576040806003193601126102c257610782906024359060043561184483611814565b61184c6142cd565b821561188d57600080516020615de88339815191528280518381528515156020820152a15b60005260f16020526000209060ff801983541691151516179055565b7ff99ee69f7cbcb8f04566c5aad13316d4989d9409c2e680f0074ee40f199d31b982805183815260006020820152a1611871565b346102c25760603660031901126102c2576020610b596040516118e381610451565b6004356118ef81610599565b81526024356118fd816105a3565b838201526044356040820152613d14565b346102c25760403660031901126102c2576004356001600160881b03811681036102c257602435906001600160801b03821682036102c25760409161195291613d82565b82516001600160781b03928316815291166020820152f35b346102c25760203660031901126102c25761078260043561198a816105a3565b6119926142cd565b614472565b600211156103fa57565b9060028210156103fa5752565b604080916119bd8482516119a1565b6020818101516001600160a01b0316908501520151910152565b6001600160781b036040608092805185526119fa602082015160208701906119ae565b015116910152565b8051600090835b60038310611a205750505060206060910151910152565b600190825181526020809101920192019190611a09565b9060209081835260a0918060c0606060a087019460018060a01b0380825116858a0152848201511660408901526040810151828901520151956080808201528651809552019401926000905b838210611a9257505050505090565b909192939483610120600192611aba838a51611aaf8482516119d7565b015186830190611a02565b0196019493920190611a83565b346102c25760203660031901126102c2576004604051611ae6816104dd565b6060806000928381528360208201528360408201520152600435815260f56020526040812090600360405192611b1b846104dd565b80546001600160a01b0390811685526001820154166020850152600281015460408501520180549091611b4d82610582565b92611b5b604051948561050b565b82845281526020808220919084015b838210611b865760608601859052604051806104378882611a37565b604051611b9281610471565b60405191611b9f83610451565b8454835260405190611bb082610451565b600186015492600260ff851610156103fa5760019460209360ff86168152600895878060a01b0390871c16858201526002890154604082015284820152611c14611c0460038a01546001600160781b031690565b6001600160781b03166040830152565b8152611c218b8801613dd2565b83820152815201930191019091611b6a565b346102c25760203660031901126102c25760043560005260f2602052606060406000206001815491015460405191611c6e8360ff83166119a1565b60081c6001600160a01b031660208301526040820152f35b346102c25760403660031901126102c257600435600052608a6020526040600020602435600052602052602060ff604060002054166040519015158152f35b346102c25760003660031901126102c257602060f054604051908152f35b346102c25761043761042b611cf73661081e565b613e24565b611d053661105c565b801561214257611d158183613a5b565b611d1e81613107565b91611d2a600092613f57565b916000905b8282106120e4575050604080516370a0823160e01b8082526001600160a01b037f000000000000000000000000b0124f5d0e906d3652d0b58f03e315ec42a57e9a81811660048501529397939493602092917f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc216908385602481855afa94851561201e576000956120c5575b50600095865b81811061202f57506000915050851561202a575034156120235760015b611de781612523565b60018103611f26575050505050611e29611e24611e79927f00000000000000000000000000000000000000000000000000000000000f4240612a33565b612a16565b611e737f0000000000000000000000000000000000000000000000000000000000001c207f0000000000000000000000005f4ec3df9cbd43714fe2740f5e3616155c5b8419614e3b565b90613fe6565b90813410611f16579181611e92611eb796938695614fb4565b803411611efd575b505b611ea683516124b2565b9290918451611ec0575b868561508f565b6107824360f055565b7f56a618cda1e34057b7f849a5792f6c8587a2dbe11c83d0254e72cb3daffda7d194611ef0925194859485614006565b0390a18038808080611eb0565b611f0a611f1091346125b8565b33614fb4565b38611e9a565b845162976f7560e21b8152600490fd5b80611f3960029298959793949698612523565b14611f50575b505050505050611eb7928291611e9c565b918491611f86611e29611e24611fac967f00000000000000000000000000000000000000000000000000000000000f4240612a33565b8a519586526001600160a01b039092166004860152909392839190829081906024820190565b03915afa92831561201e57600093611feb575b5050611fcb91926124a5565b11611fdb57388080808080611f3f565b825162976f7560e21b8152600490fd5b611fcb9350908161201092903d10612017575b612008818361050b565b810190613997565b9138611fbf565b503d611ffe565b61286b565b6002611dde565b611dde565b6120528c61204c612041848688613a38565b6101608101906124e6565b0161252d565b61205b81612523565b612068575b600101611dc1565b60016120816101a061207b848688613a38565b01613fdc565b61208a81611997565b146120b1575b806120aa6101806120a46001948688613a38565b01614bd5565b9050612060565b966120bd600191612847565b979050612090565b6120dd919550843d861161201757612008818361050b565b9338611dbb565b6120f2610426838589613a38565b6120fb816103f0565b806121215750612119846001928761211486888c613a38565b6149ac565b910190611d2f565b604051630bacf39760e31b815290819061213e90600483016103ff565b0390fd5b6040516359177c0560e11b8152600490fd5b634e487b7160e01b600052603260045260246000fd5b601081101561217c57607a0190600090565b612154565b601081101561217c57606a0190600090565b346102c25760203660031901126102c25760043560108110156102c257602090606a0154604051908152f35b346102c25760003660031901126102c257602060f454604051908152f35b346102c25760003660031901126102c25760206040517f144837c570fc50b57f62843651aeb967b68f126ea75a7de09db13ddf6cd2f2898152f35b346102c257602061086861222b366103a8565b614063565b346102c25760403660031901126102c25760043560005260696020526040600020602435600052602052602060ff604060002054166040519015158152f35b346102c25760203660031901126102c25760043561228c816105a3565b6122946142cd565b6001600160a01b038116156122ac57610782906144f5565b60405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b6064820152608490fd5b61230936611646565b9061232182612317816145c2565b949196905061476d565b805161232c81613107565b91612336826128ae565b9161234081612922565b9161234a82613107565b9660005b8381106123cd578761239d887f43ee425939c1a009b002ccea94371bae02e2b1ed3b3ae0e6d74b0990572d381e89896123958f606754926066549460405195869586615270565b0390a161508f565b6123a64360f055565b7f9f141595aedbd010c31edab62003eef8b9e3806803ea49be99d5ecdc5ca0e99f600080a2005b806123e56123dd600193866129b0565b515184615701565b6123ef838d6129b0565b526123fa82896129b0565b5261240e61240882896129b0565b51613c28565b612418828a6129b0565b52602061242582866129b0565b51015161243282886129b0565b5261243d81876129b0565b500161234e565b634e487b7160e01b600052601160045260246000fd5b906004820180921161246857565b612444565b600201908160021161246857565b600301908160031161246857565b906002820180921161246857565b906001820180921161246857565b9190820180921161246857565b906066549182018083116124685762010000106124d0576067549190565b9050606754600181018091116124685790600090565b90359060de19813603018212156102c2570190565b3561098a81610889565b3561098a816105a3565b3561098a816108bc565b3561098a81610872565b600311156103fa57565b3561098a816108a7565b903590601e19813603018212156102c257018035906001600160401b0382116102c257602001918160051b360383136102c257565b60001981019190821161246857565b60011981019190821161246857565b907f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd4791820391821161246857565b9190820391821161246857565b3561098a81610603565b919081101561217c5760051b0190565b610160810161260a6125fc60206125f684866124e6565b016124fb565b68ffffffffffffffffff1690565b3a10612840576001600160a01b038061262e608061262885876124e6565b01612505565b1615159081612825575b5061281e57612652606061264c83856124e6565b0161250f565b6001600160401b0346911603612817576126b36126af6126a861269461268061267b86886124e6565b612519565b61ffff16600052608a602052604060002090565b610100860135600052602052604060002090565b5460ff1690565b1590565b612810576126c6604061204c83856124e6565b6126cf81612523565b156127d9576126eb6126e182846124e6565b60c0810190612537565b61014084019291506127076127008486612537565b905061256c565b036127d15761271d604061204c600293866124e6565b61272681612523565b036127b75761279161277061273e61020085016125c5565b6113b7612749610548565b9133835261275b366101a089016105bf565b60208401526001600160781b03166040830152565b915b61270061278b6127828387612537565b92909387612537565b916125cf565b35036127b1576126af6127a391614063565b6127ac57600090565b600b90565b50600a90565b6127916127cb6113b736610180860161068a565b91612772565b505050600990565b6126e16127e691836124e6565b90506127f6610140830183612537565b9190500361280a576126af6127a391614063565b50600990565b5050600890565b5050600790565b5050600690565b9050612836608061262884866124e6565b1633141538612638565b5050600590565b60001981146124685760010190565b908160209103126102c2575161098a816105a3565b6040513d6000823e3d90fd5b6040519061288482610451565b6000604083828152815161289781610451565b838152836020820152838382015260208201520152565b906128b882610582565b6128c5604051918261050b565b82815280926128d6601f1991610582565b019060005b8281106128e757505050565b6020906128f2612877565b828285010152016128db565b60405190602082018281106001600160401b0382111761046c576040526020368337565b9061292c82610582565b604061293b604051928361050b565b838252819361294c601f1991610582565b019160009060005b848110612962575050505050565b602090845161297081610471565b855161297b81610451565b60603682378152828581830152828501015201612954565b80511561217c5760200190565b80516001101561217c5760400190565b805182101561217c5760209160051b010190565b5160028110156103fa5790565b90805160028110156103fa5782546020830151610100600160a81b0360089190911b1660ff929092166001600160a81b03199091161717825560400151600190910155565b90670de0b6b3a76400009182810292818404149015171561246857565b8181029291811591840414171561246857565b818110612a51575050565b60008155600101612a46565b90805160005b60038110612a7957505060206003910151910155565b600190602083519301928186015501612a63565b805490600160401b82101561046c576001820180825582101561217c5760005260206000209060031b018151805182556001820190602081015193845160028110156103fa57612b286040602094816105399988612b479660049a5460ff610100600160a81b038c86015160081b169216906affffffffffffffffffffff60a81b16171790550151600289015501516001600160781b031690565b60038601906001600160781b03166001600160781b0319825416179055565b01519101612a5d565b90815180825260208080930193019160005b828110612b70575050505090565b909192938260a082612b8560019489516119d7565b01950193929101612b62565b90815180825260208080930193019160005b828110612bb1575050505090565b9091929382608082612bc66001948951611a02565b01950193929101612ba3565b9261098a9492612bfc9260018060a01b031685526020850152608060408501526080840190612b50565b916060818403910152612b91565b90815160148111612f195760f454612c29612c2482612847565b60f455565b604051635d12928b60e01b815291600490602084838160007f000000000000000000000000ccb9212144d35c3f0fd7e3905f46c8fd1a2390136001600160a01b03165af193841561201e57600094612ee8575b50612ca77f0000000000000000000000000000000000000000000000000000000000000e10426124a5565b90612cbc8460005260f5602052604060002090565b80546001600160a01b03191633178155926001840180546001600160a01b0319166001600160a01b038816179055826002850155612cf9826128ae565b93612d0383612922565b9860005b848110612d4e575050505050612d497f9e44fb95d9376d426d7b6262d6012c682326c75100c2c7dd305e0977290a053993949596604051938493339885612bd2565b0390a3565b808b612d90826020612d618c96886129b0565b51612d6f8160038b01612a8d565b612d878382519889612d8183836129b0565b526129b0565b500151926129b0565b52612d9b818d6129b0565b506020820191612dab83516129c4565b612db481611997565b612e2257612e1c90612e0b612dff6040612df0612de4612de4612de4602060019b510160018060a01b0390511690565b6001600160a01b031690565b9301516001600160781b031690565b6001600160781b031690565b90848060a01b038d1690339061419a565b01612d07565b50906001612e3082516129c4565b612e3981611997565b03612ed75751906040612e61612de4612de4612de4612de4602088015160018060a01b031690565b92015191803b156102c257604080516323b872dd60e01b8152338882019081526001600160a01b038e16602082015291820194909452600091849182908490829060600103925af191821561201e57600192612ebe575b50612e1c565b80612ecb612ed1926104f8565b806102b7565b38612eb8565b60405163350b944160e11b81528590fd5b612f0b91945060203d602011612f12575b612f03818361050b565b810190612856565b9238612c7c565b503d612ef9565b604051638e76f9ab60e01b8152600490fd5b90600182811c92168015612f5b575b6020831014612f4557565b634e487b7160e01b600052602260045260246000fd5b91607f1691612f3a565b90604051612f7281610471565b602060018294805484520154910152565b60405191906000835b60028210612fa05750505061053982610471565b6001602081928554815201930191019091612f8c565b90604051612fc381610471565b6020610a0860028395612fd581612f83565b855201612f83565b908154612fe981610582565b92612ff7604051948561050b565b818452600090815260208082208186015b848410613016575050505050565b60028360019261302585612f65565b815201920193019290613008565b90604051613040816104c2565b809260405160009082549161305483612f2b565b8083526020936001908181169081156130eb57506001146130b7575b505092610a089282613088600f9460a097038261050b565b865261309660018301612f65565b908601526130a660038201612fb6565b60408601526115c760078201612fb6565b60008681528581209093505b8284106130d857505050810182018282613070565b80548585018701529285019281016130c3565b60ff1916868601525050151560051b8201830190508282613070565b9061311182610582565b61311e604051918261050b565b828152809261312f601f1991610582565b0190602036910137565b61098a903690610a8c565b9061012082016131548184612537565b905061318461317f6131708360005260bd602052604060002090565b60008052602052604060002090565b613033565b9060208201515115613276576131a161319c8261245a565b613107565b926101008601356131b185612993565b526131cb610b546131c66101408901896124e6565b613139565b6131d4856129a0565b5260005b82811061324557505084610dfb91610160613233969701356132026131fc8361246d565b876129b0565b5261322b61322561321f61321a3661018087016105bf565b613d14565b9261247b565b866129b0565b523690613406565b61dead321461323f5790565b50600190565b8061325c600192613256858b612537565b906125cf565b3561326f6132698361246d565b886129b0565b52016131d8565b604051639096cccb60e01b8152600490fd5b908082519081815260208091019281808460051b830101950193600080925b8584106132b8575050505050505090565b90919293949596601f19828203018452858851916101008351829087915b6004831061333957505050838392613328926133178560019801519160809283850152604085015160a08501526060850151908060c0860152840190611104565b9201519060e0818403910152611104565b9901940194019295949391906132a7565b815181528b9560019093019291820191016132d6565b61098a906040516133ef816133e160c060208301956020875261ffff815116604085015268ffffffffffffffffff6020820151166060850152604081015161339681612523565b60808581019190915260608201516001600160401b031660a08601528101516001600160a01b03168285015260a081015160e0850152015160e0610100840152610120830190613288565b03601f19810183528261050b565b519020600080516020615dc8833981519152900690565b9190610100838203126102c2576040610a0881519261342484610451565b60c084966134328382610b7f565b865261344083868301610bec565b602087015201610b7f565b90601f811161345957505050565b6000916000526020600020906020601f850160051c83019410613497575b601f0160051c01915b82811061348c57505050565b818155600101613480565b9092508290613477565b9092916001600160401b03811161046c576134c6816134c08454612f2b565b8461344b565b6000601f82116001146135075781906134f89394956000926134fc575b50508160011b916000199060031b1c19161790565b9055565b0135905038806134e3565b601f1982169461351c84600052602060002090565b91805b87811061355757508360019596971061353d575b505050811b019055565b0135600019600384901b60f8161c19169055388080613533565b9092602060018192868601358155019401910161351f565b91908060005b600281106135ad57505060400160005b600291828210156135a6579081602060019335910193828701015501613585565b5050509050565b600190602083359301928187015501613575565b903590601e19813603018212156102c257018035906001600160401b0382116102c257602001918160061b360383136102c257565b90600160401b831161046c57815483835580841061365a575b506136209091600052602060002090565b6000915b8383106136315750505050565b600260408261364e60019486906020600191803584550135910155565b01920192019190613624565b60016001600160ff1b0382811683036124685785168503612468576000908460005260206000209260011b8301928660011b015b83811061369d5750505061360f565b80836002925583838201550161368e565b908060209392818452848401376000828201840152601f01601f1916010190565b9060408080938181853701910137565b9035601e19823603018112156102c25701602081359101916001600160401b0382116102c2578160061b360383136102c257565b9160209082815201919060005b81811061372d5750505090565b909192806137476001928660208091803584520135910152565b60409081019401929101613720565b92919083526020830152606060408301528035601e19823603018112156102c2578101916020833593016001600160401b0384116102c25783360381136102c2576137b56138089161098a9561020060608601526102608501916136ae565b60208401356080840152604084013560a0840152926137da60c08401606083016136cf565b6137eb610140840160e083016136cf565b6137fd6101c0840161016083016136cf565b6101e08101906136df565b91610240605f1982860301910152613713565b1561382257565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b61389860ff60005460081c1661389381614325565b614325565b6138a1336144f5565b6138b260ff60005460081c16614325565b7f144837c570fc50b57f62843651aeb967b68f126ea75a7de09db13ddf6cd2f289606a8181556000905b60108210613956575050610539929161393961392c836138fe61393e95606555565b61390781606855565b61391d606754600052608a602052604060002090565b90600052602052604060002090565b805460ff19166001179055565b61417a565b613946614385565b61394e6143d4565b611992614423565b909161398f8160019285850155613989816139708761216a565b90919082549060031b91821b91600019901b1916179055565b806139a6565b9201906138dc565b908160209103126102c2575190565b604051906139b382610471565b815260208082019290925260405163014cf2b360e51b8152906000600483015b8460028310613a2457925050508160448173a1a752b2c3dd65381211670574c50966315c10ad5af491821561201e57600092613a0e57505090565b61098a9250803d1061201757612008818361050b565b8060019285518152019301910190916139d3565b919081101561217c5760051b8101359061021e19813603018212156102c2570190565b906000916000915b808310613a705750505090565b909192613a846126e1612041868587613a38565b9050810180911161246857926001019190613a63565b908160209103126102c2575161098a81611814565b60408101906001600160781b039081613acf84516001600160781b031690565b1615613bff5760208181018051820151909291613b2191613af8906001600160a01b0316612de4565b60405163815b534f60e01b81526001600160a01b03909116600482015291829081906024820190565b03817f0000000000000000000000009b3a451982cdec83d833f0495d7bf766430dd9786001600160a01b03165afa90811561201e57600091613bd0575b50613bc757600080516020615dc883398151915290511015613bbf57613b86600191516129c4565b613b8f81611997565b149182613ba7575b5050613ba257600090565b600490565b51600192506001600160781b03161614153880613b97565b505050600390565b50505050600290565b613bf2915060203d602011613bf8575b613bea818361050b565b810190613a9a565b38613b5e565b503d613be0565b505050600190565b60405190613c1482610471565b60058252640322e322e360dc1b6020830152565b604051613c3481610451565b815181526001600160781b036040602093613c5185820151613d14565b85850152015116604082015260405190635a53025d60e01b8252600482016000905b8460038310613cae579250505081606481737df7fad23c61b8b578362e7b4996dc192c87520d5af491821561201e57600092613a0e57505090565b806001928551815201930191019091613c73565b60405190613ccf82610471565b60006020838281520152565b60405190613ce882610471565b81604051613cf581610471565b60403682378152602060405191613d0b83610471565b60403684370152565b805160028110156103fa5715613d5957600080516020615dc883398151915290604051613d456020820180936119ae565b60608152613d52816104dd565b5190200690565b602001516001600160a01b031690565b6001600160881b03918216908216039190821161246857565b91906001600160801b03166001600160881b03808416908282021691818304149015171561246857613dbb612710613dc2920484613d69565b8093613d69565b6001600160781b03928316921690565b90604051613ddf81610471565b80926040518082906000905b60038210613e0e5750505060209181613e05600393610451565b84520154910152565b6001602081928554815201930191019091613deb565b6101408101613e3b6125fc60206125f684866124e6565b3a10612840576001600160a01b0380613e59608061262885876124e6565b1615159081613f3c575b5061281e57613e77606061264c83856124e6565b6001600160401b034691160361281757613ea06126af6126a861269461268061267b86886124e6565b612810576101208201613eb38184612537565b8093915015613f335760005b838110613ed657505050506126af6127a391613144565b613f1d6126a8613f00613eec61267b868a6124e6565b61ffff166000526069602052604060002090565b613f0e84613256888b612537565b35600052602052604060002090565b613f2957600101613ebf565b5050505050600d90565b50505050600c90565b9050613f4d608061262884866124e6565b1633141538613e63565b90613f6182610582565b604090613f71604051918261050b565b8381528093613f82601f1991610582565b019160009160005b848110613f98575050505050565b6020908351613fa68161048c565b8451613fb1816104dd565b6080908136823782528390878284015287878401526060908180850152830152828501015201613f8a565b3561098a81610599565b8115613ff0570490565b634e487b7160e01b600052601260045260246000fd5b9094939194608082019082526020956020830152608060408301528351809152602060a0830194019060005b81811061404f5750505061098a9394506060818403910152613288565b825186529487019491870191600101614032565b9061012082016140738184612537565b610140850191506140848286612537565b9190506140a261317f8361391d8460005260bd602052604060002090565b9260208401515115613276576140c361319c6140be85856124a5565b612489565b946101008801356140d387612993565b526140e8610b546131c66101608b018b6124e6565b6140f1876129a0565b5260005b83811061414f57505060005b83811061411b5750505050610dfb61323393943690613406565b8061412c600192613256858c612537565b356141486141428361413d8861246d565b6124a5565b896129b0565b5201614101565b80614160600192613256858d612537565b3561417361416d8361246d565b8a6129b0565b52016140f5565b6141826142cd565b6001600160a01b038116156122ac57610539906144f5565b6040516323b872dd60e01b60208201526001600160a01b039283166024820152929091166044830152606480830193909352918152610539916141de60848361050b565b6152df565b92916141ed610555565b60008152600060208201529080516000915b818310614257575050509261422661098a939461421f60a0840151612993565b519061541a565b916142318151615481565b92602082015160208401516040850151916080604060608801519601519601519661554d565b909192600080516020615dc883398151915261427385846129b0565b5110156142bb576142b26001916142ac61429a60a08b015161429489612497565b906129b0565b516142a588876129b0565b51906153c5565b9061541a565b930191906141ff565b60405163b4fa3fb360e01b8152600490fd5b6033546001600160a01b031633036142e157565b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b1561432c57565b60405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608490fd5b604051600080516020615de88339815191526040730219b4c1adcec8f4206b528832f66ab76766873d9283815260016020820152a160005260f16020526040600020600160ff19825416179055565b604051600080516020615de883398151915260407317cf6db98b05a0329c983f3a3b45d37d9cf1de869283815260016020820152a160005260f16020526040600020600160ff19825416179055565b604051600080516020615de8833981519152604073cc29dbf69896278a0c6b886ef8cc30a56fa6164a9283815260016020820152a160005260f16020526040600020600160ff19825416179055565b6001600160a01b039081169081156144e35760f3549081168281146144d15760407feeb293e1f8f3a9db91ade748726387ed1352ca78f5430c5f06fe3d1e1ad50579918151908582526020820152a16001600160a01b0319161760f355565b604051631310759d60e11b8152600490fd5b60405163e6c4247b60e01b8152600490fd5b603380546001600160a01b039283166001600160a01b0319821681179092559091167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0600080a3565b600080825560019181600182015560028260028301556003809201938454948481558561456e575b505050505050565b6001600160fd1b0386168603612468578452602084209460031b8501945b858110156145665780856008925585838201558584820155858582015585600782016145bb8160048501612a46565b550161458c565b9060f45482101561475b576145e18260005260f5602052604060002090565b906040928351936145f1856104dd565b60018060a01b0394858554168152600192866001870154169360208084019586526002600360028a0154998787019a8b520180549261462f84610582565b9b61463c89519d8e61050b565b848d52600092835281832090828e015b8685106146bd57505050505050505081614685614680612de493606061469296019a8b5260005260f5602052604060002090565b61453e565b516001600160a01b031690565b33036146ad5750516001600160a01b03169151925191929190565b51634971ba2d60e01b8152600490fd5b8a516146c881610471565b8b51916146d483610451565b845483528c51906146e482610451565b8a8601549260ff8416948a8610156103fa578f61473b90858f988c975289600898891c16878201528d8b0154828201528684015261472c60038b01546001600160781b031690565b6001600160781b031690830152565b815261474960048801613dd2565b8382015281520193019401939161464c565b6040516363df817160e01b8152600490fd5b90916117366117146147a39260405160208101913360601b83526034820152600160f81b6054820152603581526116e281610451565b160361177457565b6001600160a01b039182168152911660208201526001600160781b03909116604082015260600190565b9080519060005b8281106147e95750505050565b6147f381836129b0565b515190602080830161480581516129c4565b61480e81611997565b6148a05751015161482b90612de49081906001600160a01b031681565b6040928301519092906001600160781b03166001600160a01b038716803b156102c2576148729460008094518097819582946344004cc160e01b84523390600485016147ab565b03925af191821561201e5760019261488d575b505b016147dc565b80612ecb61489a926104f8565b38614885565b90925060016148af82516129c4565b6148b881611997565b146148c8575b5060019150614887565b51918201516148e390612de49081906001600160a01b031681565b6040928301519092906001600160a01b038716803b156102c2579151632012ff5960e11b81526001600160a01b0394909416600485015233602485015260448401526000908390606490829084905af191821561201e57600192156148be5780612ecb61494f926104f8565b386148be565b61ffff909116815260406020820181905281018390526001600160fb1b0383116102c25760609260051b809284830137010190565b919081101561217c5760051b8101359060fe19813603018212156102c2570190565b9190939261012083016149bf8185612537565b905060005b818110614ad25750507f781745c57906dc2f175fec80a9c691744c91c48a34a83672c41c2604774eb11f614a1d610160860192614a0e614a0761267b868a6124e6565b9188612537565b60409391935193849384614955565b0390a1614a2a81856124e6565b90614a3b60c09260c0810190612537565b95905060005b868110614a5857505050505061098a9293506124a5565b80614a6d600192613256610140860186612537565b35614a81614a7b838a6124a5565b8c6129b0565b52614acb614aa582614a9f614a9688886124e6565b89810190612537565b9061498a565b614aba614ab2848b6124a5565b91369061098d565b614ac4828a6129b0565b52876129b0565b5001614a41565b610160860190614afc6126a8614aee613eec61267b868c6124e6565b613f0e84613256898d612537565b614b1e57614b1861392c614aee613eec61267b6001968c6124e6565b016149c4565b6040516326c9d20d60e01b8152600490fd5b60408091614b48848235614b4381610599565b6119a1565b6020810135614b56816105a3565b6001600160a01b031660208501520135910152565b6001600160a01b03909116815260c08101929160009160a091614b92906020830190614b30565b600160808201520152565b92909493614bbf60a09360c0860197600180871b031686526020860190614b30565b6001600160781b03809216608085015216910152565b602081016001600160a01b038235811690614bef83613fdc565b614bf881611997565b614cf557614c929084614c37612de4612de4612de460407ff39e964f9853357ecd19dca8450c54514b7f8a9639e5a5b13969470c8df39b849a01612505565b917f000000000000000000000000b0124f5d0e906d3652d0b58f03e315ec42a57e9a1690848203614c9757614c716080614c8692016125c5565b926000925b6001600160781b038516916156ad565b60405194859485614b9d565b0390a1565b614cf09192614cab6080614c8693016125c5565b93614ce36001600160781b039586807f0000000000000000000000000000000000000000000000000000000000000019169116613d82565b94909495851688846156ad565b614c76565b506001614d0183613fdc565b614d0a81611997565b03614dbb57614d27612de4612de4612de4612de460408801612505565b803b156102c2576040516323b872dd60e01b81523060048201526001600160a01b03831660248201526060949094013560448501526000908490606490829084905af192831561201e577ff39e964f9853357ecd19dca8450c54514b7f8a9639e5a5b13969470c8df39b8493614da8575b50614c9260405192839283614b6b565b80612ecb614db5926104f8565b38614d98565b60405163350b944160e11b8152600490fd5b60405190614dda826104dd565b60006060838281528260208201528260408201520152565b519069ffffffffffffffffffff821682036102c257565b908160a09103126102c257614e1d81614df2565b9160208201519160408101519161098a608060608401519301614df2565b600460a0614e47614dcd565b9260405192838092633fabe5a360e21b8252600180861b03165afa90600082600092600094614f4a575b50614f23575b5050506000916001614e898351151590565b15151480614ef8575b80614ee9575b80614edc575b80614ece575b614ead57505090565b614ebb6060830151426125b8565b1115614ec5575090565b60409150015190565b506060820151421015614ea4565b5060608201511515614e9e565b50600060408301511215614e98565b5069ffffffffffffffffffff614f1b602084015169ffffffffffffffffffff1690565b161515614e92565b6001845269ffffffffffffffffffff16602084015260408301526060820152388080614e77565b91509250614f70915060a03d60a011614f7d575b614f68818361050b565b810190614e09565b5092905090919238614e71565b503d614f5e565b3d15614faf573d90614f958261091d565b91614fa3604051938461050b565b82523d6000602084013e565b606090565b81471061504a576000918291829182916001600160a01b03165af1614fd7614f84565b5015614fdf57565b60405162461bcd60e51b815260206004820152603a60248201527f416464726573733a20756e61626c6520746f2073656e642076616c75652c207260448201527f6563697069656e74206d617920686176652072657665727465640000000000006064820152608490fd5b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e63650000006044820152606490fd5b8051801561526c57620100006150a7826066546124a5565b1161525f575b6066546150c26150bd83836124a5565b606655565b60009182915b6010831061511357505050506150e06150e691612993565b51606555565b61053961392c615102606754600052608a602052604060002090565b606554600052602052604060002090565b600181811c926000908280851614615216575b9190915b808310615149575050505090600161514184612497565b9101916150c8565b90919295506151578161256c565b8310156151f4576151c06151ba61517061416d86612497565b51975b61517c8461256c565b861480156151e3575b6151c7575b6151aa6151998883881c6125b8565b996151a4888d6129b0565b516139a6565b6151b48a8c6129b0565b52612489565b93612489565b919061512a565b6151de6151d4878c6129b0565b516139708a61216a565b61518a565b506151ed8461257b565b8614615185565b6151c06151ba61521061520688612181565b90549060031b1c90565b97615173565b9295505061522483806125b8565b946152446152346152068761216a565b61523d89612993565b51906139a6565b61524e87896129b0565b526152598291612847565b92615126565b6152676156e6565b6150ad565b5050565b92615296906152a49395928552602095602086015260a0604086015260a0850190612b50565b908382036060850152612b91565b9060808183039101526020808451928381520193019160005b8281106152cb575050505090565b8351855293810193928101926001016152bd565b60405161533d916001600160a01b03166152f882610471565b6000806020958685527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c656487860152868151910182855af1615337614f84565b91615d2e565b8051908282159283156153ad575b505050156153565750565b6084906040519062461bcd60e51b82526004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152fd5b6153bd9350820181019101613a9a565b38828161534b565b919060409060606153d4613cc2565b94859260208551926153e584610451565b8436853780518452015160208301528482015260076107cf195a01fa1561540857565b604051634c13b44560e11b8152600490fd5b604090602060809361542a613cc2565b5081845193615438856104dd565b86368637805185520151828401528051848401520151606082015261545b613cc2565b92839160066107cf195a01fa1561546f5790565b6040516395c3fa5760e01b8152600490fd5b615489613cc2565b5080511580615541575b61552a578051907f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47916020820192806003818651948181800909089180090361551857519051615505907f30644e72e131a029b85045b68181585d97816a916871ca8d3c208c16d87cfd47900661258a565b61550d610555565b918252602082015290565b604051630eb66ab360e01b8152600490fd5b50615533610555565b600081526000602082015290565b50602081015115615493565b9491615691966156356155b860e0956103009b9561567298996155f8615571610562565b9c8d9c8d8251905260209e8f9c8d809c819a82809a81809901518288015280515160408801526155a2815160200190565b5160608801520180515160808701525160200190565b5160a0850152805160c085015201519101528d6101008251519101528d6101206155e3835160200190565b51910152018051516101408e01525160200190565b516101608c015280516101808c015201516101a08a01528051516101c08a01528051602001516101e08a0152018051516102008901525160200190565b51610220870152805161024087015201516102608501528051516102808501528051602001516102a0850152018051516102c08401525160200190565b516102e08201526156816128fe565b93849160086107cf195a01fa1590565b61569b5751151590565b604051630184a3e760e41b8152600490fd5b60405163a9059cbb60e01b60208201526001600160a01b039092166024830152604480830193909352918152610539916141de826104dd565b60685460655560006066556156fc606754612847565b606755565b91909161570c612877565b5061571683613aaf565b61571f816103f0565b80615b33575061572d612877565b906000906020918286019361574285516129c4565b61574b81611997565b61595a575050825182015161576c90612de49081906001600160a01b031681565b92604092615783848801516001600160781b031690565b946157bb6001600160781b039687807f0000000000000000000000000000000000000000000000000000000000000019169116613d82565b93878516995190516157cb610548565b918252848201526001600160781b0382168782015286516370a0823160e01b808252306004830152919891966001600160a01b0385811696929183836024818b5afa92831561201e5760009361593b575b501695863b156102c25789516344004cc160e01b80825299600082806158478a308d600485016147ab565b0381838d5af191821561201e578592615928575b508b5190815230600482015291829060249082905afa90811561201e5761588b9360009261590b575b50506125b8565b9116036158fa57813b156102c257600080946158d696519687958694859384527f000000000000000000000000b0124f5d0e906d3652d0b58f03e315ec42a57e9a90600485016147ab565b03925af1801561201e576158e957509190565b80612ecb6158f6926104f8565b9190565b8451634614828760e11b8152600490fd5b6159219250803d1061201757612008818361050b565b3880615884565b80612ecb615935926104f8565b3861585b565b615953919350843d861161201757612008818361050b565b913861581c565b9391600161596c8498959398516129c4565b61597581611997565b14615983575b505050509190565b8251820151939650919350916159a590612de49081906001600160a01b031681565b6159d1611e297f00000000000000000000000000000000000000000000000000000000000f4240612a16565b95936159f981516159f46159e482613d14565b60005260f2602052604060002090565b6129d1565b8051604001516001600160a01b03938416803b156102c257604051632012ff5960e11b81526001600160a01b038516600482015230602482015260448101929092526000908290606490829084905af192831561201e5760408693615a84938796615b20575b505101516040519485809481936331a9108f60e11b8352600483019190602083019252565b0392165afa92831561201e57600093615b01575b505030911603615aef57615acc837f000000000000000000000000b0124f5d0e906d3652d0b58f03e315ec42a57e9a614fb4565b823411615add575b3880808061597b565b615aea611f0a84346125b8565b615ad4565b60405163ab1053ff60e01b8152600490fd5b615b18929350803d10612f1257612f03818361050b565b903880615a98565b80612ecb615b2d926104f8565b38615a5f565b604051639cfe437960e01b815290819061213e90600483016103ff565b906041815114600014615b7e57615b7a916020820151906060604084015193015160001a90615cb2565b9091565b5050600090600290565b600511156103fa57565b615b9b81615b88565b80615ba35750565b615bac81615b88565b60018103615bf95760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e617475726500000000000000006044820152606490fd5b615c0281615b88565b60028103615c4f5760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e677468006044820152606490fd5b80615c5b600392615b88565b14615c6257565b60405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b6064820152608490fd5b9291907f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a08311615d225791608094939160ff602094604051948552168484015260408301526060820152600093849182805260015afa1561201e5781516001600160a01b0381161561323f579190565b50505050600090600390565b91929015615d905750815115615d42575090565b3b15615d4b5790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b825190915015615da35750805190602001fd5b60405162461bcd60e51b81526020600482015290819061213e90602483019061110456fe30644e72e131a029b85045b68181585d2833e84879b9709143e1f593f0000001b3c763e82a5af59c514ec367a2b6d3850dc8b3defac1c19a4b7fb25ef1cbd781a264697066735822122057cc093d6ca051c847f70c47465337f6297a1e4c0189b5f2f826216434f76ef064736f6c63430008170033
Verified Source Code Partial Match
Compiler: v0.8.23+commit.f704f362
EVM: paris
Optimization: Yes (200 runs)
AggregatorV3Interface.sol 20 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// solhint-disable-next-line interface-starts-with-i
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function getRoundData(
uint80 _roundId
) external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
function latestRoundData()
external
view
returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
OwnableUpgradeable.sol 95 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.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() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
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;
}
Initializable.sol 166 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @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 Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 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 functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_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 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_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() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @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 {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
AddressUpgradeable.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
ContextUpgradeable.sol 41 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
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;
}
/**
* @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[50] private __gap;
}
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
SafeERC20.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
IERC721.sol 132 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Note that the caller is responsible to confirm that the recipient is capable of receiving ERC721
* or else they may be permanently lost. Usage of {safeTransferFrom} prevents loss, though the caller must
* understand this adds an external call which potentially creates a reentrancy vulnerability.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
Address.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
StorageSlot.sol 138 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
Strings.sol 85 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(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) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
ECDSA.sol 217 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Math.sol 339 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// 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^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv 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.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 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 + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
SignedMath.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return 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 {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
Commitments.sol 150 lines
// SPDX-License-Identifier: UNLICENSED
// Based on code from MACI:
// (https://github.com/appliedzkp/maci/blob/7f36a915244a6e8f98bacfe255f8bd44193e7919/contracts/sol/IncrementalMerkleTree.sol)
pragma solidity 0.8.23;
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { SNARK_SCALAR_FIELD } from "./Globals.sol";
import { PoseidonT3 } from "./PoseidonT3.sol";
/// @title Commitments
/// @author DOP Team
/// @notice Batch Incremental Merkle Tree for commitments
/// @dev Publicly accessible functions to be put in DOPLogic. Relevant external contract calls should be in those
/// functions, not here
contract Commitments is Initializable {
/// @notice Tree zero value
bytes32 public constant ZERO_VALUE = bytes32(uint256(keccak256("DOP")) % SNARK_SCALAR_FIELD);
/// @dev Tree depth
uint256 internal constant _TREE_DEPTH = 16;
/// @notice Merkle root
bytes32 public merkleRoot;
/// @notice Next leaf index (number of inserted leaves in the current tree)
uint256 public nextLeafIndex;
/// @notice Tree number
uint256 public treeNumber;
/// @dev Store new tree root to quickly migrate to a new tree
bytes32 private _newMerkleRoot;
/// @notice Whether the contract has already seen a particular commitment nullifier
mapping(uint256 treeNumber => mapping(bytes32 nullifier => bool seen)) public nullifiers;
/// @notice The Merkle path to the leftmost leaf upon initialization. It SHOULD NOT be modified after it has been
/// set by the initialize function. Caching these values is essential to efficient appends
bytes32[_TREE_DEPTH] public zeros;
/// @dev Right-most elements at each level. Used for efficient updates of the merkle tree
bytes32[_TREE_DEPTH] private _rightMostLeafAtLevel;
/// @notice Whether the contract has already seen a particular Merkle tree root
mapping(uint256 treeNumber => mapping(bytes32 root => bool seen)) public rootHistory;
/// @notice Gets tree number that new commitments will get inserted to
/// @param newCommitments Number of new commitments
/// @return treeNumber Number of the current tree given the new commitments
/// @return startingIndex Index of the current tree given the new commitments
function getInsertionTreeNumberAndStartingIndex(uint256 newCommitments) public view returns (uint256, uint256) {
if ((nextLeafIndex + newCommitments) > (2 ** _TREE_DEPTH)) {
return (treeNumber + 1, 0);
}
return (treeNumber, nextLeafIndex);
}
/// @notice Hash 2 uint256 values
/// @param left Left side of hash
/// @param right Right side of hash
/// @return hash Poseidon processed hash
function hashLeftRight(bytes32 left, bytes32 right) public pure returns (bytes32) {
return PoseidonT3.poseidon([left, right]);
}
/// @dev Calculates initial values for Merkle Tree
function _initializeCommitments() internal onlyInitializing {
zeros[0] = ZERO_VALUE;
bytes32 currentZero = ZERO_VALUE;
for (uint256 i = 0; i < _TREE_DEPTH; ++i) {
zeros[i] = currentZero;
_rightMostLeafAtLevel[i] = currentZero;
currentZero = hashLeftRight(currentZero, currentZero);
}
_newMerkleRoot = merkleRoot = currentZero;
rootHistory[treeNumber][currentZero] = true;
}
/// @dev Calculates initial values for Merkle Tree
/// @dev Insert leaves into the current merkle tree
/// Note: This function INTENTIONALLY causes side effects to save on gas. leafHashes and count should never be
/// reused
/// @param leaves array of leaf hashes to be added to the merkle tree
function _addLeaves(bytes32[] memory leaves) internal {
uint256 leafCount = leaves.length;
if (leafCount == 0) {
return;
}
if ((nextLeafIndex + leafCount) > (2 ** _TREE_DEPTH)) {
_startNewTree();
}
uint256 insertionIndex = nextLeafIndex;
nextLeafIndex += leafCount;
uint256 nextLevelIndex;
uint256 nextLevelStartingIndex;
for (uint256 level = 0; level < _TREE_DEPTH; ++level) {
nextLevelStartingIndex = insertionIndex >> 1;
uint256 insertionElement = 0;
if (insertionIndex % 2 == 1) {
nextLevelIndex = (insertionIndex >> 1) - nextLevelStartingIndex;
leaves[nextLevelIndex] = hashLeftRight(_rightMostLeafAtLevel[level], leaves[insertionElement]);
++insertionElement;
++insertionIndex;
}
for (insertionElement; insertionElement < leafCount; insertionElement += 2) {
bytes32 right;
if (insertionElement < leafCount - 1) {
right = leaves[insertionElement + 1];
} else {
right = zeros[level];
}
if (insertionElement == leafCount - 1 || insertionElement == leafCount - 2) {
_rightMostLeafAtLevel[level] = leaves[insertionElement];
}
nextLevelIndex = (insertionIndex >> 1) - nextLevelStartingIndex;
leaves[nextLevelIndex] = hashLeftRight(leaves[insertionElement], right);
insertionIndex += 2;
}
insertionIndex = nextLevelStartingIndex;
leafCount = nextLevelIndex + 1;
}
merkleRoot = leaves[0];
rootHistory[treeNumber][merkleRoot] = true;
}
/// @dev Creates new merkle tree
function _startNewTree() internal {
merkleRoot = _newMerkleRoot;
nextLeafIndex = 0;
++treeNumber;
}
uint256[50] private _gap;
}
DOPLogic.sol 782 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { StorageSlot } from "@openzeppelin/contracts/utils/StorageSlot.sol";
import { ECDSA } from "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import { Commitments } from "./Commitments.sol";
// prettier-ignore
import {
SNARK_SCALAR_FIELD,
DecryptType,
TokenType,
ValidationType,
Balance,
Configuration,
CommitmentCiphertext,
CommitmentPreimage,
EncryptCiphertext,
EncryptRequest,
TokenData,
Transaction,
IdenticalValue,
InvalidAddress,
UnsafeVectors,
UnsupportedToken
} from "./Globals.sol";
import { ITokenBlocklist } from "./ITokenBlocklist.sol";
import { IVaultFactory, IVault } from "./IVaultFactory.sol";
import { OraclePriceFetcher } from "./OraclePriceFetcher.sol";
import { PoseidonT4 } from "./PoseidonT4.sol";
import { Verifier } from "./Verifier.sol";
/// @title DOPLogic
/// @author DOP Team
/// @notice Logic to process transactions
contract DOPLogic is Initializable, OwnableUpgradeable, Commitments, Verifier {
using SafeERC20 for IERC20;
using Address for address payable;
using ECDSA for bytes32;
using OraclePriceFetcher for AggregatorV3Interface;
/// @dev Current version of the protocol
string private constant _VERSION = "2.2.0";
/// @dev limit to the number of encrypt requests that can be initiated in a single transaction
uint256 private constant _MAX_ENCRYPT_REQUESTS = 20;
/// @dev Number of basis points that equal 100%
uint120 private constant _BASIS_POINTS = 10000;
/// @dev Maximum fee limit in basic points (BPS)
uint120 private constant _MAX_FEE_BPS = 5000;
/// @dev Encrypt fee in basis points (BPS)
uint120 private immutable _ENCRYPT_FEE_BPS;
/// @dev Decrypt fee in basis points (BPS)
uint120 private immutable _DECRYPT_FEE_BPS;
/// @dev NFT fee in fiat currency
/// NOTE: Denomination of NFT fee must be equivalent to price feed's price denomination
uint256 internal immutable _NFT_FEE_FIAT;
/// @dev Encrypt requests holding time period
uint256 private immutable _HOLDING_PERIOD;
/// @dev Treasury contract
address payable internal immutable _TREASURY;
/// @dev Vault factory contract
IVaultFactory private immutable _VAULT_FACTORY;
/// @dev Token blocklist contract
ITokenBlocklist private immutable _TOKEN_BLOCKLIST;
/// @notice Address of the native asset price feed oracle
AggregatorV3Interface internal immutable _NATIVE_ASSET_PRICE_FEED;
/// @notice Timeout in seconds to use with the price feed oracle
/// NOTE: Timeout should always be greater than the provided heartbeat
uint256 internal immutable _PRICE_FEED_TIMEOUT;
/// @notice Last event block to assist with scanning
uint256 public lastEventBlock;
/// @notice Snark safety vectors
mapping(uint256 vector => bool state) public snarkSafetyVector;
/// @notice Token ID mapping
mapping(bytes32 tokenID => TokenData tokenData) public tokenIDMapping;
/// @notice Encrypt request validatory signer
address public signer;
/// @notice Number of holdings created
uint256 public totalHoldings;
/// @dev Holdee's holding data with respect to a unique index
mapping(uint256 index => Holding holding) internal _holdings;
/// @dev Holding data structure
struct Holding {
address holdee;
IVault vault;
uint256 deadline;
EncryptRequest[] encryptRequests;
}
/// @dev Emitted when signer is changed
event SignerChanged(address newSigner, address oldSigner);
/// @dev Emitted when tokens are transferred
event Transact(uint256 treeNumber, uint256 startPosition, bytes32[] hash, CommitmentCiphertext[] ciphertext);
/// @dev Emitted when adding a snark safety vector
event VectorAdded(uint256 vector, bool state);
/// @dev Emitted when removing a snark safety vector
event VectorRemoved(uint256 vector, bool state);
/// @dev Emitted when tokens are encrypted
event Encrypt(
uint256 treeNumber,
uint256 startPosition,
CommitmentPreimage[] commitments,
EncryptCiphertext[] encryptCiphertext,
uint256[] fees
);
/// @dev Emitted when tokens are decrypted
event Decrypt(address to, TokenData token, uint256 amount, uint256 fee);
/// @dev Emitted when any commitment is nullified
event Nullified(uint16 treeNumber, bytes32[] nullifier);
/// @dev Emitted when an encrypt request is put on hold
event EncryptHeld(
uint256 indexed index,
address indexed holdee,
IVault vault,
uint256 deadline,
CommitmentPreimage[] commitments,
EncryptCiphertext[] encryptCiphertext
);
/// @dev Emitted when an approved encrypt request is finalized
event EncryptApproved(uint256 indexed index);
/// @dev Emitted when a rejected encrypt request is finalized
event EncryptRejected(uint256 indexed index);
/// @dev Emitted when an expired encrypt request is finalized
event EncryptExpired(uint256 indexed index);
error InvalidCommitment(ValidationType validationType);
error InvalidTransaction(ValidationType validationType);
error InvalidFee();
error ERC20TokenTransferFailed();
error ERC721TokenTransferFailed();
error NoteAlreadySpent();
error InvalidValue();
error InvalidIndex();
error InvalidHolder();
error HoldingNotExpired();
error EncryptRequestsOutofBounds();
error InvalidSignatureOrSigner();
/// @dev Constructor
/// @param initEncryptFee Encrypt fee
/// @param initDecryptFee Decrypt fee
/// @param initNFTFee NFT fee
/// @param initTreasury Address to send usage fees to
/// @param initVaultFactory Address that deploys vaults
/// @param initTokenBlocklist Address that checks token block status
/// @param initHoldingPeriod Encrypt request holding time period
/// @param initNativeAssetPriceFeed Address of the native asset price feed oracle
/// @param initPriceFeedTimeout Timeout in seconds to use with the price feed oracle
constructor(
uint120 initEncryptFee,
uint120 initDecryptFee,
uint256 initNFTFee,
uint256 initHoldingPeriod,
address payable initTreasury,
IVaultFactory initVaultFactory,
ITokenBlocklist initTokenBlocklist,
AggregatorV3Interface initNativeAssetPriceFeed,
uint256 initPriceFeedTimeout
) {
if (
initEncryptFee == 0 ||
initDecryptFee == 0 ||
initNFTFee == 0 ||
initHoldingPeriod == 0 ||
initPriceFeedTimeout == 0
) {
revert InvalidValue();
}
if (initEncryptFee > _MAX_FEE_BPS || initDecryptFee > _MAX_FEE_BPS) {
revert InvalidFee();
}
if (
initTreasury == address(0) ||
address(initVaultFactory) == address(0) ||
address(initTokenBlocklist) == address(0) ||
address(initNativeAssetPriceFeed) == address(0)
) {
revert InvalidAddress();
}
_ENCRYPT_FEE_BPS = initEncryptFee;
_DECRYPT_FEE_BPS = initDecryptFee;
_NFT_FEE_FIAT = initNFTFee;
_HOLDING_PERIOD = initHoldingPeriod;
_TREASURY = initTreasury;
_VAULT_FACTORY = initVaultFactory;
_TOKEN_BLOCKLIST = initTokenBlocklist;
_NATIVE_ASSET_PRICE_FEED = initNativeAssetPriceFeed;
_PRICE_FEED_TIMEOUT = initPriceFeedTimeout;
}
/// @notice Safety check for badly behaving code
function checkSafetyVectors() external {
StorageSlot.getBooleanSlot(0x8dea8703c3cf94703383ce38a9c894669dccd4ca8e65ddb43267aa0248711450).value = true;
bool result = false;
// solhint-disable-next-line no-inline-assembly
assembly {
mstore(0, caller())
mstore(32, snarkSafetyVector.slot)
let hash := keccak256(0, 64)
result := sload(hash)
}
if (!result) {
revert UnsafeVectors();
}
}
/// @notice Adds or removes a given snark safety vector, only callable by the owner, i.e. governance contract
/// @param vector Note to change state of
/// @param state New state of note
function updateVector(uint256 vector, bool state) external onlyOwner {
_updateVector(vector, state);
}
/// @notice Changes signer, only callable by the owner, i.e. governance contract
/// @param newSigner Address of the new signer
function changeSigner(address newSigner) external onlyOwner {
_changeSigner(newSigner);
}
/// @notice Finalizes an approved encrypt request
/// @param signature Signed message to determine correctness
/// @param index Unique holding index to get the encrypt requests for
function encryptApproved(bytes calldata signature, uint256 index) external payable {
(IVault vault, , EncryptRequest[] memory encryptRequests) = _validateFinalizeEncrypt(index);
_validateSignature(signature, index, true);
_encrypt(vault, encryptRequests);
emit EncryptApproved({ index: index });
}
/// @notice Finalizes a rejected encrypt request
/// @param signature Signed message to determine correctness
/// @param index Unique holding index to get the encrypt requests for
function encryptRejected(bytes calldata signature, uint256 index) external {
(IVault vault, , EncryptRequest[] memory encryptRequests) = _validateFinalizeEncrypt(index);
_validateSignature(signature, index, false);
_revertEncrypt(vault, encryptRequests);
emit EncryptRejected({ index: index });
}
/// @notice Finalizes an expired encrypt request
/// @param index Unique holding index to get the encrypt requests for
function encryptExpired(uint256 index) external {
(IVault vault, uint256 deadline, EncryptRequest[] memory encryptRequests) = _validateFinalizeEncrypt(index);
if (block.timestamp < deadline) {
revert HoldingNotExpired();
}
_revertEncrypt(vault, encryptRequests);
emit EncryptExpired({ index: index });
}
/// @notice Gets all external configuration data
/// @return configuration Data pertaining to external requirements
function configuration() external view returns (Configuration memory) {
return
Configuration({
treasury: _TREASURY,
vaultFactory: address(_VAULT_FACTORY),
tokenBlocklist: address(_TOKEN_BLOCKLIST),
encryptFeeBPS: _ENCRYPT_FEE_BPS,
decryptFeeBPS: _DECRYPT_FEE_BPS,
holdingPeriod: _HOLDING_PERIOD,
version: _VERSION
});
}
/// @notice Gets holding data from holding index
/// @param index Unique holding index
/// @return holding Holding data for the given holding index
function holdings(uint256 index) external view returns (Holding memory) {
return _holdings[index];
}
/// @notice Initialize logic contract
/// @dev OpenZeppelin initializer ensures this can only be called once. This function also calls initializers on
/// inherited contracts
/// @param owner Governance contract
/// @param initSigner Encrypt request validatory signer
function initializeDOPLogic(address owner, address initSigner) public initializer {
OwnableUpgradeable.__Ownable_init();
Commitments._initializeCommitments();
OwnableUpgradeable.transferOwnership(owner);
_updateVector(11991246288605609459798790887503763024866871101, true);
_updateVector(135932600361240492381964832893378343190771392134, true);
_updateVector(1165567609304106638376634163822860648671860889162, true);
_changeSigner(initSigner);
}
/// @notice Commits data to put an encrypt request on hold
/// @param encryptRequests List of commitments to encrypt
function initEncrypt(EncryptRequest[] memory encryptRequests) public {
uint256 length = encryptRequests.length;
if (length > _MAX_ENCRYPT_REQUESTS) {
revert EncryptRequestsOutofBounds();
}
// No concern for overflow since upper bound is 2 ^ 256 - 1 which is very unlikely to reach using this version
uint256 index = totalHoldings++;
IVault vault = _VAULT_FACTORY.createVault();
uint256 deadline = block.timestamp + _HOLDING_PERIOD;
Holding storage holding = _holdings[index];
holding.holdee = msg.sender;
holding.vault = vault;
holding.deadline = deadline;
CommitmentPreimage[] memory commitments = new CommitmentPreimage[](length);
EncryptCiphertext[] memory encryptCiphertext = new EncryptCiphertext[](length);
for (uint256 notesIter = 0; notesIter < length; ++notesIter) {
EncryptRequest memory encryptRequest = encryptRequests[notesIter];
holding.encryptRequests.push(encryptRequest);
CommitmentPreimage memory note = encryptRequest.preimage;
commitments[notesIter] = note;
encryptCiphertext[notesIter] = encryptRequest.ciphertext;
if (note.token.tokenType == TokenType.ERC20) {
IERC20 token = IERC20(address(uint160(note.token.tokenAddress)));
token.safeTransferFrom(address(msg.sender), address(vault), note.value);
} else if (note.token.tokenType == TokenType.ERC721) {
IERC721 token = IERC721(address(uint160(note.token.tokenAddress)));
token.transferFrom(address(msg.sender), address(vault), note.token.tokenSubID);
} else {
revert UnsupportedToken();
}
}
emit EncryptHeld({
index: index,
holdee: msg.sender,
vault: vault,
deadline: deadline,
commitments: commitments,
encryptCiphertext: encryptCiphertext
});
}
/// @notice Checks commitment ranges for validity
/// @param note Note to validate
/// @return validationType Whether the data is valid or not and if invalid, corresponds to a validation error
function validateCommitmentPreimage(CommitmentPreimage memory note) public view returns (ValidationType) {
if (note.value == 0) {
return ValidationType.INVALID_NOTE_VALUE;
}
if (_TOKEN_BLOCKLIST.tokenBlocklist(IERC20(note.token.tokenAddress))) {
return ValidationType.UNSUPPORTED_TOKEN;
}
if (uint256(note.npk) >= SNARK_SCALAR_FIELD) {
return ValidationType.INVALID_NOTE_NPK;
}
if (note.token.tokenType == TokenType.ERC721 && note.value != 1) {
return ValidationType.INVALID_NFT_NOTE_VALUE;
}
return ValidationType.SUCCESS;
}
/// @notice Verifies transaction validity
/// @param transaction Transaction batch
/// @return validationType Whether the data is valid or not and if invalid, corresponds to a validation error
function validateTransaction(Transaction calldata transaction) public view returns (ValidationType) {
if (tx.gasprice < transaction.boundParams.minGasPrice) {
return ValidationType.GAS_PRICE_TOO_LOW;
}
if (
transaction.boundParams.adaptContract != address(0) && transaction.boundParams.adaptContract != msg.sender
) {
return ValidationType.INVALID_ADAPT_CONTRACT_AS_SENDER;
}
if (transaction.boundParams.chainID != block.chainid) {
return ValidationType.CHAINID_MISMATCH;
}
if (!Commitments.rootHistory[transaction.boundParams.treeNumber][transaction.merkleRoot]) {
return ValidationType.INVALID_MERKLE_ROOT;
}
if (transaction.boundParams.decrypt != DecryptType.NONE) {
// Ensure ciphertext length matches the commitments length (minus 1 for decrypt output)
if (transaction.boundParams.commitmentCiphertext.length != transaction.commitments.length - 1) {
return ValidationType.INVALID_NOTE_CIPHERTEXT_ARRAY_LENGTH;
}
bytes32 hash;
if (transaction.boundParams.decrypt == DecryptType.REDIRECT) {
hash = hashCommitment(
CommitmentPreimage({
npk: bytes32(uint256(uint160(msg.sender))),
token: transaction.decryptPreimage.token,
value: transaction.decryptPreimage.value
})
);
} else {
hash = hashCommitment(transaction.decryptPreimage);
}
if (hash != transaction.commitments[transaction.commitments.length - 1]) {
return ValidationType.INVALID_WITHDRAW_NOTE;
}
} else {
if (transaction.boundParams.commitmentCiphertext.length != transaction.commitments.length) {
return ValidationType.INVALID_NOTE_CIPHERTEXT_ARRAY_LENGTH;
}
}
if (!Verifier.verify(transaction)) {
return ValidationType.INVALID_SNARK_PROOF;
}
return ValidationType.SUCCESS;
}
/// @notice Verifies balance validity
/// @param balance Transaction with balance
/// @return validationType Whether the data is valid or not and if invalid, corresponds to a validation error
function validateBalance(Balance calldata balance) public view returns (ValidationType) {
if (tx.gasprice < balance.boundParams.minGasPrice) {
return ValidationType.GAS_PRICE_TOO_LOW;
}
if (balance.boundParams.adaptContract != address(0) && balance.boundParams.adaptContract != msg.sender) {
return ValidationType.INVALID_ADAPT_CONTRACT_AS_SENDER;
}
if (balance.boundParams.chainID != block.chainid) {
return ValidationType.CHAINID_MISMATCH;
}
if (!Commitments.rootHistory[balance.boundParams.treeNumber][balance.merkleRoot]) {
return ValidationType.INVALID_MERKLE_ROOT;
}
uint256 nullifierCount = balance.nullifiers.length;
if (nullifierCount == 0) {
return ValidationType.INVALID_NULLIFIER_COUNT;
}
for (uint256 nullifierIter = 0; nullifierIter < nullifierCount; ++nullifierIter) {
if (Commitments.nullifiers[balance.boundParams.treeNumber][balance.nullifiers[nullifierIter]]) {
return ValidationType.NOTE_ALREADY_SPENT;
}
}
if (!Verifier.verifyBalance(balance)) {
return ValidationType.INVALID_SNARK_PROOF;
}
return ValidationType.SUCCESS;
}
/// @notice Get base and fee amount
/// @param amount Amount to calculate for
/// @param feeBP Fee basis points
/// @return base Base amount to be transferred
/// @return fee Fee to be collected
function getFee(uint136 amount, uint128 feeBP) public pure returns (uint120, uint120) {
uint136 base = amount - (amount * feeBP) / _BASIS_POINTS;
uint136 fee = amount - base;
return (uint120(base), uint120(fee));
}
/// @notice Hashes a commitment
/// @param note Note to hash
/// @return hashedNote Poseidon processed note
function hashCommitment(CommitmentPreimage memory note) public pure returns (bytes32) {
return PoseidonT4.poseidon([note.npk, getTokenID(note.token), bytes32(uint256(note.value))]);
}
/// @notice Sums number commitments in transaction batch
/// @param transactions Transaction batch
/// @return commitments Number of valid commitments
function sumCommitments(Transaction[] calldata transactions) public pure returns (uint256) {
uint256 length = transactions.length;
uint256 commitments = 0;
for (uint256 transactionIter = 0; transactionIter < length; ++transactionIter) {
commitments += transactions[transactionIter].boundParams.commitmentCiphertext.length;
}
return commitments;
}
/// @dev Validates data related to finalizing an encrypt request
/// @param index Holding index of the relevant holding
/// @return vault Token holding vault
/// @return encryptionRequests List of commitments to encrypt
function _validateFinalizeEncrypt(uint256 index) internal returns (IVault, uint256, EncryptRequest[] memory) {
if (index >= totalHoldings) {
revert InvalidIndex();
}
Holding memory holding = _holdings[index];
delete _holdings[index];
if (msg.sender != holding.holdee) {
revert InvalidHolder();
}
return (holding.vault, holding.deadline, holding.encryptRequests);
}
/// @dev Processes funds in the case of a rejected or expired encryption request
/// @param vault Token holding vault
/// @param encryptRequests List of commitments to encrypt
function _revertEncrypt(IVault vault, EncryptRequest[] memory encryptRequests) internal {
uint256 length = encryptRequests.length;
for (uint256 notesIter = 0; notesIter < length; ++notesIter) {
CommitmentPreimage memory note = encryptRequests[notesIter].preimage;
if (note.token.tokenType == TokenType.ERC20) {
IERC20 token = IERC20(address(uint160(note.token.tokenAddress)));
vault.withdrawERC20(token, msg.sender, note.value);
} else if (note.token.tokenType == TokenType.ERC721) {
IERC721 token = IERC721(address(uint160(note.token.tokenAddress)));
vault.withdrawERC721(token, msg.sender, note.token.tokenSubID);
}
}
}
/// @dev Encrypts requested amount and token, creates a commitment hash from supplied values and adds to tree
/// @param vault Token holding vault
/// @param encryptRequests List of commitments to encrypt
function _encrypt(IVault vault, EncryptRequest[] memory encryptRequests) internal {
uint256 length = encryptRequests.length;
bytes32[] memory insertionLeaves = new bytes32[](length);
CommitmentPreimage[] memory commitments = new CommitmentPreimage[](length);
EncryptCiphertext[] memory encryptCiphertext = new EncryptCiphertext[](length);
uint256[] memory fees = new uint256[](length);
for (uint256 notesIter = 0; notesIter < length; ++notesIter) {
(commitments[notesIter], fees[notesIter]) = _processEncrypt(vault, encryptRequests[notesIter].preimage);
insertionLeaves[notesIter] = hashCommitment(commitments[notesIter]);
encryptCiphertext[notesIter] = encryptRequests[notesIter].ciphertext;
}
emit Encrypt({
treeNumber: treeNumber,
startPosition: nextLeafIndex,
commitments: commitments,
encryptCiphertext: encryptCiphertext,
fees: fees
});
_addLeaves(insertionLeaves);
lastEventBlock = block.number;
}
/// @dev Transfers tokens to contract and adjusts preimage with fee values
/// @param vault Token holding vault
/// @param note Note to process
/// @return adjustedNote Note with amount excluded of fees
/// @return fee Platform fee for the transaction
function _processEncrypt(
IVault vault,
CommitmentPreimage memory note
) internal returns (CommitmentPreimage memory, uint256) {
ValidationType valid = validateCommitmentPreimage(note);
if (valid != ValidationType.SUCCESS) {
revert InvalidCommitment(valid);
}
CommitmentPreimage memory adjustedNote;
uint256 treasuryFee;
if (note.token.tokenType == TokenType.ERC20) {
IERC20 token = IERC20(address(uint160(note.token.tokenAddress)));
(uint120 base, uint120 fee) = getFee(note.value, _ENCRYPT_FEE_BPS);
treasuryFee = fee;
adjustedNote = CommitmentPreimage({ npk: note.npk, value: base, token: note.token });
uint256 balanceBefore = token.balanceOf(address(this));
vault.withdrawERC20(token, address(this), base);
uint256 balanceAfter = token.balanceOf(address(this));
if (balanceAfter - balanceBefore != base) {
revert ERC20TokenTransferFailed();
}
vault.withdrawERC20(token, _TREASURY, fee);
} else if (note.token.tokenType == TokenType.ERC721) {
IERC721 token = IERC721(address(uint160(note.token.tokenAddress)));
treasuryFee = (_NFT_FEE_FIAT * 1e18) / _NATIVE_ASSET_PRICE_FEED.getOraclePrice(_PRICE_FEED_TIMEOUT);
adjustedNote = note;
tokenIDMapping[getTokenID(note.token)] = note.token;
vault.withdrawERC721(token, address(this), note.token.tokenSubID);
if (token.ownerOf(note.token.tokenSubID) != address(this)) {
revert ERC721TokenTransferFailed();
}
_TREASURY.sendValue(treasuryFee);
if (msg.value > treasuryFee) {
payable(msg.sender).sendValue(msg.value - treasuryFee);
}
}
return (adjustedNote, treasuryFee);
}
/// @dev Accumulates transaction fields and nullifies nullifiers
/// @param transaction Transaction to process
/// @param commitments Commitments accumulator
/// @param commitmentsStartOffset Number of commitments already in the accumulator
/// @param ciphertext Commitment ciphertext accumulator, count will be identical to commitments accumulator
/// @return newCommitmentsStartOffset New commitments start offset to be saved in the accumulator
function _processTransfer(
Transaction calldata transaction,
bytes32[] memory commitments,
uint256 commitmentsStartOffset,
CommitmentCiphertext[] memory ciphertext
) internal returns (uint256) {
uint256 nullifierCount = transaction.nullifiers.length;
for (uint256 nullifierIter = 0; nullifierIter < nullifierCount; ++nullifierIter) {
if (Commitments.nullifiers[transaction.boundParams.treeNumber][transaction.nullifiers[nullifierIter]]) {
revert NoteAlreadySpent();
}
Commitments.nullifiers[transaction.boundParams.treeNumber][transaction.nullifiers[nullifierIter]] = true;
}
emit Nullified({ treeNumber: transaction.boundParams.treeNumber, nullifier: transaction.nullifiers });
uint256 commitmentCount = transaction.boundParams.commitmentCiphertext.length;
for (uint256 commitmentsIter = 0; commitmentsIter < commitmentCount; ++commitmentsIter) {
commitments[commitmentsStartOffset + commitmentsIter] = transaction.commitments[commitmentsIter];
ciphertext[commitmentsStartOffset + commitmentsIter] = transaction.boundParams.commitmentCiphertext[
commitmentsIter
];
}
return commitmentsStartOffset + commitmentCount;
}
/// @dev Transfers tokens to contract and adjusts preimage with fee values
/// @param note Note to process
function _processDecrypt(CommitmentPreimage calldata note) internal {
address recipient = address(uint160(uint256(note.npk)));
if (note.token.tokenType == TokenType.ERC20) {
IERC20 token = IERC20(address(uint160(note.token.tokenAddress)));
uint120 base;
uint120 fee;
if (recipient == _TREASURY) {
(base, fee) = (0, note.value);
} else {
(base, fee) = getFee(note.value, _DECRYPT_FEE_BPS);
token.safeTransfer(recipient, base);
}
token.safeTransfer(_TREASURY, fee);
emit Decrypt({ to: recipient, token: note.token, amount: base, fee: fee });
} else if (note.token.tokenType == TokenType.ERC721) {
IERC721 token = IERC721(address(uint160(note.token.tokenAddress)));
token.transferFrom(address(this), recipient, note.token.tokenSubID);
emit Decrypt({ to: recipient, token: note.token, amount: 1, fee: 0 });
} else {
revert UnsupportedToken();
}
}
/// @dev Validates an ECDSA signature
/// @param signature Signed message to determine correctness
/// @param index Unique holding index
/// @param approved Whether or not the holding is approved or rejected
function _validateSignature(bytes calldata signature, uint256 index, bool approved) internal view {
bytes32 hash = keccak256(abi.encodePacked(msg.sender, index, approved)).toEthSignedMessageHash();
if (signer != hash.recover(signature)) {
revert InvalidSignatureOrSigner();
}
}
function _updateVector(uint256 vector, bool state) private {
if (state) {
emit VectorAdded({ vector: vector, state: state });
} else {
emit VectorRemoved({ vector: vector, state: state });
}
snarkSafetyVector[vector] = state;
}
/// @dev Logic for changing signer
/// @param newSigner Address of the new signer
function _changeSigner(address newSigner) private {
if (newSigner == address(0)) {
revert InvalidAddress();
}
if (signer == newSigner) {
revert IdenticalValue();
}
emit SignerChanged({ newSigner: newSigner, oldSigner: signer });
signer = newSigner;
}
uint256[50] private _gap;
}
DOPSmartWallet.sol 176 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { INativeAssetWrapper } from "../relayer/INativeAssetWrapper.sol";
import { DOPLogic, ITokenBlocklist, IVaultFactory } from "./DOPLogic.sol";
// prettier-ignore
import {
DecryptType,
TokenType,
ValidationType,
Balance,
CommitmentCiphertext,
Transaction,
InvalidAddress
} from "./Globals.sol";
import { OraclePriceFetcher } from "./OraclePriceFetcher.sol";
/// @title DOPSmartWallet
/// @author DOP Team
/// @notice DOP private smart wallet
/// @dev Entry point for processing private meta-transactions
contract DOPSmartWallet is DOPLogic {
using Address for address payable;
using OraclePriceFetcher for AggregatorV3Interface;
INativeAssetWrapper private immutable _nativeWrapper;
enum FeeType {
NONE,
EXTERNAL,
INTERNAL
}
error InvalidTransactionData();
error InvalidFeeDecrypt();
error InsufficientFee();
/// @dev Constructor
/// @param initEncryptFee Encrypt fee
/// @param initDecryptFee Decrypt fee
/// @param initNFTFee NFT fee
/// @param initTreasury Address to send usage fees to
/// @param initVaultFactory Address that deploys vaults
/// @param initTokenBlocklist Address that checks token block status
/// @param initHoldingPeriod Encrypt request holding time period
/// @param initNativeAssetPriceFeed Address of the native asset price feed oracle
/// @param initPriceFeedTimeout Timeout in seconds to use with the price feed oracle
constructor(
uint120 initEncryptFee,
uint120 initDecryptFee,
uint256 initNFTFee,
uint256 initHoldingPeriod,
address payable initTreasury,
IVaultFactory initVaultFactory,
ITokenBlocklist initTokenBlocklist,
AggregatorV3Interface initNativeAssetPriceFeed,
uint256 initPriceFeedTimeout,
INativeAssetWrapper initNativeWrapper
)
DOPLogic(
initEncryptFee,
initDecryptFee,
initNFTFee,
initHoldingPeriod,
initTreasury,
initVaultFactory,
initTokenBlocklist,
initNativeAssetPriceFeed,
initPriceFeedTimeout
)
{
if (address(initNativeWrapper) == address(0)) {
revert InvalidAddress();
}
_nativeWrapper = initNativeWrapper;
}
/// @notice Execute batch of DOP snark transactions
/// @param transactions Transactions batch
function transact(Transaction[] calldata transactions) external payable {
uint256 transferCount = transactions.length;
if (transferCount == 0) {
revert InvalidTransactionData();
}
uint256 commitmentsCount = sumCommitments(transactions);
bytes32[] memory commitments = new bytes32[](commitmentsCount);
uint256 commitmentsStartOffset = 0;
CommitmentCiphertext[] memory ciphertext = new CommitmentCiphertext[](commitmentsCount);
for (uint256 transactionIter = 0; transactionIter < transferCount; ++transactionIter) {
ValidationType valid = validateTransaction(transactions[transactionIter]);
if (valid != ValidationType.SUCCESS) {
revert InvalidTransaction(valid);
}
commitmentsStartOffset = _processTransfer(
transactions[transactionIter],
commitments,
commitmentsStartOffset,
ciphertext
);
}
uint256 treasuryBalance = _nativeWrapper.balanceOf(_TREASURY);
uint256 nftDecryptCount = 0;
for (uint256 transactionIter = 0; transactionIter < transferCount; ++transactionIter) {
if (transactions[transactionIter].boundParams.decrypt != DecryptType.NONE) {
if (transactions[transactionIter].decryptPreimage.token.tokenType == TokenType.ERC721) {
nftDecryptCount++;
}
_processDecrypt(transactions[transactionIter].decryptPreimage);
}
}
FeeType nftFeeType = nftDecryptCount > 0
? msg.value > 0
? FeeType.EXTERNAL
: FeeType.INTERNAL
: FeeType.NONE;
if (nftFeeType == FeeType.EXTERNAL) {
uint256 treasuryFee = (_NFT_FEE_FIAT * nftDecryptCount * 1e18) /
_NATIVE_ASSET_PRICE_FEED.getOraclePrice(_PRICE_FEED_TIMEOUT);
if (msg.value < treasuryFee) {
revert InsufficientFee();
}
_TREASURY.sendValue(treasuryFee);
if (msg.value > treasuryFee) {
payable(msg.sender).sendValue(msg.value - treasuryFee);
}
} else if (nftFeeType == FeeType.INTERNAL) {
uint256 treasuryFee = (_NFT_FEE_FIAT * nftDecryptCount * 1e18) /
_NATIVE_ASSET_PRICE_FEED.getOraclePrice(_PRICE_FEED_TIMEOUT);
if (_nativeWrapper.balanceOf(_TREASURY) < treasuryBalance + treasuryFee) {
revert InsufficientFee();
}
}
(uint256 insertionTreeNumber, uint256 insertionStartIndex) = getInsertionTreeNumberAndStartingIndex(
commitments.length
);
if (commitments.length > 0) {
emit Transact({
treeNumber: insertionTreeNumber,
startPosition: insertionStartIndex,
hash: commitments,
ciphertext: ciphertext
});
}
_addLeaves(commitments);
lastEventBlock = block.number;
}
function checkBalance(Balance calldata balance) external view returns (ValidationType) {
return validateBalance(balance);
}
}
Globals.sol 153 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
bytes32 constant ACCEPT_DOP_RESPONSE = keccak256(abi.encodePacked("Accept DOP Session"));
uint256 constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
/// @dev Verification bypass address, can't be address(0) as many burn prevention mechanisms will disallow transfers to
/// address(0). Use 0x000000000000000000000000000000000000dEaD as an alternative known burn address
/// (https://etherscan.io/address/0x000000000000000000000000000000000000dEaD)
address constant VERIFICATION_BYPASS = 0x000000000000000000000000000000000000dEaD;
enum DecryptType {
NONE,
NORMAL,
REDIRECT
}
enum TokenType {
ERC20,
ERC721
}
enum ValidationType {
SUCCESS,
INVALID_NOTE_VALUE,
UNSUPPORTED_TOKEN,
INVALID_NOTE_NPK,
INVALID_NFT_NOTE_VALUE,
GAS_PRICE_TOO_LOW,
INVALID_ADAPT_CONTRACT_AS_SENDER,
CHAINID_MISMATCH,
INVALID_MERKLE_ROOT,
INVALID_NOTE_CIPHERTEXT_ARRAY_LENGTH,
INVALID_WITHDRAW_NOTE,
INVALID_SNARK_PROOF,
INVALID_NULLIFIER_COUNT,
NOTE_ALREADY_SPENT
}
struct Balance {
SnarkProof proof;
bytes32 merkleRoot;
bytes32[] nullifiers;
BoundParams boundParams;
uint256 valueCheck;
TokenData token;
}
struct BoundParams {
uint16 treeNumber;
// Only for type 0 transactions
uint72 minGasPrice;
DecryptType decrypt;
uint64 chainID;
address adaptContract;
bytes32 adaptParams;
// For decrypts do not include an element in ciphertext array
// NOTE: Ciphertext array length = commitments decrypts
CommitmentCiphertext[] commitmentCiphertext;
}
struct Configuration {
address treasury;
address vaultFactory;
address tokenBlocklist;
uint120 encryptFeeBPS;
uint120 decryptFeeBPS;
uint256 holdingPeriod;
string version;
}
struct CommitmentCiphertext {
// Ciphertext order: IV & tag (16 bytes each), encodedMPK (senderMPK XOR receiverMPK), random & amount (16 bytes
// each), token
bytes32[4] ciphertext;
bytes32 blindedSenderViewingKey;
bytes32 blindedReceiverViewingKey;
// Only for sender to decrypt
bytes annotationData;
// Added to note ciphertext for decryption
bytes memo;
}
struct CommitmentPreimage {
// Poseidon(Poseidon(spending public key, nullifying key), random)
bytes32 npk;
// Token field
TokenData token;
uint120 value;
}
struct EncryptCiphertext {
// IV shared, tag, random & IV sender (16 bytes each), receiver viewing public key (32 bytes)
bytes32[3] encryptedBundle;
// Public key to generate shared key from
bytes32 encryptKey;
}
struct EncryptRequest {
CommitmentPreimage preimage;
EncryptCiphertext ciphertext;
}
struct G1Point {
uint256 x;
uint256 y;
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint256[2] x;
uint256[2] y;
}
struct SnarkProof {
G1Point a;
G2Point b;
G1Point c;
}
struct TokenData {
TokenType tokenType;
address tokenAddress;
uint256 tokenSubID;
}
struct Transaction {
SnarkProof proof;
bytes32 merkleRoot;
bytes32[] nullifiers;
bytes32[] commitments;
BoundParams boundParams;
CommitmentPreimage decryptPreimage;
}
struct VerifyingKey {
string artifactsIPFSHash;
G1Point alpha1;
G2Point beta2;
G2Point gamma2;
G2Point delta2;
G1Point[] ic;
}
error AccessDenied();
error ETHTransferFailed();
error IdenticalValue();
error InvalidAddress();
error InvalidFeeAmount();
error UnsafeVectors();
error UnsupportedToken();
ITokenBlocklist.sol 18 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ITokenBlocklist
/// @author DOP Team
/// @notice Interface for blocklist of tokens that are incompatible with the protocol
/// @dev Tokens on this blocklist can't be encrypted to dop. Tokens on this blocklist will still be transferrable
/// internally (as internal transactions have a encrypted token ID) and decryptable (to prevent user funds from being
/// locked)
interface ITokenBlocklist {
/// @notice Gives whether the given token is in the blocklist or not
/// @param token Token to check for
/// @return blocked Whether the given token is blocked or not
function tokenBlocklist(IERC20 token) external view returns (bool);
}
IVault.sol 23 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC721 } from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
/// @title IVault
/// @author DOP Team
/// @notice Interface for token holdings vault
interface IVault {
/// @notice Withdraws ERC20 tokens, only callable by the creator
/// @param token Address of the ERC20 token
/// @param to Address of the recipient
/// @param value Amount of tokens to transfer
function withdrawERC20(IERC20 token, address to, uint256 value) external;
/// @notice Withdraws a ERC721 token, only callable by the creator
/// @param token Address of the ERC721 token
/// @param to Address of the recipient
/// @param tokenID Token ID of the token to transfer
function withdrawERC721(IERC721 token, address to, uint256 tokenID) external;
}
IVaultFactory.sol 15 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
import { IVault } from "./IVault.sol";
/// @title IVaultFactory
/// @author DOP Team
/// @notice Interface for vault creation factory
interface IVaultFactory {
/// @notice Creates a new vault via cloning the implemetation corresponding to the caller. Creates a new
/// implementation for each unique caller
/// @return vault Address of the newly created vault
function createVault() external returns (IVault);
}
OraclePriceFetcher.sol 53 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
import { AggregatorV3Interface } from "@chainlink/contracts/src/v0.8/shared/interfaces/AggregatorV3Interface.sol";
/// @title OraclePriceFetcher
/// @author DOP Team
/// @notice Off chain oracle price fetcher
library OraclePriceFetcher {
struct PriceFeedResponse {
/// @custom:member Status of the retrieved data
bool success;
/// @custom:member ID from the aggregator for which the data was retrieved combined with a phase to ensure that
/// round IDs get larger as time moves forward
uint80 roundId;
/// @custom:member Price in the given round
int256 answer;
/// @custom:member Timestamp when the round was started
uint256 updatedAt;
}
/// @notice Performs necessary checks and returns the `price` from the price aggregator
/// @param priceFeed Address of the native asset price feed oracle
/// @param timeout Timeout in seconds to use with the price feed oracle
/// @return price Retrieved price from the price aggregator
function getOraclePrice(AggregatorV3Interface priceFeed, uint256 timeout) internal view returns (uint256) {
PriceFeedResponse memory response;
try priceFeed.latestRoundData() returns (uint80 roundId, int256 answer, uint256, uint256 updatedAt, uint80) {
response.success = true;
response.roundId = roundId;
response.answer = answer;
response.updatedAt = updatedAt;
} catch {}
uint256 price;
if (
response.success == true &&
response.roundId != 0 &&
response.answer >= 0 &&
response.updatedAt != 0 &&
response.updatedAt <= block.timestamp
) {
if (block.timestamp - response.updatedAt <= timeout) {
price = uint256(response.answer);
}
}
return price;
}
}
PoseidonT3.sol 10 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
/// NOTE: Functions here are stubs for the solidity compiler to generate the right interface. The deployed library is
/// generated bytecode from the circomlib toolchain
library PoseidonT3 {
function poseidon(bytes32[2] memory input) public pure returns (bytes32) {}
}
PoseidonT4.sol 10 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
/// NOTE: Functions here are stubs for the solidity compiler to generate the right interface. The deployed library is
/// generated bytecode from the circomlib toolchain
library PoseidonT4 {
function poseidon(bytes32[3] memory input) public pure returns (bytes32) {}
}
Snark.sol 167 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
import { SNARK_SCALAR_FIELD, G1Point, G2Point, SnarkProof, VerifyingKey } from "./Globals.sol";
library Snark {
uint256 private constant _PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 private constant _PAIRING_INPUT_SIZE = 24;
uint256 private constant _PAIRING_INPUT_WIDTH = 768; // _PAIRING_INPUT_SIZE * 32
error InvalidAddition();
error InvalidInput();
error InvalidMultiplication();
error InvalidNegation();
error InvalidPairing();
/// @notice Adds 2 G1 points
/// @return result
function add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory) {
uint256[4] memory input;
input[0] = p1.x;
input[1] = p1.y;
input[2] = p2.x;
input[3] = p2.y;
bool success;
G1Point memory result;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(sub(gas(), 2000), 6, input, 0x80, result, 0x40)
}
if (!success) {
revert InvalidAddition();
}
return result;
}
/// @notice Scalar multiplies two G1 points p, s
/// @dev The product of a point on G1 and a scalar, i.e. p == p.scalar_mul(1) and p.plus(p) == p.scalar_mul(2) for
/// all points p
/// @return r Result
function scalarMul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) {
uint256[3] memory input;
input[0] = p.x;
input[1] = p.y;
input[2] = s;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(sub(gas(), 2000), 7, input, 0x60, r, 0x40)
}
if (!success) {
revert InvalidMultiplication();
}
}
/// @notice Performs pairing check on points
/// @dev The result of computing the pairing check e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1. For example,
/// pairing([P1(), P1().negate()], [P2(), P2()]) should return true
/// @return pairing Whether the pairing check passed
function pairing(
G1Point memory a1,
G2Point memory a2,
G1Point memory b1,
G2Point memory b2,
G1Point memory c1,
G2Point memory c2,
G1Point memory d1,
G2Point memory d2
) internal view returns (bool) {
uint256[_PAIRING_INPUT_SIZE] memory input = [
a1.x,
a1.y,
a2.x[0],
a2.x[1],
a2.y[0],
a2.y[1],
b1.x,
b1.y,
b2.x[0],
b2.x[1],
b2.y[0],
b2.y[1],
c1.x,
c1.y,
c2.x[0],
c2.x[1],
c2.y[0],
c2.y[1],
d1.x,
d1.y,
d2.x[0],
d2.x[1],
d2.y[0],
d2.y[1]
];
uint256[1] memory out;
bool success;
// solhint-disable-next-line no-inline-assembly
assembly {
success := staticcall(sub(gas(), 2000), 8, input, _PAIRING_INPUT_WIDTH, out, 0x20)
}
if (!success) {
revert InvalidPairing();
}
return out[0] != 0;
}
/// @notice Verifies snark proof against proving key
/// @param vk Verification Key
/// @param proof Snark proof
/// @param inputs Inputs
/// @return pairing Whether the pairing check passed
function verify(
VerifyingKey memory vk,
SnarkProof memory proof,
uint256[] memory inputs
) internal view returns (bool) {
G1Point memory vkX = G1Point(0, 0);
uint256 length = inputs.length;
for (uint256 i = 0; i < length; ++i) {
if (inputs[i] >= SNARK_SCALAR_FIELD) {
revert InvalidInput();
}
vkX = add(vkX, scalarMul(vk.ic[i + 1], inputs[i]));
}
vkX = add(vkX, vk.ic[0]);
return pairing(negate(proof.a), proof.b, vk.alpha1, vk.beta2, vkX, vk.gamma2, proof.c, vk.delta2);
}
/// @notice Computes the negation of point p
/// @dev The negation of p, i.e. p.plus(p.negate()) should be zero
/// @param p Point p
/// @return result Negation of point p
function negate(G1Point memory p) internal pure returns (G1Point memory) {
if (p.x == 0 && p.y == 0) {
return G1Point(0, 0);
}
// check for valid points y^2 = x^3 +3 % _PRIME_Q
uint256 rh = mulmod(p.x, p.x, _PRIME_Q); // x^2
rh = mulmod(rh, p.x, _PRIME_Q); // x^3
rh = addmod(rh, 3, _PRIME_Q); // x^3 + 3
uint256 lh = mulmod(p.y, p.y, _PRIME_Q); // y^2
if (lh != rh) {
revert InvalidNegation();
}
return G1Point(p.x, _PRIME_Q - (p.y % _PRIME_Q));
}
}
Verifier.sol 163 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
// prettier-ignore
import {
SNARK_SCALAR_FIELD,
VERIFICATION_BYPASS,
TokenType,
Balance,
BoundParams,
SnarkProof,
TokenData,
Transaction,
VerifyingKey
} from "./Globals.sol";
import { Snark } from "./Snark.sol";
/// @title Verifier
/// @author DOP Team
/// @notice Verifies snark proof
/// @dev Functions in this contract statelessly verify proofs, nullifiers and adaptID should be checked in DOPLogic
contract Verifier is OwnableUpgradeable {
/// @dev Verification keys
mapping(uint256 nullifier => mapping(uint256 commitment => VerifyingKey verificationKey)) private _verificationKeys;
/// @dev Emitted when verification key is set for given number of commitments and nullifiers
event VerifyingKeySet(uint256 nullifiers, uint256 commitments, VerifyingKey verifyingKey);
error KeyNotSet();
/// @notice Sets verification key
/// @param nullifiers Number of nullifiers this verification key is for
/// @param commitments Number of commitments out this verification key is for
/// @param verifyingKey VerifyingKey to set
function setVerificationKey(
uint256 nullifiers,
uint256 commitments,
VerifyingKey calldata verifyingKey
) external onlyOwner {
_verificationKeys[nullifiers][commitments] = verifyingKey;
emit VerifyingKeySet({ nullifiers: nullifiers, commitments: commitments, verifyingKey: verifyingKey });
}
/// @notice Gets verification key
/// @param nullifiers Number of nullifiers this verification key is for
/// @param commitments nNumber of commitments out this verification key is for
function getVerificationKey(uint256 nullifiers, uint256 commitments) external view returns (VerifyingKey memory) {
return _verificationKeys[nullifiers][commitments];
}
/// @notice Verifies proof
/// @param transaction Transaction to verify
/// @return validity Vailidity of balance proof
function verify(Transaction calldata transaction) public view returns (bool) {
uint256 nullifierCount = transaction.nullifiers.length;
uint256 commitmentCount = transaction.commitments.length;
VerifyingKey memory verifyingKey = _verificationKeys[nullifierCount][commitmentCount];
if (verifyingKey.alpha1.x == 0) {
revert KeyNotSet();
}
uint256[] memory inputs = new uint256[](nullifierCount + commitmentCount + 2);
inputs[0] = uint256(transaction.merkleRoot);
inputs[1] = hashBoundParams(transaction.boundParams);
for (uint256 i = 0; i < nullifierCount; ++i) {
inputs[2 + i] = uint256(transaction.nullifiers[i]);
}
for (uint256 i = 0; i < commitmentCount; ++i) {
inputs[2 + nullifierCount + i] = uint256(transaction.commitments[i]);
}
bool validity = verifyProof(verifyingKey, transaction.proof, inputs);
// solhint-disable-next-line avoid-tx-origin
if (tx.origin == VERIFICATION_BYPASS) {
return true;
}
return validity;
}
/// @notice Verifies balance proof
/// @param balance Balance to verify
/// @return validity Vailidity of balance proof
function verifyBalance(Balance calldata balance) public view returns (bool) {
uint256 nullifierCount = balance.nullifiers.length;
VerifyingKey memory verifyingKey = _verificationKeys[nullifierCount][0];
if (verifyingKey.alpha1.x == 0) {
revert KeyNotSet();
}
uint256[] memory inputs = new uint256[](nullifierCount + 4);
inputs[0] = uint256(balance.merkleRoot);
inputs[1] = hashBoundParams(balance.boundParams);
for (uint256 i = 0; i < nullifierCount; ++i) {
inputs[2 + i] = uint256(balance.nullifiers[i]);
}
inputs[2 + nullifierCount] = balance.valueCheck;
inputs[3 + nullifierCount] = uint256(getTokenID(balance.token));
bool validity = verifyProof(verifyingKey, balance.proof, inputs);
// solhint-disable-next-line avoid-tx-origin
if (tx.origin == VERIFICATION_BYPASS) {
return true;
}
return validity;
}
/// @notice Verifies inputs against a verification key
/// @param verifyingKey Verifying key to verify with
/// @param proof Proof to verify
/// @param inputs Input to verify
/// @return validity Vailidity of balance proof
function verifyProof(
VerifyingKey memory verifyingKey,
SnarkProof calldata proof,
uint256[] memory inputs
) public view returns (bool) {
return Snark.verify(verifyingKey, proof, inputs);
}
/// @notice Calculates hash of transaction bound params for snark verification
/// @param boundParams Bound parameters
/// @return bound Bound parameters hash
function hashBoundParams(BoundParams memory boundParams) public pure returns (uint256) {
return uint256(keccak256(abi.encode(boundParams))) % SNARK_SCALAR_FIELD;
}
/// @notice Gets token ID from token data
/// @param tokenData Token data
/// @return tokenID Token ID for the given token
function getTokenID(TokenData memory tokenData) public pure returns (bytes32) {
if (tokenData.tokenType == TokenType.ERC20) {
return bytes32(uint256(uint160(tokenData.tokenAddress)));
}
return bytes32(uint256(keccak256(abi.encode(tokenData))) % SNARK_SCALAR_FIELD);
}
// / @notice Implements proof verification logic
// / @param transaction Transaction to verify
// / @return validity Validity of balance proof
// / @return nullifierCount Number of nullifiers in the transaciton
// / @return commitmentCount Number of commitments in the transaciton
uint256[50] private _gap;
}
INativeAssetWrapper.sol 17 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.23;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title INativeAssetWrapper
/// @author DOP Team
/// @notice Native Asset Wrapper (e.g., WETH) interface
interface INativeAssetWrapper is IERC20 {
/// @dev Deposits Ether into the contract
function deposit() external payable;
/// @dev Withdraws a specified amount
/// @param amount The amount to withdraw
function withdraw(uint256 amount) external;
}
Read Contract
ZERO_VALUE 0xec732959 → bytes32
checkBalance 0x13d7b3df → uint8
configuration 0x6c70bee9 → tuple
getFee 0x933e0597 → uint120, uint120
getInsertionTreeNumberAndStartingIndex 0x0c9c0c8d → uint256, uint256
getTokenID 0x8203078f → bytes32
getVerificationKey 0x7b12ae83 → tuple
hashBoundParams 0xd4643f07 → uint256
hashCommitment 0x0b541c57 → bytes32
hashLeftRight 0x38bf282e → bytes32
holdings 0xaf503309 → tuple
lastEventBlock 0xcd3efe06 → uint256
merkleRoot 0x2eb4a7ab → bytes32
nextLeafIndex 0x0be4f422 → uint256
nullifiers 0xf19ea903 → bool
owner 0x8da5cb5b → address
rootHistory 0xc718dbda → bool
signer 0x238ac933 → address
snarkSafetyVector 0x129458f4 → bool
sumCommitments 0xc1f0d591 → uint256
tokenIDMapping 0xb8ceaef2 → uint8, address, uint256
totalHoldings 0xe9ec2e99 → uint256
treeNumber 0x66503315 → uint256
validateBalance 0x22c0bf8c → uint8
validateCommitmentPreimage 0x0311159a → uint8
validateTransaction 0x6d926e2e → uint8
verify 0xeb402c00 → bool
verifyBalance 0x08b09c2a → bool
verifyProof 0x21d9184a → bool
zeros 0xe8295588 → bytes32
Write Contract 12 functions
These functions modify contract state and require a wallet transaction to execute.
changeSigner 0xaad2b723
address newSigner
checkSafetyVectors 0x0804a4ee
No parameters
encryptApproved 0xf5d4e4f1
bytes signature
uint256 index
encryptExpired 0x907d1340
uint256 index
encryptRejected 0x89ff17f2
bytes signature
uint256 index
initEncrypt 0xf6917a15
tuple[] encryptRequests
initializeDOPLogic 0x35086865
address owner
address initSigner
renounceOwnership 0x715018a6
No parameters
setVerificationKey 0xc2705b12
uint256 nullifiers
uint256 commitments
tuple verifyingKey
transact 0x5cfdb766
tuple[] transactions
transferOwnership 0xf2fde38b
address newOwner
updateVector 0x925f9e84
uint256 vector
bool state
Recent Transactions
No transactions found for this address