Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xE32906b133a69566515f126bfc3328A69dEa90B4
Balance 0 ETH
Nonce 1
Code Size 16109 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

16109 bytes
0x6080604052600436106102385760003560e01c80637e5a921811610138578063ae669f0e116100b0578063e30c39781161007f578063f2fde38b11610064578063f2fde38b1461075e578063f46732c71461077e578063f479aa861461079e57600080fd5b8063e30c397814610705578063e46f6c111461072357600080fd5b8063ae669f0e14610671578063b9e6e73f14610691578063c98aeff5146106b1578063ca5ee4b2146106d157600080fd5b8063a1728ad911610107578063a81a2688116100ec578063a81a2688146105dd578063a83b674514610611578063aad240611461064157600080fd5b8063a1728ad914610587578063a7146747146105a757600080fd5b80637e5a92181461050757806380759f1f1461052757806382b4b88c1461053c5780638da5cb5b1461056957600080fd5b80633e56c1fd116101cb5780635b9e89d31161019a578063715018a61161017f578063715018a6146104bd57806377eadab7146104d257806379ba5097146104f257600080fd5b80635b9e89d31461048757806362911f7f146104a757600080fd5b80633e56c1fd146103e8578063497a816714610408578063511c53ff14610428578063529dd5ea1461044857600080fd5b80632f47238c116102075780632f47238c1461034d578063313529361461036d5780633a1e1dc8146103a85780633b3ccded146103c857600080fd5b80630977e04b146102445780630d1dafaa14610266578063150b7a02146102b7578063261864ad1461032d57600080fd5b3661023f57005b600080fd5b34801561025057600080fd5b5061026461025f366004612bff565b6107ce565b005b34801561027257600080fd5b5061029a7f0000000000000000000000008f899971c3e0b91820b983cfd57bc551291d2ba281565b6040516001600160a01b0390911681526020015b60405180910390f35b3480156102c357600080fd5b506102fc6102d2366004612cb2565b7f150b7a020000000000000000000000000000000000000000000000000000000095945050505050565b6040517fffffffff0000000000000000000000000000000000000000000000000000000090911681526020016102ae565b34801561033957600080fd5b50610264610348366004612d51565b6108be565b34801561035957600080fd5b50610264610368366004612d8a565b6109f4565b34801561037957600080fd5b5061039a610388366004612dfe565b60036020526000908152604090205481565b6040519081526020016102ae565b3480156103b457600080fd5b506102646103c3366004612dfe565b610adb565b3480156103d457600080fd5b5061039a6103e3366004612e17565b610b1f565b3480156103f457600080fd5b50610264610403366004612e57565b610bd7565b34801561041457600080fd5b50610264610423366004612ed1565b610c3b565b34801561043457600080fd5b5061039a610443366004612f13565b610d3e565b34801561045457600080fd5b5060055461046f90600160801b90046001600160801b031681565b6040516001600160801b0390911681526020016102ae565b34801561049357600080fd5b506102646104a2366004612dfe565b610dfe565b3480156104b357600080fd5b5061039a600c5481565b3480156104c957600080fd5b50610264610e54565b3480156104de57600080fd5b5061039a6104ed366004612dfe565b610eca565b3480156104fe57600080fd5b50610264610edd565b34801561051357600080fd5b50610264610522366004612f35565b610f6b565b34801561053357600080fd5b5061039a61108e565b34801561054857600080fd5b5061055c610557366004613422565b6110fa565b6040516102ae919061363c565b34801561057557600080fd5b506000546001600160a01b031661029a565b34801561059357600080fd5b506102646105a23660046136d4565b611322565b3480156105b357600080fd5b5061029a6105c2366004613716565b6008602052600090815260409020546001600160a01b031681565b3480156105e957600080fd5b5061029a7f000000000000000000000000d5235593bffa74442c552dff384fb8c9d6b7971e81565b34801561061d57600080fd5b5061063161062c366004612dfe565b61139e565b60405190151581526020016102ae565b34801561064d57600080fd5b5061063161065c366004612dfe565b600b6020526000908152604090205460ff1681565b34801561067d57600080fd5b5061039a61068c366004613733565b611410565b34801561069d57600080fd5b5060075461029a906001600160a01b031681565b3480156106bd57600080fd5b5061039a6106cc366004613764565b611486565b3480156106dd57600080fd5b5061029a7f000000000000000000000000e90481f96af203bf4cff149edeaa656a894a4c8481565b34801561071157600080fd5b506001546001600160a01b031661029a565b34801561072f57600080fd5b5061063161073e36600461379f565b600960209081526000928352604080842090915290825290205460ff1681565b34801561076a57600080fd5b50610264610779366004613716565b611545565b34801561078a57600080fd5b5060055461046f906001600160801b031681565b3480156107aa57600080fd5b506106316107b9366004613716565b600a6020526000908152604090205460ff1681565b60006107da83806137cb565b915050600181146107fe576040516301c5038960e61b815260040160405180910390fd5b600061080a8484611606565b905061081a878787846000611687565b610837576040516309bde33960e01b815260040160405180910390fd5b600c5461084584354261382b565b101561087d576040517fdc6b2d2200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b61088684611785565b6040516020840135907ff4a2ad2050abc883220ccfa35114861ce2e00ab6473da8cf511c5f0b7fdd686690600090a250505050505050565b6108c661195c565b6001600160a01b038116158015906109515750806001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610917573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061093b919061383e565b6001600160a01b0316826001600160a01b031614155b15610988576040517f2d7560c400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b0382811660008181526008602090815260409182902080546001600160a01b031916948616948517905581519283528201929092527f37351617338f925097f93c238a75ff7c12f449bbfee7e7697f8e583859cf236b91015b60405180910390a15050565b6109fc61195c565b6000610a0882806137cb565b9050905080600003610a2d576040516301c5038960e61b815260040160405180910390fd5b6000610a3a82600461385b565b610a45906001613872565b67ffffffffffffffff811115610a5d57610a5d612fa1565b604051908082528060200260200182016040528015610a86578160200160208202803683370190505b509050610a9e82610a9685613885565b6000846119b8565b9050610aad8686868486611687565b610aca576040516309bde33960e01b815260040160405180910390fd5b610ad383611785565b505050505050565b610ae361195c565b600c8190556040518181527ffdcbf6fce09c98e5c9cfe9b3d8c5de9e1d6e52a1e2b4d4e7dd09b19b20e3abc7906020015b60405180910390a150565b60007f000000000000000000000000d5235593bffa74442c552dff384fb8c9d6b7971e6001600160a01b031663248f66776040518060800160405280888152602001878152602001868152602001858152506040518263ffffffff1660e01b8152600401610b8d9190613947565b602060405180830381865afa158015610baa573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610bce9190613978565b95945050505050565b610bdf61195c565b6001600160a01b0382166000818152600a6020908152604091829020805460ff19168515159081179091558251938452908301527f35f7ed14597ce4c99cc4c9ce0f4d161a4e578bc4b107c39add59e2e0d691fb8d91016109e8565b610c4361195c565b60005b81811015610d39576000838383818110610c6257610c62613991565b9050602002016020810190610c779190613716565b6001600160a01b031603610cd25760405162461bcd60e51b815260206004820152600d60248201527f7a65726f2061646472657373210000000000000000000000000000000000000060448201526064015b60405180910390fd5b600160026000858585818110610cea57610cea613991565b9050602002016020810190610cff9190613716565b6001600160a01b031681526020810191909152604001600020805460ff191691151591909117905580610d31816139a7565b915050610c46565b505050565b6040805180820182528381526020810183905290517f29a5f2f60000000000000000000000000000000000000000000000000000000081526000916001600160a01b037f000000000000000000000000e90481f96af203bf4cff149edeaa656a894a4c8416916329a5f2f691610db6916004016139c0565b602060405180830381865afa158015610dd3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610df79190613978565b9392505050565b610e0661195c565b6000818152600660205260409081902080546001600160a01b0319169055517f2e4fe6c83a0e1e30adfe1958137de9f4abe532810e7286db4a2590b2782c118b90610b149083815260200190565b610e5c61195c565b60405162461bcd60e51b815260206004820152602160248201527f546865204f776e6572736869702063616e6e6f742062652072656e6f756e636560448201527f64000000000000000000000000000000000000000000000000000000000000006064820152608401610cc9565b6000610ed7826001611d41565b92915050565b60015433906001600160a01b03168114610f5f5760405162461bcd60e51b815260206004820152602960248201527f4f776e61626c6532537465703a2063616c6c6572206973206e6f74207468652060448201527f6e6577206f776e657200000000000000000000000000000000000000000000006064820152608401610cc9565b610f6881611d8c565b50565b610f7361195c565b60005b8381101561108757828282818110610f9057610f90613991565b9050602002016020810190610fa59190613716565b60066000878785818110610fbb57610fbb613991565b90506020020135815260200190815260200160002060006101000a8154816001600160a01b0302191690836001600160a01b031602179055507f3d47d745bf8c193d19b6eff4f8bb5ff806af27c6fe2863b21a76c292b8f48e1385858381811061102757611027613991565b9050602002013584848481811061104057611040613991565b90506020020160208101906110559190613716565b604080519283526001600160a01b0390911660208301520160405180910390a18061107f816139a7565b915050610f76565b5050505050565b6005546000906004908290600160801b90046001600160801b03166110be576110b9600160196139e8565b6110dd565b6005546110dd90600190600160801b90046001600160801b03166139e8565b6001600160801b0316815260200190815260200160002054905090565b3360009081526002602052604090205460609060ff166111825760405162461bcd60e51b815260206004820152602660248201527f45787465726e616c416374696f6e426173653a2073656e646572206e6f74206160448201527f6c6c6f77656400000000000000000000000000000000000000000000000000006064820152608401610cc9565b8160200151516001146111c1576040517f947d5a8400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60006001600160a01b03166008600084602001516000815181106111e7576111e7613991565b6020908102919091018101516001600160a01b03908116835290820192909252604001600020541603611246576040517f233e3d7400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6101a08201516001600160a01b03161561128c576040517f0f785e0300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60008060008060006112a2876102000151611da5565b93985091965094509250905060008560018111156112c2576112c2613a0f565b036112d9576112d48785848487611dd3565b6112e3565b6112e38785612104565b6040805160008082526020820190925290611314565b611301612b64565b8152602001906001900390816112f95790505b50955050505050505b919050565b61132a61195c565b6001600160a01b0383166000818152600960209081526040808320868452825291829020805460ff19168515159081179091558251938452908301859052908201527f81de547b87363785dacbfccf9de92db2183a705c3f9510a46ecd63d409c669ca9060600160405180910390a1505050565b600554600090600160801b90046001600160801b03165b806000036113c1575060195b806113cb81613a25565b600081815260046020526040902054909250840390506113ee5750600192915050565b600554600160801b90046001600160801b031681036113b55750600092915050565b600061141f6020840184613a3c565b61142f6040850160208601613a3c565b61143f6060860160408701613a3c565b6040805161ffff94851660208201529284169083015290911660608201526080810183905260a00160408051601f1981840301815291905280516020909101209392505050565b60007f0000000000000000000000008f899971c3e0b91820b983cfd57bc551291d2ba26001600160a01b0316634937a2586040518060a00160405280898152602001888152602001878152602001868152602001858152506040518263ffffffff1660e01b81526004016114fa9190613a57565b602060405180830381865afa158015611517573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061153b9190613978565b9695505050505050565b61154d61195c565b600180546001600160a01b0383166001600160a01b0319909116811790915561157e6000546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b600080546001600160a01b038381166001600160a01b0319831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60408051600780825261010082019092526060916020820160e08036833701905050905081600001358160008151811061164257611642613991565b60200260200101818152505081602001358160018151811061166657611666613991565b6020908102919091010152610df7600161167f85613885565b6002846119b8565b6000818152600660205260408120546001600160a01b0316806116ec5760405162461bcd60e51b815260206004820181905260248201527f43616e6e6f742066696e6420617070726f7072696174652076657269666965726044820152606401610cc9565b6040517f6743734c0000000000000000000000000000000000000000000000000000000081526001600160a01b03821690636743734c90611739908a908a908a908a908a90600401613a7f565b602060405180830381865afa158015611756573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061177a9190613b0e565b979650505050505050565b600061179182806137cb565b905090506117a2826080013561139e565b6117d8576040517f9dd854d300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60005b81811015610d39576117ed83806137cb565b828181106117fd576117fd613991565b9050602002013560001461194a576008600061181c60408601866137cb565b8481811061182c5761182c613991565b90506020020160208101906118419190613716565b6001600160a01b0390811682526020808301939093526040909101600020541690636e553f6590611874908601866137cb565b8481811061188457611884613991565b9050602002013585806060019061189b91906137cb565b858181106118ab576118ab613991565b90506020020160208101906118c09190613716565b6040517fffffffff0000000000000000000000000000000000000000000000000000000060e085901b16815260048101929092526001600160a01b031660248201526044016020604051808303816000875af1158015611924573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119489190613978565b505b80611954816139a7565b9150506117db565b6000546001600160a01b031633146119b65760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610cc9565b565b606083606001515185146119e2576040516306d537fb60e31b815260006004820152602401610cc9565b8360400151518514611a0a576040516306d537fb60e31b815260016004820152602401610cc9565b8360200151518514611a32576040516306d537fb60e31b815260026004820152602401610cc9565b60005b85811015611bc7578451805182908110611a5157611a51613991565b6020026020010151838580611a65906139a7565b965081518110611a7757611a77613991565b602002602001018181525050600b600086600001518381518110611a9d57611a9d613991565b60209081029190910181015182528101919091526040016000205460ff1615611af2576040517fcad2ae0200000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b8451805182908110611b0657611b06613991565b6020026020010151600014611bb5576001600b600087600001518481518110611b3157611b31613991565b6020026020010151815260200190815260200160002060006101000a81548160ff0219169083151502179055507f97b3d9d687a06831840bc45484d761035997584f7f946fb85153c6fb26db462c85600001518281518110611b9557611b95613991565b6020026020010151604051611bac91815260200190565b60405180910390a15b80611bbf816139a7565b915050611a35565b5060005b85811015611c355784606001518181518110611be957611be9613991565b60200260200101516001600160a01b0316838580611c06906139a7565b965081518110611c1857611c18613991565b602090810291909101015280611c2d816139a7565b915050611bcb565b5060005b85811015611ca35784604001518181518110611c5757611c57613991565b60200260200101516001600160a01b0316838580611c74906139a7565b965081518110611c8657611c86613991565b602090810291909101015280611c9b816139a7565b915050611c39565b5060005b85811015611d085784602001518181518110611cc557611cc5613991565b6020026020010151838580611cd9906139a7565b965081518110611ceb57611ceb613991565b602090810291909101015280611d00816139a7565b915050611ca7565b5060808401518284611d19816139a7565b955081518110611d2b57611d2b613991565b602090810291909101015250805b949350505050565b600080611d4d846122bc565b90506001836002811115611d6357611d63613a0f565b148015611d73575083816001901b105b611d7e576000611d81565b60015b60ff16019392505050565b600180546001600160a01b0319169055610f68816115b6565b600080600060608085806020019051810190611dc19190613b94565b939a9299509097509550909350915050565b600754604080516333f2026760e11b815290516000926001600160a01b0316916367e404ce9160048083019260209291908290030181865afa158015611e1d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e41919061383e565b90506000611e6c8760600151600081518110611e5f57611e5f613991565b6020026020010151612350565b905060008760200151600081518110611e8757611e87613991565b60200260200101519050826001600160a01b0316846001600160a01b031614611edc576040517f6ee7a50300000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b86600003611f16576040517f24781e8400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b0381166000908152600a602052604090205460ff1680611f6057506001600160a01b038116600090815260096020908152604080832085845290915290205460ff165b611f96576040517f2c5211c600000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b0381166120d857600754604080517f3fa4f245000000000000000000000000000000000000000000000000000000008152905184926001600160a01b031691633fa4f2459160048083019260209291908290030181865afa158015612006573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061202a9190613978565b14612061576040517f83ab423f00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600760009054906101000a90046001600160a01b03166001600160a01b03166314f6c3be6040518163ffffffff1660e01b8152600401600060405180830381600087803b1580156120b157600080fd5b505af11580156120c5573d6000803e3d6000fd5b505050506120d333836123a6565b6120e6565b6120e6818433856000612449565b6120fa8382848a8a8a8e610100015161246e565b5050505050505050565b801561213c576040517fd06eb5c000000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600754604080516333f2026760e11b815290516000926001600160a01b0316916367e404ce9160048083019260209291908290030181865afa158015612186573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121aa919061383e565b905060006121de84606001516000815181106121c8576121c8613991565b60200260200101516121d990613c2d565b612350565b9050600084602001516000815181106121f9576121f9613991565b6020908102919091018101516001600160a01b03808216600090815260089093526040928390205492517fb460af9400000000000000000000000000000000000000000000000000000000815260048101869052868216602482018190526044820152919350919091169063b460af94906064016020604051808303816000875af115801561228c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122b09190613978565b506110878184846124d1565b600080608083901c156122d157608092831c92015b604083901c156122e357604092831c92015b602083901c156122f557602092831c92015b601083901c1561230757601092831c92015b600883901c1561231957600892831c92015b600483901c1561232b57600492831c92015b600283901c1561233d57600292831c92015b600183901c15610ed75760010192915050565b6000808212156123a25760405162461bcd60e51b815260206004820181905260248201527f53616665436173743a2076616c7565206d75737420626520706f7369746976656044820152606401610cc9565b5090565b6000826001600160a01b03168260405160006040518083038185875af1925050503d80600081146123f3576040519150601f19603f3d011682016040523d82523d6000602084013e6123f8565b606091505b5050905080610d395760405162461bcd60e51b815260206004820152600f60248201527f5472616e73666572204661696c656400000000000000000000000000000000006044820152606401610cc9565b806000036124625761245d858585856124f4565b611087565b611087858585846125a8565b600061247985612627565b9050876001600160a01b0316817f0e4d20312911ce2092399ebc32f054c11ea495a00f72a494575cc1839fd1d80e878a8a8989896040516124bf96959493929190613c91565b60405180910390a35050505050505050565b6001600160a01b0383166124e957610d3982826123a6565b610d398383836127ba565b6001600160a01b038416612596578034146125775760405162461bcd60e51b815260206004820152602560248201527f6d73672e76616c756520646f65736e2774206d61746368206e6565646564206160448201527f6d6f756e740000000000000000000000000000000000000000000000000000006064820152608401610cc9565b6001600160a01b03821630146125915761259182826123a6565b6125a2565b6125a2848484846127ce565b50505050565b6040517f42842e0e0000000000000000000000000000000000000000000000000000000081526001600160a01b0384811660048301528381166024830152604482018390528516906342842e0e90606401600060405180830381600087803b15801561261357600080fd5b505af11580156120fa573d6000803e3d6000fd5b6005805460009182918290612644906001600160801b0316613ce5565b82546001600160801b039182166101009390930a83810292021916179091559050600061267260018361382b565b905061269f7f00000000000000000000000000000000000000000000000000000000000000196002613def565b6005546001600160801b031611156126f95760405162461bcd60e51b815260206004820152600d60248201527f547265652069732066756c6c2e000000000000000000000000000000000000006044820152606401610cc9565b60006127257f00000000000000000000000000000000000000000000000000000000010000008461382b565b9050600061273282610eca565b9050856127408483836127e3565b600082815260036020908152604080832054600580546001600160801b03600160801b9182900481168752600490955292909420559154601992612788929104166001613e04565b6127929190613e3a565b600580546001600160801b03928316600160801b02921691909117905561177a60018661382b565b610d396001600160a01b038416838361286f565b6125a26001600160a01b038516848484612918565b60005b8281116125a2576127f8600285613e60565b15806128045750836001145b1561283457600081815260036020526040902082905582811461282f5761282c826000610d3e565b91505b612850565b60008181526003602052604090205461284d9083610d3e565b91505b61285b600285613e74565b935080612867816139a7565b9150506127e6565b6040516001600160a01b038316602482015260448101829052610d399084907fa9059cbb00000000000000000000000000000000000000000000000000000000906064015b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff0000000000000000000000000000000000000000000000000000000090931692909217909152612969565b6040516001600160a01b03808516602483015283166044820152606481018290526125a29085907f23b872dd00000000000000000000000000000000000000000000000000000000906084016128b4565b60006129be826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316612a519092919063ffffffff16565b90508051600014806129df5750808060200190518101906129df9190613b0e565b610d395760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f742073756363656564000000000000000000000000000000000000000000006064820152608401610cc9565b6060611d39848460008585600080866001600160a01b03168587604051612a789190613e88565b60006040518083038185875af1925050503d8060008114612ab5576040519150601f19603f3d011682016040523d82523d6000602084013e612aba565b606091505b509150915061177a8783838760608315612b35578251600003612b2e576001600160a01b0385163b612b2e5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610cc9565b5081611d39565b611d398383815115612b4a5781518083602001fd5b8060405162461bcd60e51b8152600401610cc99190613ea4565b6040518060a001604052806000815260200160006001600160a01b03168152602001612bb16040518060800160405280600081526020016000815260200160008152602001600081525090565b815260200160008152602001600081525090565b8060408101831015610ed757600080fd5b8060808101831015610ed757600080fd5b600060a08284031215612bf957600080fd5b50919050565b6000806000806000858703610160811215612c1957600080fd5b612c238888612bc5565b9550612c328860408901612bd6565b9450612c418860c08901612bc5565b935061010087013567ffffffffffffffff811115612c5e57600080fd5b612c6a89828a01612be7565b935050604061011f1982011215612c8057600080fd5b50610120860190509295509295909350565b6001600160a01b0381168114610f6857600080fd5b803561131d81612c92565b600080600080600060808688031215612cca57600080fd5b8535612cd581612c92565b94506020860135612ce581612c92565b935060408601359250606086013567ffffffffffffffff80821115612d0957600080fd5b818801915088601f830112612d1d57600080fd5b813581811115612d2c57600080fd5b896020828501011115612d3e57600080fd5b9699959850939650602001949392505050565b60008060408385031215612d6457600080fd5b8235612d6f81612c92565b91506020830135612d7f81612c92565b809150509250929050565b6000806000806101208587031215612da157600080fd5b612dab8686612bc5565b9350612dba8660408701612bd6565b9250612dc98660c08701612bc5565b915061010085013567ffffffffffffffff811115612de657600080fd5b612df287828801612be7565b91505092959194509250565b600060208284031215612e1057600080fd5b5035919050565b60008060008060808587031215612e2d57600080fd5b5050823594602084013594506040840135936060013592509050565b8015158114610f6857600080fd5b60008060408385031215612e6a57600080fd5b8235612e7581612c92565b91506020830135612d7f81612e49565b60008083601f840112612e9757600080fd5b50813567ffffffffffffffff811115612eaf57600080fd5b6020830191508360208260051b8501011115612eca57600080fd5b9250929050565b60008060208385031215612ee457600080fd5b823567ffffffffffffffff811115612efb57600080fd5b612f0785828601612e85565b90969095509350505050565b60008060408385031215612f2657600080fd5b50508035926020909101359150565b60008060008060408587031215612f4b57600080fd5b843567ffffffffffffffff80821115612f6357600080fd5b612f6f88838901612e85565b90965094506020870135915080821115612f8857600080fd5b50612f9587828801612e85565b95989497509550505050565b634e487b7160e01b600052604160045260246000fd5b6040516080810167ffffffffffffffff81118282101715612fda57612fda612fa1565b60405290565b604051610240810167ffffffffffffffff81118282101715612fda57612fda612fa1565b60405160a0810167ffffffffffffffff81118282101715612fda57612fda612fa1565b604051601f8201601f1916810167ffffffffffffffff8111828210171561305057613050612fa1565b604052919050565b600067ffffffffffffffff82111561307257613072612fa1565b5060051b60200190565b600082601f83011261308d57600080fd5b813560206130a261309d83613058565b613027565b82815260059290921b840181019181810190868411156130c157600080fd5b8286015b848110156130e55780356130d881612c92565b83529183019183016130c5565b509695505050505050565b600082601f83011261310157600080fd5b8135602061311161309d83613058565b82815260059290921b8401810191818101908684111561313057600080fd5b8286015b848110156130e55780358352918301918301613134565b600082601f83011261315c57600080fd5b8135602061316c61309d83613058565b82815260059290921b8401810191818101908684111561318b57600080fd5b8286015b848110156130e557803567ffffffffffffffff8111156131af5760008081fd5b6131bd8986838b01016130f0565b84525091830191830161318f565b600067ffffffffffffffff8211156131e5576131e5612fa1565b50601f01601f191660200190565b600082601f83011261320457600080fd5b813561321261309d826131cb565b81815284602083860101111561322757600080fd5b816020850160208301376000918101602001919091529392505050565b600082601f83011261325557600080fd5b8135602061326561309d83613058565b82815260059290921b8401810191818101908684111561328457600080fd5b8286015b848110156130e557803567ffffffffffffffff808211156132a857600080fd5b818901915089603f8301126132bc57600080fd5b858201356132cc61309d82613058565b81815260059190911b830160400190878101908c8311156132ec57600080fd5b604085015b838110156133255780358581111561330857600080fd5b6133178f6040838a01016131f3565b8452509189019189016132f1565b50875250505092840192508301613288565b60006080828403121561334957600080fd5b613351612fb7565b90508135815260208201356020820152604082013560408201526060820135606082015292915050565b803561ffff8116811461131d57600080fd5b60006080828403121561339f57600080fd5b6133a7612fb7565b905081356133b481612c92565b815260208201356133c481612c92565b6020820152604082013567ffffffffffffffff808211156133e457600080fd5b6133f0858386016131f3565b6040840152606084013591508082111561340957600080fd5b50613416848285016131f3565b60608301525092915050565b60006020828403121561343457600080fd5b813567ffffffffffffffff8082111561344c57600080fd5b908301906102a0828603121561346157600080fd5b613469612fe0565b8235815260208301358281111561347f57600080fd5b61348b8782860161307c565b6020830152506040830135828111156134a357600080fd5b6134af878286016130f0565b6040830152506060830135828111156134c757600080fd5b6134d3878286016130f0565b6060830152506080830135828111156134eb57600080fd5b6134f78782860161314b565b60808301525060a08301358281111561350f57600080fd5b61351b8782860161314b565b60a08301525060c08301358281111561353357600080fd5b61353f87828601613244565b60c08301525060e08301358281111561355757600080fd5b613563878286016130f0565b60e083015250610100838101359082015261012061358387828601613337565b908201526101a0838101356101408301526101c0808501356101608401526101e06135af81870161337b565b6101808501526102006135c3818801612ca7565b8486015261022093506135d7848801612ca7565b83860152610240870135828601526102608701359250858311156135fa57600080fd5b6136068a8489016131f3565b9085015250506102808401358381111561361f57600080fd5b61362b8882870161338d565b918301919091525095945050505050565b602080825282518282018190526000919060409081850190868401855b828110156136c757815180518552868101516001600160a01b0316878601528581015180518787015280880151606080880191909152818801516080808901919091529181015160a088015282015160c0870152015160e08501526101009093019290850190600101613659565b5091979650505050505050565b6000806000606084860312156136e957600080fd5b83356136f481612c92565b925060208401359150604084013561370b81612e49565b809150509250925092565b60006020828403121561372857600080fd5b8135610df781612c92565b600080828403608081121561374757600080fd5b606081121561375557600080fd5b50919360608501359350915050565b600080600080600060a0868803121561377c57600080fd5b505083359560208501359550604085013594606081013594506080013592509050565b600080604083850312156137b257600080fd5b82356137bd81612c92565b946020939093013593505050565b6000808335601e198436030181126137e257600080fd5b83018035915067ffffffffffffffff8211156137fd57600080fd5b6020019150600581901b3603821315612eca57600080fd5b634e487b7160e01b600052601160045260246000fd5b81810381811115610ed757610ed7613815565b60006020828403121561385057600080fd5b8151610df781612c92565b8082028115828204841417610ed757610ed7613815565b80820180821115610ed757610ed7613815565b600060a0823603121561389757600080fd5b61389f613004565b823567ffffffffffffffff808211156138b757600080fd5b6138c3368387016130f0565b835260208501359150808211156138d957600080fd5b6138e5368387016130f0565b602084015260408501359150808211156138fe57600080fd5b61390a3683870161307c565b6040840152606085013591508082111561392357600080fd5b506139303682860161307c565b606083015250608092830135928101929092525090565b60808101818360005b600481101561396f578151835260209283019290910190600101613950565b50505092915050565b60006020828403121561398a57600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b6000600182016139b9576139b9613815565b5060010190565b60408101818360005b600281101561396f5781518352602092830192909101906001016139c9565b6001600160801b03828116828216039080821115613a0857613a08613815565b5092915050565b634e487b7160e01b600052602160045260246000fd5b600081613a3457613a34613815565b506000190190565b600060208284031215613a4e57600080fd5b610df78261337b565b60a08101818360005b600581101561396f578151835260209283019290910190600101613a60565b60006101408083016040808a86378085018960005b6002811015613ab157838284379183019190830190600101613a94565b505050808860c08701375061010084019190915284519081905261016083019060209081870160005b82811015613af657815185529383019390830190600101613ada565b50505050610120929092019290925295945050505050565b600060208284031215613b2057600080fd5b8151610df781612e49565b60005b83811015613b46578181015183820152602001613b2e565b50506000910152565b600082601f830112613b6057600080fd5b8151613b6e61309d826131cb565b818152846020838601011115613b8357600080fd5b611d39826020830160208701613b2b565b600080600080600060a08688031215613bac57600080fd5b855160028110613bbb57600080fd5b602087015160408801519196509450613bd381612c92565b606087015190935067ffffffffffffffff80821115613bf157600080fd5b613bfd89838a01613b4f565b93506080880151915080821115613c1357600080fd5b50613c2088828901613b4f565b9150509295509295909350565b60007f80000000000000000000000000000000000000000000000000000000000000008203613c5e57613c5e613815565b5060000390565b60008151808452613c7d816020860160208601613b2b565b601f01601f19169290920160200192915050565b8681526001600160a01b038616602082015284604082015260c060608201526000613cbf60c0830186613c65565b8281036080840152613cd18186613c65565b9150508260a0830152979650505050505050565b60006001600160801b03808316818103613d0157613d01613815565b6001019392505050565b600181815b80851115613d46578160001904821115613d2c57613d2c613815565b80851615613d3957918102915b93841c9390800290613d10565b509250929050565b600082613d5d57506001610ed7565b81613d6a57506000610ed7565b8160018114613d805760028114613d8a57613da6565b6001915050610ed7565b60ff841115613d9b57613d9b613815565b50506001821b610ed7565b5060208310610133831016604e8410600b8410161715613dc9575081810a610ed7565b613dd38383613d0b565b8060001904821115613de757613de7613815565b029392505050565b6000610df76001600160801b03841683613d4e565b6001600160801b03818116838216019080821115613a0857613a08613815565b634e487b7160e01b600052601260045260246000fd5b60006001600160801b0380841680613e5457613e54613e24565b92169190910692915050565b600082613e6f57613e6f613e24565b500690565b600082613e8357613e83613e24565b500490565b60008251613e9a818460208701613b2b565b9190910192915050565b602081526000610df76020830184613c6556fea26469706673582212201e5e8c61530d000bfc8d4662d75a383455d788eaceb9b27481cddb6df260b55464736f6c63430008110033

Verified Source Code Full Match

Compiler: v0.8.17+commit.8df45f5f EVM: london Optimization: Yes (1000 runs)
Merkle.sol 157 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import "./types/IPoseidon2.sol";
import "./MerkleBase.sol";

///@title Hinkal Merkle Tree
contract Merkle is MerkleBase {
    constructor(
        MerkleConstructorArgs memory constructorArgs
    ) MerkleBase(constructorArgs) {}

    function outputGas(uint256 index, uint256[] memory gasUsed) internal view {
        gasUsed[index] = gasleft();
    }

    ///@notice insert a single new leaf to Merkle Tree
    ///@param leaf value to be inserted
    ///@return index index of node inserted
    function insert(uint256 leaf) internal override returns (uint256) {
        uint256 newIndex = ++m_index;
        uint256 currentNodeIndex = newIndex - 1;

        require(m_index <= uint256(2) ** LEVELS, "Tree is full.");

        uint256 fullCount = newIndex - MINIMUM_INDEX; // number of inserted leaves
        uint256 twoPower = logarithm2(fullCount); // number of tree levels to be updated, (e.g. if 9 => 4 levels should be updated)

        uint256 prevHash = leaf;

        insertOne(currentNodeIndex, twoPower, prevHash);

        roots[rootIndex] = tree[twoPower]; // adding root to roots mapping
        rootIndex = (rootIndex + 1) % MAX_ROOT_NUMBER;
        return newIndex - 1;
    }

    function insertMany(
        uint256[] memory leaves
    ) internal returns (uint256[] memory insertedIndexes) {
        m_index += uint128(leaves.length);
        uint256 newIndex = m_index;
        uint256 currentNodeIndex = newIndex - leaves.length;

        require(m_index <= uint256(2) ** LEVELS, "Tree is full.");

        insertedIndexes = new uint256[](leaves.length);
        for (uint256 i = 0; i < insertedIndexes.length; i++) {
            insertedIndexes[i] = currentNodeIndex + i;
        }

        uint256[][] memory sortedLeaves = sortInPairs(leaves, currentNodeIndex);

        uint256 fullCount = newIndex - MINIMUM_INDEX; // number of inserted leaves
        uint256 twoPower = logarithm2(fullCount); // number of tree levels to be updated, (e.g. if 9 => 4 levels should be updated)

        for (uint256 i = 0; i < sortedLeaves.length; i++) {
            if (sortedLeaves[i].length == 1)
                insertOne(currentNodeIndex++, twoPower, sortedLeaves[i][0]);
            else {
                insertTwo(
                    sortedLeaves[i][0],
                    sortedLeaves[i][1],
                    currentNodeIndex,
                    twoPower
                );
                currentNodeIndex += 2;
            }
        }

        roots[rootIndex] = tree[twoPower]; // adding root to roots mapping
        rootIndex = (rootIndex + 1) % MAX_ROOT_NUMBER;
    }

    ///@notice insert single value and update Merkle Tree
    ///@param currentNodeIndex Index of the last node before insertion
    ///@param twoPower Nodes in Merkle Tree that must be updated
    ///@param prevHash node to be inserted
    function insertOne(
        uint256 currentNodeIndex,
        uint256 twoPower,
        uint256 prevHash
    ) internal {
        for (uint256 i = 0; i <= twoPower; i++) {
            if (currentNodeIndex % 2 == 0 || currentNodeIndex == 1) {
                tree[i] = prevHash;
                if (i != twoPower) prevHash = hash2(prevHash, 0);
            } else {
                prevHash = hash2(tree[i], prevHash);
            }
            currentNodeIndex /= 2;
        }
    }

    function insertTwo(
        uint256 left,
        uint256 right,
        uint256 currentNodeIndex,
        uint256 twoPower
    ) internal {
        uint256 prevHash = hash2(left, right);
        currentNodeIndex /= 2; // we are starting from i = 1, so we need one iteration

        for (uint256 i = 1; i <= twoPower; i++) {
            if (currentNodeIndex % 2 == 0 || currentNodeIndex == 1) {
                tree[i] = prevHash;
                if (i != twoPower) prevHash = hash2(prevHash, 0);
            } else {
                prevHash = hash2(tree[i], prevHash);
            }
            currentNodeIndex /= 2;
        }
    }

    ///@notice Sort leaf nodes in pairs of left and right nodes.
    ///@param leaves leaves to be sorted
    ///@param currentNodeIndex Index of the last node to be inserted
    ///@return sortedLeaves leaves sorted in pairs of left and right
    function sortInPairs(
        uint256[] memory leaves,
        uint256 currentNodeIndex
    ) internal pure returns (uint256[][] memory sortedLeaves) {
        uint leavesLength = leaves.length;
        bool firstLeafIfRight = currentNodeIndex % 2 != 0;

        uint256 firstElement = firstLeafIfRight ? 1 : 0;
        uint256 netElements = leavesLength - firstElement;

        uint256 lengthWithoutFirst = (netElements % 2 == 0)
            ? netElements / 2
            : (netElements + 1) / 2;

        sortedLeaves = new uint256[][](firstElement + lengthWithoutFirst);

        if (firstLeafIfRight) {
            uint256[] memory first = new uint256[](1);
            first[0] = leaves[0];
            sortedLeaves[0] = first;
        }

        uint arrIndex = firstLeafIfRight ? 1 : 0;
        uint sortedArrayIndex = arrIndex;
        while (arrIndex < leavesLength) {
            uint256[] memory arr;
            if (arrIndex + 1 < leavesLength) {
                arr = new uint256[](2);
                arr[0] = leaves[arrIndex];
                arr[1] = leaves[++arrIndex];
            } else {
                arr = new uint256[](1);
                arr[0] = leaves[arrIndex];
            }
            sortedLeaves[sortedArrayIndex++] = arr;
            ++arrIndex;
        }
    }
}
MerkleBase.sol 89 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/utils/math/Math.sol";
import "./types/IPoseidon2.sol";
import "./types/IPoseidon4.sol";
import "./types/IPoseidon5.sol";
import "./types/IMerkle.sol";

abstract contract MerkleBase is IMerkle {
    using Math for uint256;

    // states
    mapping(uint256 => uint256) public tree;
    mapping(uint256 => uint256) roots;
    uint128 public m_index; // current index of the tree
    uint128 public rootIndex = 0;
    // constants
    uint128 immutable LEVELS; // deepness of tree
    uint128 constant MAX_ROOT_NUMBER = 25;
    uint256 immutable MINIMUM_INDEX;
    IPoseidon2 public immutable poseidon2; // hashing
    IPoseidon4 public immutable poseidon4; // hashing
    IPoseidon5 public immutable poseidon5;

    // please see deployment scripts to understand how to create and instance of Poseidon contract
    constructor(MerkleConstructorArgs memory constructorArgs) {
        LEVELS = constructorArgs.levels;
        m_index = uint128(2 ** (LEVELS - 1));
        MINIMUM_INDEX = 2 ** (LEVELS - 1);
        poseidon2 = IPoseidon2(constructorArgs.poseidon2);
        poseidon4 = IPoseidon4(constructorArgs.poseidon4);
        poseidon5 = IPoseidon5(constructorArgs.poseidon5);
    }

    function hash2(
        uint256 a,
        uint256 b
    ) public view returns (uint256 poseidonHash) {
        poseidonHash = poseidon2.poseidon([a, b]);
    }

    function hash4(
        uint256 a0,
        uint256 a1,
        uint256 a2,
        uint256 a3
    ) public view returns (uint256 poseidonHash) {
        poseidonHash = poseidon4.poseidon([a0, a1, a2, a3]);
    }

    function hash5(
        uint256 a0,
        uint256 a1,
        uint256 a2,
        uint256 a3,
        uint256 a4
    ) public view returns (uint256 poseidonHash) {
        poseidonHash = poseidon5.poseidon([a0, a1, a2, a3, a4]);
    }

    function insert(uint256 leaf) internal virtual returns (uint256);

    function getRootHash() public view returns (uint256) {
        return roots[rootIndex > 0 ? rootIndex - 1 : MAX_ROOT_NUMBER - 1];
    }

    function rootHashExists(uint256 _root) public view returns (bool) {
        uint256 i = rootIndex; // latest root hash
        do {
            if (i == 0) {
                i = MAX_ROOT_NUMBER;
            }
            i--;
            if (_root == roots[i]) {
                return true;
            }
        } while (i != rootIndex);
        return false;
    }

    ///@notice logarithm of x with base 2.
    ///@notice instead of rounding down, this function rounds up.
    ///@param x operand
    ///@return y logarithm base 2 of input
    function logarithm2(uint256 x) public pure returns (uint256 y) {
        y = Math.log2(x, Math.Rounding.Up);
    }
}
Transferer.sol 266 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./TransfererBase.sol";

contract Transferer is TransfererBase {
    using SafeERC20 for IERC20;

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

    function unsafeApproveERC20Token(
        address _erc20TokenAddress,
        address _to,
        uint256 _value
    ) internal {
        IERC20(_erc20TokenAddress).approve(_to, 0);
        IERC20(_erc20TokenAddress).approve(_to, _value);
    }

    function getERC20Allowance(
        address _erc20TokenAddress,
        address owner,
        address spender
    ) internal view returns (uint256) {
        IERC20 outToken = IERC20(_erc20TokenAddress);
        return outToken.allowance(owner, spender);
    }

    function approveERC721Token(
        address _erc20TokenAddress,
        address _to,
        uint256 _tokenId
    ) internal {
        IERC721(_erc20TokenAddress).approve(_to, _tokenId);
    }

    function approveToken(
        address _erc20TokenAddress,
        address _to,
        uint256 _tokenId,
        uint256 _value
    ) internal {
        if (_tokenId == 0) {
            unsafeApproveERC20Token(_erc20TokenAddress, _to, _value);
        } else {
            approveERC721Token(_erc20TokenAddress, _to, _tokenId);
        }
    }

    function transferERC20TokenFrom(
        address _erc20TokenAddress,
        address _from,
        address _to,
        uint256 _value
    ) internal {
        IERC20(_erc20TokenAddress).safeTransferFrom(_from, _to, _value);
    }

    function transferNftFrom(
        address _erc20TokenAddress,
        address _from,
        address _to,
        uint256 _tokenId
    ) internal {
        IERC721(_erc20TokenAddress).safeTransferFrom(_from, _to, _tokenId);
    }

    function transferERC20TokenOrETH(
        address _erc20TokenAddress,
        address _to,
        uint256 _value
    ) internal {
        if (_erc20TokenAddress == address(0)) {
            transferETH(_to, _value);
        } else {
            transferERC20Token(_erc20TokenAddress, _to, _value);
        }
    }

    function transferToken(
        address _erc20TokenAddress,
        address _to,
        uint256 _value,
        uint256 _tokenId
    ) internal {
        if (_tokenId == 0) {
            transferERC20TokenOrETH(_erc20TokenAddress, _to, _value);
        } else {
            transferNftFrom(_erc20TokenAddress, address(this), _to, _tokenId);
        }
    }

    function multiTransfer(
        address[] memory erc20TokenAddresses,
        address _to,
        uint256[] memory amounts
    ) internal returns (bool) {
        for (uint64 i = 0; i < erc20TokenAddresses.length; i++) {
            if (amounts[i] > 0)
                transferERC20TokenOrETH(
                    erc20TokenAddresses[i],
                    _to,
                    amounts[i]
                );
        }
        return true;
    }

    function transferERC20TokenFromOrCheckETH(
        address _contractAddress,
        address _from,
        address _to,
        uint256 _value
    ) internal {
        if (_contractAddress == address(0)) {
            require(
                msg.value == _value,
                "msg.value doesn't match needed amount"
            );
            if (_to != address(this)) {
                transferETH(_to, _value);
            }
        } else {
            transferERC20TokenFrom(_contractAddress, _from, _to, _value);
        }
    }

    function transferTokenFrom(
        address _erc20TokenAddress,
        address _from,
        address _to,
        uint256 _value,
        uint256 _tokenId
    ) internal {
        if (_tokenId == 0) {
            transferERC20TokenFromOrCheckETH(
                _erc20TokenAddress,
                _from,
                _to,
                _value
            );
        } else {
            transferNftFrom(_erc20TokenAddress, _from, _to, _tokenId);
        }
    }

    function multiTransferFrom(
        address[] memory erc20TokenAddresses,
        address _from,
        address _to,
        uint256[] memory amounts
    ) internal returns (bool) {
        for (uint64 i = 0; i < erc20TokenAddresses.length; i++) {
            if (amounts[i] > 0) {
                transferERC20TokenFromOrCheckETH(
                    erc20TokenAddresses[i],
                    _from,
                    _to,
                    amounts[i]
                );
            }
        }
        return true;
    }

    function getERC20OrETHBalance(
        address _erc20TokenAddress
    ) internal view returns (uint256) {
        if (_erc20TokenAddress == address(0)) {
            return address(this).balance;
        } else {
            IERC20 outToken = IERC20(_erc20TokenAddress);
            return outToken.balanceOf(address(this));
        }
    }

    function getNftBalance(
        address _erc20TokenAddress,
        uint256 tokenId
    ) internal view returns (uint256) {
        IERC721 outToken = IERC721(_erc20TokenAddress);
        try outToken.ownerOf(tokenId) returns (address owner) {
            if (owner == address(this)) return 1;
            else return 0;
        } catch {
            return 0;
        }
    }

    function getBalancesForArrayMemory(
        address[] memory erc20TokenAddresses
    ) internal view returns (uint256[] memory balances) {
        balances = new uint256[](erc20TokenAddresses.length);
        for (uint64 i; i < erc20TokenAddresses.length; i++) {
            balances[i] = getERC20OrETHBalance(erc20TokenAddresses[i]);
        }
    }

    function getBalancesForArrayMemory(
        address[] memory erc20TokenAddresses,
        uint256[] memory tokenIds
    ) internal view returns (uint256[] memory balances) {
        balances = new uint256[](erc20TokenAddresses.length);
        for (uint64 i; i < erc20TokenAddresses.length; i++) {
            if (tokenIds[i] == 0) {
                balances[i] = getERC20OrETHBalance(erc20TokenAddresses[i]);
            } else {
                balances[i] = getNftBalance(
                    erc20TokenAddresses[i],
                    tokenIds[i]
                );
            }
        }
    }

    function getBalancesForArray(
        address[] calldata erc20TokenAddresses
    ) internal view returns (uint256[] memory balances) {
        balances = new uint256[](erc20TokenAddresses.length);
        for (uint64 i; i < erc20TokenAddresses.length; i++) {
            balances[i] = getERC20OrETHBalance(erc20TokenAddresses[i]);
        }
    }

    function getBalancesForArray(
        address[] calldata erc20TokenAddresses,
        uint256[] calldata tokenIds
    ) internal view returns (uint256[] memory balances) {
        balances = new uint256[](erc20TokenAddresses.length);
        for (uint64 i; i < erc20TokenAddresses.length; i++) {
            if (tokenIds[i] == 0) {
                balances[i] = getERC20OrETHBalance(erc20TokenAddresses[i]);
            } else {
                balances[i] = getNftBalance(
                    erc20TokenAddresses[i],
                    tokenIds[i]
                );
            }
        }
    }

    function sendToRelay(
        address relay,
        uint256 actualAmount,
        address erc20TokenAddress
    ) internal {
        if (relay != address(0) && actualAmount > 0) {
            transferERC20TokenOrETH(
                erc20TokenAddress,
                relay,
                uint256(actualAmount)
            );
        }
    }
}
UTXO.sol 17 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;

import "./StealthAddressStructure.sol";

struct UTXO {
    uint256 amount;
    address erc20Address;
    StealthAddressStructure stealthAddressStructure;
    uint256 timeStamp;
    uint256 tokenId;
}

struct OnChainCommitment {
    UTXO utxo;
    uint256 commitment;
}
OwnerHinkal.sol 10 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.17;

import "@openzeppelin/contracts/access/Ownable2Step.sol";

contract OwnerHinkal is Ownable2Step {
    function renounceOwnership() public view override onlyOwner {
        revert("The Ownership cannot be renounced");
    }
}
IMerkle.sol 20 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

interface IMerkle {

    struct MerkleConstructorArgs {
        uint128 levels;
        address poseidon2;
        address poseidon4;
        address poseidon5;
    }

    function hash2(uint256 a, uint256 b) external view returns (uint256);

    function getRootHash() external view returns (uint256);

    function rootHashExists(uint256 _root) external view returns (bool);

    function logarithm2(uint256 x) external pure returns (uint256);
}
TransfererBase.sol 44 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import "@openzeppelin/contracts/interfaces/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";

contract TransfererBase {
    using SafeERC20 for IERC20;

    function transferETH(address _recepient, uint256 _value) internal {
        (bool success, ) = _recepient.call{value: _value}("");
        require(success, "Transfer Failed");
    }

    function transferERC20Token(
        address _erc20TokenAddress,
        address _to,
        uint256 _value
    ) internal {
        IERC20(_erc20TokenAddress).safeTransfer(_to, _value);
    }

    function approveERC20Token(
        address _erc20TokenAddress,
        address _to,
        uint256 _value
    ) internal {
        IERC20(_erc20TokenAddress).safeApprove(_to, 0);
        IERC20(_erc20TokenAddress).safeApprove(_to, _value);
    }

    function approveUnlimited(
        address _erc20TokenAddress,
        address _to
    ) internal {
        if (
            IERC20(_erc20TokenAddress).allowance(address(this), _to) <
            type(uint256).max / 2
        ) {
            IERC20(_erc20TokenAddress).safeApprove(_to, 0);
            IERC20(_erc20TokenAddress).safeApprove(_to, type(uint256).max);
        }
    }
}
VerifierFacade.sol 59 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import "./OwnerHinkal.sol";
import "./types/Dimensions.sol";
import "./types/IVerifierFacade.sol";
import "./types/IVerifier.sol";

///@title A Facade pattern for zk proof Verifiers
contract VerifierFacade is IVerifierFacade, OwnerHinkal {
    mapping(uint256 => IVerifier) internal verifierMap;

    function registerVerifiers(
        uint256[] calldata verifierIds,
        address[] calldata verifierAddresses
    ) external onlyOwner {
        for (uint i = 0; i < verifierIds.length; i++) {
            verifierMap[verifierIds[i]] = IVerifier(verifierAddresses[i]);
            emit VerifierRegistered(verifierIds[i], verifierAddresses[i]);
        }
    }

    function removeVerifier(uint256 verifierId) external onlyOwner {
        delete verifierMap[verifierId];
        emit VerifierRemoved(verifierId);
    }

    function buildVerifierId(
        Dimensions calldata dimensions,
        uint256 externalActionId
    ) public pure returns (uint256) {
        return
            uint256(
                keccak256(
                    abi.encode(
                        dimensions.tokenNumber,
                        dimensions.nullifierAmount,
                        dimensions.outputAmount,
                        externalActionId
                    )
                )
            );
    }

    function verifyProof(
        uint256[2] calldata a,
        uint256[2][2] calldata b,
        uint256[2] calldata c,
        uint256[] memory input,
        uint256 verifierId
    ) internal view returns (bool) {
        IVerifier verifier = verifierMap[verifierId];
        require(
            address(verifier) != address(0),
            "Cannot find appropriate verifier"
        );
        return verifier.verifyProof(a, b, c, input, verifierId);
    }
}
IVerifier.sol 12 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.6;

interface IVerifier {
    function verifyProof(
        uint256[2] memory a,
        uint256[2][2] memory b,
        uint256[2] memory c,
        uint256[] memory input,
        uint256 verifierId
    ) view external returns (bool);
}
CircomData.sol 34 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.6;

import "./StealthAddressStructure.sol";

uint256 constant CIRCOM_P = 21888242871839275222246405745257275088548364400416034343698204186575808495617; // https://docs.circom.io/circom-language/basic-operators/

struct CircomData {
    uint256 rootHashHinkal;
    address[] erc20TokenAddresses;
    uint256[] tokenIds;
    int256[] amountChanges;
    uint256[][] inputNullifiers;
    uint256[][] outCommitments;
    bytes[][] encryptedOutputs;
    uint256[] flatFees;
    uint256 timeStamp;
    StealthAddressStructure stealthAddressStructure;
    uint256 rootHashAccessToken;
    uint256 calldataHash;
    uint16 publicSignalCount;
    address relay;
    address externalAddress;
    uint256 externalActionId;
    bytes externalActionMetadata;
    HookData hookData;
}

struct HookData {
    address preHookContract;
    address hookContract;
    bytes preHookMetadata;
    bytes postHookMetadata;
}
Dimensions.sol 8 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.6;

struct Dimensions {
    uint16 tokenNumber;
    uint16 nullifierAmount;
    uint16 outputAmount;
}
IPoseidon2.sol 8 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;

interface IPoseidon2 {
    function poseidon(uint256[2] memory input) external pure returns (uint256);

    function poseidon(bytes32[2] memory input) external pure returns (bytes32);
}
IPoseidon4.sol 8 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;

interface IPoseidon4 {
    function poseidon(uint256[4] memory input) external pure returns (uint256);

    function poseidon(bytes32[4] memory input) external pure returns (bytes32);
}
IPoseidon5.sol 8 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;

interface IPoseidon5 {
    function poseidon(uint256[5] memory input) external pure returns (uint256);

    function poseidon(bytes32[5] memory input) external pure returns (bytes32);
}
IRelayStore.sol 51 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

struct RelayEntry {
    address relayAddress;
    string url;
    uint256 priority;
}

interface IRelayStore {
    event RelayPercentageChanged(uint32 newRelayPercentage);
    event RelayPercentageExternalChanged(uint32 newRelayPercentage);
    event RelayAddedOrSet(address relayAddress, string url, uint256 priority);
    event RelayRemoved(address relayAddress);

    function getRelayPercentage(
        uint256 amount,
        address erc20Address
    ) external view returns (uint32);

    function setRelayPercentage(uint32 _relayPercentage) external;

    function getRelayPercentageExternal(
        uint256 amount,
        address erc20Address,
        uint256 externalActionId
    ) external view returns (uint32);

    function setRelayPercentageExternal(
        uint32 _relayPercentageExternal
    ) external;

    function isRelayInList(address relay) external view returns (bool);

    function getRelayStore() external view returns (RelayEntry[] memory);

    function removeRelay(address _relayAddress) external;

    function addOrSetRelay(
        address relayAddress,
        string memory url,
        uint256 priority
    ) external;

    function calculateRelayFee(
        uint256 balance,
        address tokenAddress,
        uint256 flatFee,
        uint256 externalActionId
    ) external view returns (uint256 relayFee);
}
IHinkalHelper.sol 24 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import "./IRelayStore.sol";
import "./ICircomDataBuilder.sol";
import "./Dimensions.sol";
import "./IRelayStore.sol";
import "./IERC20TokenRegistry.sol";

interface IHinkalHelper is IRelayStore, IERC20TokenRegistry {
    function getRelayStore() external view returns (RelayEntry[] memory);

    function relayerIsValid(address relay) external view;

    function checkTokenRegistry(
        address[] calldata erc20TokenAddresses,
        int256[] calldata amountChanges
    ) external view;

    function performHinkalChecks(
        CircomData calldata circomData,
        Dimensions calldata dimensions
    ) external view returns (uint256[] memory);
}
IHinkalWrapper.sol 10 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

interface IHinkalWrapper {
    function sender() external view returns (address);

    function value() external view returns (uint256);

    function getETH() external;
}
IExternalAction.sol 11 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.6;

import "./CircomData.sol";
import "./UTXO.sol";

interface IExternalAction {
    function runAction(
        CircomData calldata circomData
    ) external returns (UTXO[] memory);
}
IVerifierFacade.sol 21 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;
import "./IVerifier.sol";
import "./Dimensions.sol";

interface IVerifierFacade {
    event VerifierRegistered(uint256 verifierId, address verifierAddress);
    event VerifierRemoved(uint256 verifierId);

    function registerVerifiers(
        uint256[] calldata verifierIds,
        address[] calldata verifierAddresses
    ) external;

    function removeVerifier(uint256 verifierId) external;

    function buildVerifierId(
        Dimensions calldata dimensions,
        uint256 externalActionId
    ) external pure returns (uint256);
}
ICircomDataBuilder.sol 14 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.0;

import "./CircomData.sol";

interface ICircomDataBuilder {
    function getHashedCalldata(
        CircomData memory circomData
    ) external pure returns (uint256);

    function formInputForCircom(
        CircomData memory circomData
    ) external pure returns (uint256[] memory input);
}
IERC20TokenRegistry.sol 28 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

interface IERC20TokenRegistry {

    event RegistryStateChanged(bool isEnabled);
    event TokenAdded(address erc20Token);
    event TokenRemoved(address erc20Token);
    event TokenLimit(address erc20Token, uint256 tokenLimit);

    function tokenRegistry(address) external returns (bool);

    function tokenLimits(address) external returns (uint256);

    function enabled() external view returns (bool);

    function changeState(bool _enabled) external;

    function addERCToken(address erc20Token) external;

    function removeToken(address erc20Token) external;

    function tokenInRegistry(address erc20Token) external view returns (bool);

    function setTokenLimit(address _token, uint256 _tokenLimit) external;

    function getTokenLimit(address _token) external view returns (uint256);
}
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);
        }
    }
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)

pragma solidity ^0.8.0;

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

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
Ownable.sol 83 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions. 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);
    }
}
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);
        }
    }
}
StealthAddressStructure.sol 9 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.6;

struct StealthAddressStructure {
    uint256 extraRandomization;
    uint256 stealthAddress;
    uint256 H0;
    uint256 H1;
}
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
IERC721.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC721.sol)

pragma solidity ^0.8.0;

import "../token/ERC721/IERC721.sol";
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);
}
Ownable2Step.sol 57 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable2Step.sol)

pragma solidity ^0.8.0;

import "./Ownable.sol";

/**
 * @dev Contract module which provides 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} and {acceptOwnership}.
 *
 * This module is used through inheritance. It will make available all functions
 * from parent (Ownable).
 */
abstract contract Ownable2Step is Ownable {
    address private _pendingOwner;

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

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

    /**
     * @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual override onlyOwner {
        _pendingOwner = newOwner;
        emit OwnershipTransferStarted(owner(), newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual override {
        delete _pendingOwner;
        super._transferOwnership(newOwner);
    }

    /**
     * @dev The new owner accepts the ownership transfer.
     */
    function acceptOwnership() public virtual {
        address sender = _msgSender();
        require(pendingOwner() == sender, "Ownable2Step: caller is not the new owner");
        _transferOwnership(sender);
    }
}
IERC4626.sol 232 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
 * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
 *
 * _Available since v4.7._
 */
interface IERC4626 is IERC20, IERC20Metadata {
    event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);

    event Withdraw(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256 assets,
        uint256 shares
    );

    /**
     * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
     *
     * - MUST be an ERC-20 token contract.
     * - MUST NOT revert.
     */
    function asset() external view returns (address assetTokenAddress);

    /**
     * @dev Returns the total amount of the underlying asset that is “managed” by Vault.
     *
     * - SHOULD include any compounding that occurs from yield.
     * - MUST be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT revert.
     */
    function totalAssets() external view returns (uint256 totalManagedAssets);

    /**
     * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToShares(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     *
     * - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
     * - MUST NOT show any variations depending on the caller.
     * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
     * - MUST NOT revert.
     *
     * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
     * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
     * from.
     */
    function convertToAssets(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
     * through a deposit call.
     *
     * - MUST return a limited value if receiver is subject to some deposit limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
     * - MUST NOT revert.
     */
    function maxDeposit(address receiver) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
     *   call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
     *   in the same transaction.
     * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
     *   deposit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewDeposit(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   deposit execution, and are accounted for during deposit.
     * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function deposit(uint256 assets, address receiver) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
     * - MUST return a limited value if receiver is subject to some mint limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
     * - MUST NOT revert.
     */
    function maxMint(address receiver) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
     * current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
     *   in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
     *   same transaction.
     * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
     *   would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by minting.
     */
    function previewMint(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
     *
     * - MUST emit the Deposit event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
     *   execution, and are accounted for during mint.
     * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
     *   approving enough underlying tokens to the Vault contract, etc).
     *
     * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
     */
    function mint(uint256 shares, address receiver) external returns (uint256 assets);

    /**
     * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
     * Vault, through a withdraw call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxWithdraw(address owner) external view returns (uint256 maxAssets);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
     *   call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
     *   called
     *   in the same transaction.
     * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
     *   the withdrawal would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by depositing.
     */
    function previewWithdraw(uint256 assets) external view returns (uint256 shares);

    /**
     * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   withdraw execution, and are accounted for during withdraw.
     * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);

    /**
     * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
     * through a redeem call.
     *
     * - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
     * - MUST NOT revert.
     */
    function maxRedeem(address owner) external view returns (uint256 maxShares);

    /**
     * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
     * given current on-chain conditions.
     *
     * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
     *   in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
     *   same transaction.
     * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
     *   redemption would be accepted, regardless if the user has enough shares, etc.
     * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
     * - MUST NOT revert.
     *
     * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
     * share price or some other type of condition, meaning the depositor will lose assets by redeeming.
     */
    function previewRedeem(uint256 shares) external view returns (uint256 assets);

    /**
     * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
     *
     * - MUST emit the Withdraw event.
     * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
     *   redeem execution, and are accounted for during redeem.
     * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
     *   not having enough shares, etc).
     *
     * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
     * Those methods should be performed separately.
     */
    function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
SafeCast.sol 1136 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.

pragma solidity ^0.8.0;

/**
 * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
 * checks.
 *
 * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
 * easily result in undesired exploitation or bugs, since developers usually
 * assume that overflows raise errors. `SafeCast` restores this intuition by
 * reverting the transaction when such an operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 *
 * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
 * all math on `uint256` and `int256` and then downcasting.
 */
library SafeCast {
    /**
     * @dev Returns the downcasted uint248 from uint256, reverting on
     * overflow (when the input is greater than largest uint248).
     *
     * Counterpart to Solidity's `uint248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toUint248(uint256 value) internal pure returns (uint248) {
        require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
        return uint248(value);
    }

    /**
     * @dev Returns the downcasted uint240 from uint256, reverting on
     * overflow (when the input is greater than largest uint240).
     *
     * Counterpart to Solidity's `uint240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toUint240(uint256 value) internal pure returns (uint240) {
        require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
        return uint240(value);
    }

    /**
     * @dev Returns the downcasted uint232 from uint256, reverting on
     * overflow (when the input is greater than largest uint232).
     *
     * Counterpart to Solidity's `uint232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toUint232(uint256 value) internal pure returns (uint232) {
        require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
        return uint232(value);
    }

    /**
     * @dev Returns the downcasted uint224 from uint256, reverting on
     * overflow (when the input is greater than largest uint224).
     *
     * Counterpart to Solidity's `uint224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.2._
     */
    function toUint224(uint256 value) internal pure returns (uint224) {
        require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
        return uint224(value);
    }

    /**
     * @dev Returns the downcasted uint216 from uint256, reverting on
     * overflow (when the input is greater than largest uint216).
     *
     * Counterpart to Solidity's `uint216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toUint216(uint256 value) internal pure returns (uint216) {
        require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
        return uint216(value);
    }

    /**
     * @dev Returns the downcasted uint208 from uint256, reverting on
     * overflow (when the input is greater than largest uint208).
     *
     * Counterpart to Solidity's `uint208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toUint208(uint256 value) internal pure returns (uint208) {
        require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
        return uint208(value);
    }

    /**
     * @dev Returns the downcasted uint200 from uint256, reverting on
     * overflow (when the input is greater than largest uint200).
     *
     * Counterpart to Solidity's `uint200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toUint200(uint256 value) internal pure returns (uint200) {
        require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
        return uint200(value);
    }

    /**
     * @dev Returns the downcasted uint192 from uint256, reverting on
     * overflow (when the input is greater than largest uint192).
     *
     * Counterpart to Solidity's `uint192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toUint192(uint256 value) internal pure returns (uint192) {
        require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
        return uint192(value);
    }

    /**
     * @dev Returns the downcasted uint184 from uint256, reverting on
     * overflow (when the input is greater than largest uint184).
     *
     * Counterpart to Solidity's `uint184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toUint184(uint256 value) internal pure returns (uint184) {
        require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
        return uint184(value);
    }

    /**
     * @dev Returns the downcasted uint176 from uint256, reverting on
     * overflow (when the input is greater than largest uint176).
     *
     * Counterpart to Solidity's `uint176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toUint176(uint256 value) internal pure returns (uint176) {
        require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
        return uint176(value);
    }

    /**
     * @dev Returns the downcasted uint168 from uint256, reverting on
     * overflow (when the input is greater than largest uint168).
     *
     * Counterpart to Solidity's `uint168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toUint168(uint256 value) internal pure returns (uint168) {
        require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
        return uint168(value);
    }

    /**
     * @dev Returns the downcasted uint160 from uint256, reverting on
     * overflow (when the input is greater than largest uint160).
     *
     * Counterpart to Solidity's `uint160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toUint160(uint256 value) internal pure returns (uint160) {
        require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
        return uint160(value);
    }

    /**
     * @dev Returns the downcasted uint152 from uint256, reverting on
     * overflow (when the input is greater than largest uint152).
     *
     * Counterpart to Solidity's `uint152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toUint152(uint256 value) internal pure returns (uint152) {
        require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
        return uint152(value);
    }

    /**
     * @dev Returns the downcasted uint144 from uint256, reverting on
     * overflow (when the input is greater than largest uint144).
     *
     * Counterpart to Solidity's `uint144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toUint144(uint256 value) internal pure returns (uint144) {
        require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
        return uint144(value);
    }

    /**
     * @dev Returns the downcasted uint136 from uint256, reverting on
     * overflow (when the input is greater than largest uint136).
     *
     * Counterpart to Solidity's `uint136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toUint136(uint256 value) internal pure returns (uint136) {
        require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
        return uint136(value);
    }

    /**
     * @dev Returns the downcasted uint128 from uint256, reverting on
     * overflow (when the input is greater than largest uint128).
     *
     * Counterpart to Solidity's `uint128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v2.5._
     */
    function toUint128(uint256 value) internal pure returns (uint128) {
        require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
        return uint128(value);
    }

    /**
     * @dev Returns the downcasted uint120 from uint256, reverting on
     * overflow (when the input is greater than largest uint120).
     *
     * Counterpart to Solidity's `uint120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toUint120(uint256 value) internal pure returns (uint120) {
        require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
        return uint120(value);
    }

    /**
     * @dev Returns the downcasted uint112 from uint256, reverting on
     * overflow (when the input is greater than largest uint112).
     *
     * Counterpart to Solidity's `uint112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toUint112(uint256 value) internal pure returns (uint112) {
        require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
        return uint112(value);
    }

    /**
     * @dev Returns the downcasted uint104 from uint256, reverting on
     * overflow (when the input is greater than largest uint104).
     *
     * Counterpart to Solidity's `uint104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toUint104(uint256 value) internal pure returns (uint104) {
        require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
        return uint104(value);
    }

    /**
     * @dev Returns the downcasted uint96 from uint256, reverting on
     * overflow (when the input is greater than largest uint96).
     *
     * Counterpart to Solidity's `uint96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.2._
     */
    function toUint96(uint256 value) internal pure returns (uint96) {
        require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
        return uint96(value);
    }

    /**
     * @dev Returns the downcasted uint88 from uint256, reverting on
     * overflow (when the input is greater than largest uint88).
     *
     * Counterpart to Solidity's `uint88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toUint88(uint256 value) internal pure returns (uint88) {
        require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
        return uint88(value);
    }

    /**
     * @dev Returns the downcasted uint80 from uint256, reverting on
     * overflow (when the input is greater than largest uint80).
     *
     * Counterpart to Solidity's `uint80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toUint80(uint256 value) internal pure returns (uint80) {
        require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
        return uint80(value);
    }

    /**
     * @dev Returns the downcasted uint72 from uint256, reverting on
     * overflow (when the input is greater than largest uint72).
     *
     * Counterpart to Solidity's `uint72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toUint72(uint256 value) internal pure returns (uint72) {
        require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
        return uint72(value);
    }

    /**
     * @dev Returns the downcasted uint64 from uint256, reverting on
     * overflow (when the input is greater than largest uint64).
     *
     * Counterpart to Solidity's `uint64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v2.5._
     */
    function toUint64(uint256 value) internal pure returns (uint64) {
        require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
        return uint64(value);
    }

    /**
     * @dev Returns the downcasted uint56 from uint256, reverting on
     * overflow (when the input is greater than largest uint56).
     *
     * Counterpart to Solidity's `uint56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toUint56(uint256 value) internal pure returns (uint56) {
        require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
        return uint56(value);
    }

    /**
     * @dev Returns the downcasted uint48 from uint256, reverting on
     * overflow (when the input is greater than largest uint48).
     *
     * Counterpart to Solidity's `uint48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toUint48(uint256 value) internal pure returns (uint48) {
        require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
        return uint48(value);
    }

    /**
     * @dev Returns the downcasted uint40 from uint256, reverting on
     * overflow (when the input is greater than largest uint40).
     *
     * Counterpart to Solidity's `uint40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toUint40(uint256 value) internal pure returns (uint40) {
        require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
        return uint40(value);
    }

    /**
     * @dev Returns the downcasted uint32 from uint256, reverting on
     * overflow (when the input is greater than largest uint32).
     *
     * Counterpart to Solidity's `uint32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v2.5._
     */
    function toUint32(uint256 value) internal pure returns (uint32) {
        require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
        return uint32(value);
    }

    /**
     * @dev Returns the downcasted uint24 from uint256, reverting on
     * overflow (when the input is greater than largest uint24).
     *
     * Counterpart to Solidity's `uint24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toUint24(uint256 value) internal pure returns (uint24) {
        require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
        return uint24(value);
    }

    /**
     * @dev Returns the downcasted uint16 from uint256, reverting on
     * overflow (when the input is greater than largest uint16).
     *
     * Counterpart to Solidity's `uint16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v2.5._
     */
    function toUint16(uint256 value) internal pure returns (uint16) {
        require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
        return uint16(value);
    }

    /**
     * @dev Returns the downcasted uint8 from uint256, reverting on
     * overflow (when the input is greater than largest uint8).
     *
     * Counterpart to Solidity's `uint8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v2.5._
     */
    function toUint8(uint256 value) internal pure returns (uint8) {
        require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
        return uint8(value);
    }

    /**
     * @dev Converts a signed int256 into an unsigned uint256.
     *
     * Requirements:
     *
     * - input must be greater than or equal to 0.
     *
     * _Available since v3.0._
     */
    function toUint256(int256 value) internal pure returns (uint256) {
        require(value >= 0, "SafeCast: value must be positive");
        return uint256(value);
    }

    /**
     * @dev Returns the downcasted int248 from int256, reverting on
     * overflow (when the input is less than smallest int248 or
     * greater than largest int248).
     *
     * Counterpart to Solidity's `int248` operator.
     *
     * Requirements:
     *
     * - input must fit into 248 bits
     *
     * _Available since v4.7._
     */
    function toInt248(int256 value) internal pure returns (int248 downcasted) {
        downcasted = int248(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
    }

    /**
     * @dev Returns the downcasted int240 from int256, reverting on
     * overflow (when the input is less than smallest int240 or
     * greater than largest int240).
     *
     * Counterpart to Solidity's `int240` operator.
     *
     * Requirements:
     *
     * - input must fit into 240 bits
     *
     * _Available since v4.7._
     */
    function toInt240(int256 value) internal pure returns (int240 downcasted) {
        downcasted = int240(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
    }

    /**
     * @dev Returns the downcasted int232 from int256, reverting on
     * overflow (when the input is less than smallest int232 or
     * greater than largest int232).
     *
     * Counterpart to Solidity's `int232` operator.
     *
     * Requirements:
     *
     * - input must fit into 232 bits
     *
     * _Available since v4.7._
     */
    function toInt232(int256 value) internal pure returns (int232 downcasted) {
        downcasted = int232(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
    }

    /**
     * @dev Returns the downcasted int224 from int256, reverting on
     * overflow (when the input is less than smallest int224 or
     * greater than largest int224).
     *
     * Counterpart to Solidity's `int224` operator.
     *
     * Requirements:
     *
     * - input must fit into 224 bits
     *
     * _Available since v4.7._
     */
    function toInt224(int256 value) internal pure returns (int224 downcasted) {
        downcasted = int224(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
    }

    /**
     * @dev Returns the downcasted int216 from int256, reverting on
     * overflow (when the input is less than smallest int216 or
     * greater than largest int216).
     *
     * Counterpart to Solidity's `int216` operator.
     *
     * Requirements:
     *
     * - input must fit into 216 bits
     *
     * _Available since v4.7._
     */
    function toInt216(int256 value) internal pure returns (int216 downcasted) {
        downcasted = int216(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
    }

    /**
     * @dev Returns the downcasted int208 from int256, reverting on
     * overflow (when the input is less than smallest int208 or
     * greater than largest int208).
     *
     * Counterpart to Solidity's `int208` operator.
     *
     * Requirements:
     *
     * - input must fit into 208 bits
     *
     * _Available since v4.7._
     */
    function toInt208(int256 value) internal pure returns (int208 downcasted) {
        downcasted = int208(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
    }

    /**
     * @dev Returns the downcasted int200 from int256, reverting on
     * overflow (when the input is less than smallest int200 or
     * greater than largest int200).
     *
     * Counterpart to Solidity's `int200` operator.
     *
     * Requirements:
     *
     * - input must fit into 200 bits
     *
     * _Available since v4.7._
     */
    function toInt200(int256 value) internal pure returns (int200 downcasted) {
        downcasted = int200(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
    }

    /**
     * @dev Returns the downcasted int192 from int256, reverting on
     * overflow (when the input is less than smallest int192 or
     * greater than largest int192).
     *
     * Counterpart to Solidity's `int192` operator.
     *
     * Requirements:
     *
     * - input must fit into 192 bits
     *
     * _Available since v4.7._
     */
    function toInt192(int256 value) internal pure returns (int192 downcasted) {
        downcasted = int192(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
    }

    /**
     * @dev Returns the downcasted int184 from int256, reverting on
     * overflow (when the input is less than smallest int184 or
     * greater than largest int184).
     *
     * Counterpart to Solidity's `int184` operator.
     *
     * Requirements:
     *
     * - input must fit into 184 bits
     *
     * _Available since v4.7._
     */
    function toInt184(int256 value) internal pure returns (int184 downcasted) {
        downcasted = int184(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
    }

    /**
     * @dev Returns the downcasted int176 from int256, reverting on
     * overflow (when the input is less than smallest int176 or
     * greater than largest int176).
     *
     * Counterpart to Solidity's `int176` operator.
     *
     * Requirements:
     *
     * - input must fit into 176 bits
     *
     * _Available since v4.7._
     */
    function toInt176(int256 value) internal pure returns (int176 downcasted) {
        downcasted = int176(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
    }

    /**
     * @dev Returns the downcasted int168 from int256, reverting on
     * overflow (when the input is less than smallest int168 or
     * greater than largest int168).
     *
     * Counterpart to Solidity's `int168` operator.
     *
     * Requirements:
     *
     * - input must fit into 168 bits
     *
     * _Available since v4.7._
     */
    function toInt168(int256 value) internal pure returns (int168 downcasted) {
        downcasted = int168(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
    }

    /**
     * @dev Returns the downcasted int160 from int256, reverting on
     * overflow (when the input is less than smallest int160 or
     * greater than largest int160).
     *
     * Counterpart to Solidity's `int160` operator.
     *
     * Requirements:
     *
     * - input must fit into 160 bits
     *
     * _Available since v4.7._
     */
    function toInt160(int256 value) internal pure returns (int160 downcasted) {
        downcasted = int160(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
    }

    /**
     * @dev Returns the downcasted int152 from int256, reverting on
     * overflow (when the input is less than smallest int152 or
     * greater than largest int152).
     *
     * Counterpart to Solidity's `int152` operator.
     *
     * Requirements:
     *
     * - input must fit into 152 bits
     *
     * _Available since v4.7._
     */
    function toInt152(int256 value) internal pure returns (int152 downcasted) {
        downcasted = int152(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
    }

    /**
     * @dev Returns the downcasted int144 from int256, reverting on
     * overflow (when the input is less than smallest int144 or
     * greater than largest int144).
     *
     * Counterpart to Solidity's `int144` operator.
     *
     * Requirements:
     *
     * - input must fit into 144 bits
     *
     * _Available since v4.7._
     */
    function toInt144(int256 value) internal pure returns (int144 downcasted) {
        downcasted = int144(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
    }

    /**
     * @dev Returns the downcasted int136 from int256, reverting on
     * overflow (when the input is less than smallest int136 or
     * greater than largest int136).
     *
     * Counterpart to Solidity's `int136` operator.
     *
     * Requirements:
     *
     * - input must fit into 136 bits
     *
     * _Available since v4.7._
     */
    function toInt136(int256 value) internal pure returns (int136 downcasted) {
        downcasted = int136(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
    }

    /**
     * @dev Returns the downcasted int128 from int256, reverting on
     * overflow (when the input is less than smallest int128 or
     * greater than largest int128).
     *
     * Counterpart to Solidity's `int128` operator.
     *
     * Requirements:
     *
     * - input must fit into 128 bits
     *
     * _Available since v3.1._
     */
    function toInt128(int256 value) internal pure returns (int128 downcasted) {
        downcasted = int128(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
    }

    /**
     * @dev Returns the downcasted int120 from int256, reverting on
     * overflow (when the input is less than smallest int120 or
     * greater than largest int120).
     *
     * Counterpart to Solidity's `int120` operator.
     *
     * Requirements:
     *
     * - input must fit into 120 bits
     *
     * _Available since v4.7._
     */
    function toInt120(int256 value) internal pure returns (int120 downcasted) {
        downcasted = int120(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
    }

    /**
     * @dev Returns the downcasted int112 from int256, reverting on
     * overflow (when the input is less than smallest int112 or
     * greater than largest int112).
     *
     * Counterpart to Solidity's `int112` operator.
     *
     * Requirements:
     *
     * - input must fit into 112 bits
     *
     * _Available since v4.7._
     */
    function toInt112(int256 value) internal pure returns (int112 downcasted) {
        downcasted = int112(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
    }

    /**
     * @dev Returns the downcasted int104 from int256, reverting on
     * overflow (when the input is less than smallest int104 or
     * greater than largest int104).
     *
     * Counterpart to Solidity's `int104` operator.
     *
     * Requirements:
     *
     * - input must fit into 104 bits
     *
     * _Available since v4.7._
     */
    function toInt104(int256 value) internal pure returns (int104 downcasted) {
        downcasted = int104(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
    }

    /**
     * @dev Returns the downcasted int96 from int256, reverting on
     * overflow (when the input is less than smallest int96 or
     * greater than largest int96).
     *
     * Counterpart to Solidity's `int96` operator.
     *
     * Requirements:
     *
     * - input must fit into 96 bits
     *
     * _Available since v4.7._
     */
    function toInt96(int256 value) internal pure returns (int96 downcasted) {
        downcasted = int96(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
    }

    /**
     * @dev Returns the downcasted int88 from int256, reverting on
     * overflow (when the input is less than smallest int88 or
     * greater than largest int88).
     *
     * Counterpart to Solidity's `int88` operator.
     *
     * Requirements:
     *
     * - input must fit into 88 bits
     *
     * _Available since v4.7._
     */
    function toInt88(int256 value) internal pure returns (int88 downcasted) {
        downcasted = int88(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
    }

    /**
     * @dev Returns the downcasted int80 from int256, reverting on
     * overflow (when the input is less than smallest int80 or
     * greater than largest int80).
     *
     * Counterpart to Solidity's `int80` operator.
     *
     * Requirements:
     *
     * - input must fit into 80 bits
     *
     * _Available since v4.7._
     */
    function toInt80(int256 value) internal pure returns (int80 downcasted) {
        downcasted = int80(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
    }

    /**
     * @dev Returns the downcasted int72 from int256, reverting on
     * overflow (when the input is less than smallest int72 or
     * greater than largest int72).
     *
     * Counterpart to Solidity's `int72` operator.
     *
     * Requirements:
     *
     * - input must fit into 72 bits
     *
     * _Available since v4.7._
     */
    function toInt72(int256 value) internal pure returns (int72 downcasted) {
        downcasted = int72(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
    }

    /**
     * @dev Returns the downcasted int64 from int256, reverting on
     * overflow (when the input is less than smallest int64 or
     * greater than largest int64).
     *
     * Counterpart to Solidity's `int64` operator.
     *
     * Requirements:
     *
     * - input must fit into 64 bits
     *
     * _Available since v3.1._
     */
    function toInt64(int256 value) internal pure returns (int64 downcasted) {
        downcasted = int64(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
    }

    /**
     * @dev Returns the downcasted int56 from int256, reverting on
     * overflow (when the input is less than smallest int56 or
     * greater than largest int56).
     *
     * Counterpart to Solidity's `int56` operator.
     *
     * Requirements:
     *
     * - input must fit into 56 bits
     *
     * _Available since v4.7._
     */
    function toInt56(int256 value) internal pure returns (int56 downcasted) {
        downcasted = int56(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
    }

    /**
     * @dev Returns the downcasted int48 from int256, reverting on
     * overflow (when the input is less than smallest int48 or
     * greater than largest int48).
     *
     * Counterpart to Solidity's `int48` operator.
     *
     * Requirements:
     *
     * - input must fit into 48 bits
     *
     * _Available since v4.7._
     */
    function toInt48(int256 value) internal pure returns (int48 downcasted) {
        downcasted = int48(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
    }

    /**
     * @dev Returns the downcasted int40 from int256, reverting on
     * overflow (when the input is less than smallest int40 or
     * greater than largest int40).
     *
     * Counterpart to Solidity's `int40` operator.
     *
     * Requirements:
     *
     * - input must fit into 40 bits
     *
     * _Available since v4.7._
     */
    function toInt40(int256 value) internal pure returns (int40 downcasted) {
        downcasted = int40(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
    }

    /**
     * @dev Returns the downcasted int32 from int256, reverting on
     * overflow (when the input is less than smallest int32 or
     * greater than largest int32).
     *
     * Counterpart to Solidity's `int32` operator.
     *
     * Requirements:
     *
     * - input must fit into 32 bits
     *
     * _Available since v3.1._
     */
    function toInt32(int256 value) internal pure returns (int32 downcasted) {
        downcasted = int32(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
    }

    /**
     * @dev Returns the downcasted int24 from int256, reverting on
     * overflow (when the input is less than smallest int24 or
     * greater than largest int24).
     *
     * Counterpart to Solidity's `int24` operator.
     *
     * Requirements:
     *
     * - input must fit into 24 bits
     *
     * _Available since v4.7._
     */
    function toInt24(int256 value) internal pure returns (int24 downcasted) {
        downcasted = int24(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
    }

    /**
     * @dev Returns the downcasted int16 from int256, reverting on
     * overflow (when the input is less than smallest int16 or
     * greater than largest int16).
     *
     * Counterpart to Solidity's `int16` operator.
     *
     * Requirements:
     *
     * - input must fit into 16 bits
     *
     * _Available since v3.1._
     */
    function toInt16(int256 value) internal pure returns (int16 downcasted) {
        downcasted = int16(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
    }

    /**
     * @dev Returns the downcasted int8 from int256, reverting on
     * overflow (when the input is less than smallest int8 or
     * greater than largest int8).
     *
     * Counterpart to Solidity's `int8` operator.
     *
     * Requirements:
     *
     * - input must fit into 8 bits
     *
     * _Available since v3.1._
     */
    function toInt8(int256 value) internal pure returns (int8 downcasted) {
        downcasted = int8(value);
        require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
    }

    /**
     * @dev Converts an unsigned uint256 into a signed int256.
     *
     * Requirements:
     *
     * - input must be less than or equal to maxInt256.
     *
     * _Available since v3.0._
     */
    function toInt256(uint256 value) internal pure returns (int256) {
        // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
        require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
        return int256(value);
    }
}
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);
}
ExternalActionBase.sol 42 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import {CircomData} from "../types/CircomData.sol";
import {UTXO} from "../types/UTXO.sol";
import {IExternalAction} from "../types/IExternalAction.sol";
import {OwnerHinkal} from "../OwnerHinkal.sol";

abstract contract ExternalActionBase is IExternalAction, OwnerHinkal {
    mapping(address => bool) internal isAllowedRecipient;

    /*
     * @dev Modifier to check if the sender is allowed to call the action
     * @dev Used to handle VolatileTokenAction and Hinkal interactions
     */
    modifier onlyAllowedRecipient() {
        require(
            isAllowedRecipient[msg.sender],
            "ExternalActionBase: sender not allowed"
        );
        _;
    }

    constructor(address[] memory _allowedRecipients) {
        for (uint i = 0; i < _allowedRecipients.length; i++) {
            isAllowedRecipient[_allowedRecipients[i]] = true;
        }
    }

    function setAllowedRecipients(
        address[] calldata recipients
    ) external onlyOwner {
        for (uint i = 0; i < recipients.length; i++) {
            require(recipients[i] != address(0), "zero address!");
            isAllowedRecipient[recipients[i]] = true;
        }
    }

    function runAction(
        CircomData calldata circomData
    ) external virtual returns (UTXO[] memory utxoSet) {}
}
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));
    }
}
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);
}
IERC721Receiver.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)

pragma solidity ^0.8.0;

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

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
HinkalStakeDataDecoder.sol 16 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

enum HinkalStakeAction {
    DepositOrStake,
    Unstake
}

abstract contract HinkalStakeDataDecoder {
    function decodeHinkalStake(bytes memory data) internal pure returns (HinkalStakeAction, uint256, address, bytes memory, bytes memory) {
        return abi.decode(
            data,
            (HinkalStakeAction, uint256, address, bytes, bytes)
        );
    }
}
HinkalStakeExternalAction.sol 349 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.17;

import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
import {IERC4626} from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import {IHinkalHelper} from "../../types/IHinkalHelper.sol";
import {CircomData} from "../../types/IExternalAction.sol";
import {ExternalActionBase} from "../ExternalActionBase.sol";
import {Transferer} from "../../Transferer.sol";
import {UTXO} from "../../types/UTXO.sol";
import {IHinkalWrapper} from "../../types/IHinkalWrapper.sol";
import {Merkle} from "../../Merkle.sol";
import {VerifierFacade} from "../../VerifierFacade.sol";
import {OwnerHinkal} from "../../OwnerHinkal.sol";
import {HinkalStakeDataDecoder, HinkalStakeAction} from "./HinkalStakeDataDecoder.sol";

struct StakeProverData {
    uint256[] nullifiers;
    uint256[] stakeAmounts;
    address[] erc20TokenAddresses;
    address[] stakedTokenRecipients;
    uint256 stakedMerkleRoot;
}

struct StakeProverPermissionlessData {
    uint256 maxAllowedTimestamp;
    uint256 stakeCommitment;
}

contract HinkalStakeExternalAction is
    ExternalActionBase,
    Merkle,
    VerifierFacade,
    Transferer,
    HinkalStakeDataDecoder
{
    IHinkalWrapper public hinkalWrapper;

    mapping(address => IERC4626) public tokenToHtoken;
    mapping(address => mapping(uint256 => bool)) public isAmountValid;
    mapping(address => bool) public isRestrictionDisabled;
    mapping(uint256 => bool) public usedNullifiers;

    uint256 public minAllowedTimestampOffset;

    event NewStakeCommitment(
        uint256 indexed index,
        uint256 stakeCommitment,
        address indexed staker,
        address baseToken,
        uint256 stakedAmount,
        bytes encryptedStakeCommitmentContent,
        bytes encryptedStakeCommitmentContentAlt,
        uint256 timeStamp
    );

    event StakeNullified(uint256 nullifier);
    event PermissionlessMint(uint256 indexed commitment);

    event MinAllowedTimestampOffsetUpdate(uint256);
    event AmountValidityUpdate(address, uint256, bool);
    event IsRestrictionDisabledUpdate(address, bool);
    event TokenRegistryUpdate(address, address);

    error BaseTokenNotRegistered();
    error RelayForbidden();
    error MustBeDepositOrStake();
    error MustBeUnstake();
    error EtherMismatch();
    error SenderDepositorMismatch();
    error InvalidAmount();
    error InvalidInputCount();
    error InvalidProof();
    error LengthMismatch(uint8 which);
    error InvalidMerkleRoot();
    error TimestampTooNew();
    error NullifierAlreadyUsed();
    error InvalidLength();
    error InvalidHToken();

    constructor(
        address _hinkalWrapper,
        address[] memory allowedRecipients,
        MerkleConstructorArgs memory merkleConstructorArgs
    ) ExternalActionBase(allowedRecipients) Merkle(merkleConstructorArgs) {
        hinkalWrapper = IHinkalWrapper(_hinkalWrapper);
    }

    receive() external payable {}

    function updateMinAllowedTimestampOffset(
        uint256 newMinAllowedTimestampOffset
    ) external onlyOwner {
        minAllowedTimestampOffset = newMinAllowedTimestampOffset;
        emit MinAllowedTimestampOffsetUpdate(newMinAllowedTimestampOffset);
    }

    function updateAmountValidity(
        address collateral,
        uint256 amount,
        bool isValid
    ) external onlyOwner {
        isAmountValid[collateral][amount] = isValid;
        emit AmountValidityUpdate(collateral, amount, isValid);
    }

    function updateIsRestrictionDisabled(
        address collateral,
        bool isDisabled
    ) external onlyOwner {
        isRestrictionDisabled[collateral] = isDisabled;
        emit IsRestrictionDisabledUpdate(collateral, isDisabled);
    }

    function updateTokenRegistry(
        address collateral,
        address hToken
    ) external onlyOwner {
        if (hToken != address(0) && collateral != IERC4626(hToken).asset()) revert InvalidHToken();
        tokenToHtoken[collateral] = IERC4626(hToken);
        emit TokenRegistryUpdate(collateral, hToken);
    }

    function runAction(
        CircomData memory circomData
    ) external override onlyAllowedRecipient returns (UTXO[] memory) {
        if (circomData.erc20TokenAddresses.length != 1) revert InvalidLength();
        if (
            address(tokenToHtoken[circomData.erc20TokenAddresses[0]]) ==
            address(0)
        ) revert BaseTokenNotRegistered();

        if (circomData.relay != address(0)) revert RelayForbidden();

        (
            HinkalStakeAction action,
            uint256 stakeCommitment,
            address depositorAddress,
            bytes memory encryptedStakeCommitmentContent,
            bytes memory encryptedStakeCommitmentContentAlt
        ) = decodeHinkalStake(circomData.externalActionMetadata);

        if (action == HinkalStakeAction.DepositOrStake) {
            stake(
                circomData,
                stakeCommitment,
                encryptedStakeCommitmentContent,
                encryptedStakeCommitmentContentAlt,
                depositorAddress
            );
        } else {
            unstake(circomData, stakeCommitment);
        }

        return new UTXO[](0);
    }

    function stake(
        CircomData memory circomData,
        uint256 stakeCommitment,
        bytes memory encryptedStakeCommitmentContent,
        bytes memory encryptedStakeCommitmentContentAlt,
        address depositorAddress
    ) internal {
        address staker = hinkalWrapper.sender();
        uint256 amount = SafeCast.toUint256(circomData.amountChanges[0]);
        address baseToken = circomData.erc20TokenAddresses[0];

        if (depositorAddress != staker) revert SenderDepositorMismatch();

        if (stakeCommitment == 0) revert MustBeDepositOrStake();

        if (
            !(isRestrictionDisabled[baseToken] ||
                isAmountValid[baseToken][amount])
        ) {
            revert InvalidAmount();
        }
        if (baseToken == address(0)) {
            if (hinkalWrapper.value() != amount) revert EtherMismatch();
            hinkalWrapper.getETH();
            transferETH(msg.sender, amount);
        } else {
            transferTokenFrom(baseToken, staker, msg.sender, amount, 0);
        }

        addToMintingQueue(
            staker,
            baseToken,
            amount,
            stakeCommitment,
            encryptedStakeCommitmentContent,
            encryptedStakeCommitmentContentAlt,
            circomData.timeStamp
        );
    }

    function addToMintingQueue(
        address staker,
        address baseToken,
        uint256 amount,
        uint256 stakeCommitment,
        bytes memory encryptedStakeCommitmentContent,
        bytes memory encryptedStakeCommitmentContentAlt,
        uint256 timeStamp
    ) internal {
        uint256 index = insert(stakeCommitment);
        emit NewStakeCommitment(
            index,
            stakeCommitment,
            staker,
            baseToken,
            amount,
            encryptedStakeCommitmentContent,
            encryptedStakeCommitmentContentAlt,
            timeStamp
        );
    }

    function unstake(
        CircomData memory circomData,
        uint256 stakeCommitment
    ) internal {
        if (stakeCommitment != 0) revert MustBeUnstake();
        address unstaker = hinkalWrapper.sender();
        uint256 unstakedAmount = SafeCast.toUint256(
            -circomData.amountChanges[0]
        );
        address token = circomData.erc20TokenAddresses[0];

        tokenToHtoken[token].withdraw(unstakedAmount, unstaker, unstaker);
        transferERC20TokenOrETH(token, unstaker, unstakedAmount);
    }

    function mint(
        uint[2] calldata a,
        uint[2][2] calldata b,
        uint[2] calldata c,
        StakeProverData calldata stakeProverData
    ) external onlyOwner {
        uint256 inputCount = stakeProverData.nullifiers.length;
        if (inputCount == 0) revert InvalidInputCount();

        uint256[] memory input = new uint256[](4 * inputCount + 1); // stakeAmounts, erc20TokenAddresses, stakedTokenRecipients, nullifiers (x4) + stakeMerkleRoot (+1)
        input = formInput(inputCount, stakeProverData, 0, input);

        if (!verifyProof(a, b, c, input, inputCount)) revert InvalidProof();

        _mint(stakeProverData);
    }

    function mintPermissionless(
        uint[2] calldata a,
        uint[2][2] calldata b,
        uint[2] calldata c,
        StakeProverData calldata stakeProverData,
        StakeProverPermissionlessData calldata stakeProverPermissionlessData
    ) external {
        uint256 inputCount = stakeProverData.nullifiers.length;
        if (inputCount != 1) revert InvalidInputCount();

        uint256[] memory input = formPermissionLessInput(
            stakeProverData,
            stakeProverPermissionlessData
        );

        if (!verifyProof(a, b, c, input, 0)) revert InvalidProof();

        if (
            block.timestamp -
                stakeProverPermissionlessData.maxAllowedTimestamp <
            minAllowedTimestampOffset
        ) revert TimestampTooNew();

        _mint(stakeProverData);

        emit PermissionlessMint(stakeProverPermissionlessData.stakeCommitment);
    }

    function formPermissionLessInput(
        StakeProverData calldata stakeProverData,
        StakeProverPermissionlessData calldata stakeProverPermissionlessData
    ) internal returns (uint256[] memory input) {
        input = new uint256[](7);
        input[0] = stakeProverPermissionlessData.maxAllowedTimestamp;
        input[1] = stakeProverPermissionlessData.stakeCommitment;
        return formInput(1, stakeProverData, 2, input);
    }

    function _mint(StakeProverData calldata stakeProverData) internal {
        uint256 inputCount = stakeProverData.nullifiers.length;

        if (!rootHashExists(stakeProverData.stakedMerkleRoot))
            revert InvalidMerkleRoot();

        for (uint256 i = 0; i < inputCount; i++) {
            if (stakeProverData.nullifiers[i] != 0)
                tokenToHtoken[stakeProverData.erc20TokenAddresses[i]].deposit(
                    stakeProverData.stakeAmounts[i],
                    stakeProverData.stakedTokenRecipients[i]
                );
        }
    }

    function formInput(
        uint256 inputCount,
        StakeProverData memory stakeProverData,
        uint256 index,
        uint256[] memory input
    ) internal returns (uint256[] memory) {
        // dimension checks
        if (inputCount != stakeProverData.stakedTokenRecipients.length)
            revert LengthMismatch(0);
        if (inputCount != stakeProverData.erc20TokenAddresses.length)
            revert LengthMismatch(1);
        if (inputCount != stakeProverData.stakeAmounts.length)
            revert LengthMismatch(2);

        for (uint256 i = 0; i < inputCount; i++) {
            input[index++] = stakeProverData.nullifiers[i];
            if (usedNullifiers[stakeProverData.nullifiers[i]])
                revert NullifierAlreadyUsed();
            if (stakeProverData.nullifiers[i] != 0) {
                usedNullifiers[stakeProverData.nullifiers[i]] = true;
                emit StakeNullified(stakeProverData.nullifiers[i]);
            }
        }

        for (uint256 i = 0; i < inputCount; i++) {
            input[index++] = uint256(
                uint160(stakeProverData.stakedTokenRecipients[i])
            );
        }

        for (uint256 i = 0; i < inputCount; i++) {
            input[index++] = uint256(
                uint160(stakeProverData.erc20TokenAddresses[i])
            );
        }

        for (uint256 i = 0; i < inputCount; i++) {
            input[index++] = stakeProverData.stakeAmounts[i];
        }

        input[index++] = stakeProverData.stakedMerkleRoot;

        return input;
    }
}

Read Contract

buildVerifierId 0xf675f22c → uint256
getRootHash 0x80759f1f → uint256
hash2 0x511c53ff → uint256
hash4 0x3b3ccded → uint256
hash5 0xc98aeff5 → uint256
hinkalWrapper 0xb9e6e73f → address
isAmountValid 0xe46f6c11 → bool
isRestrictionDisabled 0xf479aa86 → bool
logarithm2 0x77eadab7 → uint256
m_index 0xf46732c7 → uint128
minAllowedTimestampOffset 0x62911f7f → uint256
onERC721Received 0x150b7a02 → bytes4
owner 0x8da5cb5b → address
pendingOwner 0xe30c3978 → address
poseidon2 0xca5ee4b2 → address
poseidon4 0xa81a2688 → address
poseidon5 0x0d1dafaa → address
renounceOwnership 0x715018a6
rootHashExists 0xa83b6745 → bool
rootIndex 0x529dd5ea → uint128
tokenToHtoken 0xa7146747 → address
tree 0x31352936 → uint256
usedNullifiers 0xaad24061 → bool

Write Contract 12 functions

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

acceptOwnership 0x79ba5097
No parameters
mint 0x607b0370
uint256[2] a
uint256[2][2] b
uint256[2] c
tuple stakeProverData
mintPermissionless 0x29b3eeba
uint256[2] a
uint256[2][2] b
uint256[2] c
tuple stakeProverData
tuple stakeProverPermissionlessData
registerVerifiers 0x7e5a9218
uint256[] verifierIds
address[] verifierAddresses
removeVerifier 0x5b9e89d3
uint256 verifierId
runAction 0x8e55854f
tuple circomData
returns: tuple[]
setAllowedRecipients 0x497a8167
address[] recipients
transferOwnership 0xf2fde38b
address newOwner
updateAmountValidity 0xa1728ad9
address collateral
uint256 amount
bool isValid
updateIsRestrictionDisabled 0x3e56c1fd
address collateral
bool isDisabled
updateMinAllowedTimestampOffset 0x3a1e1dc8
uint256 newMinAllowedTimestampOffset
updateTokenRegistry 0x261864ad
address collateral
address hToken

Recent Transactions

No transactions found for this address