Address Contract Verified
Address
0x94FeBdF8D9813928eA15Bc99d80632D59c190810
Balance
0 ETH
Nonce
1
Code Size
22873 bytes
Creator
0xBfB24BBC...7A85 at tx 0x8afef5b7...40a220
Indexed Transactions
0
Contract Bytecode
22873 bytes
0x6080604052600436106101ff5760003560e01c80637aed3f021161010e578063c0c53b8b1161009b578063c0c53b8b146105cc578063c45a0155146105ec578063c7cd97481461060c578063db6754ed1461061f578063df2ab5bb14610640578063e525b10b14610653578063ec48e31214610666578063f2d5d56b14610686578063f2fde38b14610699578063fa483e72146106b957600080fd5b80637aed3f02146104af5780638456cb59146104c557806384b0196e146104da5780638da5cb5b146105025780639c7c21b8146105175780639fd0506d14610532578063aaf10f4214610553578063ac9650d814610568578063ae61c65d1461057b578063b666dc0a1461059b57600080fd5b80634aa4a4fc1161018c5780634aa4a4fc146103a55780634f1ef286146103c55780635131e1fb146103d857806352d1902d146103f8578063569b578d1461041b5780635ae401dc1461042e5780635c975abb1461044e5780635dc7b98114610467578063715018a61461047a57806372a8ddc91461048f57600080fd5b8063086eae401461023657806311d9c9561461026d5780631c58db4f146102b957806327a92b53146102cc5780632d88af4a146102ec57806331cfa1ac1461030c5780633659cfe61461033d578063372a771b1461035d5780633f4ba83a1461037d57806349404b7c1461039257600080fd5b36610231576001546001600160a01b0316331461022f57604051635b35ec7160e11b815260040160405180910390fd5b005b600080fd5b34801561024257600080fd5b5061016154610257906001600160a01b031681565b6040516102649190614530565b60405180910390f35b34801561027957600080fd5b506102a9610288366004614564565b61016560209081526000928352604080842090915290825290205460ff1681565b6040519015158152602001610264565b61022f6102c73660046145aa565b6106d9565b3480156102d857600080fd5b5061022f6102e73660046145dc565b610745565b3480156102f857600080fd5b5061022f61030736600461460a565b610779565b34801561031857600080fd5b506102a961032736600461460a565b6101636020526000908152604090205460ff1681565b34801561034957600080fd5b5061022f61035836600461460a565b6107a4565b34801561036957600080fd5b5061022f61037836600461460a565b610875565b34801561038957600080fd5b5061022f6108c6565b61022f6103a0366004614627565b6108d8565b3480156103b157600080fd5b50600154610257906001600160a01b031681565b61022f6103d336600461475a565b610a30565b3480156103e457600080fd5b50600254610257906001600160a01b031681565b34801561040457600080fd5b5061040d610ae5565b604051908152602001610264565b61022f6104293660046147a9565b610b93565b61044161043c366004614819565b610be8565b6040516102649190614909565b34801561045a57600080fd5b506101c65460ff166102a9565b61040d610475366004614a25565b610c44565b34801561048657600080fd5b5061022f61107d565b34801561049b57600080fd5b5061022f6104aa36600461460a565b61108f565b3480156104bb57600080fd5b5061040d61271081565b3480156104d157600080fd5b5061022f611116565b3480156104e657600080fd5b506104ef611171565b6040516102649796959493929190614b12565b34801561050e57600080fd5b50610257611211565b34801561052357600080fd5b50610164546102a99060ff1681565b34801561053e57600080fd5b5061016254610257906001600160a01b031681565b34801561055f57600080fd5b50610257611220565b610441610576366004614ba8565b61122f565b34801561058757600080fd5b5061022f610596366004614be9565b61137b565b3480156105a757600080fd5b506102a96105b636600461460a565b6101666020526000908152604090205460ff1681565b3480156105d857600080fd5b5061022f6105e7366004614c06565b611397565b3480156105f857600080fd5b50600054610257906001600160a01b031681565b61040d61061a366004614a25565b611526565b34801561062b57600080fd5b506101f854610257906001600160a01b031681565b61022f61064e366004614c51565b6118fb565b61022f610661366004614ca0565b6119a7565b34801561067257600080fd5b5061022f610681366004614e2c565b611dd1565b61022f6106943660046147a9565b611e8e565b3480156106a557600080fd5b5061022f6106b436600461460a565b611e9a565b3480156106c557600080fd5b5061022f6106d4366004614e97565b611f10565b600160009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0826040518263ffffffff1660e01b81526004016000604051808303818588803b15801561072957600080fd5b505af115801561073d573d6000803e3d6000fd5b505050505050565b61074d611ff8565b6001600160a01b0391909116600090815261016360205260409020805460ff1916911515919091179055565b610781611ff8565b61016280546001600160a01b0319166001600160a01b0392909216919091179055565b6001600160a01b037f00000000000000000000000094febdf8d9813928ea15bc99d80632d59c1908101630036107f55760405162461bcd60e51b81526004016107ec90614f16565b60405180910390fd5b7f00000000000000000000000094febdf8d9813928ea15bc99d80632d59c1908106001600160a01b0316610827612057565b6001600160a01b03161461084d5760405162461bcd60e51b81526004016107ec90614f62565b61085681612073565b604080516000808252602082019092526108729183919061207b565b50565b61087d611ff8565b6001600160a01b0381166108a4576040516321a945f160e11b815260040160405180910390fd5b600280546001600160a01b0319166001600160a01b0392909216919091179055565b6108ce611ff8565b6108d66121eb565b565b6108e0612238565b6001546040516370a0823160e01b81526000916001600160a01b0316906370a0823190610911903090600401614530565b602060405180830381865afa15801561092e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109529190614fae565b9050828110156109995760405162461bcd60e51b8152602060048201526012602482015271496e73756666696369656e7420574554483960701b60448201526064016107ec565b8015610a21576001546002546109bc916001600160a01b03908116911683612291565b60025460405163595a942960e11b81526001600160a01b039091169063b2b52852906109ee9084908690600401614fc7565b600060405180830381600087803b158015610a0857600080fd5b505af1158015610a1c573d6000803e3d6000fd5b505050505b50610a2c6001603355565b5050565b6001600160a01b037f00000000000000000000000094febdf8d9813928ea15bc99d80632d59c190810163003610a785760405162461bcd60e51b81526004016107ec90614f16565b7f00000000000000000000000094febdf8d9813928ea15bc99d80632d59c1908106001600160a01b0316610aaa612057565b6001600160a01b031614610ad05760405162461bcd60e51b81526004016107ec90614f62565b610ad982612073565b610a2c8282600161207b565b6000306001600160a01b037f00000000000000000000000094febdf8d9813928ea15bc99d80632d59c1908101614610b805760405162461bcd60e51b815260206004820152603860248201527f555550535570677261646561626c653a206d757374206e6f742062652063616c6044820152771b1959081d1a1c9bdd59da0819195b1959d85d1958d85b1b60421b60648201526084016107ec565b506000805160206158dd83398151915290565b610b9b611ff8565b4715610bab57610bab82826122ac565b7f1d14dcdd9ab23126863433a4b7281b02648ae1e413f0bc96e37ae9b1362bb79c8282604051610bdc929190614fde565b60405180910390a15050565b60608380421115610c315760405162461bcd60e51b8152602060048201526013602482015272151c985b9cd858dd1a5bdb881d1bdbc81bdb19606a1b60448201526064016107ec565b610c3b848461122f565b95945050505050565b6000610c4e612238565b610c5661234f565b333214801590610c6957506101645460ff165b8015610c865750336000908152610163602052604090205460ff16155b15610ca45760405163ce502e8f60e01b815260040160405180910390fd5b610cb2828360a00151612396565b610ccf57604051632913f36160e21b815260040160405180910390fd5b8160400151600003610cf457604051631febc42d60e11b815260040160405180910390fd5b6000610d0383600001516123d5565b509050610d0e6144d2565b60a08201516001600160a01b031680825247604080840191909152516370a0823160e01b81526370a0823190610d48903090600401614530565b602060405180830381865afa158015610d65573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610d899190614fae565b60608201523415610e5d5760015460a08301516001600160a01b03908116911614610dc75760405163bd28e88960e01b815260040160405180910390fd5b3484604001511115610dec57604051631febc42d60e11b815260040160405180910390fd5b600160009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b158015610e3c57600080fd5b505af1158015610e50573d6000803e3d6000fd5b5050600160c08501525050505b6101208201516001600160a01b03163314610e94578161012001513360405163294fde3b60e01b81526004016107ec929190614ff7565b8060c00151610ea35733610ea5565b305b6001600160a01b031660208201526080840151604085015160a084015160c0840151610ed39392919061267e565b6040808601829052602086015190517f598150b82ea875d58e1d8f33db4ac9f8c9d57a83bda9a42d63a50ad741296df292610f0f929091614fc7565b60405180910390a160005b6000610f298660000151612760565b9050606060008760c0015151118015610f4657508660c001515183105b15610f9d578660c001518381518110610f6157610f61615011565b6020908102919091018101516040808801516001600160a01b031660009081526101669093529091205490915060ff1615610f9d576001909201915b610fe8876040015183610fb4578860200151610fb6565b305b6040518060400160405280610fce8c600001516127a5565b81526020898101516001600160a01b0316910152846127ed565b60408801528115611018573060208501528651611004906129cb565b808852611010906123d5565b509450611026565b86604001519550505061102d565b5050610f1a565b846060015184101561106257606085015160405163a20e999d60e01b81526107ec918691600401918252602082015260400190565b61106b82612abe565b5050506110786001603355565b919050565b611085611ff8565b6108d66000612be8565b611097611ff8565b6001600160a01b0381166110be576040516321a945f160e11b815260040160405180910390fd5b61016180546001600160a01b0319166001600160a01b0383169081179091556040517f39c7a830dbd5669f23ad7f1320ac9e96d275f9d97d54c7a428cd3a02b9588f709161110b91614530565b60405180910390a150565b61111e611211565b6001600160a01b0316336001600160a01b03161415801561114b5750610162546001600160a01b03163314155b15611169576040516360eb74fb60e11b815260040160405180910390fd5b6108d6612c3a565b60006060806000806000606061012d546000801b148015611193575061012e54155b6111d75760405162461bcd60e51b81526020600482015260156024820152741152540dcc4c8e88155b9a5b9a5d1a585b1a5e9959605a1b60448201526064016107ec565b6111df612c78565b6111e7612d0b565b60408051600080825260208201909252600f60f81b9b939a50919850469750309650945092509050565b6097546001600160a01b031690565b600061122a612057565b905090565b6060816001600160401b038111156112495761124961464c565b60405190808252806020026020018201604052801561127c57816020015b60608152602001906001900390816112675790505b50905060005b8281101561137457600080308686858181106112a0576112a0615011565b90506020028101906112b29190615027565b6040516112c092919061506d565b600060405180830381855af49150503d80600081146112fb576040519150601f19603f3d011682016040523d82523d6000602084013e611300565b606091505b50915091508161134c5760448151101561131957600080fd5b60048101905080806020019051810190611333919061507d565b60405162461bcd60e51b81526004016107ec91906150ea565b8084848151811061135f5761135f615011565b60209081029190910101525050600101611282565b5092915050565b611383611ff8565b610164805460ff1916911515919091179055565b603254610100900460ff16158080156113b75750603254600160ff909116105b806113d857506113c630612d1b565b1580156113d8575060325460ff166001145b61143b5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b60648201526084016107ec565b6032805460ff19166001179055801561145e576032805461ff0019166101001790555b6114688484612d2a565b6114b06040518060400160405280600d81526020016c3730ba34bb32903937baba32b960991b815250604051806040016040528060018152602001603160f81b815250612e2a565b6114b8612e5b565b6114c0612e8a565b6114c8612eb9565b6114d18261108f565b6114d9612ee0565b8015611520576032805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498906020015b60405180910390a15b50505050565b6000611530612238565b61153861234f565b33321480159061154b57506101645460ff165b80156115685750336000908152610163602052604090205460ff16155b156115865760405163ce502e8f60e01b815260040160405180910390fd5b815161159190612760565b156115af5760405163238fdf7d60e01b815260040160405180910390fd5b60018260c001515111156115d657604051630d7558bb60e11b815260040160405180910390fd5b6115e4828360a00151612396565b61160157604051632913f36160e21b815260040160405180910390fd5b816040015160000361162657604051631febc42d60e11b815260040160405180910390fd5b600061163583600001516123d5565b5090506116406144d2565b60a0820180516001600160a01b03908116835247604080850191909152915191516370a0823160e01b81529116906370a0823190611682903090600401614530565b602060405180830381865afa15801561169f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116c39190614fae565b606082015234156117975760015460a08301516001600160a01b039081169116146117015760405163bd28e88960e01b815260040160405180910390fd5b348460400151111561172657604051631febc42d60e11b815260040160405180910390fd5b600160009054906101000a90046001600160a01b03166001600160a01b031663d0e30db0346040518263ffffffff1660e01b81526004016000604051808303818588803b15801561177657600080fd5b505af115801561178a573d6000803e3d6000fd5b5050600160c08501525050505b6101208201516001600160a01b031633146117ce578161012001513360405163294fde3b60e01b81526004016107ec929190614ff7565b6117ea846080015185604001518460a001518460c0015161267e565b6040808601829052602086015190517f598150b82ea875d58e1d8f33db4ac9f8c9d57a83bda9a42d63a50ad741296df292611826929091614fc7565b60405180910390a16118af846040015185602001516040518060400160405280886000015181526020018560c0015161185f5733611861565b305b6001600160a01b0316905260c08801515161188b57604051806020016040528060008152506127ed565b8760c001516000815181106118a2576118a2615011565b60200260200101516127ed565b925083606001518310156118e657606084015160405163a20e999d60e01b81526107ec918591600401918252602082015260400190565b6118ef81612abe565b50506110786001603355565b611903611ff8565b6040516370a0823160e01b81526000906001600160a01b038516906370a0823190611932903090600401614530565b602060405180830381865afa15801561194f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906119739190614fae565b905080831115611996576040516324c0fc0160e01b815260040160405180910390fd5b801561152057611520848383612291565b6119af612238565b6119b881612f0f565b60008054825160405163290e0f6360e21b81526001600160a01b039092169163a4383d8c916119e991600401614530565b602060405180830381865afa158015611a06573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a2a91906150fd565b9050600081611a395730611a9f565b82600001516001600160a01b03166361d027b36040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a7b573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a9f919061511a565b9050600034118015611ab45750826101600151155b15611bbf5760608301516001600160a01b031615611ae55760405163bd28e88960e01b815260040160405180910390fd5b348360a001511115611b0a57604051631febc42d60e11b815260040160405180910390fd5b600160009054906101000a90046001600160a01b03166001600160a01b031663d0e30db08460a001516040518263ffffffff1660e01b81526004016000604051808303818588803b158015611b5e57600080fd5b505af1158015611b72573d6000803e3d6000fd5b505050506101a084015160a085015160018054611b9994506001600160a01b03169061267e565b60a08401819052600154611bba916001600160a01b03909116908390612291565b611c10565b611bd9836101a001518460a001518560600151600061267e565b60a084015261016083015115611bfc57611bba8360600151828560a00151612291565b611c10836060015133838660a00151612f84565b8115611c7c57825160405163e525b10b60e01b81526001600160a01b039091169063e525b10b90611c45908690600401615145565b600060405180830381600087803b158015611c5f57600080fd5b505af1158015611c73573d6000803e3d6000fd5b50505050611dc5565b82516001600160a01b03166000908152610166602052604090205460ff1615611dac5760006040518061016001604052806000815260200160006001600160a01b0316815260200185600001516001600160a01b0316815260200160006001600160a01b0316815260200185608001516001600160a01b0316815260200185606001516001600160a01b031681526020018560e0015181526020018560c0015181526020018561010001518152602001336001600160a01b031681526020018561014001516001600160801b03191681525090506000611d6c828660a00151876040015130896101e00151612f99565b9050846102000151811015611da55761020085015160405163a20e999d60e01b81526107ec918391600401918252602082015260400190565b5050611dc5565b6040516321dac2fd60e21b815260040160405180910390fd5b50506108726001603355565b611dd9611ff8565b828114611df95760405163434f49f560e11b815260040160405180910390fd5b60005b83811015611e8757828282818110611e1657611e16615011565b9050602002016020810190611e2b9190614be9565b6101666000878785818110611e4257611e42615011565b9050602002016020810190611e57919061460a565b6001600160a01b031681526020810191909152604001600020805460ff1916911515919091179055600101611dfc565b5050505050565b610a2c82333084612f84565b611ea2611ff8565b6001600160a01b038116611f075760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b60648201526084016107ec565b61087281612be8565b611f1861234f565b60008413158015611f2a575060008313155b15611f5257604051630a99307360e01b815260048101859052602481018490526044016107ec565b6000611f60828401846152bd565b90506000611f7182600001516123d5565b50905080604001516001600160a01b0316336001600160a01b031614611fac5733604051631459372b60e11b81526004016107ec9190614530565b6000546040820151611fc7916001600160a01b031690613395565b506000808712611fd75786611fd9565b855b9050611fef8260a001518460200151338461344e565b50505050505050565b33612001611211565b6001600160a01b0316146108d65760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e657260448201526064016107ec565b6000805160206158dd833981519152546001600160a01b031690565b610872611ff8565b7f4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd91435460ff16156120b3576120ae8361347a565b505050565b826001600160a01b03166352d1902d6040518163ffffffff1660e01b8152600401602060405180830381865afa92505050801561210d575060408051601f3d908101601f1916820190925261210a91810190614fae565b60015b6121705760405162461bcd60e51b815260206004820152602e60248201527f45524331393637557067726164653a206e657720696d706c656d656e7461746960448201526d6f6e206973206e6f74205555505360901b60648201526084016107ec565b6000805160206158dd83398151915281146121df5760405162461bcd60e51b815260206004820152602960248201527f45524331393637557067726164653a20756e737570706f727465642070726f786044820152681a58589b195555525160ba1b60648201526084016107ec565b506120ae838383613514565b6121f3613539565b6101c6805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b60405161222e9190614530565b60405180910390a1565b60026033540361228a5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064016107ec565b6002603355565b6120ae6001600160a01b0384168383613583565b6001603355565b604080516000808252602082019092526001600160a01b0384169083906040516122d69190615356565b60006040518083038185875af1925050503d8060008114612313576040519150601f19603f3d011682016040523d82523d6000602084013e612318565b606091505b50509050806120ae5760405162461bcd60e51b815260206004820152600360248201526253544560e81b60448201526064016107ec565b6101c65460ff16156108d65760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b60448201526064016107ec565b6000806123aa6123a5856135d9565b61369a565b905060006123b882856136c7565b610161546001600160a01b03908116911614925050505b92915050565b6040805161016081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e0810182905261010081018290526101208101829052610140810191909152606082516000141580156124845750601061244b60206004615388565b61245760146006615388565b612461919061539f565b61246b919061539f565b61247690604161539f565b835161248291906153c8565b155b6124a05760405162461bcd60e51b81526004016107ec906153dc565b6124ab8360006136eb565b82526124b8836020613749565b6001600160a01b03166020808401919091526124e1906124da9060149061539f565b8490613749565b6001600160a01b031660408301526125096124fe60146002615388565b6124da90602061539f565b6001600160a01b031660608301526125266124fe60146003615388565b6001600160a01b031660808301526125436124fe60146004615388565b6001600160a01b031660a083015261257261256060146005615388565b61256b90602061539f565b84906136eb565b60c083015261259c61258660146005615388565b61259260206002615388565b61256b919061539f565b60e08301526125bc6125b060146005615388565b61259260206003615388565b6101008301526125e76125d160146005615388565b6125dd60206004615388565b6124da919061539f565b6001600160a01b031661012083015261262461260560146006615388565b61261160206004615388565b61261b919061539f565b849060106137ae565b61262d9061542a565b6001600160801b031916610140830152612677601061264e60206004615388565b61265a60146006615388565b612664919061539f565b61266e919061539f565b849060416137ae565b9050915091565b60408401516000901561275557612710856040015111156126b25760405163965a1fab60e01b815260040160405180910390fd5b60006127108660400151866126c79190615388565b6126d19190615461565b90506126ef84846126e257336126e4565b305b886020015184612f84565b60208087015160408089015181516001600160a01b039384168152938401528201839052851660608201527f55be346d3a3628b5060716bacd516632c5a911ce5835123ea18a84ea0ff3ea939060800160405180910390a16127518186615475565b9450505b50825b949350505050565b6000601061277060206004615388565b61277c60146006615388565b612786919061539f565b612790919061539f565b61279b90604161539f565b8251119050919050565b60606123cf600060106127ba60206004615388565b6127c660146006615388565b6127d0919061539f565b6127da919061539f565b6127e590604161539f565b8491906137ae565b60008060006127ff85600001516123d5565b600080546040808501519051630d9bff2960e31b8152949650929450909283926001600160a01b0390921691636cdff9489161283e9190600401614530565b602060405180830381865afa15801561285b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061287f91906150fd565b156129465783604001516001600160a01b031663d025fdfa856040516020016128a89190615488565b604051602081830303815290604052858c8c8c6040516020016128cb9190615541565b6040516020818303038152906040526040518663ffffffff1660e01b81526004016128fa95949392919061557e565b60408051808303816000875af1158015612918573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061293c91906155cd565b90925090506129a5565b6040808501516001600160a01b03166000908152610166602052205460ff16156129865761297b848a8a8a602001518a612f99565b945050505050612758565b836040015160405163e12334e160e01b81526004016107ec9190614530565b600082136129b357816129b5565b805b6129be906155f1565b9998505050505050505050565b60608151600014158015612a21575060106129e860206004615388565b6129f460146006615388565b6129fe919061539f565b612a08919061539f565b612a1390604161539f565b8251612a1f91906153c8565b155b612a3d5760405162461bcd60e51b81526004016107ec906153dc565b6123cf6010612a4e60206004615388565b612a5a60146006615388565b612a64919061539f565b612a6e919061539f565b612a7990604161539f565b6010612a8760206004615388565b612a9360146006615388565b612a9d919061539f565b612aa7919061539f565b612ab290604161539f565b84516127e59190615475565b8060400151471115612ae357612ae333826040015147612ade9190615475565b6122ac565b606081015181516040516370a0823160e01b81526001600160a01b03909116906370a0823190612b17903090600401614530565b602060405180830381865afa158015612b34573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612b589190614fae565b111561087257805160608201516040516370a0823160e01b8152610872929133916001600160a01b038416906370a0823190612b98903090600401614530565b602060405180830381865afa158015612bb5573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612bd99190614fae565b612be39190615475565b612291565b609780546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b612c4261234f565b6101c6805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586122213390565b606061012f8054612c889061560d565b80601f0160208091040260200160405190810160405280929190818152602001828054612cb49061560d565b8015612d015780601f10612cd657610100808354040283529160200191612d01565b820191906000526020600020905b815481529060010190602001808311612ce457829003601f168201915b5050505050905090565b60606101308054612c889061560d565b6001600160a01b03163b151590565b6001600160a01b038216612d945760405162461bcd60e51b815260206004820152602b60248201527f50657269706865727953746174653a20666163746f727920616464726573732060448201526a063616e6e6f7420626520360ac1b60648201526084016107ec565b6001600160a01b038116612dfc5760405162461bcd60e51b815260206004820152602960248201527f50657269706865727953746174653a205745544839206164647265737320636160448201526806e6e6f7420626520360bc1b60648201526084016107ec565b600080546001600160a01b039384166001600160a01b03199182161790915560018054929093169116179055565b603254610100900460ff16612e515760405162461bcd60e51b81526004016107ec90615641565b610a2c82826138bd565b603254610100900460ff16612e825760405162461bcd60e51b81526004016107ec90615641565b6108d6613910565b603254610100900460ff16612eb15760405162461bcd60e51b81526004016107ec90615641565b6108d6613937565b603254610100900460ff166108d65760405162461bcd60e51b81526004016107ec90615641565b603254610100900460ff16612f075760405162461bcd60e51b81526004016107ec90615641565b6108d6613967565b8060c001518160a001511115612f3857604051631febc42d60e11b815260040160405180910390fd5b428161010001511015612f5e57604051636f6dd72560e01b815260040160405180910390fd5b612f678161399b565b61087257604051632913f36160e21b815260040160405180910390fd5b6115206001600160a01b038516848484613ac5565b60004286610100015111612fc0576040516362b439dd60e11b815260040160405180910390fd5b84600003612fe1576040516367dc7bf960e11b815260040160405180910390fd5b600080612fee8789613afd565b915091506130068860a0015186838b60400151613b85565b60808801516040516370a0823160e01b81526000916001600160a01b0316906370a0823190613039903090600401614530565b602060405180830381865afa158015613056573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061307a9190614fae565b9050600089608001516001600160a01b03166370a08231896040518263ffffffff1660e01b81526004016130ae9190614530565b602060405180830381865afa1580156130cb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906130ef9190614fae565b905060008a604001516001600160a01b03168760405161310f9190615356565b6000604051808303816000865af19150503d806000811461314c576040519150601f19603f3d011682016040523d82523d6000602084013e613151565b606091505b505090508061319c5760408b01516131688861568c565b604051638a67d2ef60e01b81526001600160a01b0390921660048301526001600160e01b03191660248201526044016107ec565b50600080828c608001516001600160a01b03166370a082318c6040518263ffffffff1660e01b81526004016131d19190614530565b602060405180830381865afa1580156131ee573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132129190614fae565b61321c9190615475565b90506000848d608001516001600160a01b03166370a08231306040518263ffffffff1660e01b81526004016132519190614530565b602060405180830381865afa15801561326e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906132929190614fae565b61329c9190615475565b9050808210156133435760808d01516132bf906001600160a01b03168c83613583565b60808d01516040516370a0823160e01b815285916001600160a01b0316906370a08231906132f1908f90600401614530565b602060405180830381865afa15801561330e573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906133329190614fae565b61333c9190615475565b9250613347565b8192505b8683101561336857604051630154e07b60e01b815260040160405180910390fd5b5061338790508b8561337c846000196156bf565b8e6101400151613bbe565b9a9950505050505050505050565b604051630d9bff2960e31b81526000906001600160a01b03841690636cdff948906133c4908590600401614530565b602060405180830381865afa1580156133e1573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061340591906150fd565b6134485760405162461bcd60e51b8152602060048201526014602482015273496e76616c696420706f6f6c206164647265737360601b60448201526064016107ec565b50919050565b306001600160a01b0384160361346e57613469848383612291565b611520565b61152084848484612f84565b61348381612d1b565b6134e55760405162461bcd60e51b815260206004820152602d60248201527f455243313936373a206e657720696d706c656d656e746174696f6e206973206e60448201526c1bdd08184818dbdb9d1c9858dd609a1b60648201526084016107ec565b6000805160206158dd83398151915280546001600160a01b0319166001600160a01b0392909216919091179055565b61351d83613c45565b60008251118061352a5750805b156120ae576115208383613c85565b6101c65460ff166108d65760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b60448201526064016107ec565b6120ae8363a9059cbb60e01b84846040516024016135a2929190614fde565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152613caa565b805160c082015160405160009283927f50633b43aed804655952b7d637f3a9e9e37e437639698443e3c5b2136f0885b7926136189291906020016156ef565b60408051808303601f190181528282528051602091820120878201516080808a01518051818601519187015195880198909852948601929092526001600160a01b03908116606086015294851690840152921660a082015260c081019190915260e00160408051601f1981840301815291905280516020909101209392505050565b60006123cf6136a7613d7f565b8360405161190160f01b8152600281019290925260228201526042902090565b60008060006136d68585613d89565b915091506136e381613dcb565b509392505050565b60006136f882602061539f565b835110156137405760405162461bcd60e51b8152602060048201526015602482015274746f55696e743235365f6f75744f66426f756e647360581b60448201526064016107ec565b50016020015190565b600061375682601461539f565b8351101561379e5760405162461bcd60e51b8152602060048201526015602482015274746f416464726573735f6f75744f66426f756e647360581b60448201526064016107ec565b500160200151600160601b900490565b6060816137bc81601f61539f565b10156137fb5760405162461bcd60e51b815260206004820152600e60248201526d736c6963655f6f766572666c6f7760901b60448201526064016107ec565b613805828461539f565b845110156138495760405162461bcd60e51b8152602060048201526011602482015270736c6963655f6f75744f66426f756e647360781b60448201526064016107ec565b60608215801561386857604051915060008252602082016040526138b2565b6040519150601f8416801560200281840101858101878315602002848b0101015b818310156138a1578051835260209283019201613889565b5050858452601f01601f1916604052505b5090505b9392505050565b603254610100900460ff166138e45760405162461bcd60e51b81526004016107ec90615641565b61012f6138f1838261575a565b506101306138ff828261575a565b5050600061012d81905561012e5550565b603254610100900460ff166122a55760405162461bcd60e51b81526004016107ec90615641565b603254610100900460ff1661395e5760405162461bcd60e51b81526004016107ec90615641565b6108d633612be8565b603254610100900460ff1661398e5760405162461bcd60e51b81526004016107ec90615641565b6101c6805460ff19169055565b600080826000015183602001518460400151856060015186608001518760c001518860e001518961010001518a61012001518b61016001518c61018001518d6101e00151336040516020016139fc9d9c9b9a99989796959493929190615819565b60408051808303601f1901815282825280516020918201206101a0870151805181840151918501517fb201bfccac55f76ea682ca784c5c76bf35169274d36136f4ffd0bf77f428afbf948701949094529385018290526001600160a01b03938416606086015292909216608084015260a08301529150600090613a979060c0016040516020818303038152906040528051906020012061369a565b90506000613aaa82866101c001516136c7565b610161546001600160a01b0390811691161495945050505050565b6040516001600160a01b03808516602483015283166044820152606481018290526115209085906323b872dd60e01b906084016135a2565b60c081015160e08201516000918291801580613b17575081155b80613b20575085155b15613b3e57604051632880eda160e11b815260040160405180910390fd5b80861015613b5757613b51868383613f10565b91508590505b81600003613b7857604051636df048c960e01b815260040160405180910390fd5b90925090505b9250929050565b6001600160a01b0383163014613baa57613baa6001600160a01b038516843085613ac5565b6115206001600160a01b0385168284614079565b60408085015161012086015160a0808801516080808a015186516001600160a01b03968716815294861660208601529185169584019590955292909216606082015291820185905281018390526001600160801b0319821660c08201527f0c3ca67555399daacbfbeef89219bf4eca6380fdc58f2ed80cdc0841616c58189060e001611517565b613c4e8161347a565b6040516001600160a01b038216907fbc7cd75a20ee27fd9adebab32041f755214dbc6bffa90cc0225b39da2e5c2d3b90600090a250565b60606138b683836040518060600160405280602781526020016158fd60279139614115565b6000613cff826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661418d9092919063ffffffff16565b9050805160001480613d20575080806020019051810190613d2091906150fd565b6120ae5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016107ec565b600061122a61419c565b6000808251604103613dbf5760208301516040840151606085015160001a613db387828585614210565b94509450505050613b7e565b50600090506002613b7e565b6000816004811115613ddf57613ddf6158c6565b03613de75750565b6001816004811115613dfb57613dfb6158c6565b03613e435760405162461bcd60e51b815260206004820152601860248201527745434453413a20696e76616c6964207369676e617475726560401b60448201526064016107ec565b6002816004811115613e5757613e576158c6565b03613ea45760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e6774680060448201526064016107ec565b6003816004811115613eb857613eb86158c6565b036108725760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c604482015261756560f01b60648201526084016107ec565b6000808060001985870985870292508281108382030391505080600003613fac5760008411613fa15760405162461bcd60e51b815260206004820152603760248201527f46756c6c4d6174683a206d756c4469763a2064656e6f6d696e61746f72206d7560448201527673742062652067726561746572207468656e207a65726f60481b60648201526084016107ec565b5082900490506138b6565b8084116140105760405162461bcd60e51b815260206004820152602c60248201527f46756c6c4d6174683a206d756c4469763a20726573756c74206772656174657260448201526b103a3430b710191515191a9b60a11b60648201526084016107ec565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b604051636eb1769f60e11b81526000906001600160a01b0385169063dd62ed3e906140aa9030908790600401614ff7565b602060405180830381865afa1580156140c7573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906140eb9190614fae565b90506115208463095ea7b360e01b85614104868661539f565b6040516024016135a2929190614fde565b6060600080856001600160a01b0316856040516141329190615356565b600060405180830381855af49150503d806000811461416d576040519150601f19603f3d011682016040523d82523d6000602084013e614172565b606091505b5091509150614183868383876142ca565b9695505050505050565b60606127588484600085614341565b60007f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f6141c761441c565b6141cf614476565b60408051602081019490945283019190915260608201524660808201523060a082015260c00160405160208183030381529060405280519060200120905090565b6000806fa2a8918ca85bafe22016d0b997e4df60600160ff1b0383111561423d57506000905060036142c1565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015614291573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b0381166142ba576000600192509250506142c1565b9150600090505b94509492505050565b60608315614337578251600003614330576142e485612d1b565b6143305760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016107ec565b5081612758565b61275883836144a8565b6060824710156143a25760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016107ec565b600080866001600160a01b031685876040516143be9190615356565b60006040518083038185875af1925050503d80600081146143fb576040519150601f19603f3d011682016040523d82523d6000602084013e614400565b606091505b5091509150614411878383876142ca565b979650505050505050565b600080614427612c78565b80519091501561443e578051602090910120919050565b61012d54801561444e5792915050565b7fc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a4709250505090565b600080614481612d0b565b805190915015614498578051602090910120919050565b61012e54801561444e5792915050565b8151156144b85781518083602001fd5b8060405162461bcd60e51b81526004016107ec91906150ea565b6040518060e0016040528060006001600160a01b0316815260200160006001600160a01b03168152602001600081526020016000815260200160008152602001600081526020016000151581525090565b6001600160a01b03169052565b6001600160a01b0391909116815260200190565b6001600160a01b038116811461087257600080fd5b803561107881614544565b6000806040838503121561457757600080fd5b823561458281614544565b915060208301356001600160e01b03198116811461459f57600080fd5b809150509250929050565b6000602082840312156145bc57600080fd5b5035919050565b801515811461087257600080fd5b8035611078816145c3565b600080604083850312156145ef57600080fd5b82356145fa81614544565b9150602083013561459f816145c3565b60006020828403121561461c57600080fd5b81356138b681614544565b6000806040838503121561463a57600080fd5b82359150602083013561459f81614544565b634e487b7160e01b600052604160045260246000fd5b60405160e081016001600160401b03811182821017156146845761468461464c565b60405290565b60405161022081016001600160401b03811182821017156146845761468461464c565b604051601f8201601f191681016001600160401b03811182821017156146d5576146d561464c565b604052919050565b60006001600160401b038211156146f6576146f661464c565b50601f01601f191660200190565b600082601f83011261471557600080fd5b8135614728614723826146dd565b6146ad565b81815284602083860101111561473d57600080fd5b816020850160208301376000918101602001919091529392505050565b6000806040838503121561476d57600080fd5b823561477881614544565b915060208301356001600160401b0381111561479357600080fd5b61479f85828601614704565b9150509250929050565b600080604083850312156147bc57600080fd5b82356147c781614544565b946020939093013593505050565b60008083601f8401126147e757600080fd5b5081356001600160401b038111156147fe57600080fd5b6020830191508360208260051b8501011115613b7e57600080fd5b60008060006040848603121561482e57600080fd5b8335925060208401356001600160401b0381111561484b57600080fd5b614857868287016147d5565b9497909650939450505050565b60005b8381101561487f578181015183820152602001614867565b50506000910152565b600081518084526148a0816020860160208601614864565b601f01601f19169290920160200192915050565b600081518084526020808501808196508360051b8101915082860160005b858110156148fc5782840389526148ea848351614888565b988501989350908401906001016148d2565b5091979650505050505050565b6020815260006138b660208301846148b4565b60006060828403121561492e57600080fd5b604051606081018181106001600160401b03821117156149505761495061464c565b604052905080823561496181614544565b8152602083013561497181614544565b6020820152604092830135920191909152919050565b600082601f83011261499857600080fd5b813560206001600160401b03808311156149b4576149b461464c565b8260051b6149c38382016146ad565b93845285810183019383810190888611156149dd57600080fd5b84880192505b85831015614a19578235848111156149fb5760008081fd5b614a098a87838c0101614704565b83525091840191908401906149e3565b98975050505050505050565b600060208284031215614a3757600080fd5b81356001600160401b0380821115614a4e57600080fd5b908301906101208286031215614a6357600080fd5b614a6b614662565b823582811115614a7a57600080fd5b614a8687828601614704565b825250614a9560208401614559565b60208201526040830135604082015260608301356060820152614abb866080850161491c565b608082015260e083013582811115614ad257600080fd5b614ade87828601614704565b60a08301525061010083013582811115614af757600080fd5b614b0387828601614987565b60c08301525095945050505050565b60ff60f81b881681526000602060e081840152614b3260e084018a614888565b8381036040850152614b44818a614888565b606085018990526001600160a01b038816608086015260a0850187905284810360c0860152855180825283870192509083019060005b81811015614b9657835183529284019291840191600101614b7a565b50909c9b505050505050505050505050565b60008060208385031215614bbb57600080fd5b82356001600160401b03811115614bd157600080fd5b614bdd858286016147d5565b90969095509350505050565b600060208284031215614bfb57600080fd5b81356138b6816145c3565b600080600060608486031215614c1b57600080fd5b8335614c2681614544565b92506020840135614c3681614544565b91506040840135614c4681614544565b809150509250925092565b600080600060608486031215614c6657600080fd5b8335614c7181614544565b9250602084013591506040840135614c4681614544565b80356001600160801b03198116811461107857600080fd5b600060208284031215614cb257600080fd5b81356001600160401b0380821115614cc957600080fd5b908301906102608286031215614cde57600080fd5b614ce661468a565b614cef83614559565b8152614cfd60208401614559565b6020820152614d0e60408401614559565b6040820152614d1f60608401614559565b6060820152614d3060808401614559565b608082015260a083013560a082015260c083013560c082015260e083013560e0820152610100808401358183015250610120808401358183015250610140614d79818501614c88565b90820152610160614d8b8482016145d1565b908201526101808381013583811115614da357600080fd5b614daf88828701614704565b8284015250506101a0614dc48782860161491c565b908201526102008381013583811115614ddc57600080fd5b614de888828701614704565b6101c08401525061022084013583811115614e0257600080fd5b614e0e88828701614704565b6101e084015250610240840135818301525080935050505092915050565b60008060008060408587031215614e4257600080fd5b84356001600160401b0380821115614e5957600080fd5b614e65888389016147d5565b90965094506020870135915080821115614e7e57600080fd5b50614e8b878288016147d5565b95989497509550505050565b60008060008060608587031215614ead57600080fd5b843593506020850135925060408501356001600160401b0380821115614ed257600080fd5b818701915087601f830112614ee657600080fd5b813581811115614ef557600080fd5b886020828501011115614f0757600080fd5b95989497505060200194505050565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b19195b1959d85d1958d85b1b60a21b606082015260800190565b6020808252602c908201527f46756e6374696f6e206d7573742062652063616c6c6564207468726f7567682060408201526b6163746976652070726f787960a01b606082015260800190565b600060208284031215614fc057600080fd5b5051919050565b9182526001600160a01b0316602082015260400190565b6001600160a01b03929092168252602082015260400190565b6001600160a01b0392831681529116602082015260400190565b634e487b7160e01b600052603260045260246000fd5b6000808335601e1984360301811261503e57600080fd5b8301803591506001600160401b0382111561505857600080fd5b602001915036819003821315613b7e57600080fd5b8183823760009101908152919050565b60006020828403121561508f57600080fd5b81516001600160401b038111156150a557600080fd5b8201601f810184136150b657600080fd5b80516150c4614723826146dd565b8181528560208385010111156150d957600080fd5b610c3b826020830160208601614864565b6020815260006138b66020830184614888565b60006020828403121561510f57600080fd5b81516138b6816145c3565b60006020828403121561512c57600080fd5b81516138b681614544565b6001600160801b0319169052565b60208152615157602082018351614523565b6000602083015161516b6040840182614523565b50604083015161517e6060840182614523565b5060608301516151916080840182614523565b5060808301516151a460a0840182614523565b5060a083015160c083015260c083015160e083015260e08301516101008181850152808501519150506101208181850152808501519150506101408181850152808501519150506101606151fa81850183615137565b840151905061018061520f8482018315159052565b808501519150506102606101a0818186015261522f610280860184614888565b908601519092506101c06152678682018380516001600160a01b03908116835260208083015190911690830152604090810151910152565b860151601f1986850381016102208801529091506152858483614888565b93506101e087015191508086850301610240870152506152a58382614888565b92505061020085015181850152508091505092915050565b6000602082840312156152cf57600080fd5b81356001600160401b03808211156152e657600080fd5b90830190604082860312156152fa57600080fd5b6040516040810181811083821117156153155761531561464c565b60405282358281111561532757600080fd5b61533387828601614704565b8252506020830135925061534683614544565b6020810192909252509392505050565b60008251615368818460208701614864565b9190910192915050565b634e487b7160e01b600052601160045260246000fd5b80820281158282048414176123cf576123cf615372565b808201808211156123cf576123cf615372565b634e487b7160e01b600052601260045260246000fd5b6000826153d7576153d76153b2565b500690565b6020808252602e908201527f4f72646572733a206465636f646546697273744f726465723a20696e76616c6960408201526d0c840c4f2e8cae640d8cadccee8d60931b606082015260800190565b805160208201516001600160801b031980821692919060108310156154595780818460100360031b1b83161693505b505050919050565b600082615470576154706153b2565b500490565b818103818111156123cf576123cf615372565b815181526020808301516101608301916154a490840182614523565b5060408301516154b76040840182614523565b5060608301516154ca6060840182614523565b5060808301516154dd6080840182614523565b5060a08301516154f060a0840182614523565b5060c083015160c083015260e083015160e08301526101008084015181840152506101208084015161552482850182614523565b50506101408084015161553982850182615137565b505092915050565b60208152600082516040602084015261555d6060840182614888565b602094909401516001600160a01b0316604093909301929092525090919050565b60a08152600061559160a0830188614888565b82810360208401526155a38188614888565b604084018790526001600160a01b038616606085015283810360808501529050614a198185614888565b600080604083850312156155e057600080fd5b505080516020909101519092909150565b6000600160ff1b820161560657615606615372565b5060000390565b600181811c9082168061562157607f821691505b60208210810361344857634e487b7160e01b600052602260045260246000fd5b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b805160208201516001600160e01b031980821692919060048310156154595760049290920360031b82901b161692915050565b80820260008212600160ff1b841416156156db576156db615372565b81810583148215176123cf576123cf615372565b6040815260006157026040830185614888565b8281036020840152610c3b81856148b4565b601f8211156120ae57600081815260208120601f850160051c8101602086101561573b5750805b601f850160051c820191505b8181101561073d57828155600101615747565b81516001600160401b038111156157735761577361464c565b61578781615781845461560d565b84615714565b602080601f8311600181146157bc57600084156157a45750858301515b600019600386901b1c1916600185901b17855561073d565b600085815260208120601f198616915b828110156157eb578886015182559484019460019091019084016157cc565b50858210156158095787850151600019600388901b60f8161c191681555b5050505050600190811b01905550565b6001600160a01b038e811682528d811660208301528c166040820152615842606082018c614523565b61584f608082018b614523565b8860a08201528760c08201528660e08201528561010082015261587761012082018615159052565b6101a061014082015260006158906101a0830186614888565b8281036101608401526158a38186614888565b9150506158b4610180830184614523565b9e9d5050505050505050505050505050565b634e487b7160e01b600052602160045260246000fdfe360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc416464726573733a206c6f772d6c6576656c2064656c65676174652063616c6c206661696c6564a264697066735822122050321d8902c7ea02e15822e37813324ff66a3d7f08700ad98703862c7b0812bd64736f6c63430008110033
Verified Source Code Full Match
Compiler: v0.8.17+commit.8df45f5f
EVM: london
Optimization: Yes (50 runs)
INativeRouter.sol 89 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "./ISwapCallback.sol";
import {INativeRfqPool} from "./INativeRfqPool.sol";
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Native
interface INativeRouter is ISwapCallback {
struct WidgetFee {
address signer;
address feeRecipient;
uint256 feeRate;
}
event SetWidgetFeeSigner(address widgetFeeSigner);
event WidgetFeeTransfer(
address widgetFeeRecipient,
uint256 widgetFeeRate,
uint256 widgetFeeAmount,
address widgetFeeToken
);
event RefundETHRecipient(address recipient, uint256 amount);
function setWidgetFeeSigner(address _widgetFeeSigner) external;
function setPauser(address _pauser) external;
function setContractCallerWhitelistToggle(bool value) external;
function setContractCallerWhitelist(address caller, bool value) external;
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputParams calldata params) external payable returns (uint256 amountOut);
function tradeRFQT(INativeRfqPool.RFQTQuote memory quote) external payable;
struct ExactInputParams {
bytes orders;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
WidgetFee widgetFee;
bytes widgetFeeSignature;
bytes[] fallbackSwapDataArray;
}
struct ExactInputExecutionState {
address sellerToken;
address payer;
uint256 initialEthBalance;
uint256 initialSellertokenBalance;
uint256 fallbackSwapDataIdx;
uint256 amountOut;
bool hasAlreadyPaid;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
error ZeroAddressInput();
error InvalidDeltaValue(int amount0Delta, int amount1Delta);
error CallbackNotFromOrderBuyer(address caller);
error MultipleOrdersForInputSingle();
error MultipleFallbackDataForInputSingle();
error InvalidWidgetFeeSignature();
error InvalidWidgetFeeRate();
error InvalidAmountInValue();
error CallerNotMsgSender(address caller, address msgSender);
error CallerNotEOAAndNotWhitelisted();
error NotEnoughAmountOut(uint256 amountOut, uint256 amountOutMinimum);
error OnlyOwnerOrPauserCanCall();
error InvalidOrderBuyer(address orderBuyer);
error InsufficientTokenToSweep();
error InputArraysLengthMismatch();
error UnexpectedMsgValue();
error RfqQuoteExpired();
error InvalidRfqPool();
}
OwnableUpgradeable.sol 95 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
IERC1967Upgradeable.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC1967.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC-1967: Proxy Storage Slots. This interface contains the events defined in the ERC.
*
* _Available since v4.8.3._
*/
interface IERC1967Upgradeable {
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Emitted when the beacon is changed.
*/
event BeaconUpgraded(address indexed beacon);
}
IERC5267Upgradeable.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.0;
interface IERC5267Upgradeable {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
draft-IERC1822Upgradeable.sol 20 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822ProxiableUpgradeable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
ERC1967UpgradeUpgradeable.sol 170 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeaconUpgradeable.sol";
import "../../interfaces/IERC1967Upgradeable.sol";
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/StorageSlotUpgradeable.sol";
import "../utils/Initializable.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*/
abstract contract ERC1967UpgradeUpgradeable is Initializable, IERC1967Upgradeable {
function __ERC1967Upgrade_init() internal onlyInitializing {
}
function __ERC1967Upgrade_init_unchained() internal onlyInitializing {
}
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract");
StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(address newImplementation, bytes memory data, bool forceCall) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
AddressUpgradeable.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(address newImplementation, bytes memory data, bool forceCall) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822ProxiableUpgradeable(newImplementation).proxiableUUID() returns (bytes32 slot) {
require(slot == _IMPLEMENTATION_SLOT, "ERC1967Upgrade: unsupported proxiableUUID");
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract");
require(
AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(address newBeacon, bytes memory data, bool forceCall) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
AddressUpgradeable.functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data);
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
IBeaconUpgradeable.sol 16 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeaconUpgradeable {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function implementation() external view returns (address);
}
Initializable.sol 166 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
UUPSUpgradeable.sol 112 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/UUPSUpgradeable.sol)
pragma solidity ^0.8.0;
import "../../interfaces/draft-IERC1822Upgradeable.sol";
import "../ERC1967/ERC1967UpgradeUpgradeable.sol";
import "./Initializable.sol";
/**
* @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an
* {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy.
*
* A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is
* reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing
* `UUPSUpgradeable` with a custom implementation of upgrades.
*
* The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism.
*
* _Available since v4.1._
*/
abstract contract UUPSUpgradeable is Initializable, IERC1822ProxiableUpgradeable, ERC1967UpgradeUpgradeable {
function __UUPSUpgradeable_init() internal onlyInitializing {
}
function __UUPSUpgradeable_init_unchained() internal onlyInitializing {
}
/// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
address private immutable __self = address(this);
/**
* @dev Check that the execution is being performed through a delegatecall call and that the execution context is
* a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case
* for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a
* function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to
* fail.
*/
modifier onlyProxy() {
require(address(this) != __self, "Function must be called through delegatecall");
require(_getImplementation() == __self, "Function must be called through active proxy");
_;
}
/**
* @dev Check that the execution is not being performed through a delegate call. This allows a function to be
* callable on the implementing contract but not through proxies.
*/
modifier notDelegated() {
require(address(this) == __self, "UUPSUpgradeable: must not be called through delegatecall");
_;
}
/**
* @dev Implementation of the ERC1822 {proxiableUUID} function. This returns the storage slot used by the
* implementation. It is used to validate the implementation's compatibility when performing an upgrade.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy. This is guaranteed by the `notDelegated` modifier.
*/
function proxiableUUID() external view virtual override notDelegated returns (bytes32) {
return _IMPLEMENTATION_SLOT;
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeTo(address newImplementation) public virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, new bytes(0), false);
}
/**
* @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call
* encoded in `data`.
*
* Calls {_authorizeUpgrade}.
*
* Emits an {Upgraded} event.
*
* @custom:oz-upgrades-unsafe-allow-reachable delegatecall
*/
function upgradeToAndCall(address newImplementation, bytes memory data) public payable virtual onlyProxy {
_authorizeUpgrade(newImplementation);
_upgradeToAndCallUUPS(newImplementation, data, true);
}
/**
* @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by
* {upgradeTo} and {upgradeToAndCall}.
*
* Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}.
*
* ```solidity
* function _authorizeUpgrade(address) internal override onlyOwner {}
* ```
*/
function _authorizeUpgrade(address newImplementation) internal virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
PausableUpgradeable.sol 117 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
ReentrancyGuardUpgradeable.sol 89 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
IERC20Upgradeable.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 IERC20Upgradeable {
/**
* @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);
}
IERC20PermitUpgradeable.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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.
*/
interface IERC20PermitUpgradeable {
/**
* @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].
*/
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);
}
SafeERC20Upgradeable.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {
using AddressUpgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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. Compatible with tokens that require the approval to be set to
* 0 before setting it to a non-zero value.
*/
function forceApprove(IERC20Upgradeable 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(
IERC20PermitUpgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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))) && AddressUpgradeable.isContract(address(token));
}
}
AddressUpgradeable.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
ContextUpgradeable.sol 37 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
StorageSlotUpgradeable.sol 138 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlotUpgradeable {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
StringsUpgradeable.sol 85 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/MathUpgradeable.sol";
import "./math/SignedMathUpgradeable.sol";
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = MathUpgradeable.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMathUpgradeable.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, MathUpgradeable.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
ECDSAUpgradeable.sol 217 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../StringsUpgradeable.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSAUpgradeable {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", StringsUpgradeable.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
EIP712Upgradeable.sol 205 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.8;
import "./ECDSAUpgradeable.sol";
import "../../interfaces/IERC5267Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* _Available since v3.4._
*
* @custom:storage-size 52
*/
abstract contract EIP712Upgradeable is Initializable, IERC5267Upgradeable {
bytes32 private constant _TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/// @custom:oz-renamed-from _HASHED_NAME
bytes32 private _hashedName;
/// @custom:oz-renamed-from _HASHED_VERSION
bytes32 private _hashedVersion;
string private _name;
string private _version;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal onlyInitializing {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal onlyInitializing {
_name = name;
_version = version;
// Reset prior values in storage if upgrading
_hashedName = 0;
_hashedVersion = 0;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator();
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash(), block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSAUpgradeable.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {EIP-5267}.
*
* _Available since v4.9._
*/
function eip712Domain()
public
view
virtual
override
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
// If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized
// and the EIP712 domain is not reliable, as it will be missing name and version.
require(_hashedName == 0 && _hashedVersion == 0, "EIP712: Uninitialized");
return (
hex"0f", // 01111
_EIP712Name(),
_EIP712Version(),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
/**
* @dev The name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Name() internal virtual view returns (string memory) {
return _name;
}
/**
* @dev The version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712Version() internal virtual view returns (string memory) {
return _version;
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Name` instead.
*/
function _EIP712NameHash() internal view returns (bytes32) {
string memory name = _EIP712Name();
if (bytes(name).length > 0) {
return keccak256(bytes(name));
} else {
// If the name is empty, the contract may have been upgraded without initializing the new storage.
// We return the name hash in storage if non-zero, otherwise we assume the name is empty by design.
bytes32 hashedName = _hashedName;
if (hashedName != 0) {
return hashedName;
} else {
return keccak256("");
}
}
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: In previous versions this function was virtual. In this version you should override `_EIP712Version` instead.
*/
function _EIP712VersionHash() internal view returns (bytes32) {
string memory version = _EIP712Version();
if (bytes(version).length > 0) {
return keccak256(bytes(version));
} else {
// If the version is empty, the contract may have been upgraded without initializing the new storage.
// We return the version hash in storage if non-zero, otherwise we assume the version is empty by design.
bytes32 hashedVersion = _hashedVersion;
if (hashedVersion != 0) {
return hashedVersion;
} else {
return keccak256("");
}
}
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[48] private __gap;
}
MathUpgradeable.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 MathUpgradeable {
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);
}
}
}
SignedMathUpgradeable.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMathUpgradeable {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
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);
}
}
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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.
*/
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].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
SafeERC20.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (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. Compatible with tokens that require the approval to be set to
* 0 before setting it to a non-zero value.
*/
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));
}
}
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 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
Blacklistable.sol 73 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
/**
* @title Blacklistable Token
* @dev Allows accounts to be blacklisted by a "blacklister" role
*/
contract Blacklistable is OwnableUpgradeable {
address public blacklister;
mapping(address => bool) internal blacklisted;
event Blacklisted(address indexed _account);
event UnBlacklisted(address indexed _account);
event BlacklisterChanged(address indexed newBlacklister);
/**
* @dev Throws if called by any account other than the blacklister
*/
modifier onlyBlacklister() {
require(msg.sender == blacklister, "Blacklistable: caller is not the blacklister");
_;
}
/**
* @dev Throws if argument account is blacklisted
* @param _account The address to check
*/
modifier notBlacklisted(address _account) {
require(!blacklisted[_account], "Blacklistable: account is blacklisted");
_;
}
/**
* @dev Checks if account is blacklisted
* @param _account The address to check
*/
function isBlacklisted(address _account) external view returns (bool) {
return blacklisted[_account];
}
/**
* @dev Adds account to blacklist
* @param _account The address to blacklist
*/
function blacklist(address _account) external onlyBlacklister {
blacklisted[_account] = true;
emit Blacklisted(_account);
}
/**
* @dev Removes account from blacklist
* @param _account The address to remove from the blacklist
*/
function unBlacklist(address _account) external onlyBlacklister {
blacklisted[_account] = false;
emit UnBlacklisted(_account);
}
function updateBlacklister(address _newBlacklister) external onlyOwner {
require(_newBlacklister != address(0), "Blacklistable: new blacklister is the zero address");
blacklister = _newBlacklister;
emit BlacklisterChanged(blacklister);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[48] private __gap;
}
ExternalSwapRouterUpgradeable.sol 137 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "./interfaces/IPancakeRouter02.sol";
import "./interfaces/IUniswapV3SwapRouter.sol";
import "./interfaces/IPeripheryState.sol";
import "./interfaces/IWETH9.sol";
import "./libraries/Order.sol";
import "./libraries/FullMath.sol";
abstract contract ExternalSwapRouterUpgradeable is Initializable {
using SafeERC20 for IERC20;
address public pancakeswapRouter; // legacy variable, not removing it just to maintain the storage layout of upgradable contract
event ExternalSwap(
address externalRouter,
address sender,
address tokenIn,
address tokenOut,
int256 amountIn,
int256 amountOut,
bytes16 quoteId
);
error OrderExpired();
error ZeroFlexibleAmount();
error ExternalCallFailed(address, bytes4);
error InvalidZeroInputAmount();
error InvalidZeroOutputAmount();
error NotEnoughTokenOutReceived();
error EthTransferFail();
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function calculateTokenAmount(
uint256 flexibleAmount,
Orders.Order memory _order
) private pure returns (uint256, uint256) {
uint256 buyerTokenAmount = _order.buyerTokenAmount;
uint256 sellerTokenAmount = _order.sellerTokenAmount;
if (sellerTokenAmount == 0 || buyerTokenAmount == 0 || flexibleAmount == 0) {
revert InvalidZeroInputAmount();
}
if (flexibleAmount < sellerTokenAmount) {
buyerTokenAmount = FullMath.mulDiv(flexibleAmount, buyerTokenAmount, sellerTokenAmount);
sellerTokenAmount = flexibleAmount;
}
if (buyerTokenAmount == 0) {
revert InvalidZeroOutputAmount();
}
return (buyerTokenAmount, sellerTokenAmount);
}
function externalSwap(
Orders.Order memory order,
uint256 flexibleAmount,
address recipient,
address payer,
bytes memory fallbackSwapCalldata
) internal returns (uint256) {
if (order.deadlineTimestamp <= block.timestamp) {
revert OrderExpired();
}
if (flexibleAmount == 0) {
revert ZeroFlexibleAmount();
}
(uint256 buyerTokenAmount, uint256 sellerTokenAmount) = calculateTokenAmount(flexibleAmount, order);
prepareTokenIn(IERC20(order.sellerToken), payer, sellerTokenAmount, order.buyer);
uint256 routerTokenOutBalanceBefore = IERC20(order.buyerToken).balanceOf(address(this));
uint256 recipientTokenOutBalanceBefore = IERC20(order.buyerToken).balanceOf(recipient);
{
// call to external contract
(bool success, ) = order.buyer.call(fallbackSwapCalldata);
if (!success) {
revert ExternalCallFailed(order.buyer, bytes4(fallbackSwapCalldata));
}
}
uint256 amountOut;
{
// assume the tokenOut is sent to "recipient" by external call directly
uint256 recipientDiff = IERC20(order.buyerToken).balanceOf(recipient) - recipientTokenOutBalanceBefore;
uint256 routerDiff = IERC20(order.buyerToken).balanceOf(address(this)) - routerTokenOutBalanceBefore;
// if routerDiff is more, router has the tokens, so router transfers it out to recipient
if (recipientDiff < routerDiff) {
IERC20(order.buyerToken).safeTransfer(recipient, routerDiff);
amountOut = IERC20(order.buyerToken).balanceOf(recipient) - recipientTokenOutBalanceBefore;
} else {
// otherwise, recipient has the tokens, so we can use recipientDiff
amountOut = recipientDiff;
}
// amountOut is always the difference in after - before of recipient balance, to account for fee on transfer tokens
if (amountOut < buyerTokenAmount) {
revert NotEnoughTokenOutReceived();
}
}
emitExternalSwapEvent(order, int256(sellerTokenAmount), (-1 * int256(amountOut)), order.quoteId);
return amountOut;
}
function emitExternalSwapEvent(
Orders.Order memory order,
int256 amountIn,
int256 amountOut,
bytes16 quoteId
) private {
emit ExternalSwap(order.buyer, order.caller, order.sellerToken, order.buyerToken, amountIn, amountOut, quoteId);
}
function prepareTokenIn(IERC20 tokenIn, address payer, uint256 tokenAmount, address externalRouter) internal {
if (payer != address(this)) {
tokenIn.safeTransferFrom(payer, address(this), tokenAmount);
}
tokenIn.safeIncreaseAllowance(externalRouter, tokenAmount);
}
uint256[49] private __gap;
}
NativePool.sol 483 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import {INativePool} from "./interfaces/INativePool.sol";
import {INativeRouter} from "./interfaces/INativeRouter.sol";
import {INativeTreasuryV2} from "./interfaces/INativeTreasury.sol";
import {IWETH9} from "./interfaces/IWETH9.sol";
import {Orders} from "./libraries/Order.sol";
import {Blacklistable} from "./Blacklistable.sol";
import {Registry} from "./Registry.sol";
import {NativeRouter} from "./NativeRouter.sol";
import "./libraries/TransferHelper.sol";
import "./libraries/FullMath.sol";
import "./libraries/NoDelegateCallUpgradable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "./storage/NativePoolStorage.sol";
contract NativePool is
INativePool,
EIP712Upgradeable,
ReentrancyGuardUpgradeable,
OwnableUpgradeable,
PausableUpgradeable,
NoDelegateCallUpgradable,
Blacklistable,
UUPSUpgradeable,
NativePoolStorage
{
using SafeERC20Upgradeable for IERC20Upgradeable;
using SafeERC20Upgradeable for IWETH9;
uint256 public constant FIXED_PRICE_MODEL_ID = 99;
uint256 public constant PMM_PRICE_MODEL_ID = 100;
uint256 public constant CONSTANT_SUM_PRICE_MODEL_ID = 0;
uint256 public constant UNISWAP_V2_PRICE_MODEL_ID = 1;
uint256 internal constant TEN_THOUSAND_DENOMINATOR = 10000;
// keccak256("Order(uint256 id,address signer,address buyer,address seller,address buyerToken,address sellerToken,uint256 buyerTokenAmount,uint256 sellerTokenAmount,uint256 deadlineTimestamp,address caller,bytes16 quoteId)");
bytes32 private constant ORDER_SIGNATURE_HASH = 0xcdd3cf1659a8da07564b163a4df90f66944547e93f0bb61ba676c459a2db4e20;
modifier onlyRouter() {
require(msg.sender == router, "Message sender should only be the router");
_;
}
modifier onlyNotPmm() {
require(!isPmm, "Not allowed to call this function when PMM is used");
_;
}
modifier onlyPrivateTreasury() {
require(!isPublicTreasury, "only private treasury is allowed for this operation");
_;
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function initialize(
NewPoolConfig calldata poolConfig,
address _pricingModelRegistry
) external override initializer {
__EIP712_init("native pool", "1");
__ReentrancyGuard_init();
__Ownable_init();
__Pausable_init();
__NoDelegateCall_init();
require(poolConfig.treasuryAddress != address(0), "treasury address specified should not be zero address");
require(
poolConfig.poolOwnerAddress != address(0),
"treasuryOwner address specified should not be zero address"
);
require(poolConfig.signerAddress != address(0), "signer address specified should not be zero address");
require(
_pricingModelRegistry != address(0),
"pricingModelRegistry address specified should not be zero address"
);
treasury = poolConfig.treasuryAddress;
treasuryOwner = poolConfig.poolOwnerAddress;
isSigner[poolConfig.signerAddress] = true;
pricingModelRegistry = _pricingModelRegistry;
setRouter(poolConfig.routerAddress);
executeUpdatePairs(poolConfig.fees, poolConfig.tokenAs, poolConfig.tokenBs, poolConfig.pricingModelIds);
poolFactory = msg.sender;
isTreasuryContract = poolConfig.isTreasuryContract;
isPublicTreasury = poolConfig.isPublicTreasury;
emit SetTreasury(treasury);
emit SetTreasuryOwner(treasuryOwner);
emit AddSigner(poolConfig.signerAddress);
}
function _authorizeUpgrade(address) internal view override {
require(msg.sender == poolFactory, "only PoolFactory can call this");
}
function getImplementation() public view returns (address) {
return _getImplementation();
}
function setRouter(address _router) internal {
require(_router != address(0), "router address specified should not be zero address");
require(router == address(0), "router address is already set");
router = _router;
emit SetRouter(router);
}
function isOnChainPricing() public view returns (bool) {
if (isPmm || pairCount == 0) {
return false;
} else {
// should only have 1 pair
address tokenA = tokenAs[0];
address tokenB = tokenBs[0];
Pair storage pair = pairs[tokenA][tokenB];
return
pair.pricingModelId == CONSTANT_SUM_PRICE_MODEL_ID || pair.pricingModelId == UNISWAP_V2_PRICE_MODEL_ID;
}
}
function setPauser(address _pauser) external onlyOwner {
pauser = _pauser;
emit PauserSet(_pauser);
}
modifier onlyOwnerOrPauserOrPoolFactory() {
if (msg.sender != owner() && msg.sender != pauser && msg.sender != poolFactory) {
revert onlyOwnerOrPauserOrPoolFactoryCanCall();
}
_;
}
function pause() external onlyOwnerOrPauserOrPoolFactory {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function setTreasury(address newTreasury, bool isNewTreasuryContract) external override onlyOwner {
treasury = newTreasury;
isTreasuryContract = isNewTreasuryContract;
emit SetTreasury(newTreasury);
}
function addSigner(address _signer) external override onlyOwner whenNotPaused {
require(!isSigner[_signer], "Signer is already added");
isSigner[_signer] = true;
emit AddSigner(_signer);
}
function removeSigner(address _signer) external override onlyOwner whenNotPaused {
require(isSigner[_signer], "Signer has not added");
isSigner[_signer] = false;
emit RemoveSigner(_signer);
}
function swap(
bytes memory order,
bytes calldata signature,
uint256 flexibleAmount,
address recipient,
bytes calldata callback
) external override nonReentrant whenNotPaused onlyRouter returns (int256, int256) {
Orders.Order memory _order = abi.decode(order, (Orders.Order));
if (!isOnChainPricing()) {
require(verifySignature(_order, signature), "Signature is invalid");
}
require(_order.deadlineTimestamp > block.timestamp, "Order is expired");
require(!nonceMapping[_order.caller][_order.id], "Nonce already used");
nonceMapping[_order.caller][_order.id] = true;
require(pairExist(_order.sellerToken, _order.buyerToken), "Pair not exist");
require(flexibleAmount != 0, "Flexible amount cannot be 0");
require(!blacklisted[_order.caller], "Account is blacklisted");
uint256 buyerTokenAmount;
uint256 sellerTokenAmount;
uint256 pricingModelId;
pricingModelId = getPairPricingModel(_order.sellerToken, _order.buyerToken);
{
(buyerTokenAmount, sellerTokenAmount) = calculateTokenAmount(flexibleAmount, _order, pricingModelId);
}
{
(int256 amount0Delta, int256 amount1Delta) = executeSwap(
SwapParam({
buyerTokenAmount: buyerTokenAmount,
sellerTokenAmount: sellerTokenAmount,
_order: _order,
recipient: recipient,
callback: callback,
pricingModelId: pricingModelId
})
);
uint256 fee = getPairFee(_order.sellerToken, _order.buyerToken);
if (amount0Delta < 0) {
emit Swap(
_order.caller,
recipient,
_order.sellerToken,
_order.buyerToken,
amount1Delta,
amount0Delta,
FullMath.mulDivRoundingUp(uint256(amount1Delta), fee, TEN_THOUSAND_DENOMINATOR),
_order.quoteId,
_order.signer
);
if (isTreasuryContract) {
// call aqua vault here
INativeTreasuryV2(treasury).nativeTreasuryCallback(
_order.signer,
_order.sellerToken,
amount1Delta,
_order.buyerToken,
-amount0Delta
);
}
} else {
emit Swap(
_order.caller,
recipient,
_order.sellerToken,
_order.buyerToken,
amount0Delta,
amount1Delta,
FullMath.mulDivRoundingUp(uint256(amount0Delta), fee, TEN_THOUSAND_DENOMINATOR),
_order.quoteId,
_order.signer
);
if (isTreasuryContract) {
// call aqua vault here
INativeTreasuryV2(treasury).nativeTreasuryCallback(
_order.signer,
_order.sellerToken,
-amount0Delta,
_order.buyerToken,
amount1Delta
);
}
}
return (amount0Delta, amount1Delta);
}
}
function pairExist(address tokenIn, address tokenOut) public view returns (bool exist) {
(address token0, address token1) = tokenIn < tokenOut ? (tokenIn, tokenOut) : (tokenOut, tokenIn);
return pairs[token0][token1].isExist;
}
function getTokenAs() public view returns (address[] memory) {
return tokenAs;
}
function getTokenBs() public view returns (address[] memory) {
return tokenBs;
}
function getPairPricingModel(address tokenIn, address tokenOut) public view returns (uint256 pricingModelId) {
require(pairExist(tokenIn, tokenOut), "Pair not exist");
(address token0, address token1) = tokenIn < tokenOut ? (tokenIn, tokenOut) : (tokenOut, tokenIn);
return pairs[token0][token1].pricingModelId;
}
function getPairFee(address tokenIn, address tokenOut) public view returns (uint256 fee) {
require(pairExist(tokenIn, tokenOut), "Pair not exist");
(address token0, address token1) = tokenIn < tokenOut ? (tokenIn, tokenOut) : (tokenOut, tokenIn);
return pairs[token0][token1].fee;
}
function executeUpdatePairs(
uint256[] memory _fees,
address[] memory _tokenAs,
address[] memory _tokenBs,
uint256[] memory _pricingModelIds
) private {
require(
_fees.length == _tokenAs.length &&
_fees.length == _tokenBs.length &&
_fees.length == _pricingModelIds.length,
"Pair array length mismatch"
);
for (uint i = 0; i < _fees.length; ) {
require(_tokenAs[i] != _tokenBs[i], "Identical addresses");
require(_fees[i] <= 10000, "Fee should be between 0 and 10k basis points");
(address token0, address token1) = _tokenAs[i] < _tokenBs[i]
? (_tokenAs[i], _tokenBs[i])
: (_tokenBs[i], _tokenAs[i]);
require(token0 != address(0), "Zero address in pair");
bool isPairExist = pairExist(token0, token1);
if (isPmm) {
require(_pricingModelIds[i] == PMM_PRICE_MODEL_ID, "Can only add PMM pairs to pool using PMM");
} else {
require(pairCount == 0 || isPairExist, "Can not have more than 1 pair for non PMM pool");
}
uint256 pricingModelIdOld = 0;
uint256 feeOld = 0;
if (!isPairExist) {
tokenAs.push(token0);
tokenBs.push(token1);
pairCount++;
} else {
pricingModelIdOld = pairs[token0][token1].pricingModelId;
feeOld = pairs[token0][token1].fee;
}
pairs[token0][token1] = Pair({fee: _fees[i], isExist: true, pricingModelId: _pricingModelIds[i]});
if (!isPmm && _pricingModelIds[i] == PMM_PRICE_MODEL_ID) {
isPmm = true;
}
emit UpdatePair(token0, token1, feeOld, _fees[i], pricingModelIdOld, _pricingModelIds[i]);
unchecked {
i++;
}
}
}
function updatePairs(
uint256[] calldata _fees,
address[] calldata _tokenAs,
address[] calldata _tokenBs,
uint256[] calldata _pricingModelIds
) public whenNotPaused onlyPrivateTreasury {
require(msg.sender == treasuryOwner, "Unauthorized to whitelist pairs");
executeUpdatePairs(_fees, _tokenAs, _tokenBs, _pricingModelIds);
}
function removePair(uint256 removingIdx) public whenNotPaused {
require(removingIdx < pairCount, "removePair: index out of range");
require(removingIdx < tokenAs.length, "removePair: index out of range");
require(msg.sender == treasuryOwner, "Unauthorized to whitelist pairs");
address token0 = tokenAs[removingIdx];
address token1 = tokenBs[removingIdx];
require(pairExist(token0, token1), "Pair not exist");
delete pairs[token0][token1];
tokenAs[removingIdx] = tokenAs[tokenAs.length - 1];
tokenAs.pop();
tokenBs[removingIdx] = tokenBs[tokenBs.length - 1];
tokenBs.pop();
pairCount--;
emit RemovePair(token0, token1);
}
function getAmountOut(uint256 amountIn, address _tokenIn, address _tokenOut) public view returns (uint amountOut) {
uint256 pricingModelId = getPairPricingModel(_tokenIn, _tokenOut);
require(
pricingModelId != FIXED_PRICE_MODEL_ID && pricingModelId != PMM_PRICE_MODEL_ID,
"Off-chain pricing unsupported"
);
Registry registry = Registry(pricingModelRegistry);
address tokenIn = _tokenIn;
address tokenOut = _tokenOut;
uint256 fee = getPairFee(tokenIn, tokenOut);
return registry.getAmountOut(amountIn, fee, pricingModelId, treasury, tokenIn, tokenOut, isTreasuryContract);
}
function getPricingModelRegistry() public view returns (address) {
return pricingModelRegistry;
}
// private methods
function calculateTokenAmount(
uint256 flexibleAmount,
Orders.Order memory _order,
uint256 pricingModelId
) private view returns (uint256, uint256) {
uint256 buyerTokenAmount;
uint256 sellerTokenAmount;
sellerTokenAmount = flexibleAmount >= _order.sellerTokenAmount ? _order.sellerTokenAmount : flexibleAmount;
if (pricingModelId != FIXED_PRICE_MODEL_ID && pricingModelId != PMM_PRICE_MODEL_ID) {
buyerTokenAmount = getAmountOut(sellerTokenAmount, _order.sellerToken, _order.buyerToken);
} else {
require(_order.sellerTokenAmount > 0 && _order.buyerTokenAmount > 0, "Non-zero amount required");
buyerTokenAmount = FullMath.mulDiv(sellerTokenAmount, _order.buyerTokenAmount, _order.sellerTokenAmount);
}
require(buyerTokenAmount > 0 && sellerTokenAmount > 0, "Non-zero amount required");
return (buyerTokenAmount, sellerTokenAmount);
}
function executeSwap(SwapParam memory swapParam) private returns (int256, int256) {
// Transfer token from treasury to user / router
executeSwapFromTreasury(swapParam.buyerTokenAmount, swapParam._order, swapParam.recipient);
// Transfer token from user / router, to pool, then to treasury
return
executeSwapToTreasury(
swapParam._order,
swapParam.sellerTokenAmount,
swapParam.buyerTokenAmount,
swapParam.callback
);
}
// internal methods
function getMessageHash(Orders.Order memory _order) internal pure returns (bytes32) {
bytes32 hash = keccak256(
abi.encode(
ORDER_SIGNATURE_HASH,
_order.id,
_order.signer,
_order.buyer,
_order.seller,
_order.buyerToken,
_order.sellerToken,
_order.buyerTokenAmount,
_order.sellerTokenAmount,
_order.deadlineTimestamp,
_order.caller,
_order.quoteId
)
);
return hash;
}
function verifySignature(Orders.Order memory _order, bytes calldata signature) internal view returns (bool) {
require(isSigner[_order.signer], "Signer is invalid");
bytes32 digest = _hashTypedDataV4(getMessageHash(_order));
address recoveredSigner = ECDSAUpgradeable.recover(digest, signature);
return _order.signer == recoveredSigner;
}
function executeSwapFromTreasury(uint256 amount, Orders.Order memory _order, address recipient) internal {
address buyerToken = _order.buyerToken;
uint256 treasuryBalanceInitial = IERC20Upgradeable(buyerToken).balanceOf(address(treasury));
require(treasuryBalanceInitial >= amount, "Insufficient fund in treasury");
TransferHelper.safeTransferFrom(_order.buyerToken, treasury, recipient, amount);
uint256 treasuryBalanceFinal = IERC20Upgradeable(buyerToken).balanceOf(address(treasury));
require((treasuryBalanceInitial - treasuryBalanceFinal) == amount, "Swap amount not match");
}
function executeSwapToTreasury(
Orders.Order memory _order,
uint256 sellerTokenAmount,
uint256 buyerTokenAmount,
bytes memory callback
) internal returns (int256, int256) {
require(
sellerTokenAmount <= uint256(type(int256).max),
"sellerTokenAmount is too large and would cause an overflow error"
);
require(
buyerTokenAmount <= uint256(type(int256).max),
"buyerTokenAmount is too large and would cause an overflow error"
);
int256 outputSellerTokenAmount = int256(sellerTokenAmount);
int256 outputBuyerTokenAmount = -1 * int256(buyerTokenAmount);
address sellerToken = _order.sellerToken;
uint256 treasuryBalanceInitial = IERC20Upgradeable(sellerToken).balanceOf(address(treasury));
uint256 treasuryBalanceFinal;
INativeRouter(msg.sender).swapCallback(outputBuyerTokenAmount, outputSellerTokenAmount, callback);
TransferHelper.safeTransfer(sellerToken, treasury, sellerTokenAmount);
treasuryBalanceFinal = IERC20Upgradeable(sellerToken).balanceOf(address(treasury));
require((treasuryBalanceFinal - treasuryBalanceInitial) == sellerTokenAmount, "Swap amount not match");
return (outputBuyerTokenAmount, outputSellerTokenAmount);
}
}
NativeRfqPool.sol 221 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {NativeRfqPoolStorage} from "./storage/NativeRfqPoolStorage.sol";
import {INativeRfqPool} from "./interfaces/INativeRfqPool.sol";
import {INativeTreasuryV2} from "./interfaces/INativeTreasury.sol";
import {IWETH9} from "./interfaces/IWETH9.sol";
contract NativeRfqPool is
INativeRfqPool,
Initializable,
Context,
UUPSUpgradeable,
EIP712Upgradeable,
NativeRfqPoolStorage
{
using Address for address payable;
using SafeERC20 for IERC20;
// This follows the existing NativePool order signature format
// keccak256("Order(uint256 id,address signer,address buyer,address seller,address buyerToken,address sellerToken,uint256 buyerTokenAmount,uint256 sellerTokenAmount,uint256 deadlineTimestamp,address caller,bytes16 quoteId)");
bytes32 private constant ORDER_SIGNATURE_HASH = 0xcdd3cf1659a8da07564b163a4df90f66944547e93f0bb61ba676c459a2db4e20;
bool public constant isNativeRfqPool = true;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
receive() external payable {}
function _authorizeUpgrade(address newImplementation) internal view override {
if (msg.sender != poolFactory) {
revert CallerNotFactory();
}
if (!NativeRfqPool(payable(newImplementation)).isNativeRfqPool()) {
revert InvalidNewImplementation();
}
}
function getImplementation() public view returns (address) {
return _getImplementation();
}
function initialize(
string memory _name,
address _owner,
address _signer,
address _router,
address _weth,
address _treasury
) public initializer {
if (
_owner == address(0) || _router == address(0) || bytes(_name).length == 0 || _weth == address(0)
|| _treasury == address(0) || _signer == address(0)
) {
revert ZeroOrEmptyInput();
}
__EIP712_init("native pool", "1");
name = _name;
owner = _owner;
router = _router;
weth = _weth;
treasury = _treasury;
poolFactory = msg.sender;
isSigner[_signer] = true;
}
modifier onlyOwner() {
if (msg.sender != owner) {
revert CallerNotOwner();
}
_;
}
modifier onlyRouter() {
if (msg.sender != router) {
revert CallerNotRouter();
}
_;
}
function setPendingOwner(address newOwner) public onlyOwner {
pendingOwner = newOwner;
}
function acceptOwner() public {
if (msg.sender != pendingOwner) {
revert CallerNotPendingOwner();
}
owner = pendingOwner;
emit OwnerSet(pendingOwner);
}
function setTreasury(address newTreasury) public onlyOwner {
treasury = newTreasury;
emit TreasurySet(newTreasury);
}
function tradeRFQT(RFQTQuote memory quote) external override onlyRouter {
/// Trust assumption: the Router has transferred sellerToken.
if (paused) {
revert TradePaused();
}
address originalBuyerToken = quote.buyerToken;
quote.buyerToken = quote.buyerToken == address(0) ? weth : quote.buyerToken;
quote.sellerToken = quote.sellerToken == address(0) ? weth : quote.sellerToken;
if (!verifySignature(quote)) {
revert InvalidSignature();
}
_updateNonce(quote.nonce);
uint256 buyerTokenAmount = quote.buyerTokenAmount;
if (quote.effectiveSellerTokenAmount < quote.sellerTokenAmount) {
buyerTokenAmount = (quote.effectiveSellerTokenAmount * quote.buyerTokenAmount) / quote.sellerTokenAmount;
}
emit RfqTrade(
quote.recipient,
quote.sellerToken,
quote.buyerToken,
quote.effectiveSellerTokenAmount,
buyerTokenAmount,
quote.quoteId,
quote.signer
);
if (enableTreasuryCallback) {
if (
quote.effectiveSellerTokenAmount > uint256(type(int256).max)
|| buyerTokenAmount > uint256(type(int256).max)
) {
revert Overflow();
}
INativeTreasuryV2(treasury).nativeTreasuryCallback(
quote.signer,
quote.sellerToken,
int256(quote.effectiveSellerTokenAmount),
quote.buyerToken,
int256(buyerTokenAmount)
);
}
_transferFromTreasury(originalBuyerToken, quote.recipient, buyerTokenAmount);
}
function updateSigner(address signer, bool value) external onlyOwner {
isSigner[signer] = value;
emit SignerUpdated(signer, value);
}
function setPostTradeCallback(bool value) external onlyOwner {
enableTreasuryCallback = value;
emit PostTradeCallbackSet(value);
}
function setPause(bool value) external onlyOwner {
paused = value;
emit PauseSet(value);
}
/**
* @dev Prevents against replay for RFQ-T. Checks that nonces are strictly increasing.
*/
function _updateNonce(uint256 nonce) internal {
if (nonces[nonce]) {
revert NonceUsed();
}
nonces[nonce] = true;
}
/// @dev Helper function to transfer buyerToken from external account.
function _transferFromTreasury(address token, address receiver, uint256 value) private {
if (token == address(0)) {
IERC20(weth).safeTransferFrom(treasury, address(this), value);
IWETH9(weth).withdraw(value);
payable(receiver).sendValue(value);
} else {
IERC20(token).safeTransferFrom(treasury, receiver, value);
}
}
function verifySignature(RFQTQuote memory quote) internal view returns (bool) {
if (!isSigner[quote.signer]) {
revert InvalidSigner();
}
bytes32 digest = _hashTypedDataV4(
keccak256(
abi.encode(
ORDER_SIGNATURE_HASH,
quote.nonce,
quote.signer,
address(this),
quote.recipient,
quote.buyerToken,
quote.sellerToken,
quote.buyerTokenAmount,
quote.sellerTokenAmount,
quote.deadlineTimestamp,
quote.recipient,
quote.quoteId
)
)
);
address recoveredSigner = ECDSAUpgradeable.recover(digest, quote.signature);
return quote.signer == recoveredSigner;
}
}
NativeRouter.sol 526 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
pragma abicoder v2;
import "./interfaces/INativeRouter.sol";
import "./interfaces/INativePool.sol";
import "./interfaces/INativePoolFactory.sol";
import "./libraries/SafeCast.sol";
import "./libraries/CallbackValidation.sol";
import "./libraries/Order.sol";
import "./libraries/PeripheryPayments.sol";
import "./libraries/TransferHelper.sol";
import "./libraries/Multicall.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/cryptography/EIP712Upgradeable.sol";
import "./storage/NativeRouterStorage.sol";
import "./ExternalSwapRouterUpgradeable.sol";
import {NativeRfqPool} from "./NativeRfqPool.sol";
contract NativeRouter is
INativeRouter,
PeripheryPayments,
ReentrancyGuardUpgradeable,
OwnableUpgradeable,
UUPSUpgradeable,
EIP712Upgradeable,
Multicall,
NativeRouterStorage,
PausableUpgradeable,
ExternalSwapRouterUpgradeable
{
using Orders for bytes;
using SafeCast for uint256;
uint256 public constant TEN_THOUSAND_DENOMINATOR = 10000;
// keccak256("NativeSwapCalldata(bytes32 orders,address recipient,address signer,address feeRecipient,uint256 feeRate)")
bytes32 private constant EXACT_INPUT_SIGNATURE_HASH =
0x50633b43aed804655952b7d637f3a9e9e37e437639698443e3c5b2136f0885b7;
// keccak256("RFQTQuote(bytes32 quote,address widgetFeeSigner,address widgetFeeRecipient,uint256 widgetFeeRate)")
bytes32 private constant RFQ_QUOTE_WIDGET_SIGNATURE_HASH =
0xb201bfccac55f76ea682ca784c5c76bf35169274d36136f4ffd0bf77f428afbf;
struct SwapCallbackData {
bytes orders;
address payer;
}
event SwapCalculations(uint256 amountIn, address recipient);
function initialize(address factory, address weth9, address _widgetFeeSigner) public initializer {
initializeState(factory, weth9);
__EIP712_init("native router", "1");
__ReentrancyGuard_init();
__Ownable_init();
__UUPSUpgradeable_init();
setWidgetFeeSigner(_widgetFeeSigner);
__Pausable_init();
}
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() {
_disableInitializers();
}
function getImplementation() public view returns (address) {
return _getImplementation();
}
function _authorizeUpgrade(address newImplementation) internal override onlyOwner {}
function setWeth9Unwrapper(address payable _weth9Unwrapper) public override onlyOwner {
if (_weth9Unwrapper == address(0)) {
revert ZeroAddressInput();
}
weth9Unwrapper = _weth9Unwrapper;
}
function setPauser(address _pauser) external onlyOwner {
pauser = _pauser;
}
modifier onlyOwnerOrPauser() {
if (msg.sender != owner() && msg.sender != pauser) {
revert OnlyOwnerOrPauserCanCall();
}
_;
}
function pause() external onlyOwnerOrPauser {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
function setWidgetFeeSigner(address _widgetFeeSigner) public onlyOwner {
if (_widgetFeeSigner == address(0)) {
revert ZeroAddressInput();
}
widgetFeeSigner = _widgetFeeSigner;
emit SetWidgetFeeSigner(widgetFeeSigner);
}
function swapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata _data
) external override whenNotPaused {
if (amount0Delta <= 0 && amount1Delta <= 0) {
revert InvalidDeltaValue(amount0Delta, amount1Delta);
}
SwapCallbackData memory data = abi.decode(_data, (SwapCallbackData));
(Orders.Order memory order, ) = data.orders.decodeFirstOrder();
if (msg.sender != order.buyer) {
revert CallbackNotFromOrderBuyer(msg.sender);
}
CallbackValidation.verifyCallback(factory, order.buyer);
uint256 amountToPay = amount0Delta < 0 ? uint256(amount1Delta) : uint256(amount0Delta);
pay(order.sellerToken, data.payer, msg.sender, amountToPay);
}
function setContractCallerWhitelistToggle(bool value) external onlyOwner {
contractCallerWhitelistEnabled = value;
}
function setContractCallerWhitelist(address caller, bool value) external onlyOwner {
contractCallerWhitelist[caller] = value;
}
function setExternalRouterWhitelist(address[] calldata routers, bool[] calldata values) external onlyOwner {
if (routers.length != values.length) {
revert InputArraysLengthMismatch();
}
for (uint256 i; i < routers.length; ) {
externalRouterWhitelist[routers[i]] = values[i];
unchecked {
i++;
}
}
}
modifier onlyEOAorWhitelistContract() {
if (msg.sender != tx.origin && contractCallerWhitelistEnabled && !contractCallerWhitelist[msg.sender]) {
revert CallerNotEOAAndNotWhitelisted();
}
_;
}
function exactInputSingle(
ExactInputParams memory params
) external payable override nonReentrant whenNotPaused onlyEOAorWhitelistContract returns (uint256 amountOut) {
if (params.orders.hasMultiplePools()) {
revert MultipleOrdersForInputSingle();
}
if (params.fallbackSwapDataArray.length > 1) {
revert MultipleFallbackDataForInputSingle();
}
if (!verifyWidgetFeeSignature(params, params.widgetFeeSignature)) {
revert InvalidWidgetFeeSignature();
}
if (params.amountIn == 0) {
revert InvalidAmountInValue();
}
(Orders.Order memory order, ) = params.orders.decodeFirstOrder();
ExactInputExecutionState memory state;
state.sellerToken = order.sellerToken;
state.initialEthBalance = address(this).balance;
state.initialSellertokenBalance = IERC20(order.sellerToken).balanceOf(address(this));
if (msg.value > 0) {
if (order.sellerToken != WETH9) {
revert UnexpectedMsgValue();
}
if (params.amountIn > msg.value) {
revert InvalidAmountInValue();
}
IWETH9(WETH9).deposit{value: msg.value}();
state.hasAlreadyPaid = true;
}
if (order.caller != msg.sender) {
revert CallerNotMsgSender(order.caller, msg.sender);
}
params.amountIn = processWidgetFee(params.widgetFee, params.amountIn, order.sellerToken, state.hasAlreadyPaid);
emit SwapCalculations(params.amountIn, params.recipient);
amountOut = exactInputInternal(
params.amountIn,
params.recipient,
SwapCallbackData({orders: params.orders, payer: state.hasAlreadyPaid ? address(this) : msg.sender}),
params.fallbackSwapDataArray.length > 0 ? params.fallbackSwapDataArray[0] : bytes("")
);
if (amountOut < params.amountOutMinimum) {
revert NotEnoughAmountOut(amountOut, params.amountOutMinimum);
}
refundResidual(state);
}
/// @inheritdoc INativeRouter
function exactInput(
ExactInputParams memory params
) external payable override nonReentrant whenNotPaused onlyEOAorWhitelistContract returns (uint256 amountOut) {
if (!verifyWidgetFeeSignature(params, params.widgetFeeSignature)) {
revert InvalidWidgetFeeSignature();
}
if (params.amountIn == 0) {
revert InvalidAmountInValue();
}
(Orders.Order memory order, ) = params.orders.decodeFirstOrder();
ExactInputExecutionState memory state;
state.sellerToken = order.sellerToken;
state.initialEthBalance = address(this).balance;
state.initialSellertokenBalance = IERC20(state.sellerToken).balanceOf(address(this));
// bool hasAlreadyPaid;
if (msg.value > 0) {
if (order.sellerToken != WETH9) {
revert UnexpectedMsgValue();
}
if (params.amountIn > msg.value) {
revert InvalidAmountInValue();
}
IWETH9(WETH9).deposit{value: msg.value}();
state.hasAlreadyPaid = true;
}
if (order.caller != msg.sender) {
revert CallerNotMsgSender(order.caller, msg.sender);
}
state.payer = state.hasAlreadyPaid ? address(this) : msg.sender;
params.amountIn = processWidgetFee(params.widgetFee, params.amountIn, order.sellerToken, state.hasAlreadyPaid);
emit SwapCalculations(params.amountIn, params.recipient);
uint256 fallbackSwapDataIdx = 0;
while (true) {
bool hasMultiplePools = params.orders.hasMultiplePools();
bytes memory fallbackSwapData;
if (params.fallbackSwapDataArray.length > 0 && fallbackSwapDataIdx < params.fallbackSwapDataArray.length) {
fallbackSwapData = params.fallbackSwapDataArray[fallbackSwapDataIdx];
// Step index forward if it's external router. Otherwise assume it's NativePool and remain the same
if (externalRouterWhitelist[order.buyer]) {
unchecked {
fallbackSwapDataIdx++;
}
}
}
// the outputs of prior swaps become the inputs to subsequent ones
params.amountIn = exactInputInternal(
params.amountIn,
hasMultiplePools ? address(this) : params.recipient,
SwapCallbackData({
orders: params.orders.getFirstOrder(), // only the first pool in the path is necessary
payer: state.payer
}),
fallbackSwapData
);
// decide whether to continue or terminate
if (hasMultiplePools) {
state.payer = address(this);
params.orders = params.orders.skipOrder();
(order, ) = params.orders.decodeFirstOrder();
} else {
amountOut = params.amountIn;
break;
}
}
if (amountOut < params.amountOutMinimum) {
revert NotEnoughAmountOut(amountOut, params.amountOutMinimum);
}
refundResidual(state);
}
// refund the residual ETH and tokens back to the sender after the swap with the difference between the initial and final balances
function refundResidual(ExactInputExecutionState memory state) internal {
if (address(this).balance > state.initialEthBalance)
TransferHelper.safeTransferETH(msg.sender, address(this).balance - state.initialEthBalance);
if (IERC20(state.sellerToken).balanceOf(address(this)) > state.initialSellertokenBalance)
TransferHelper.safeTransfer(
state.sellerToken,
msg.sender,
IERC20(state.sellerToken).balanceOf(address(this)) - state.initialSellertokenBalance
);
}
function processWidgetFee(
WidgetFee memory widgetFee,
uint amountIn,
address sellerToken,
bool hasAlreadyPaid
) internal returns (uint256) {
if (widgetFee.feeRate > 0) {
if (widgetFee.feeRate > TEN_THOUSAND_DENOMINATOR) {
revert InvalidWidgetFeeRate();
}
uint256 widgetFeeAmount = (amountIn * widgetFee.feeRate) / TEN_THOUSAND_DENOMINATOR;
TransferHelper.safeTransferFrom(
sellerToken,
hasAlreadyPaid ? address(this) : msg.sender,
widgetFee.feeRecipient,
widgetFeeAmount
);
emit WidgetFeeTransfer(widgetFee.feeRecipient, widgetFee.feeRate, widgetFeeAmount, sellerToken);
amountIn -= widgetFeeAmount;
}
return amountIn;
}
// private methods
/// @dev Performs a single exact input swap
function exactInputInternal(
uint256 amountIn,
address recipient,
SwapCallbackData memory data,
bytes memory fallbackSwapData
) private returns (uint256 amountOut) {
(Orders.Order memory order, bytes memory signature) = data.orders.decodeFirstOrder();
int256 amount0Delta;
int256 amount1Delta;
if (INativePoolFactory(factory).verifyPool(order.buyer)) {
(amount0Delta, amount1Delta) = INativePool(order.buyer).swap(
abi.encode(order),
signature,
amountIn,
recipient,
abi.encode(data)
);
} else if (externalRouterWhitelist[order.buyer]) {
return externalSwap(order, amountIn, recipient, data.payer, fallbackSwapData);
} else {
revert InvalidOrderBuyer(order.buyer);
}
return uint256(-(amount0Delta > 0 ? amount1Delta : amount0Delta));
}
function getExactInputMessageHash(ExactInputParams memory inputParams) internal pure returns (bytes32) {
bytes32 hash = keccak256(
abi.encode(
EXACT_INPUT_SIGNATURE_HASH,
keccak256(abi.encode(inputParams.orders, inputParams.fallbackSwapDataArray)),
inputParams.recipient,
inputParams.widgetFee.signer,
inputParams.widgetFee.feeRecipient,
inputParams.widgetFee.feeRate
)
);
return hash;
}
function verifyWidgetFeeSignature(
ExactInputParams memory params,
bytes memory signature
) internal view returns (bool) {
bytes32 digest = _hashTypedDataV4(getExactInputMessageHash(params));
address recoveredSigner = ECDSAUpgradeable.recover(digest, signature);
return widgetFeeSigner == recoveredSigner;
}
function sweepToken(address token, uint256 amountMinimum, address recipient) public payable onlyOwner {
uint256 balanceToken = IERC20Upgradeable(token).balanceOf(address(this));
if (amountMinimum > balanceToken) {
revert InsufficientTokenToSweep();
}
if (balanceToken > 0) {
TransferHelper.safeTransfer(token, recipient, balanceToken);
}
}
function refundETHRecipient(address recipient, uint256 amount) public payable onlyOwner {
if (address(this).balance > 0) TransferHelper.safeTransferETH(recipient, amount);
emit RefundETHRecipient(recipient, amount);
}
function unwrapWETH9(uint256 amountMinimum, address recipient) public payable nonReentrant {
uint256 balanceWETH9 = IWETH9(WETH9).balanceOf(address(this));
require(balanceWETH9 >= amountMinimum, "Insufficient WETH9");
if (balanceWETH9 > 0) {
TransferHelper.safeTransfer(WETH9, weth9Unwrapper, balanceWETH9);
Weth9Unwrapper(weth9Unwrapper).unwrapWeth9(balanceWETH9, recipient);
}
}
function tradeRFQT(NativeRfqPool.RFQTQuote memory quote) external payable override nonReentrant {
_validateRFQTQuote(quote);
bool isRfqPool = INativePoolFactory(factory).isRfqPool(quote.pool);
address payee = isRfqPool ? NativeRfqPool(payable(quote.pool)).treasury() : address(this); // address(this) is used for externalSwap
if (msg.value > 0 && !quote.multiHop) {
if (quote.sellerToken != address(0)) {
revert UnexpectedMsgValue();
}
if (quote.effectiveSellerTokenAmount > msg.value) {
revert InvalidAmountInValue();
}
IWETH9(WETH9).deposit{value: quote.effectiveSellerTokenAmount}();
quote.effectiveSellerTokenAmount = processWidgetFee(
quote.widgetFee,
quote.effectiveSellerTokenAmount,
WETH9,
true
);
TransferHelper.safeTransfer(WETH9, payee, quote.effectiveSellerTokenAmount);
} else {
quote.effectiveSellerTokenAmount = processWidgetFee(
quote.widgetFee,
quote.effectiveSellerTokenAmount,
quote.sellerToken,
false
);
if (quote.multiHop) {
TransferHelper.safeTransfer(quote.sellerToken, payee, quote.effectiveSellerTokenAmount);
} else {
TransferHelper.safeTransferFrom(quote.sellerToken, msg.sender, payee, quote.effectiveSellerTokenAmount);
}
}
if (isRfqPool) {
NativeRfqPool(payable(quote.pool)).tradeRFQT(quote);
} else if (externalRouterWhitelist[quote.pool]) {
Orders.Order memory order = Orders.Order({
id: 0, // not used
signer: address(0), // not used
buyer: quote.pool,
seller: address(0), // not used
buyerToken: quote.buyerToken,
sellerToken: quote.sellerToken,
buyerTokenAmount: quote.buyerTokenAmount,
sellerTokenAmount: quote.sellerTokenAmount,
deadlineTimestamp: quote.deadlineTimestamp,
caller: msg.sender,
quoteId: quote.quoteId
});
uint actualAmountOut = externalSwap(
order,
quote.effectiveSellerTokenAmount,
quote.recipient,
address(this),
quote.externalSwapCalldata
);
if (actualAmountOut < quote.amountOutMinimum) {
revert NotEnoughAmountOut(actualAmountOut, quote.amountOutMinimum);
}
} else {
revert InvalidRfqPool();
}
}
function _validateRFQTQuote(NativeRfqPool.RFQTQuote memory quote) private view {
if (quote.effectiveSellerTokenAmount > quote.sellerTokenAmount) {
revert InvalidAmountInValue();
}
if (quote.deadlineTimestamp < block.timestamp) {
revert RfqQuoteExpired();
}
if (!verifyRfqWidgetFeeSignature(quote)) {
revert InvalidWidgetFeeSignature();
}
}
function verifyRfqWidgetFeeSignature(NativeRfqPool.RFQTQuote memory quote) private view returns (bool) {
bytes32 quoteHash = keccak256(
abi.encode(
quote.pool,
quote.signer,
quote.recipient,
quote.sellerToken,
quote.buyerToken,
quote.sellerTokenAmount,
quote.buyerTokenAmount,
quote.deadlineTimestamp,
quote.nonce,
quote.multiHop,
quote.signature,
quote.externalSwapCalldata,
msg.sender
)
);
bytes32 digest = _hashTypedDataV4(
keccak256(
abi.encode(
RFQ_QUOTE_WIDGET_SIGNATURE_HASH,
quoteHash,
quote.widgetFee.signer,
quote.widgetFee.feeRecipient,
quote.widgetFee.feeRate
)
)
);
address recoveredSigner = ECDSAUpgradeable.recover(digest, quote.widgetFeeSignature);
return widgetFeeSigner == recoveredSigner;
}
}
Registry.sol 68 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/IPricer.sol";
import "./interfaces/INativeTreasury.sol";
contract Registry is Ownable {
mapping(uint256 => address) public pricer;
// constructor
constructor(address[] memory pricers) Ownable() {
for (uint256 i = 0; i < pricers.length; ) {
pricer[i] = pricers[i];
unchecked {
i++;
}
}
}
// public methods
function registerPricer(uint256 id, address addr) public onlyOwner {
require(pricer[id] == address(0), "pricer already set for this id");
pricer[id] = addr;
}
function getAmountOut(
uint256 amountIn,
uint256 fee,
uint256 id,
address treasury,
address tokenIn,
address tokenOut,
bool isTreasuryContract
) public view returns (uint amountOut) {
require(amountIn > 0, "Non-zero amount required");
uint reserveIn;
uint reserveOut;
if (isTreasuryContract) {
(uint reserve0, uint reserve1) = INativeTreasury(treasury).getReserves();
if (tokenIn == INativeTreasury(treasury).token0()) {
reserveIn = reserve0;
reserveOut = reserve1;
} else {
reserveIn = reserve1;
reserveOut = reserve0;
}
} else {
reserveIn = IERC20(tokenIn).balanceOf(address(treasury));
reserveOut = IERC20(tokenOut).balanceOf(address(treasury));
}
amountOut = _getAmountOut(amountIn, reserveIn, reserveOut, fee, id);
}
function _getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut,
uint256 fee,
uint256 id
) internal view returns (uint amountOut) {
require(reserveIn > 0 && reserveOut > 0, "Registry: INSUFFICIENT_LIQUIDITY");
amountOut = IPricer(pricer[id]).getAmountOut(amountIn, reserveIn, reserveOut, fee);
}
}
IMulticall.sol 20 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
pragma abicoder v2;
/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
/// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
/// @dev The `msg.value` should not be trusted for any method callable from multicall.
/// @param deadline The time by which this function must be called before failing
/// @param data The encoded function data for each of the calls to make to this contract
/// @return results The results from each of the calls passed in via data
function multicall(uint256 deadline, bytes[] calldata data) external payable returns (bytes[] memory results);
}
INativePool.sol 89 lines
// SPDX-License-Identifier: GPL-3.0
import {Orders} from "../libraries/Order.sol";
pragma solidity 0.8.17;
interface INativePool {
struct Pair {
uint256 fee;
bool isExist;
uint256 pricingModelId;
}
struct NewPoolConfig {
address treasuryAddress;
address poolOwnerAddress;
address signerAddress;
address routerAddress;
bool isPublicTreasury;
bool isTreasuryContract;
uint256[] fees;
address[] tokenAs;
address[] tokenBs;
uint256[] pricingModelIds;
}
struct SwapParam {
uint256 buyerTokenAmount;
uint256 sellerTokenAmount;
Orders.Order _order;
address recipient;
bytes callback;
uint256 pricingModelId;
}
function initialize(NewPoolConfig calldata poolConfig, address _pricingModelRegistry) external;
function setTreasury(address newTreasury, bool isNewTreasuryContract) external;
function addSigner(address _signer) external;
function removeSigner(address _signer) external;
function swap(
bytes memory _order,
bytes calldata signature,
uint256 flexibleAmount,
address recipient,
bytes calldata callback
) external returns (int256, int256);
function setPauser(address _pauser) external;
event Swap(
address indexed sender,
address indexed recipient,
address tokenIn,
address tokenOut,
int256 amountIn,
int256 amountOut,
uint256 fee,
bytes16 quoteId,
address signer
);
event UpdatePair(
address indexed tokenA,
address indexed tokenB,
uint256 feeOld,
uint256 feeNew,
uint256 pricingModelIdOld,
uint256 pricingModelIdNew
);
event RemovePair(address tokenA, address tokenB);
event AddSigner(address signer);
event RemoveSigner(address signer);
event SetRouter(address router);
event SetTreasury(address treasury);
event SetTreasuryOwner(address treasuryOwner);
event PauserSet(address pauser);
error onlyOwnerOrPauserOrPoolFactoryCanCall();
}
INativePoolFactory.sol 63 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "../NativePool.sol";
import "../interfaces/INativePool.sol";
struct NewPoolConfig {
address treasuryAddress;
address poolOwnerAddress;
address signerAddress;
address routerAddress;
bool isPublicTreasury;
bool isTreasuryContract;
uint256[] fees;
address[] tokenAs;
address[] tokenBs;
uint256[] pricingModelIds;
}
interface INativePoolFactory {
/// @notice Emitted when a pool is created
/// @param treasury The address of treasury for the pool
/// @param owner The address of owner of the pool
/// @param pool The address of the created pool
event PoolCreated(address treasury, address owner, address signer, address pool, address impl);
event PoolUpgraded(address pool, address impl);
event AddPoolCreator(address poolCreater);
event RemovePoolCreator(address poolCreater);
event AddMultiPoolTreasury(address treasury);
event RemoveMultiPoolTreasury(address treasury);
event RfqPoolCreated(address pool, address impl);
event PoolImplementationSet(address poolImplementation);
event RegistrySet(address registry);
error AlreadyMultiPoolTreasury();
error NotMultiPoolTreasury();
error NotMultiPoolTreasuryAndBoundToOtherPool(address treasuryAddress);
error ZeroAddressInput();
error RegistryAlreadySet();
error RegistryNotSet();
error InputArrayLengthMismatch();
error PoolUpgradeFailed();
error OnlyOwnerOrPauserCanCall();
error PoolNotFound(address pool);
function createNewPool(NewPoolConfig calldata poolConfig) external returns (address pool);
function upgradePools(address[] calldata _pools, address[] calldata _impls) external;
function upgradePool(address pool, address impl) external;
function getPool(address treasuryAddress) external view returns (address[] memory);
function verifyPool(address poolAddress) external view returns (bool);
function setPoolImplementation(address newPoolImplementation) external;
function setPauser(address _pauser) external;
function isRfqPool(address pool) external view returns (bool);
}
INativeRfqPool.sol 86 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import {INativeRouter} from "./INativeRouter.sol";
interface INativeRfqPool {
/// @notice Used for intra-chain RFQ-T trades.
struct RFQTQuote {
address pool;
address signer;
/// @notice The recipient of the buyerToken at the end of the trade.
address recipient;
/**
* @notice The account "effectively" making the trade (ultimately receiving the funds).
* This is commonly used by aggregators, where a proxy contract (the 'trader')
* receives the buyerToken, and the effective trader is the user initiating the call.
*
* This field DOES NOT influence movement of funds. However, it is used to check against
* quote replay.
*/
// address effectiveTrader;
/// @notice The token that the trader sells.
address sellerToken;
/// @notice The token that the trader buys.
address buyerToken;
/**
* @notice The amount of sellerToken sold in this trade. The exchange rate
* is going to be preserved as the buyerTokenAmount / sellerTokenAmount ratio.
*
* Most commonly, effectiveSellerTokenAmount will == sellerTokenAmount.
*/
uint256 effectiveSellerTokenAmount;
/// @notice The max amount of sellerToken sold.
uint256 sellerTokenAmount;
/// @notice The amount of buyerToken bought when sellerTokenAmount is sold.
uint256 buyerTokenAmount;
/// @notice The Unix timestamp (in seconds) when the quote expires.
/// @dev This gets checked against block.timestamp.
uint256 deadlineTimestamp;
/// @notice The nonce used by this effectiveTrader. Nonces are used to protect against replay.
uint256 nonce;
/// @notice Unique identifier for the quote.
/// @dev Generated off-chain via a distributed UUID generator.
bytes16 quoteId;
/// @dev false if this quote is for the 1st hop of a multi-hop or a single-hop, in which case msg.sender is the payer.
/// true if this quote is for 2nd or later hop of a multi-hop, in which case router is the payer.
bool multiHop;
/// @notice Signature provided by the market maker (EIP-191).
bytes signature;
INativeRouter.WidgetFee widgetFee;
bytes widgetFeeSignature;
/// @notice not used for RFQ flow, only for external swaps
bytes externalSwapCalldata;
/// @notice not used for RFQ flow, only for external swaps for slippage check
uint amountOutMinimum;
}
function tradeRFQT(RFQTQuote memory quote) external;
event SignerUpdated(address signer, bool value);
event OwnerSet(address owner);
event TreasurySet(address treasury);
event PostTradeCallbackSet(bool value);
event PauseSet(bool value);
event RfqTrade(
address recipient,
address sellerToken,
address buyerToken,
uint256 sellerTokenAmount,
uint256 buyerTokenAmount,
bytes16 quoteId,
address signer
);
error InvalidNewImplementation();
error CallerNotFactory();
error CallerNotRouter();
error CallerNotOwner();
error CallerNotPendingOwner();
error ZeroOrEmptyInput();
error TradePaused();
error NonceUsed();
error InvalidSigner();
error InvalidSignature();
error Overflow();
}
INativeTreasury.sol 27 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
// generic interface to treasury contract
interface INativeTreasury {
event ReservesSynced(uint128 reserve0, uint128 reserve1);
function syncReserve() external;
function getReserves() external view returns (uint128 _reserve0, uint128 _reserve1);
function setPoolAddress(address _pool) external;
function token0() external view returns (address);
function token1() external view returns (address);
}
interface INativeTreasuryV2 {
function nativeTreasuryCallback(
address signer,
address sellerToken,
int256 amount0Delta,
address buyerToken,
int256 amount1Delta
) external;
}
IPancakeRouter01.sol 155 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
interface IPancakeRouter01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts);
}
IPancakeRouter02.sol 51 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
import "./IPancakeRouter01.sol";
interface IPancakeRouter02 is IPancakeRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
IPeripheryState.sol 12 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryState {
/// @return Returns the address of the Native factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
IPricer.sol 11 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
interface IPricer {
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut,
uint256 fee
) external pure returns (uint);
}
ISwapCallback.sol 17 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface ISwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param _data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function swapCallback(int256 amount0Delta, int256 amount1Delta, bytes calldata _data) external;
}
IUniswapV3SwapRouter.sol 22 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
// ref: https://github.com/Uniswap/swap-router-contracts/blob/main/contracts/interfaces/IV3SwapRouter.sol
interface IUniswapV3SwapRouter {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @dev Setting `amountIn` to 0 will cause the contract to look up its own balance,
/// and swap the entire amount, enabling contracts to send tokens before calling this function.
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
}
IWETH9.sol 20 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Interface for WETH9
interface IWETH9 is IERC20 {
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint256) external;
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
BytesLib.sol 105 lines
// SPDX-License-Identifier: GPL-3.0 /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity 0.8.17; library BytesLib { function slice(bytes memory _bytes, uint256 _start, uint256 _length) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_bytes.length >= _start + 3, "toUint24_outOfBounds"); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) { require(_bytes.length >= _start + 32, "toUint256_outOfBounds"); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } }
CallbackValidation.sol 17 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "../interfaces/INativePoolFactory.sol";
import "../interfaces/INativePool.sol";
/// @notice Provides validation for callbacks from Native Pools
library CallbackValidation {
/// @notice Returns the address of a valid Native Pool
/// @param factory The contract address of the Native factory
/// @param pool The contract address of a Pool
/// @return verifiedPool The Native pool contract address
function verifyCallback(address factory, address pool) internal view returns (INativePool) {
require(INativePoolFactory(factory).verifyPool(pool), "Invalid pool address");
return INativePool(pool);
}
}
FullMath.sol 121 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0, "FullMath: mulDiv: denominator must be greater then zero");
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1, "FullMath: mulDiv: result greater than 2**256");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
// uint256 twos = -denominator & denominator;
uint256 twos = denominator & (~denominator + 1);
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
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
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use 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.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // 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 precoditions 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 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(uint256 a, uint256 b, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max, "FullMath: mulDivRoundingUp: result greater than 2**256");
result++;
}
}
}
}
Multicall.sol 40 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
pragma abicoder v2;
import "./PeripheryValidation.sol";
import "../interfaces/IMulticall.sol";
/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall, PeripheryValidation {
/// @inheritdoc IMulticall
function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
results = new bytes[](data.length);
for (uint256 i = 0; i < data.length; ) {
(bool success, bytes memory result) = address(this).delegatecall(data[i]);
if (!success) {
// Next 5 lines from https://ethereum.stackexchange.com/a/83577
if (result.length < 68) revert();
assembly {
result := add(result, 0x04)
}
revert(abi.decode(result, (string)));
}
results[i] = result;
unchecked {
i++;
}
}
}
/// @inheritdoc IMulticall
function multicall(
uint256 deadline,
bytes[] calldata data
) external payable override checkDeadline(deadline) returns (bytes[] memory) {
return multicall(data);
}
}
NoDelegateCallUpgradable.sol 37 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.17;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/// @title Prevents delegatecall to a contract
/// @notice Base contract that provides a modifier for preventing delegatecall to methods in a child contract
abstract contract NoDelegateCallUpgradable is Initializable {
/// @dev The original address of this contract
address private original;
function __NoDelegateCall_init() internal onlyInitializing {
__NoDelegateCall_init_unchained();
}
function __NoDelegateCall_init_unchained() internal onlyInitializing {
original = address(this);
}
/// @dev Private method is used instead of inlining into modifier because modifiers are copied into each method,
/// and the use of immutable means the address bytes are copied in every place the modifier is used.
function checkNotDelegateCall() private view {
require(address(this) == original, "delegate call check violation");
}
/// @notice Prevents delegatecall into the modified method
modifier noDelegateCall() {
checkNotDelegateCall();
_;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
Order.sol 66 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
pragma abicoder v2;
import "./BytesLib.sol";
//import "hardhat/console.sol";
library Orders {
using BytesLib for bytes;
struct Order {
uint256 id;
address signer;
address buyer;
address seller;
address buyerToken;
address sellerToken;
uint256 buyerTokenAmount;
uint256 sellerTokenAmount;
uint256 deadlineTimestamp;
address caller;
bytes16 quoteId;
}
uint256 private constant ADDR_SIZE = 20;
uint256 private constant UINT256_SIZE = 32;
uint256 private constant UUID_SIZE = 16;
uint256 private constant ORDER_SIZE = ADDR_SIZE * 6 + UINT256_SIZE * 4 + UUID_SIZE;
uint256 private constant SIG_SIZE = 65;
uint256 private constant HOP_SIZE = SIG_SIZE + ORDER_SIZE;
function hasMultiplePools(bytes memory orders) internal pure returns (bool) {
return orders.length > HOP_SIZE;
}
function numPools(bytes memory orders) internal pure returns (uint256) {
// Ignore the first token address. From then on every fee and token offset indicates a pool.
return (orders.length / HOP_SIZE);
}
function decodeFirstOrder(bytes memory orders) internal pure returns (Order memory order, bytes memory signature) {
require(orders.length != 0 && orders.length % HOP_SIZE == 0, "Orders: decodeFirstOrder: invalid bytes length");
order.id = orders.toUint256(0);
order.signer = orders.toAddress(UINT256_SIZE);
order.buyer = orders.toAddress(UINT256_SIZE + ADDR_SIZE);
order.seller = orders.toAddress(UINT256_SIZE + ADDR_SIZE * 2);
order.buyerToken = orders.toAddress(UINT256_SIZE + ADDR_SIZE * 3);
order.sellerToken = orders.toAddress(UINT256_SIZE + ADDR_SIZE * 4);
order.buyerTokenAmount = orders.toUint256(UINT256_SIZE + ADDR_SIZE * 5);
order.sellerTokenAmount = orders.toUint256(UINT256_SIZE * 2 + ADDR_SIZE * 5);
order.deadlineTimestamp = orders.toUint256(UINT256_SIZE * 3 + ADDR_SIZE * 5);
order.caller = orders.toAddress(UINT256_SIZE * 4 + ADDR_SIZE * 5);
order.quoteId = bytes16(orders.slice(UINT256_SIZE * 4 + ADDR_SIZE * 6, UUID_SIZE));
signature = orders.slice(ORDER_SIZE, SIG_SIZE);
}
function getFirstOrder(bytes memory orders) internal pure returns (bytes memory) {
return orders.slice(0, HOP_SIZE);
}
function skipOrder(bytes memory orders) internal pure returns (bytes memory) {
require(orders.length != 0 && orders.length % HOP_SIZE == 0, "Orders: decodeFirstOrder: invalid bytes length");
return orders.slice(HOP_SIZE, orders.length - HOP_SIZE);
}
}
PeripheryPayments.sol 41 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./TransferHelper.sol";
import "../interfaces/IWETH9.sol";
import "./PeripheryState.sol";
import "./Weth9Unwrapper.sol";
abstract contract PeripheryPayments is PeripheryState {
error CallerNotWeth9();
receive() external payable {
if (msg.sender != WETH9) {
revert CallerNotWeth9();
}
}
function wrapETH(uint256 value) external payable {
IWETH9(WETH9).deposit{value: value}();
}
function pull(address token, uint256 value) external payable {
TransferHelper.safeTransferFrom(token, msg.sender, address(this), value);
}
// internal methods
/// @param token The token to pay
/// @param payer The entity that must pay
/// @param recipient The entity that will receive payment
/// @param value The amount to pay
function pay(address token, address payer, address recipient, uint256 value) internal {
if (payer == address(this)) {
// pay with tokens already in the contract (for the exact input multihop case)
TransferHelper.safeTransfer(token, recipient, value);
} else {
// pull payment
TransferHelper.safeTransferFrom(token, payer, recipient, value);
}
}
}
PeripheryState.sol 27 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "../interfaces/IPeripheryState.sol";
import "../storage/NativeRouterStorage.sol";
abstract contract PeripheryState is IPeripheryState {
address public override factory;
address public override WETH9;
address payable public weth9Unwrapper;
function initializeState(address _factory, address _WETH9) internal {
require(_factory != address(0), "PeripheryState: factory address cannot be 0");
require(_WETH9 != address(0), "PeripheryState: WETH9 address cannot be 0");
factory = _factory;
WETH9 = _WETH9;
}
function setWeth9Unwrapper(address payable _weth9Unwrapper) public virtual;
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[47] private __gap;
}
PeripheryValidation.sol 9 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
abstract contract PeripheryValidation {
modifier checkDeadline(uint256 deadline) {
require(block.timestamp <= deadline, "Transaction too old");
_;
}
}
SafeCast.sol 28 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param y The uint256 to be downcasted
/// @return z The downcasted integer, now type uint160
function toUint160(uint256 y) internal pure returns (uint160 z) {
require((z = uint160(y)) == y);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param y The int256 to be downcasted
/// @return z The downcasted integer, now type int128
function toInt128(int256 y) internal pure returns (int128 z) {
require((z = int128(y)) == y);
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param y The uint256 to be casted
/// @return z The casted integer, now type int256
function toInt256(uint256 y) internal pure returns (int256 z) {
require(y <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
z = int256(y);
}
}
TransferHelper.sol 45 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
library TransferHelper {
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice Transfers tokens from the targeted address to the given destination
/// @notice Errors with 'STF' if transfer fails
/// @param token The contract address of the token to be transferred
/// @param from The originating address from which the tokens will be transferred
/// @param to The destination address of the transfer
/// @param value The amount to be transferred
function safeTransferFrom(address token, address from, address to, uint256 value) internal {
IERC20Upgradeable(token).safeTransferFrom(from, to, value);
}
/// @notice Transfers tokens from msg.sender to a recipient
/// @dev Errors with ST if transfer fails
/// @param token The contract address of the token which will be transferred
/// @param to The recipient of the transfer
/// @param value The value of the transfer
function safeTransfer(address token, address to, uint256 value) internal {
IERC20Upgradeable(token).safeTransfer(to, value);
}
function safeIncreaseAllowance(address token, address to, uint256 value) internal {
IERC20Upgradeable(token).safeIncreaseAllowance(to, value);
}
function safeDecreaseAllowance(address token, address to, uint256 value) internal {
IERC20Upgradeable(token).safeDecreaseAllowance(to, value);
}
/// @notice Transfers ETH to the recipient address
/// @dev Fails with `STE`
/// @param to The destination of the transfer
/// @param value The value to be transferred
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "STE");
}
}
Weth9Unwrapper.sol 23 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import "../interfaces/IWETH9.sol";
import "./TransferHelper.sol";
contract Weth9Unwrapper {
address public immutable weth9;
address public immutable nativeRouter;
constructor(address _weth9, address _router) {
weth9 = _weth9;
nativeRouter = _router;
}
receive() external payable {}
function unwrapWeth9(uint256 amount, address recipient) public {
require(msg.sender == nativeRouter, "only NativeRouter can call this function");
IWETH9(weth9).withdraw(amount);
TransferHelper.safeTransferETH(recipient, amount);
}
}
NativePoolStorage.sol 27 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
import {INativePool} from "../interfaces/INativePool.sol";
abstract contract NativePoolStorage {
bool public isPmm;
address public router;
address public poolFactory;
address public treasury;
address public treasuryOwner;
address public pricingModelRegistry;
address[] public tokenAs;
address[] public tokenBs;
uint256 public pairCount;
mapping(address => mapping(address => INativePool.Pair)) internal pairs;
mapping(address => bool) public isSigner;
mapping(address => uint256) internal nonce; // deprecated, not used anymore
bool public isPublicTreasury;
bool public isTreasuryContract;
mapping(address => mapping(uint256 => bool)) public nonceMapping;
address public pauser;
uint256[98] private __gap;
}
NativeRfqPoolStorage.sol 16 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
abstract contract NativeRfqPoolStorage {
string public name;
bool public paused;
address public owner;
address public router;
address public poolFactory;
mapping(uint256 => bool) public nonces;
mapping(address => bool) public isSigner;
bool public enableTreasuryCallback;
address public weth;
address public treasury;
address public pendingOwner;
}
NativeRouterStorage.sol 14 lines
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.17;
// just a placeholder now in case there is any future state variables
abstract contract NativeRouterStorage {
address public widgetFeeSigner;
address public pauser;
mapping(address => bool) public contractCallerWhitelist;
bool public contractCallerWhitelistEnabled;
mapping(address => mapping(bytes4 => bool)) public externalRouterSelectorWhitelist; // deprecated vairable DO NOT DELETE
mapping(address => bool) public externalRouterWhitelist;
uint256[95] private __gap;
}
Read Contract
TEN_THOUSAND_DENOMINATOR 0x7aed3f02 → uint256
WETH9 0x4aa4a4fc → address
contractCallerWhitelist 0x31cfa1ac → bool
contractCallerWhitelistEnabled 0x9c7c21b8 → bool
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
externalRouterSelectorWhitelist 0x11d9c956 → bool
externalRouterWhitelist 0xb666dc0a → bool
factory 0xc45a0155 → address
getImplementation 0xaaf10f42 → address
owner 0x8da5cb5b → address
pancakeswapRouter 0xdb6754ed → address
paused 0x5c975abb → bool
pauser 0x9fd0506d → address
proxiableUUID 0x52d1902d → bytes32
weth9Unwrapper 0x5131e1fb → address
widgetFeeSigner 0x086eae40 → address
Write Contract 24 functions
These functions modify contract state and require a wallet transaction to execute.
exactInput 0x80fb3ad6
tuple params
returns: uint256
exactInputSingle 0x5d76b977
tuple params
returns: uint256
initialize 0xc0c53b8b
address factory
address weth9
address _widgetFeeSigner
multicall 0x5ae401dc
uint256 deadline
bytes[] data
returns: bytes[]
multicall 0xac9650d8
bytes[] data
returns: bytes[]
pause 0x8456cb59
No parameters
pull 0xf2d5d56b
address token
uint256 value
refundETHRecipient 0x569b578d
address recipient
uint256 amount
renounceOwnership 0x715018a6
No parameters
setContractCallerWhitelist 0x27a92b53
address caller
bool value
setContractCallerWhitelistToggle 0xae61c65d
bool value
setExternalRouterWhitelist 0xec48e312
address[] routers
bool[] values
setPauser 0x2d88af4a
address _pauser
setWeth9Unwrapper 0x372a771b
address _weth9Unwrapper
setWidgetFeeSigner 0x72a8ddc9
address _widgetFeeSigner
swapCallback 0xfa483e72
int256 amount0Delta
int256 amount1Delta
bytes _data
sweepToken 0xdf2ab5bb
address token
uint256 amountMinimum
address recipient
tradeRFQT 0x9561fc41
tuple quote
transferOwnership 0xf2fde38b
address newOwner
unpause 0x3f4ba83a
No parameters
unwrapWETH9 0x49404b7c
uint256 amountMinimum
address recipient
upgradeTo 0x3659cfe6
address newImplementation
upgradeToAndCall 0x4f1ef286
address newImplementation
bytes data
wrapETH 0x1c58db4f
uint256 value
Recent Transactions
No transactions found for this address