Address Contract Partially Verified
Address
0xA5AdC5484f9997fBF7D405b9AA62A7d88883C345
Balance
0 ETH
Nonce
1
Code Size
24373 bytes
Creator
0xf6C6dbE1...E76E at tx 0xd0b7ff43...ece2a4
Indexed Transactions
0
Contract Bytecode
24373 bytes
0x608060405234801561001057600080fd5b50600436106102ea5760003560e01c80636b29e1bd1161018c578063a217fddf116100ee578063d547741f11610097578063e744092e11610071578063e744092e1461082f578063f1accf3914610852578063fc4481581461086557600080fd5b8063d547741f146107f6578063d6d788c314610809578063ded700a61461081c57600080fd5b8063bc063e1a116100c8578063bc063e1a146107b9578063c67e32e9146107c3578063cc7a2049146107e357600080fd5b8063a217fddf1461078b578063b2b513c114610793578063b39461e5146107a657600080fd5b80637d361dd311610150578063808ba8e01161012a578063808ba8e0146106b55780638456cb591461074a57806391d148541461075257600080fd5b80637d361dd31461066e5780637d8e8603146106775780637dc0d1d01461068a57600080fd5b80636b29e1bd1461060f5780636eefd1341461062257806372ada4c51461063557806374ae623b146106485780637adbf9731461065b57600080fd5b8063480b379611610250578063560c6499116101f95780635b6fd01d116101d35780635b6fd01d146105c05780635c975abb146105e057806364857370146105e857600080fd5b8063560c64991461056a57806357ae1cec1461057d578063582cf84b1461059257600080fd5b80634aa91aee1161022a5780634aa91aee146104c75780634eeeb3eb1461053557806354cf2aeb1461053e57600080fd5b8063480b37961461045a578063480e5da11461047a5780634997cdc3146104a757600080fd5b8063248a9ca3116102b2578063366395801161028c57806336639580146104365780633f4ba83a1461043f5780633feb14931461044757600080fd5b8063248a9ca3146103eb5780632f2ff15d1461040e57806336568abe1461042357600080fd5b806301ffc9a7146102ef5780630b1aa9841461031757806316cd7af81461036d57806317621890146103ae5780631b8b8c34146103cf575b600080fd5b6103026102fd366004614a51565b61088c565b60405190151581526020015b60405180910390f35b610358610325366004614acc565b60046020908152600094855260408086208252938552838520815291845282842090915282529020805460019091015482565b6040805192835260208301919091520161030e565b61039661037b366004614b24565b600c602052600090815260409020546001600160781b031681565b6040516001600160781b03909116815260200161030e565b6103c16103bc366004614b41565b6108c3565b60405190815260200161030e565b6103d861271081565b60405161ffff909116815260200161030e565b6103c16103f9366004614b71565b60009081526006602052604090206001015490565b61042161041c366004614b41565b610976565b005b610421610431366004614b41565b6109a0565b6103c160105481565b610421610a1e565b610421610455366004614bce565b610a35565b61046d610468366004614c0f565b610aea565b60405161030e9190614ca0565b600a5461048e90600160c01b900460f81b81565b6040516001600160f81b0319909116815260200161030e565b6104ba6104b5366004614d46565b610d2c565b60405161030e9190614f01565b6105156104d5366004614acc565b60036020908152600094855260408086208252938552838520815291845282842090915282529020546001600160801b0380821691600160801b90041682565b604080516001600160801b0393841681529290911660208301520161030e565b6103c160095481565b600a5461055590600160a01b900463ffffffff1681565b60405163ffffffff909116815260200161030e565b610421610578366004614f14565b61144f565b600a546103d890600160c81b900461ffff1681565b61048e6105a0366004614f4b565b600160209081526000928352604080842090915290825290205460f81b81565b6105d36105ce366004614b71565b6115d6565b60405161030e9190614f79565b610302611794565b6103c17f052bd61fb293c90e13fa32c291e2dcb25630630baf169861d2a103dfe65025f481565b6103c161061d366004614ffe565b6117a3565b6104216106303660046150a3565b611b43565b6103586106433660046150c7565b611bce565b6104216106563660046150fe565b611e1b565b610421610669366004614b24565b611fe0565b6103c160085481565b610421610685366004614bce565b612050565b600a5461069d906001600160a01b031681565b6040516001600160a01b03909116815260200161030e565b6107136106c3366004615169565b60056020908152600093845260408085208252928452828420905282529020805460019091015463ffffffff808316926001600160e01b03600160201b9182900481169392831692919091041684565b6040805163ffffffff95861681526001600160e01b039485166020820152949092169184019190915216606082015260800161030e565b6104216120df565b610302610760366004614b41565b60009182526006602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6103c1600081565b6103c16107a13660046151b0565b6120f3565b6104ba6107b4366004615285565b612157565b610555620186a081565b6103c16107d1366004614b24565b60026020526000908152604090205481565b600d5461069d906001600160a01b031681565b610421610804366004614b41565b612634565b6104216108173660046153b1565b612659565b61042161082a3660046153cc565b6126c2565b61030261083d366004614b24565b600b6020526000908152604090205460ff1681565b6104216108603660046153f8565b612708565b6103c17f73c06b41830ea810d4e9dd3dfb0309555fbff1642391fb7644bc4a0b0f7a77fd81565b60006001600160e01b03198216637965db0b60e01b14806108bd57506301ffc9a760e01b6001600160e01b03198316145b92915050565b60006002600054036108f05760405162461bcd60e51b81526004016108e790615440565b60405180910390fd5b60026000556108fe8261274f565b60008061090a85612776565b91509150610919818584612886565b604080518681526001600160a01b0383811660208301529181018490529085169033907fcade65431cead780eb2b14b84a6594e1b235278a02e31abf3fc04c7c3e8ab4ee9060600160405180910390a35060016000559392505050565b600082815260066020526040902060010154610991816128a0565b61099b83836128aa565b505050565b6001600160a01b0381163314610a105760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084016108e7565b610a1a828261294c565b5050565b600854610a2a816128a0565b610a326129cf565b50565b600854610a41816128a0565b60005b82811015610aab57610a7b848483818110610a6157610a61615477565b9050602002016020810190610a7691906153b1565b612a21565b600a805460ff60c01b198116600160c01b9182900460f890811b9490941790931c02919091179055600101610a44565b507fd691741464555eddf67afe8f82b0cbe92f8859926856aec4a48a106ceb1b1bee8383604051610add92919061548d565b60405180910390a1505050565b6060600260005403610b0e5760405162461bcd60e51b81526004016108e790615440565b6002600055610b1c8261274f565b826001600160401b03811115610b3457610b346154d6565b604051908082528060200260200182016040528015610b5d578160200160208202803683370190505b50905060005b83811015610cd0576000858583818110610b7f57610b7f615477565b9050602002810190610b9191906154ec565b610b9f906020810190614b24565b90506000868684818110610bb557610bb5615477565b9050602002810190610bc791906154ec565b610bd590602081019061550c565b8080602002602001604051908101604052809392919081815260200183836020028082843760009201829052509394505050505b8151811015610ca157600080610c37848481518110610c2a57610c2a615477565b6020026020010151612776565b91509150846001600160a01b0316816001600160a01b031614610c6d5760405163305663b560e11b815260040160405180910390fd5b81878781518110610c8057610c80615477565b60200260200101818151610c94919061556b565b9052505050600101610c09565b50610cc68286868681518110610cb957610cb9615477565b6020026020010151612886565b5050600101610b63565b50816001600160a01b0316336001600160a01b03167fdc1e0c1e1b707ce83f3d3a8c66a6abc1d23d95f81a61fc1f578355e0d968fd2d868685604051610d1893929190615617565b60405180910390a360016000559392505050565b6040805180820190915260608082526020820152600a5463ffffffff600160a01b820416906001600160a01b03166000896001600160401b03811115610d7457610d746154d6565b604051908082528060200260200182016040528015610d9d578160200160208202803683370190505b50905060008a6001600160401b03811115610dba57610dba6154d6565b604051908082528060200260200182016040528015610de3578160200160208202803683370190505b509050886001600160401b03811115610dfe57610dfe6154d6565b604051908082528060200260200182016040528015610e3757816020015b610e246149f8565b815260200190600190039081610e1c5790505b50602086015260005b898110156111905760008b8b83818110610e5c57610e5c615477565b610e7292602060409092020190810191506156c2565b905060008c8c84818110610e8857610e88615477565b9050604002016020016020810190610ea091906156c2565b90508060ff168260ff16101580610f7c5750600083118015610f7c57508c8c610eca6001866156df565b818110610ed957610ed9615477565b610eef92602060409092020190810191506156c2565b60ff168260ff161080610f7c57508c8c610f0a6001866156df565b818110610f1957610f19615477565b610f2f92602060409092020190810191506156c2565b60ff168260ff16148015610f7c57508c8c610f4b6001866156df565b818110610f5a57610f5a615477565b9050604002016020016020810190610f7291906156c2565b60ff168160ff1611155b15610f9a57604051635dd49b5d60e01b815260040160405180910390fd5b610fa26149f8565b8f8f8460ff16818110610fb757610fb7615477565b9050602002016020810190610fcc9190614b24565b6001600160a01b031681528f8f60ff8416818110610fec57610fec615477565b90506020020160208101906110019190614b24565b6001600160a01b031660208201819052815161101d918e612b0d565b6001600160f81b03191660c08401526060830152604082018190528651879060ff861690811061104f5761104f615477565b60200260200101818151611063919061556b565b90525060608101518651879060ff851690811061108257611082615477565b60200260200101818151611096919061556b565b90525060408051808201909152600080825260208201526110c2826000015183602001518a8f8f612cdb565b60a085018290526080850192909252602082015160608501519293506110ea9290918c612dd5565b868560ff16815181106110ff576110ff615477565b60200260200101818151611113919061556b565b90525080516040830151608084015161112e9291908c612dd5565b868460ff168151811061114357611143615477565b60200260200101818151611157919061556b565b90525060208a015180518391908790811061117457611174615477565b6020026020010181905250848060010195505050505050610e40565b50600a54600160c81b900461ffff168b6001600160401b038111156111b7576111b76154d6565b60405190808252806020026020018201604052801561121c57816020015b611209604051806080016040528060006001600160a01b031681526020016000815260200160008152602001600081525090565b8152602001906001900390816111d55790505b50865260005b86515181101561143e5760008e8e8381811061124057611240615477565b90506020020160208101906112559190614b24565b6001600160a01b0381166000908152600b602052604090205490915060ff16611291576040516306d022d560e51b815260040160405180910390fd5b6000821180156112e357508e8e6112a96001856156df565b8181106112b8576112b8615477565b90506020020160208101906112cd9190614b24565b6001600160a01b0316816001600160a01b031611155b15611301576040516333910aef60e11b815260040160405180910390fd5b611335604051806080016040528060006001600160a01b031681526020016000815260200160008152602001600081525090565b6001600160a01b0382168152845160009086908590811061135857611358615477565b60200260200101519050600087858151811061137657611376615477565b60200260200101519050600082118061138f5750600081115b1561140b5760006113a08b84612e1f565b905060006127106113b561ffff8a16846156f2565b6113bf9190615727565b905060006113cd858561573b565b9050818113156113eb576113e1828261573b565b6020870152611403565b81811215611403576113fd818361573b565b60408701525b506060850152505b828b60000151868151811061142257611422615477565b6020026020010181905250848060010195505050505050611222565b505050505050979650505050505050565b6002600054036114715760405162461bcd60e51b81526004016108e790615440565b60026000557f73c06b41830ea810d4e9dd3dfb0309555fbff1642391fb7644bc4a0b0f7a77fd6114a0816128a0565b60005b8381101561157d578484828181106114bd576114bd615477565b90506040020160200135600260008787858181106114dd576114dd615477565b6114f39260206040909202019081019150614b24565b6001600160a01b03166001600160a01b03168152602001908152602001600020600082825461152291906156df565b90915550611575905085858381811061153d5761153d615477565b6115539260206040909202019081019150614b24565b8487878581811061156657611566615477565b90506040020160200135612886565b6001016114a3565b50816001600160a01b0316336001600160a01b03167fc372140441ddd3b3a7319bbc36cbc33b5600b15c211eda1d1fc9d35bb7ebb3a886866040516115c392919061575b565b60405180910390a3505060016000555050565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e08101919091526000828152600e60209081526040808320815160e081018352815463ffffffff8082168352600160201b82041694820194909452600160401b840460f81b6001600160f81b031916928101839052600160481b84046001600160a01b0390811660608301819052600160e81b90950462ffffff1660808301526001909201546001600160601b03811660a0830152600160601b900490911660c082018190529093926116c592909190612e67565b905060006116d7828460200151612ec1565b60608401516001600160a01b03908116865260c08501511660208601528351909150611704908290612ee2565b63ffffffff166060850152602083015161171e9083612ee2565b63ffffffff1660a08501526117338383612f08565b60c085015261174183612f3a565b6001600160781b031660e085015260408301516001600160f81b0319161561178c576117708360400151612f6b565b63ffffffff166040850152611786858484613077565b60808501525b505050919050565b600061179e6132a1565b905090565b60006002600054036117c75760405162461bcd60e51b81526004016108e790615440565b60026000556117d46132af565b6001600160a01b03891615806117f157506001600160a01b038816155b8061180357506001600160a01b038416155b156118215760405163d92e233d60e01b815260040160405180910390fd5b876001600160a01b0316896001600160a01b0316036118535760405163c1ab6dc160e01b815260040160405180910390fd5b8660000361187457604051631f2a200560e01b815260040160405180910390fd5b8563ffffffff1660000361189b57604051633c92196b60e11b815260040160405180910390fd5b6118a589896132f9565b60006118b18888613358565b905060006010600081546118c4906157b4565b9182905550905060006118e28c8c8b6118dc8c612a21565b87613395565b6040810151600a549192506001600160f81b0319600160c01b90920460f81b161660000361192357604051638b52594f60e01b815260040160405180910390fd5b600d546040516306d66a1360e31b81526001600160a01b03909116906336b35098906119599085908b908b908b906004016158b1565b600060405180830381600087803b15801561197357600080fd5b505af1158015611987573d6000803e3d6000fd5b5050505061199a8c8c836040015161346e565b6119af8c8c8360400151846020015187613588565b6000828152600e60209081526040918290208351815492850151938501516060860151608087015163ffffffff93841667ffffffffffffffff1990961695909517600160201b96841696909602959095177fffffff000000000000000000000000000000000000000000ffffffffffffffff16600160401b60f89290921c919091027fffffff0000000000000000000000000000000000000000ffffffffffffffffff1617600160481b6001600160a01b0395861602176001600160e81b0316600160e81b62ffffff9094169390930292909217815560a084015160c08501516001600160601b03909116600160601b9185169190910217600190910155611ac0918e1690339030908e9061359e16565b866001600160a01b0316336001600160a01b03167f1915b09a20b5793f1bd89b84dc928fe4ee36b0b9270ec217a3b2c278999f0967848f8f8d8988600001516001611b0b91906158e4565b89602001518f8f604051611b2799989796959493929190615901565b60405180910390a35060016000559a9950505050505050505050565b600954611b4f816128a0565b61271061ffff83161115611b76576040516314bc5e9d60e21b815260040160405180910390fd5b600a805461ffff60c81b1916600160c81b61ffff8516908102919091179091556040519081527f6c234431526967795ada65665e195191d4b2fc63c9f564d1ea626478325ae9d9906020015b60405180910390a15050565b600080600260005403611bf35760405162461bcd60e51b81526004016108e790615440565b60026000556001600160a01b0384161580611c1557506001600160a01b038316155b15611c335760405163d92e233d60e01b815260040160405180910390fd5b6000858152600e6020908152604091829020825160e081018452815463ffffffff8082168352600160201b82041693820193909352600160401b830460f81b6001600160f81b03191693810193909352600160481b82046001600160a01b039081166060850152600160e81b90920462ffffff166080840152600101546001600160601b03811660a0840152600160601b90041660c0820152611cd88682600361360f565b6000611cf182606001518360c001518460400151612e67565b9050611cfe878383613077565b9250611d0a8282612f08565b9350611d1682826136d0565b6000878152600e60209081526040808320838155600101839055600f90915280822091909155600d549051630852cd8d60e31b8152600481018990526001600160a01b03909116906342966c6890602401600060405180830381600087803b158015611d8157600080fd5b505af1158015611d95573d6000803e3d6000fd5b50505050611da88260c001518685612886565b611db782606001518786612886565b60408051888152602081018690529081018490526001600160a01b03808716919088169033907f2577f709b454c4d5c1118a01186dd48d4a6bacf43fe4c26aad2f66a51bf5290d9060600160405180910390a4505060016000559094909350915050565b600854611e27816128a0565b838214611e47576040516389db169560e01b815260040160405180910390fd5b60005b84811015611f9b576000868683818110611e6657611e66615477565b9050602002016020810190611e7b9190614b24565b9050848483818110611e8f57611e8f615477565b9050602002016020810190611ea49190615970565b6001600160a01b0382166000908152600b60209081526040808320805460ff191694151594909417909355600c9052908120546001600160781b03169003611f9257806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f24573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f48919061598d565b611f5390600a615a8e565b6001600160a01b0382166000908152600c6020526040902080546effffffffffffffffffffffffffffff19166001600160781b03929092169190911790555b50600101611e4a565b507f205ab319bb13f5ff529e58d094941772894e6d3a1905e971dafc88a1bf8bf44b85858585604051611fd19493929190615a9d565b60405180910390a15050505050565b600954611fec816128a0565b611ff58261274f565b600a805473ffffffffffffffffffffffffffffffffffffffff19166001600160a01b0384169081179091556040519081527f3f32684a32a11dabdbb8c0177de80aa3ae36a004d75210335b49e544e48cd0aa90602001611bc2565b60085461205c816128a0565b60005b828110156120ad5761207c848483818110610a6157610a61615477565b600a805460ff60c01b1981169219600160c01b9182900460f890811b91909116901c0291909117905560010161205f565b507fd0359552feffede26fee29bd110dd8e1a3237acd35c7e17a9d3b7330b02f88258383604051610add92919061548d565b6008546120eb816128a0565b610a3261370f565b60006121058b8b8b8b8b8b8b8b6117a3565b90508115612149577fa9c989cd063ac13a33305492ca3b3643f4bf38968e009d020c750e27b3ee287e81848460405161214093929190615b56565b60405180910390a15b9a9950505050505050505050565b604080518082019091526060808252602082015260026000540361218d5760405162461bcd60e51b81526004016108e790615440565b600260005561219a6132af565b600a543360009081527f27ccd2b72600e18cc022b84bd75816633eb853378ec088e72fcd29312a6b933e6020526040902054600160a01b90910463ffffffff16906121f1908f908f908f908f9060ff168989610d2c565b9150426000805b8460200151518110156122c65760008560200151828151811061221d5761221d615477565b602090810291909101015160c0810151909150600160f81b5b6001600160f81b03198082169083161080159061225c57506001600160f81b0319811615155b156122bb576001600160f81b031982821616156122ad576122a3836000015184602001518361228f8b886080015161374c565b61229d8c8960a0015161374c565b8b613775565b846122ad57600194505b60011b607f60f91b16612236565b5050506001016121f8565b50806122e5576040516346f8d7b160e11b815260040160405180910390fd5b50508151516000906001600160401b03811115612304576123046154d6565b60405190808252806020026020018201604052801561232d578160200160208202803683370190505b50905060005b83515181101561242a5760008460000151828151811061235557612355615477565b6020026020010151905060008b8b8481811061237357612373615477565b90506020020135905060008260400151118061238f5750600081115b156123be57815161239f90613b6c565b8484815181106123b1576123b1615477565b6020026020010181815250505b8c6001600160a01b03168e6001600160a01b0316036124005760008183602001516123e9919061556b565b90506123fa83600001518f83612886565b50612420565b61241382600001518f8460200151612886565b8151612420908e83612886565b5050600101612333565b508251604051632c0be4cf60e11b81526001600160a01b038c1691635817c99e916124619133918e908e908e908e90600401615b79565b600060405180830381600087803b15801561247b57600080fd5b505af115801561248f573d6000803e3d6000fd5b5050505060005b8351518110156125c1576000846000015182815181106124b8576124b8615477565b602002602001015190506000816060015190506000826040015111806124f6575060008c8c858181106124ed576124ed615477565b90506020020135115b156125825760008260200151836040015186868151811061251957612519615477565b602002602001015161252b919061556b565b61253591906156df565b905060006125468460000151613b6c565b9050818110156125695760405163d562e29f60e01b815260040160405180910390fd5b61257382826156df565b61257d908461556b565b925050505b80156125b75781516001600160a01b0316600090815260026020526040812080548392906125b190849061556b565b90915550505b5050600101612496565b50896001600160a01b03168b6001600160a01b0316336001600160a01b03167fcd70d819eddb1c1256dfb394594df26f85cdba0554232914fe64f842bec10f83868d8d886040516126159493929190615bd0565b60405180910390a4505060016000559c9b505050505050505050505050565b60008281526006602052604090206001015461264f816128a0565b61099b838361294c565b600954612665816128a0565b61266e82613bd7565b600a805463ffffffff60a01b1916600160a01b63ffffffff8516908102919091179091556040519081527f5658872a8436367e842f76c14ffbbf8e67a2e70f47b28b3c4154134f72e902d690602001611bc2565b6002600054036126e45760405162461bcd60e51b81526004016108e790615440565b60026000556126f16132af565b6126fe8383836000613c30565b5050600160005550565b60026000540361272a5760405162461bcd60e51b81526004016108e790615440565b60026000556127388161274f565b61274484848484613c30565b505060016000555050565b6001600160a01b038116610a325760405163d92e233d60e01b815260040160405180910390fd5b6000818152600e60209081526040808320815160e081018352815463ffffffff8082168352600160201b82041694820194909452600160401b840460f81b6001600160f81b03191692810192909252600160481b83046001600160a01b039081166060840152600160e81b90930462ffffff166080830152600101546001600160601b03811660a0830152600160601b900490911660c0820152819061281e8482600261360f565b600061283782606001518360c001518460400151612e67565b9050612844858383613077565b60c0909201516000958652600e60209081526040808820805463ffffffff90951663ffffffff1990951694909417909355600f90529085209490945593915050565b801561099b5761099b6001600160a01b0384168383613f89565b610a328133613fb9565b60008281526006602090815260408083206001600160a01b038516845290915290205460ff16610a1a5760008281526006602090815260408083206001600160a01b03851684529091529020805460ff191660011790556129083390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b60008281526006602090815260408083206001600160a01b038516845290915290205460ff1615610a1a5760008281526006602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6129d7614039565b6007805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b60008163ffffffff16603c03612a3c5750600160f81b919050565b8163ffffffff1661012c03612a565750600160f91b919050565b8163ffffffff1661038403612a705750600160fa1b919050565b8163ffffffff1661070803612a8a5750600160fb1b919050565b8163ffffffff16610e1003612aa45750600160fc1b919050565b8163ffffffff1661384003612abe5750600160fd1b919050565b8163ffffffff166201518003612ad95750600160fe1b919050565b8163ffffffff1662093a8003612af45750600160ff1b919050565b6040516305fabb6160e41b815260040160405180910390fd5b6001600160a01b0383811660009081526001602090815260408083209386168352929052908120548190819060f81b42600160f81b5b6001600160f81b031980821690841610801590612b6957506001600160f81b0319811615155b15612cb9576001600160f81b03198382161615612cab576001600160a01b03808a166000908152600560209081526040808320938c1683529281528282206001600160f81b03198516835281528282208351608081018552815463ffffffff80821683526001600160e01b03600160201b9283900481169584019590955260019093015492831695820195909552939004166060830152612c0983612f6b565b9050600081828460400151612c1e9190615c0e565b612c299060016158e4565b612c339190615c31565b905089612c5257612c45600383615c0e565b612c4f90826158e4565b90505b8463ffffffff168163ffffffff161115612c6e57505050612cb9565b602083015196841796612c8a906001600160e01b03168a61556b565b985082606001516001600160e01b031688612ca5919061556b565b97505050505b60011b607f60f91b16612b43565b85158015612cc5575084155b15612ccf57600093505b50505093509350939050565b600080612cfb604051806040016040528060008152602001600081525090565b6001600160a01b038089166000908152600c60208181526040808420546001600160781b0390811687528c861685529282529283902054909116908401819052905163d08a8a1960e01b81529188169163d08a8a1991612d66918b91908d908b908b90600401615c5d565b602060405180830381865afa158015612d83573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612da79190615c9b565b91508181600001518260200151612dbe91906156f2565b612dc89190615727565b9250955095509592505050565b600080612deb83612de686886156f2565b61408d565b9050612df78682615727565b9150612e038682615cb4565b15612e165781612e12816157b4565b9250505b50949350505050565b600082612e2f6127106064615cc8565b62ffffff16612e3e9190615cea565b63ffffffff168363ffffffff1683612e5691906156f2565b612e609190615727565b9392505050565b6000806000612e7686866140b9565b6001600160a01b0391821660009081526005602090815260408083209390941682529182528281206001600160f81b031988168252909152205463ffffffff16925050509392505050565b60008163ffffffff168363ffffffff1611612edc5782612e60565b50919050565b60008163ffffffff168363ffffffff1611612efe576000612e60565b612e608284615cea565b6000612f1383612f3a565b6001600160781b0316612f2a846020015184612ee2565b63ffffffff16612e6091906156f2565b6000816080015162ffffff1660188360a001516001600160601b03166001600160781b0316901b6108bd9190615d07565b60006001600160f81b03198216600160f81b03612f8a5750603c919050565b6001600160f81b03198216600160f91b03612fa8575061012c919050565b6001600160f81b03198216600160fa1b03612fc65750610384919050565b6001600160f81b03198216600160fb1b03612fe45750610708919050565b6001600160f81b03198216600160fc1b036130025750610e10919050565b6001600160f81b03198216600160fd1b036130205750613840919050565b6001600160f81b03198216600160fe1b0361303f575062015180919050565b6001600160f81b03198216600160ff1b0361305e575062093a80919050565b60405163bf3cad0b60e01b815260040160405180910390fd5b600080613088838560200151612ec1565b90508063ffffffff16846000015163ffffffff1611156130ac576000915050612e60565b835163ffffffff8083169116036130d35750506000838152600f6020526040902054612e60565b60008460c001516001600160a01b031685606001516001600160a01b0316101561316d5760608501516001600160a01b03908116600090815260046020908152604080832060c08a01519094168352928152828220838901516001600160f81b03191683528152828220885163ffffffff908116845291819052838320549186168352929091205461316591906156df565b9150506131e8565b60c08501516001600160a01b03908116600090815260046020908152604080832060608a01519094168352928152828220838901516001600160f81b03191683528152828220885163ffffffff9081168452918190528383206001908101549287168452939092209092015490916131e4916156df565b9150505b60608501516001600160a01b03166000908152600c60205260408120546001600160781b03169061321887612f3a565b905060008061323085846001600160781b03166140ea565b9092509050600061271083613262576001600160781b0385166132538789615727565b61325d91906156f2565b61326c565b61326c8684615727565b6132769190615727565b60008c8152600f6020526040902054909150613292908261556b565b9b9a5050505050505050505050565b600061179e60075460ff1690565b6132b7611794565b156132f75760405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b60448201526064016108e7565b565b6001600160a01b0382166000908152600b602052604090205460ff16158061333a57506001600160a01b0381166000908152600b602052604090205460ff16155b15610a1a576040516306d022d560e51b815260040160405180910390fd5b60008061336b63ffffffff841685615727565b90506001600160781b03811115612e6057604051636b2f218360e01b815260040160405180910390fd5b6040805160e081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c08101829052906133d9878786612e67565b6040805160e0810190915263ffffffff8216815290915083906001600160601b03601883901c16906020810161340f89866158e4565b63ffffffff168152602001876001600160f81b03191681526020018a6001600160a01b031681526020018362ffffff168152602001826001600160601b03168152602001896001600160a01b0316815250935050505095945050505050565b60008061347b85856140b9565b6001600160a01b03808316600090815260016020908152604080832093851683529290529081205492945090925060f89190911b906001600160f81b0319858316169003613580576001600160f81b0319811660000361354b57600a5460405163d0a26eb360e01b81526001600160a01b038581166004830152848116602483015260606044830152600060648301529091169063d0a26eb390608401600060405180830381600087803b15801561353257600080fd5b505af1158015613546573d6000803e3d6000fd5b505050505b6001600160a01b038381166000908152600160209081526040808320938616835292905220805460ff191685831760f81c1790555b505050505050565b61359785858585856001614135565b5050505050565b6040516001600160a01b03808516602483015283166044820152606481018290526136099085906323b872dd60e01b906084015b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b0319909316929092179091526145d8565b50505050565b60408201516001600160f81b03191660000361363e5760405163673f032f60e11b815260040160405180910390fd5b600d5460405163823abfd960e01b81526001600160a01b039091169063823abfd99061367290869033908690600401615d27565b602060405180830381865afa15801561368f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906136b39190615d4a565b61099b57604051635c427cd960e01b815260040160405180910390fd5b8063ffffffff16826020015163ffffffff161115610a1a57610a1a82606001518360c001518460400151856020015161370887612f3a565b6000614135565b6137176132af565b6007805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612a043390565b6000613759606484615c0e565b61376590612710615cea565b612e609063ffffffff16836156f2565b6001600160a01b03808716600090815260056020908152604080832093891683529281528282206001600160f81b0319881683528152908290208251608081018452815463ffffffff80821683526001600160e01b03600160201b9283900481169584018690526001909401549081169583019590955290930416606083015215158061380f5750600081606001516001600160e01b0316115b15613b58576001600160a01b038088166000818152600460209081526040808320948b168084529482528083206001600160f81b03198b1680855290835281842094845260038352818420958452948252808320948352938152838220855163ffffffff16835283825291849020845180860186528154815260019091015491810191909152835180850190945280519293919290919081906138b3908a9061556b565b81526020018783602001516138c8919061556b565b9052845184906000906138dc9060016158e4565b63ffffffff16815260208082019290925260400160009081208351815592909101516001909201919091558451839082906139189060026158e4565b63ffffffff168152602080820192909252604090810160009081208251808401909352546001600160801b03808216808552600160801b9092041683850152928801519193509161396891615d67565b9050600082602001516001600160801b031687606001516139899190615d67565b90506040518060800160405280886000015160016139a791906158e4565b63ffffffff168152602001836001600160e01b031681526020018963ffffffff168152602001826001600160e01b0316815250600560008f6001600160a01b03166001600160a01b0316815260200190815260200160002060008e6001600160a01b03166001600160a01b0316815260200190815260200160002060008d6001600160f81b0319166001600160f81b031916815260200190815260200160002060008201518160000160006101000a81548163ffffffff021916908363ffffffff16021790555060208201518160000160046101000a8154816001600160e01b0302191690836001600160e01b0316021790555060408201518160010160006101000a81548163ffffffff021916908363ffffffff16021790555060608201518160010160046101000a8154816001600160e01b0302191690836001600160e01b0316021790555090505084600088600001516002613b0691906158e4565b63ffffffff16815260208101919091526040016000908120556001600160e01b038216158015613b3d57506001600160e01b038116155b15613b4d57613b4d8d8d8d6146aa565b505050505050613b63565b613b638787876146aa565b50505050505050565b6040516370a0823160e01b81523060048201526000906001600160a01b038316906370a0823190602401602060405180830381865afa158015613bb3573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108bd9190615c9b565b620186a063ffffffff82161115613c01576040516314041af760e31b815260040160405180910390fd5b613c0c606482615d87565b63ffffffff1615610a32576040516358d620b360e01b815260040160405180910390fd5b6000848152600e6020908152604091829020825160e081018452815463ffffffff8082168352600160201b82041693820193909352600160401b830460f81b6001600160f81b03191693810193909352600160481b82046001600160a01b039081166060850152600160e81b90920462ffffff166080840152600101546001600160601b03811660a0840152600160601b9004811660c0830152821615613ce5868383613cde57600161360f565b600061360f565b8015613d5857613cfd82606001518360c001516132f9565b600080613d1284606001518560c001516140b9565b6040868101516001600160a01b03938416600090815260016020908152838220949095168152929093529020805460ff19811660f891821b909317901c91909117905550505b6000613d7183606001518460c001518560400151612e67565b90506000613d7f8483612f08565b9050600083613d9757613d9288836156df565b613da1565b613da1888361556b565b90508015801590613db6575063ffffffff8716155b15613dd457604051633c92196b60e11b815260040160405180910390fd5b80158015613de8575060008763ffffffff16115b15613df257600096505b600063ffffffff881615613e0f57613e0a8289613358565b613e12565b60005b60008b8152600e602052604081206001810180546bffffffffffffffffffffffff19166001600160601b03601886901c1617905580546001600160e81b0316600160e81b62ffffff851602179055909150613e6d89866158e4565b60008c8152600e60205260409020805463ffffffff808416600160201b0267ffffffffffffffff19909216908916171790559050613eac8b8887613077565b60008c8152600f6020526040902055613ec587866136d0565b613ede87606001518860c0015189604001518486613588565b8915613f18578515613f09576060870151613f04906001600160a01b031633308d61359e565b613f18565b613f188760600151898c612886565b337f1e52a79a98c3fbf6230e862913323047a9c0ec511d2c289b1eeeeb9cc97c5bea8c84613f478960016158e4565b604080519384526001600160781b0392909216602084015263ffffffff9081168383015285166060830152519081900360800190a25050505050505050505050565b6040516001600160a01b03831660248201526044810182905261099b90849063a9059cbb60e01b906064016135d2565b60008281526006602090815260408083206001600160a01b038516845290915290205460ff16610a1a57613ff7816001600160a01b031660146146ec565b6140028360206146ec565b604051602001614013929190615dce565b60408051601f198184030181529082905262461bcd60e51b82526108e791600401615e43565b614041611794565b6132f75760405162461bcd60e51b815260206004820152601460248201527f5061757361626c653a206e6f742070617573656400000000000000000000000060448201526064016108e7565b600061271061409d606485615c0e565b6140a990612710615cea565b612e569063ffffffff16846156f2565b600080826001600160a01b0316846001600160a01b0316106140dc5782846140df565b83835b909590945092505050565b60008083600003614101575060019050600061412e565b8383028385828161411457614114615711565b041461412757600080925092505061412e565b6001925090505b9250929050565b846001600160a01b0316866001600160a01b0316101561438a578015614284576001600160a01b03868116600090815260056020908152604080832093891683529281528282206001600160f81b03198816835290522080546001600160781b03841691906004906141b8908490600160201b90046001600160e01b0316615e76565b82546001600160e01b039182166101009390930a9283029190920219909116179055506001600160a01b03808716600090815260036020908152604080832093891683529281528282206001600160f81b03198816835290529081206001600160781b0384169161422a8660016158e4565b63ffffffff16815260208101919091526040016000908120805490919061425b9084906001600160801b0316615e96565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550613580565b6001600160a01b03868116600090815260056020908152604080832093891683529281528282206001600160f81b03198816835290522080546001600160781b03841691906004906142e7908490600160201b90046001600160e01b0316615d67565b82546001600160e01b039182166101009390930a9283029190920219909116179055506001600160a01b03808716600090815260036020908152604080832093891683529281528282206001600160f81b03198816835290529081206001600160781b038416916143598660016158e4565b63ffffffff16815260208101919091526040016000908120805490919061425b9084906001600160801b0316615eb6565b801561449e576001600160a01b038581166000908152600560209081526040808320938a1683529281528282206001600160f81b03198816835290522060010180546001600160781b03841691906004906143f6908490600160201b90046001600160e01b0316615e76565b82546001600160e01b039182166101009390930a9283029190920219909116179055506001600160a01b038086166000908152600360209081526040808320938a1683529281528282206001600160f81b03198816835290529081206001600160781b038416916144688660016158e4565b63ffffffff1681526020810191909152604001600020805460109061425b908490600160801b90046001600160801b0316615e96565b6001600160a01b038581166000908152600560209081526040808320938a1683529281528282206001600160f81b03198816835290522060010180546001600160781b0384169190600490614504908490600160201b90046001600160e01b0316615d67565b82546001600160e01b039182166101009390930a9283029190920219909116179055506001600160a01b038086166000908152600360209081526040808320938a1683529281528282206001600160f81b03198816835290529081206001600160781b038416916145768660016158e4565b63ffffffff168152602081019190915260400160002080546010906145ac908490600160801b90046001600160801b0316615eb6565b92506101000a8154816001600160801b0302191690836001600160801b03160217905550505050505050565b600061462d826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b03166148879092919063ffffffff16565b80519091501561099b578080602001905181019061464b9190615d4a565b61099b5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b60648201526084016108e7565b6001600160a01b03928316600090815260016020908152604080832094909516825292909252919020805460ff198116921960f891821b16901c919091179055565b606060006146fb8360026156f2565b61470690600261556b565b6001600160401b0381111561471d5761471d6154d6565b6040519080825280601f01601f191660200182016040528015614747576020820181803683370190505b509050600360fc1b8160008151811061476257614762615477565b60200101906001600160f81b031916908160001a905350600f60fb1b8160018151811061479157614791615477565b60200101906001600160f81b031916908160001a90535060006147b58460026156f2565b6147c090600161556b565b90505b6001811115614838576f181899199a1a9b1b9c1cb0b131b232b360811b85600f16601081106147f4576147f4615477565b1a60f81b82828151811061480a5761480a615477565b60200101906001600160f81b031916908160001a90535060049490941c9361483181615ed6565b90506147c3565b508315612e605760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016108e7565b6060614896848460008561489e565b949350505050565b6060824710156148ff5760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b60648201526084016108e7565b6001600160a01b0385163b6149565760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e747261637400000060448201526064016108e7565b600080866001600160a01b031685876040516149729190615eed565b60006040518083038185875af1925050503d80600081146149af576040519150601f19603f3d011682016040523d82523d6000602084013e6149b4565b606091505b5091509150612e12828286606083156149ce575081612e60565b8251156149de5782518084602001fd5b8160405162461bcd60e51b81526004016108e79190615e43565b6040518060e0016040528060006001600160a01b0316815260200160006001600160a01b031681526020016000815260200160008152602001600081526020016000815260200160006001600160f81b03191681525090565b600060208284031215614a6357600080fd5b81356001600160e01b031981168114612e6057600080fd5b6001600160a01b0381168114610a3257600080fd5b8035614a9b81614a7b565b919050565b80356001600160f81b031981168114614a9b57600080fd5b803563ffffffff81168114614a9b57600080fd5b60008060008060808587031215614ae257600080fd5b8435614aed81614a7b565b93506020850135614afd81614a7b565b9250614b0b60408601614aa0565b9150614b1960608601614ab8565b905092959194509250565b600060208284031215614b3657600080fd5b8135612e6081614a7b565b60008060408385031215614b5457600080fd5b823591506020830135614b6681614a7b565b809150509250929050565b600060208284031215614b8357600080fd5b5035919050565b60008083601f840112614b9c57600080fd5b5081356001600160401b03811115614bb357600080fd5b6020830191508360208260051b850101111561412e57600080fd5b60008060208385031215614be157600080fd5b82356001600160401b03811115614bf757600080fd5b614c0385828601614b8a565b90969095509350505050565b600080600060408486031215614c2457600080fd5b83356001600160401b03811115614c3a57600080fd5b614c4686828701614b8a565b9094509250506020840135614c5a81614a7b565b809150509250925092565b600081518084526020808501945080840160005b83811015614c9557815187529582019590820190600101614c79565b509495945050505050565b602081526000612e606020830184614c65565b60008083601f840112614cc557600080fd5b5081356001600160401b03811115614cdc57600080fd5b6020830191508360208260061b850101111561412e57600080fd5b8015158114610a3257600080fd5b60008083601f840112614d1757600080fd5b5081356001600160401b03811115614d2e57600080fd5b60208301915083602082850101111561412e57600080fd5b60008060008060008060006080888a031215614d6157600080fd5b87356001600160401b0380821115614d7857600080fd5b614d848b838c01614b8a565b909950975060208a0135915080821115614d9d57600080fd5b614da98b838c01614cb3565b909750955060408a01359150614dbe82614cf7565b90935060608901359080821115614dd457600080fd5b50614de18a828b01614d05565b989b979a50959850939692959293505050565b600081518084526020808501945080840160005b83811015614c9557815180516001600160a01b031688528381015184890152604080820151908901526060908101519088015260809096019590820190600101614e08565b600060408251818552614e6282860182614df4565b60208581015187830388830152805180845290820193509091600091908301905b80831015614ef557845180516001600160a01b0390811684528582015116858401528681015187840152606080820151908401526080808201519084015260a0808201519084015260c0908101516001600160f81b03191690830152938301936001929092019160e090910190614e83565b50979650505050505050565b602081526000612e606020830184614e4d565b600080600060408486031215614f2957600080fd5b83356001600160401b03811115614f3f57600080fd5b614c4686828701614cb3565b60008060408385031215614f5e57600080fd5b8235614f6981614a7b565b91506020830135614b6681614a7b565b6000610100820190506001600160a01b0380845116835280602085015116602084015250604083015163ffffffff8082166040850152806060860151166060850152608085015160808501528060a08601511660a0850152505060c083015160c083015260e0830151614ff760e08401826001600160781b03169052565b5092915050565b60008060008060008060008060e0898b03121561501a57600080fd5b883561502581614a7b565b9750602089013561503581614a7b565b96506040890135955061504a60608a01614ab8565b945061505860808a01614ab8565b935060a089013561506881614a7b565b925060c08901356001600160401b0381111561508357600080fd5b61508f8b828c01614b8a565b999c989b5096995094979396929594505050565b6000602082840312156150b557600080fd5b813561ffff81168114612e6057600080fd5b6000806000606084860312156150dc57600080fd5b8335925060208401356150ee81614a7b565b91506040840135614c5a81614a7b565b6000806000806040858703121561511457600080fd5b84356001600160401b038082111561512b57600080fd5b61513788838901614b8a565b9096509450602087013591508082111561515057600080fd5b5061515d87828801614b8a565b95989497509550505050565b60008060006060848603121561517e57600080fd5b833561518981614a7b565b9250602084013561519981614a7b565b91506151a760408501614aa0565b90509250925092565b6000806000806000806000806000806101008b8d0312156151d057600080fd5b8a356151db81614a7b565b995060208b01356151eb81614a7b565b985060408b0135975061520060608c01614ab8565b965061520e60808c01614ab8565b955060a08b013561521e81614a7b565b945060c08b01356001600160401b038082111561523a57600080fd5b6152468e838f01614b8a565b909650945060e08d013591508082111561525f57600080fd5b5061526c8d828e01614d05565b915080935050809150509295989b9194979a5092959850565b60008060008060008060008060008060008060e08d8f0312156152a757600080fd5b6001600160401b038d3511156152bc57600080fd5b6152c98e8e358f01614b8a565b909c509a506001600160401b0360208e013511156152e657600080fd5b6152f68e60208f01358f01614cb3565b909a50985061530760408e01614a90565b975061531560608e01614a90565b96506001600160401b0360808e0135111561532f57600080fd5b61533f8e60808f01358f01614b8a565b90965094506001600160401b0360a08e0135111561535c57600080fd5b61536c8e60a08f01358f01614d05565b90945092506001600160401b0360c08e0135111561538957600080fd5b6153998e60c08f01358f01614d05565b81935080925050509295989b509295989b509295989b565b6000602082840312156153c357600080fd5b612e6082614ab8565b6000806000606084860312156153e157600080fd5b83359250602084013591506151a760408501614ab8565b6000806000806080858703121561540e57600080fd5b843593506020850135925061542560408601614ab8565b9150606085013561543581614a7b565b939692955090935050565b6020808252601f908201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604082015260600190565b634e487b7160e01b600052603260045260246000fd5b60208082528181018390526000908460408401835b868110156154cb5763ffffffff6154b884614ab8565b16825291830191908301906001016154a2565b509695505050505050565b634e487b7160e01b600052604160045260246000fd5b60008235603e1983360301811261550257600080fd5b9190910192915050565b6000808335601e1984360301811261552357600080fd5b8301803591506001600160401b0382111561553d57600080fd5b6020019150600581901b360382131561412e57600080fd5b634e487b7160e01b600052601160045260246000fd5b808201808211156108bd576108bd615555565b6000808335601e1984360301811261559557600080fd5b83016020810192503590506001600160401b038111156155b457600080fd5b8060051b360382131561412e57600080fd5b81835260006001600160fb1b038311156155df57600080fd5b8260051b80836020870137939093016020019392505050565b60008235603e1983360301811261560e57600080fd5b90910192915050565b60408082528181018490526000906060600586901b8401810190840187845b8881101561569e57868403605f19018352615651828b6155f8565b803561565c81614a7b565b6001600160a01b0316855260206156758282018361557e565b9250878288015261568988880184836155c6565b96505093840193929092019150600101615636565b5050508381036020850152612e128186614c65565b60ff81168114610a3257600080fd5b6000602082840312156156d457600080fd5b8135612e60816156b3565b818103818111156108bd576108bd615555565b600081600019048311821515161561570c5761570c615555565b500290565b634e487b7160e01b600052601260045260246000fd5b60008261573657615736615711565b500490565b8181036000831280158383131683831282161715614ff757614ff7615555565b6020808252818101839052600090604080840186845b878110156157a757813561578481614a7b565b6001600160a01b0316835281850135858401529183019190830190600101615771565b5090979650505050505050565b6000600182016157c6576157c6615555565b5060010190565b600481106157eb57634e487b7160e01b600052602160045260246000fd5b9052565b81835260006020808501808196508560051b810191508460005b878110156158a457828403895261582082886155f8565b6040808601823561583081614a7b565b6001600160a01b031687526158478389018461557e565b888a019390935290829052909150606086019060005b8381101561588f5781356004811061587457600080fd5b61587e84826157cd565b50918801919088019060010161585d565b50509986019994505090840190600101615809565b5091979650505050505050565b8481526001600160a01b03841660208201526060604082015260006158da6060830184866157ef565b9695505050505050565b63ffffffff818116838216019080821115614ff757614ff7615555565b8981526001600160a01b0389811660208301528816604082015263ffffffff87811660608301526001600160781b038716608083015285811660a0830152841660c082015261010060e0820181905260009061596083820185876157ef565b9c9b505050505050505050505050565b60006020828403121561598257600080fd5b8135612e6081614cf7565b60006020828403121561599f57600080fd5b8151612e60816156b3565b600181815b808511156159e55781600019048211156159cb576159cb615555565b808516156159d857918102915b93841c93908002906159af565b509250929050565b6000826159fc575060016108bd565b81615a09575060006108bd565b8160018114615a1f5760028114615a2957615a45565b60019150506108bd565b60ff841115615a3a57615a3a615555565b50506001821b6108bd565b5060208310610133831016604e8410600b8410161715615a68575081810a6108bd565b615a7283836159aa565b8060001904821115615a8657615a86615555565b029392505050565b6000612e6060ff8416836159ed565b6040808252810184905260008560608301825b87811015615ae0578235615ac381614a7b565b6001600160a01b0316825260209283019290910190600101615ab0565b5083810360208581019190915285825291508590820160005b86811015615b20578235615b0c81614cf7565b151582529183019190830190600101615af9565b5098975050505050505050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b838152604060208201526000615b70604083018486615b2d565b95945050505050565b6001600160a01b0387168152608060208201526000615b9b6080830188614df4565b8281036040840152615bae8187896155c6565b90508281036060840152615bc3818587615b2d565b9998505050505050505050565b606081526000615be36060830187614e4d565b8281036020840152615bf68186886155c6565b91505063ffffffff8316604083015295945050505050565b600063ffffffff80841680615c2557615c25615711565b92169190910492915050565b600063ffffffff80831681851681830481118215151615615c5457615c54615555565b02949350505050565b60006001600160a01b03808816835286602084015280861660408401525060806060830152615c90608083018486615b2d565b979650505050505050565b600060208284031215615cad57600080fd5b5051919050565b600082615cc357615cc3615711565b500690565b600062ffffff80831681851681830481118215151615615c5457615c54615555565b63ffffffff828116828216039080821115614ff757614ff7615555565b6001600160781b03818116838216019080821115614ff757614ff7615555565b8381526001600160a01b03831660208201526060810161489660408301846157cd565b600060208284031215615d5c57600080fd5b8151612e6081614cf7565b6001600160e01b03828116828216039080821115614ff757614ff7615555565b600063ffffffff80841680615d9e57615d9e615711565b92169190910692915050565b60005b83811015615dc5578181015183820152602001615dad565b50506000910152565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351615e06816017850160208801615daa565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351615e37816028840160208801615daa565b01602801949350505050565b6020815260008251806020840152615e62816040850160208701615daa565b601f01601f19169190910160400192915050565b6001600160e01b03818116838216019080821115614ff757614ff7615555565b6001600160801b03818116838216019080821115614ff757614ff7615555565b6001600160801b03828116828216039080821115614ff757614ff7615555565b600081615ee557615ee5615555565b506000190190565b60008251615502818460208701615daa56fea2646970667358221220c2cf82bb19f04338a214b20d2b96bbb94aeb454e221020715d46fb72c2060ccb64736f6c63430008100033
Verified Source Code Partial Match
Compiler: v0.8.16+commit.07a7930e
EVM: london
Optimization: Yes (300 runs)
Address.sol 222 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "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");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(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) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(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) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason 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 {
// 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;
}
}
Strings.sol 75 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_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) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @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] = _HEX_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);
}
}
Math.sol 226 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds up instead
* of rounding down.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator,
Rounding rounding
) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. It 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)`.
// We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
// This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
// Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
// good first aproximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1;
uint256 x = a;
if (x >> 128 > 0) {
x >>= 128;
result <<= 64;
}
if (x >> 64 > 0) {
x >>= 64;
result <<= 32;
}
if (x >> 32 > 0) {
x >>= 32;
result <<= 16;
}
if (x >> 16 > 0) {
x >>= 16;
result <<= 8;
}
if (x >> 8 > 0) {
x >>= 8;
result <<= 4;
}
if (x >> 4 > 0) {
x >>= 4;
result <<= 2;
}
if (x >> 2 > 0) {
result <<= 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) {
uint256 result = sqrt(a);
if (rounding == Rounding.Up && result * result < a) {
result += 1;
}
return result;
}
}
Pausable.sol 105 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.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 Pausable is Context {
/**
* @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.
*/
constructor() {
_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());
}
}
IERC20.sol 82 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.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);
}
SafeMath.sol 227 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
AccessControl.sol 247 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role);
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `_msgSender()` is missing `role`.
* Overriding this function changes the behavior of the {onlyRole} modifier.
*
* Format of the revert message is described in {_checkRole}.
*
* _Available since v4.6._
*/
function _checkRole(bytes32 role) internal view virtual {
_checkRole(role, _msgSender());
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view virtual {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* May emit a {RoleGranted} event.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleGranted} event.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*
* May emit a {RoleRevoked} event.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
IERC721.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
IAccessControl.sol 88 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
ReentrancyGuard.sol 63 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
DCAHub.sol 22 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.7 <0.9.0;
import './DCAHubParameters.sol';
import './DCAHubPositionHandler.sol';
import './DCAHubSwapHandler.sol';
import './DCAHubConfigHandler.sol';
import './DCAHubPlatformHandler.sol';
contract DCAHub is DCAHubParameters, DCAHubConfigHandler, DCAHubSwapHandler, DCAHubPositionHandler, DCAHubPlatformHandler, IDCAHub {
constructor(
address _immediateGovernor,
address _timeLockedGovernor,
ITokenPriceOracle _oracle,
IDCAPermissionManager _permissionManager
) DCAHubPositionHandler(_permissionManager) DCAHubConfigHandler(_immediateGovernor, _timeLockedGovernor, _oracle) {}
/// @inheritdoc IDCAHubConfigHandler
function paused() public view override(IDCAHubConfigHandler, DCAHubConfigHandler) returns (bool) {
return super.paused();
}
}
ERC165.sol 29 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
SafeERC20.sol 116 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/draft-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;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
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));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
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");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
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");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
FeeMath.sol 33 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
/// @title Fee Math library
/// @notice Provides functions to calculate and apply fees to amounts
library FeeMath {
/// @notice How much would a 1% fee be
uint24 public constant FEE_PRECISION = 10000;
/// @notice Takes a fee and an amount that has had the fee subtracted, and returns the amount that was subtracted
/// @param _fee Fee that was applied
/// @param _subtractionResult Amount that had the fee subtracted
/// @return The amount that was subtracted
function calculateSubtractedFee(uint32 _fee, uint256 _subtractionResult) internal pure returns (uint256) {
return (_subtractionResult * _fee) / (FEE_PRECISION * 100 - _fee);
}
/// @notice Takes a fee and applies it to a certain amount. So if fee is 0.6%, it would return the 0.6% of the given amount
/// @param _fee Fee to apply
/// @param _amount Amount to apply the fee to
/// @return The calculated fee
function calculateFeeForAmount(uint32 _fee, uint256 _amount) internal pure returns (uint256) {
return (_amount * _fee) / FEE_PRECISION / 100;
}
/// @notice Takes a fee and a certain amount, and subtracts the fee. So if fee is 0.6%, it would return 99.4% of the given amount
/// @param _fee Fee to subtract
/// @param _amount Amount that subtract the fee from
/// @return The amount with the fee subtracted
function subtractFeeFromAmount(uint32 _fee, uint256 _amount) internal pure returns (uint256) {
return (_amount * (FEE_PRECISION - _fee / 100)) / FEE_PRECISION;
}
}
IDCAHub.sol 699 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
import '@mean-finance/oracles/solidity/interfaces/ITokenPriceOracle.sol';
import './IDCAPermissionManager.sol';
/**
* @title The interface for all state related queries
* @notice These methods allow users to read the hubs's current values
*/
interface IDCAHubParameters {
/**
* @notice Returns how much will the amount to swap differ from the previous swap. f.e. if the returned value is -100, then the amount to swap will be 100 less than the swap just before it
* @dev `tokenA` must be smaller than `tokenB` (tokenA < tokenB)
* @param tokenA One of the pair's token
* @param tokenB The other of the pair's token
* @param swapIntervalMask The byte representation of the swap interval to check
* @param swapNumber The swap number to check
* @return swapDeltaAToB How much less of token A will the following swap require
* @return swapDeltaBToA How much less of token B will the following swap require
*/
function swapAmountDelta(
address tokenA,
address tokenB,
bytes1 swapIntervalMask,
uint32 swapNumber
) external view returns (uint128 swapDeltaAToB, uint128 swapDeltaBToA);
/**
* @notice Returns the sum of the ratios reported in all swaps executed until the given swap number
* @dev `tokenA` must be smaller than `tokenB` (tokenA < tokenB)
* @param tokenA One of the pair's token
* @param tokenB The other of the pair's token
* @param swapIntervalMask The byte representation of the swap interval to check
* @param swapNumber The swap number to check
* @return accumRatioAToB The sum of all ratios from A to B
* @return accumRatioBToA The sum of all ratios from B to A
*/
function accumRatio(
address tokenA,
address tokenB,
bytes1 swapIntervalMask,
uint32 swapNumber
) external view returns (uint256 accumRatioAToB, uint256 accumRatioBToA);
/**
* @notice Returns swapping information about a specific pair
* @dev `tokenA` must be smaller than `tokenB` (tokenA < tokenB)
* @param tokenA One of the pair's token
* @param tokenB The other of the pair's token
* @param swapIntervalMask The byte representation of the swap interval to check
* @return performedSwaps How many swaps have been executed
* @return nextAmountToSwapAToB How much of token A will be swapped on the next swap
* @return lastSwappedAt Timestamp of the last swap
* @return nextAmountToSwapBToA How much of token B will be swapped on the next swap
*/
function swapData(
address tokenA,
address tokenB,
bytes1 swapIntervalMask
)
external
view
returns (
uint32 performedSwaps,
uint224 nextAmountToSwapAToB,
uint32 lastSwappedAt,
uint224 nextAmountToSwapBToA
);
/**
* @notice Returns the byte representation of the set of actice swap intervals for the given pair
* @dev `tokenA` must be smaller than `tokenB` (tokenA < tokenB)
* @param tokenA The smaller of the pair's token
* @param tokenB The other of the pair's token
* @return The byte representation of the set of actice swap intervals
*/
function activeSwapIntervals(address tokenA, address tokenB) external view returns (bytes1);
/**
* @notice Returns how much of the hub's token balance belongs to the platform
* @param token The token to check
* @return The amount that belongs to the platform
*/
function platformBalance(address token) external view returns (uint256);
}
/**
* @title The interface for all position related matters
* @notice These methods allow users to create, modify and terminate their positions
*/
interface IDCAHubPositionHandler {
/// @notice The position of a certain user
struct UserPosition {
// The token that the user deposited and will be swapped in exchange for "to"
IERC20Metadata from;
// The token that the user will get in exchange for their "from" tokens in each swap
IERC20Metadata to;
// How frequently the position's swaps should be executed
uint32 swapInterval;
// How many swaps were executed since deposit, last modification, or last withdraw
uint32 swapsExecuted;
// How many "to" tokens can currently be withdrawn
uint256 swapped;
// How many swaps left the position has to execute
uint32 swapsLeft;
// How many "from" tokens there are left to swap
uint256 remaining;
// How many "from" tokens need to be traded in each swap
uint120 rate;
}
/// @notice A list of positions that all have the same `to` token
struct PositionSet {
// The `to` token
address token;
// The position ids
uint256[] positionIds;
}
/**
* @notice Emitted when a position is terminated
* @param user The address of the user that terminated the position
* @param recipientUnswapped The address of the user that will receive the unswapped tokens
* @param recipientSwapped The address of the user that will receive the swapped tokens
* @param positionId The id of the position that was terminated
* @param returnedUnswapped How many "from" tokens were returned to the caller
* @param returnedSwapped How many "to" tokens were returned to the caller
*/
event Terminated(
address indexed user,
address indexed recipientUnswapped,
address indexed recipientSwapped,
uint256 positionId,
uint256 returnedUnswapped,
uint256 returnedSwapped
);
/**
* @notice Emitted when a position is created
* @param depositor The address of the user that creates the position
* @param owner The address of the user that will own the position
* @param positionId The id of the position that was created
* @param fromToken The address of the "from" token
* @param toToken The address of the "to" token
* @param swapInterval How frequently the position's swaps should be executed
* @param rate How many "from" tokens need to be traded in each swap
* @param startingSwap The number of the swap when the position will be executed for the first time
* @param lastSwap The number of the swap when the position will be executed for the last time
* @param permissions The permissions defined for the position
*/
event Deposited(
address indexed depositor,
address indexed owner,
uint256 positionId,
address fromToken,
address toToken,
uint32 swapInterval,
uint120 rate,
uint32 startingSwap,
uint32 lastSwap,
IDCAPermissionManager.PermissionSet[] permissions
);
/**
* @notice Emitted when a position is created and extra data is provided
* @param positionId The id of the position that was created
* @param data The extra data that was provided
*/
event Miscellaneous(uint256 positionId, bytes data);
/**
* @notice Emitted when a user withdraws all swapped tokens from a position
* @param withdrawer The address of the user that executed the withdraw
* @param recipient The address of the user that will receive the withdrawn tokens
* @param positionId The id of the position that was affected
* @param token The address of the withdrawn tokens. It's the same as the position's "to" token
* @param amount The amount that was withdrawn
*/
event Withdrew(address indexed withdrawer, address indexed recipient, uint256 positionId, address token, uint256 amount);
/**
* @notice Emitted when a user withdraws all swapped tokens from many positions
* @param withdrawer The address of the user that executed the withdraws
* @param recipient The address of the user that will receive the withdrawn tokens
* @param positions The positions to withdraw from
* @param withdrew The total amount that was withdrawn from each token
*/
event WithdrewMany(address indexed withdrawer, address indexed recipient, PositionSet[] positions, uint256[] withdrew);
/**
* @notice Emitted when a position is modified
* @param user The address of the user that modified the position
* @param positionId The id of the position that was modified
* @param rate How many "from" tokens need to be traded in each swap
* @param startingSwap The number of the swap when the position will be executed for the first time
* @param lastSwap The number of the swap when the position will be executed for the last time
*/
event Modified(address indexed user, uint256 positionId, uint120 rate, uint32 startingSwap, uint32 lastSwap);
/// @notice Thrown when a user tries to create a position with the same `from` & `to`
error InvalidToken();
/// @notice Thrown when a user tries to create a position with a swap interval that is not allowed
error IntervalNotAllowed();
/// @notice Thrown when a user tries operate on a position that doesn't exist (it might have been already terminated)
error InvalidPosition();
/// @notice Thrown when a user tries operate on a position that they don't have access to
error UnauthorizedCaller();
/// @notice Thrown when a user tries to create a position with zero swaps
error ZeroSwaps();
/// @notice Thrown when a user tries to create a position with zero funds
error ZeroAmount();
/// @notice Thrown when a user tries to withdraw a position whose `to` token doesn't match the specified one
error PositionDoesNotMatchToken();
/// @notice Thrown when a user tries create or modify a position with an amount too big
error AmountTooBig();
/**
* @notice Returns the permission manager contract
* @return The contract itself
*/
function permissionManager() external view returns (IDCAPermissionManager);
/**
* @notice Returns total created positions
* @return The total created positions
*/
function totalCreatedPositions() external view returns (uint256);
/**
* @notice Returns a user position
* @param positionId The id of the position
* @return position The position itself
*/
function userPosition(uint256 positionId) external view returns (UserPosition memory position);
/**
* @notice Creates a new position
* @dev Will revert:
* - With ZeroAddress if from, to or owner are zero
* - With InvalidToken if from == to
* - With ZeroAmount if amount is zero
* - With AmountTooBig if amount is too big
* - With ZeroSwaps if amountOfSwaps is zero
* - With IntervalNotAllowed if swapInterval is not allowed
* @param from The address of the "from" token
* @param to The address of the "to" token
* @param amount How many "from" tokens will be swapped in total
* @param amountOfSwaps How many swaps to execute for this position
* @param swapInterval How frequently the position's swaps should be executed
* @param owner The address of the owner of the position being created
* @param permissions Extra permissions to add to the position. Can be empty
* @return positionId The id of the created position
*/
function deposit(
address from,
address to,
uint256 amount,
uint32 amountOfSwaps,
uint32 swapInterval,
address owner,
IDCAPermissionManager.PermissionSet[] calldata permissions
) external returns (uint256 positionId);
/**
* @notice Creates a new position
* @dev Will revert:
* - With ZeroAddress if from, to or owner are zero
* - With InvalidToken if from == to
* - With ZeroAmount if amount is zero
* - With AmountTooBig if amount is too big
* - With ZeroSwaps if amountOfSwaps is zero
* - With IntervalNotAllowed if swapInterval is not allowed
* @param from The address of the "from" token
* @param to The address of the "to" token
* @param amount How many "from" tokens will be swapped in total
* @param amountOfSwaps How many swaps to execute for this position
* @param swapInterval How frequently the position's swaps should be executed
* @param owner The address of the owner of the position being created
* @param permissions Extra permissions to add to the position. Can be empty
* @param miscellaneous Bytes that will be emitted, and associated with the position
* @return positionId The id of the created position
*/
function deposit(
address from,
address to,
uint256 amount,
uint32 amountOfSwaps,
uint32 swapInterval,
address owner,
IDCAPermissionManager.PermissionSet[] calldata permissions,
bytes calldata miscellaneous
) external returns (uint256 positionId);
/**
* @notice Withdraws all swapped tokens from a position to a recipient
* @dev Will revert:
* - With InvalidPosition if positionId is invalid
* - With UnauthorizedCaller if the caller doesn't have access to the position
* - With ZeroAddress if recipient is zero
* @param positionId The position's id
* @param recipient The address to withdraw swapped tokens to
* @return swapped How much was withdrawn
*/
function withdrawSwapped(uint256 positionId, address recipient) external returns (uint256 swapped);
/**
* @notice Withdraws all swapped tokens from multiple positions
* @dev Will revert:
* - With InvalidPosition if any of the position ids are invalid
* - With UnauthorizedCaller if the caller doesn't have access to the position to any of the given positions
* - With ZeroAddress if recipient is zero
* - With PositionDoesNotMatchToken if any of the positions do not match the token in their position set
* @param positions A list positions, grouped by `to` token
* @param recipient The address to withdraw swapped tokens to
* @return withdrawn How much was withdrawn for each token
*/
function withdrawSwappedMany(PositionSet[] calldata positions, address recipient) external returns (uint256[] memory withdrawn);
/**
* @notice Takes the unswapped balance, adds the new deposited funds and modifies the position so that
* it is executed in newSwaps swaps
* @dev Will revert:
* - With InvalidPosition if positionId is invalid
* - With UnauthorizedCaller if the caller doesn't have access to the position
* - With AmountTooBig if amount is too big
* @param positionId The position's id
* @param amount Amount of funds to add to the position
* @param newSwaps The new amount of swaps
*/
function increasePosition(
uint256 positionId,
uint256 amount,
uint32 newSwaps
) external;
/**
* @notice Withdraws the specified amount from the unswapped balance and modifies the position so that
* it is executed in newSwaps swaps
* @dev Will revert:
* - With InvalidPosition if positionId is invalid
* - With UnauthorizedCaller if the caller doesn't have access to the position
* - With ZeroSwaps if newSwaps is zero and amount is not the total unswapped balance
* @param positionId The position's id
* @param amount Amount of funds to withdraw from the position
* @param newSwaps The new amount of swaps
* @param recipient The address to send tokens to
*/
function reducePosition(
uint256 positionId,
uint256 amount,
uint32 newSwaps,
address recipient
) external;
/**
* @notice Terminates the position and sends all unswapped and swapped balance to the specified recipients
* @dev Will revert:
* - With InvalidPosition if positionId is invalid
* - With UnauthorizedCaller if the caller doesn't have access to the position
* - With ZeroAddress if recipientUnswapped or recipientSwapped is zero
* @param positionId The position's id
* @param recipientUnswapped The address to withdraw unswapped tokens to
* @param recipientSwapped The address to withdraw swapped tokens to
* @return unswapped The unswapped balance sent to `recipientUnswapped`
* @return swapped The swapped balance sent to `recipientSwapped`
*/
function terminate(
uint256 positionId,
address recipientUnswapped,
address recipientSwapped
) external returns (uint256 unswapped, uint256 swapped);
}
/**
* @title The interface for all swap related matters
* @notice These methods allow users to get information about the next swap, and how to execute it
*/
interface IDCAHubSwapHandler {
/// @notice Information about a swap
struct SwapInfo {
// The tokens involved in the swap
TokenInSwap[] tokens;
// The pairs involved in the swap
PairInSwap[] pairs;
}
/// @notice Information about a token's role in a swap
struct TokenInSwap {
// The token's address
address token;
// How much will be given of this token as a reward
uint256 reward;
// How much of this token needs to be provided by swapper
uint256 toProvide;
// How much of this token will be paid to the platform
uint256 platformFee;
}
/// @notice Information about a pair in a swap
struct PairInSwap {
// The address of one of the tokens
address tokenA;
// The address of the other token
address tokenB;
// The total amount of token A swapped in this pair
uint256 totalAmountToSwapTokenA;
// The total amount of token B swapped in this pair
uint256 totalAmountToSwapTokenB;
// How much is 1 unit of token A when converted to B
uint256 ratioAToB;
// How much is 1 unit of token B when converted to A
uint256 ratioBToA;
// The swap intervals involved in the swap, represented as a byte
bytes1 intervalsInSwap;
}
/// @notice A pair of tokens, represented by their indexes in an array
struct PairIndexes {
// The index of the token A
uint8 indexTokenA;
// The index of the token B
uint8 indexTokenB;
}
/**
* @notice Emitted when a swap is executed
* @param sender The address of the user that initiated the swap
* @param rewardRecipient The address that received the reward
* @param callbackHandler The address that executed the callback
* @param swapInformation All information related to the swap
* @param borrowed How much was borrowed
* @param fee The swap fee at the moment of the swap
*/
event Swapped(
address indexed sender,
address indexed rewardRecipient,
address indexed callbackHandler,
SwapInfo swapInformation,
uint256[] borrowed,
uint32 fee
);
/// @notice Thrown when pairs indexes are not sorted correctly
error InvalidPairs();
/// @notice Thrown when trying to execute a swap, but there is nothing to swap
error NoSwapsToExecute();
/**
* @notice Returns all information related to the next swap
* @dev Will revert with:
* - With InvalidTokens if tokens are not sorted, or if there are duplicates
* - With InvalidPairs if pairs are not sorted (first by indexTokenA and then indexTokenB), or if indexTokenA >= indexTokenB for any pair
* @param tokens The tokens involved in the next swap
* @param pairs The pairs that you want to swap. Each element of the list points to the index of the token in the tokens array
* @param calculatePrivilegedAvailability Some accounts get privileged availability and can execute swaps before others. This flag provides
* the possibility to calculate the next swap information for privileged and non-privileged accounts
* @param oracleData Bytes to send to the oracle when executing a quote
* @return swapInformation The information about the next swap
*/
function getNextSwapInfo(
address[] calldata tokens,
PairIndexes[] calldata pairs,
bool calculatePrivilegedAvailability,
bytes calldata oracleData
) external view returns (SwapInfo memory swapInformation);
/**
* @notice Executes a flash swap
* @dev Will revert with:
* - With InvalidTokens if tokens are not sorted, or if there are duplicates
* - With InvalidPairs if pairs are not sorted (first by indexTokenA and then indexTokenB), or if indexTokenA >= indexTokenB for any pair
* - With Paused if swaps are paused by protocol
* - With NoSwapsToExecute if there are no swaps to execute for the given pairs
* - With LiquidityNotReturned if the required tokens were not back during the callback
* @param tokens The tokens involved in the next swap
* @param pairsToSwap The pairs that you want to swap. Each element of the list points to the index of the token in the tokens array
* @param rewardRecipient The address to send the reward to
* @param callbackHandler Address to call for callback (and send the borrowed tokens to)
* @param borrow How much to borrow of each of the tokens in tokens. The amount must match the position of the token in the tokens array
* @param callbackData Bytes to send to the caller during the callback
* @param oracleData Bytes to send to the oracle when executing a quote
* @return Information about the executed swap
*/
function swap(
address[] calldata tokens,
PairIndexes[] calldata pairsToSwap,
address rewardRecipient,
address callbackHandler,
uint256[] calldata borrow,
bytes calldata callbackData,
bytes calldata oracleData
) external returns (SwapInfo memory);
}
/**
* @title The interface for handling all configuration
* @notice This contract will manage configuration that affects all pairs, swappers, etc
*/
interface IDCAHubConfigHandler {
/**
* @notice Emitted when a new oracle is set
* @param oracle The new oracle contract
*/
event OracleSet(ITokenPriceOracle oracle);
/**
* @notice Emitted when a new swap fee is set
* @param feeSet The new swap fee
*/
event SwapFeeSet(uint32 feeSet);
/**
* @notice Emitted when new swap intervals are allowed
* @param swapIntervals The new swap intervals
*/
event SwapIntervalsAllowed(uint32[] swapIntervals);
/**
* @notice Emitted when some swap intervals are no longer allowed
* @param swapIntervals The swap intervals that are no longer allowed
*/
event SwapIntervalsForbidden(uint32[] swapIntervals);
/**
* @notice Emitted when a new platform fee ratio is set
* @param platformFeeRatio The new platform fee ratio
*/
event PlatformFeeRatioSet(uint16 platformFeeRatio);
/**
* @notice Emitted when allowed states of tokens are updated
* @param tokens Array of updated tokens
* @param allowed Array of new allow state per token were allowed[i] is the updated state of tokens[i]
*/
event TokensAllowedUpdated(address[] tokens, bool[] allowed);
/// @notice Thrown when trying to interact with an unallowed token
error UnallowedToken();
/// @notice Thrown when set allowed tokens input is not valid
error InvalidAllowedTokensInput();
/// @notice Thrown when trying to set a fee higher than the maximum allowed
error HighFee();
/// @notice Thrown when trying to set a fee that is not multiple of 100
error InvalidFee();
/// @notice Thrown when trying to set a fee ratio that is higher that the maximum allowed
error HighPlatformFeeRatio();
/**
* @notice Returns the max fee ratio that can be set
* @dev Cannot be modified
* @return The maximum possible value
*/
// solhint-disable-next-line func-name-mixedcase
function MAX_PLATFORM_FEE_RATIO() external view returns (uint16);
/**
* @notice Returns the fee charged on swaps
* @return swapFee The fee itself
*/
function swapFee() external view returns (uint32 swapFee);
/**
* @notice Returns the price oracle contract
* @return oracle The contract itself
*/
function oracle() external view returns (ITokenPriceOracle oracle);
/**
* @notice Returns how much will the platform take from the fees collected in swaps
* @return The current ratio
*/
function platformFeeRatio() external view returns (uint16);
/**
* @notice Returns the max fee that can be set for swaps
* @dev Cannot be modified
* @return maxFee The maximum possible fee
*/
// solhint-disable-next-line func-name-mixedcase
function MAX_FEE() external view returns (uint32 maxFee);
/**
* @notice Returns a byte that represents allowed swap intervals
* @return allowedSwapIntervals The allowed swap intervals
*/
function allowedSwapIntervals() external view returns (bytes1 allowedSwapIntervals);
/**
* @notice Returns if a token is currently allowed or not
* @return Allowed state of token
*/
function allowedTokens(address token) external view returns (bool);
/**
* @notice Returns token's magnitude (10**decimals)
* @return Stored magnitude for token
*/
function tokenMagnitude(address token) external view returns (uint120);
/**
* @notice Returns whether swaps and deposits are currently paused
* @return isPaused Whether swaps and deposits are currently paused
*/
function paused() external view returns (bool isPaused);
/**
* @notice Sets a new swap fee
* @dev Will revert with HighFee if the fee is higher than the maximum
* @dev Will revert with InvalidFee if the fee is not multiple of 100
* @param fee The new swap fee
*/
function setSwapFee(uint32 fee) external;
/**
* @notice Sets a new price oracle
* @dev Will revert with ZeroAddress if the zero address is passed
* @param oracle The new oracle contract
*/
function setOracle(ITokenPriceOracle oracle) external;
/**
* @notice Sets a new platform fee ratio
* @dev Will revert with HighPlatformFeeRatio if given ratio is too high
* @param platformFeeRatio The new ratio
*/
function setPlatformFeeRatio(uint16 platformFeeRatio) external;
/**
* @notice Adds new swap intervals to the allowed list
* @param swapIntervals The new swap intervals
*/
function addSwapIntervalsToAllowedList(uint32[] calldata swapIntervals) external;
/**
* @notice Removes some swap intervals from the allowed list
* @param swapIntervals The swap intervals to remove
*/
function removeSwapIntervalsFromAllowedList(uint32[] calldata swapIntervals) external;
/// @notice Pauses all swaps and deposits
function pause() external;
/// @notice Unpauses all swaps and deposits
function unpause() external;
}
/**
* @title The interface for handling platform related actions
* @notice This contract will handle all actions that affect the platform in some way
*/
interface IDCAHubPlatformHandler {
/**
* @notice Emitted when someone withdraws from the paltform balance
* @param sender The address of the user that initiated the withdraw
* @param recipient The address that received the withdraw
* @param amounts The tokens (and the amount) that were withdrawn
*/
event WithdrewFromPlatform(address indexed sender, address indexed recipient, IDCAHub.AmountOfToken[] amounts);
/**
* @notice Withdraws tokens from the platform balance
* @param amounts The amounts to withdraw
* @param recipient The address that will receive the tokens
*/
function withdrawFromPlatformBalance(IDCAHub.AmountOfToken[] calldata amounts, address recipient) external;
}
interface IDCAHub is IDCAHubParameters, IDCAHubConfigHandler, IDCAHubSwapHandler, IDCAHubPositionHandler, IDCAHubPlatformHandler {
/// @notice Specifies an amount of a token. For example to determine how much to borrow from certain tokens
struct AmountOfToken {
// The tokens' address
address token;
// How much to borrow or withdraw of the specified token
uint256 amount;
}
/// @notice Thrown when one of the parameters is a zero address
error ZeroAddress();
/// @notice Thrown when the expected liquidity is not returned in flash swaps
error LiquidityNotReturned();
/// @notice Thrown when a list of token pairs is not sorted, or if there are duplicates
error InvalidTokens();
}
Intervals.sol 60 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
/// @title Intervals library
/// @notice Provides functions to easily convert from swap intervals to their byte representation and viceversa
library Intervals {
/// @notice Thrown when a user tries convert and invalid interval to a byte representation
error InvalidInterval();
/// @notice Thrown when a user tries convert and invalid byte representation to an interval
error InvalidMask();
/// @notice Takes a swap interval and returns its byte representation
/// @dev Will revert with InvalidInterval if the swap interval is not valid
/// @param _swapInterval The swap interval
/// @return The interval's byte representation
function intervalToMask(uint32 _swapInterval) internal pure returns (bytes1) {
if (_swapInterval == 1 minutes) return 0x01;
if (_swapInterval == 5 minutes) return 0x02;
if (_swapInterval == 15 minutes) return 0x04;
if (_swapInterval == 30 minutes) return 0x08;
if (_swapInterval == 1 hours) return 0x10;
if (_swapInterval == 4 hours) return 0x20;
if (_swapInterval == 1 days) return 0x40;
if (_swapInterval == 1 weeks) return 0x80;
revert InvalidInterval();
}
/// @notice Takes a byte representation of a swap interval and returns the swap interval
/// @dev Will revert with InvalidMask if the byte representation is not valid
/// @param _mask The byte representation
/// @return The swap interval
function maskToInterval(bytes1 _mask) internal pure returns (uint32) {
if (_mask == 0x01) return 1 minutes;
if (_mask == 0x02) return 5 minutes;
if (_mask == 0x04) return 15 minutes;
if (_mask == 0x08) return 30 minutes;
if (_mask == 0x10) return 1 hours;
if (_mask == 0x20) return 4 hours;
if (_mask == 0x40) return 1 days;
if (_mask == 0x80) return 1 weeks;
revert InvalidMask();
}
/// @notice Takes a byte representation of a set of swap intervals and returns which ones are in the set
/// @dev Will always return an array of length 8, with zeros at the end if there are less than 8 intervals
/// @param _byte The byte representation
/// @return _intervals The swap intervals in the set
function intervalsInByte(bytes1 _byte) internal pure returns (uint32[] memory _intervals) {
_intervals = new uint32[](8);
uint8 _index;
bytes1 _mask = 0x01;
while (_byte >= _mask && _mask > 0) {
if (_byte & _mask != 0) {
_intervals[_index++] = maskToInterval(_mask);
}
_mask <<= 1;
}
}
}
TokenSorting.sol 15 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >0.6;
/// @title TokenSorting library
/// @notice Provides functions to sort tokens easily
library TokenSorting {
/// @notice Takes two tokens, and returns them sorted
/// @param _tokenA One of the tokens
/// @param _tokenB The other token
/// @return __tokenA The first of the tokens
/// @return __tokenB The second of the tokens
function sortTokens(address _tokenA, address _tokenB) internal pure returns (address __tokenA, address __tokenB) {
(__tokenA, __tokenB) = _tokenA < _tokenB ? (_tokenA, _tokenB) : (_tokenB, _tokenA);
}
}
DCAHubParameters.sol 67 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '../interfaces/IDCAHub.sol';
import '../libraries/TokenSorting.sol';
abstract contract DCAHubParameters is IDCAHubParameters {
/// @notice Swap information about a specific pair
struct SwapData {
// How many swaps have been executed
uint32 performedSwaps;
// How much of token A will be swapped on the next swap
uint224 nextAmountToSwapAToB;
// Timestamp of the last swap
uint32 lastSwappedAt;
// How much of token B will be swapped on the next swap
uint224 nextAmountToSwapBToA;
}
/// @notice The difference of tokens to swap between a swap, and the previous one
struct SwapDelta {
// How much less of token A will the following swap require
uint128 swapDeltaAToB;
// How much less of token B will the following swap require
uint128 swapDeltaBToA;
}
/// @notice The sum of the ratios the oracle reported in all executed swaps
struct AccumRatio {
// The sum of all ratios from A to B
uint256 accumRatioAToB;
// The sum of all ratios from B to A
uint256 accumRatioBToA;
}
using SafeERC20 for IERC20Metadata;
/// @inheritdoc IDCAHubParameters
mapping(address => mapping(address => bytes1)) public activeSwapIntervals; // token A => token B => active swap intervals
/// @inheritdoc IDCAHubParameters
mapping(address => uint256) public platformBalance; // token => balance
/// @inheritdoc IDCAHubParameters
mapping(address => mapping(address => mapping(bytes1 => mapping(uint32 => SwapDelta)))) public swapAmountDelta; // token A => token B => swap interval => swap number => delta
/// @inheritdoc IDCAHubParameters
mapping(address => mapping(address => mapping(bytes1 => mapping(uint32 => AccumRatio)))) public accumRatio; // token A => token B => swap interval => swap number => accum
/// @inheritdoc IDCAHubParameters
mapping(address => mapping(address => mapping(bytes1 => SwapData))) public swapData; // token A => token B => swap interval => swap data
function _assertNonZeroAddress(address _address) internal pure {
if (_address == address(0)) revert IDCAHub.ZeroAddress();
}
function _transfer(
address _token,
address _to,
uint256 _amount
) internal {
if (_amount > 0) {
IERC20Metadata(_token).safeTransfer(_to, _amount);
}
}
function _balanceOf(address _token) internal view returns (uint256) {
return IERC20Metadata(_token).balanceOf(address(this));
}
}
ITokenPriceOracle.sol 78 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/**
* @title The interface for an oracle that provides price quotes
* @notice These methods allow users to add support for pairs, and then ask for quotes
*/
interface ITokenPriceOracle {
/// @notice Thrown when trying to add support for a pair that cannot be supported
error PairCannotBeSupported(address tokenA, address tokenB);
/// @notice Thrown when trying to execute a quote with a pair that isn't supported yet
error PairNotSupportedYet(address tokenA, address tokenB);
/**
* @notice Returns whether this oracle can support the given pair of tokens
* @dev tokenA and tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order
* @param tokenA One of the pair's tokens
* @param tokenB The other of the pair's tokens
* @return Whether the given pair of tokens can be supported by the oracle
*/
function canSupportPair(address tokenA, address tokenB) external view returns (bool);
/**
* @notice Returns whether this oracle is already supporting the given pair of tokens
* @dev tokenA and tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order
* @param tokenA One of the pair's tokens
* @param tokenB The other of the pair's tokens
* @return Whether the given pair of tokens is already being supported by the oracle
*/
function isPairAlreadySupported(address tokenA, address tokenB) external view returns (bool);
/**
* @notice Returns a quote, based on the given tokens and amount
* @dev Will revert if pair isn't supported
* @param tokenIn The token that will be provided
* @param amountIn The amount that will be provided
* @param tokenOut The token we would like to quote
* @param data Custom data that the oracle might need to operate
* @return amountOut How much `tokenOut` will be returned in exchange for `amountIn` amount of `tokenIn`
*/
function quote(
address tokenIn,
uint256 amountIn,
address tokenOut,
bytes calldata data
) external view returns (uint256 amountOut);
/**
* @notice Add or reconfigures the support for a given pair. This function will let the oracle take some actions
* to configure the pair, in preparation for future quotes. Can be called many times in order to let the oracle
* re-configure for a new context
* @dev Will revert if pair cannot be supported. tokenA and tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order
* @param tokenA One of the pair's tokens
* @param tokenB The other of the pair's tokens
* @param data Custom data that the oracle might need to operate
*/
function addOrModifySupportForPair(
address tokenA,
address tokenB,
bytes calldata data
) external;
/**
* @notice Adds support for a given pair if the oracle didn't support it already. If called for a pair that is already supported,
* then nothing will happen. This function will let the oracle take some actions to configure the pair, in preparation
* for future quotes
* @dev Will revert if pair cannot be supported. tokenA and tokenB may be passed in either tokenA/tokenB or tokenB/tokenA order
* @param tokenA One of the pair's tokens
* @param tokenB The other of the pair's tokens
* @param data Custom data that the oracle might need to operate
*/
function addSupportForPairIfNeeded(
address tokenA,
address tokenB,
bytes calldata data
) external;
}
DCAHubSwapHandler.sol 357 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/utils/math/Math.sol';
import '../interfaces/IDCAHubSwapCallee.sol';
import '../libraries/Intervals.sol';
import '../libraries/FeeMath.sol';
import './DCAHubConfigHandler.sol';
abstract contract DCAHubSwapHandler is ReentrancyGuard, DCAHubConfigHandler, IDCAHubSwapHandler {
struct PairMagnitudes {
uint256 magnitudeA;
uint256 magnitudeB;
}
using SafeERC20 for IERC20Metadata;
function _registerSwap(
address _tokenA,
address _tokenB,
bytes1 _swapIntervalMask,
uint256 _ratioAToB,
uint256 _ratioBToA,
uint32 _timestamp
) internal virtual {
SwapData memory _swapDataMem = swapData[_tokenA][_tokenB][_swapIntervalMask];
if (_swapDataMem.nextAmountToSwapAToB > 0 || _swapDataMem.nextAmountToSwapBToA > 0) {
mapping(uint32 => AccumRatio) storage _accumRatioRef = accumRatio[_tokenA][_tokenB][_swapIntervalMask];
mapping(uint32 => SwapDelta) storage _swapAmountDeltaRef = swapAmountDelta[_tokenA][_tokenB][_swapIntervalMask];
AccumRatio memory _accumRatioMem = _accumRatioRef[_swapDataMem.performedSwaps];
_accumRatioRef[_swapDataMem.performedSwaps + 1] = AccumRatio({
accumRatioAToB: _accumRatioMem.accumRatioAToB + _ratioAToB,
accumRatioBToA: _accumRatioMem.accumRatioBToA + _ratioBToA
});
SwapDelta memory _swapDeltaMem = _swapAmountDeltaRef[_swapDataMem.performedSwaps + 2];
uint224 _nextAmountToSwapAToB = _swapDataMem.nextAmountToSwapAToB - _swapDeltaMem.swapDeltaAToB;
uint224 _nextAmountToSwapBToA = _swapDataMem.nextAmountToSwapBToA - _swapDeltaMem.swapDeltaBToA;
swapData[_tokenA][_tokenB][_swapIntervalMask] = SwapData({
performedSwaps: _swapDataMem.performedSwaps + 1,
lastSwappedAt: _timestamp,
nextAmountToSwapAToB: _nextAmountToSwapAToB,
nextAmountToSwapBToA: _nextAmountToSwapBToA
});
delete _swapAmountDeltaRef[_swapDataMem.performedSwaps + 2];
if (_nextAmountToSwapAToB == 0 && _nextAmountToSwapBToA == 0) {
_markIntervalAsInactive(_tokenA, _tokenB, _swapIntervalMask);
}
} else {
_markIntervalAsInactive(_tokenA, _tokenB, _swapIntervalMask);
}
}
function _convertTo(
uint256 _fromTokenMagnitude,
uint256 _amountFrom,
uint256 _ratioFromTo,
uint32 _swapFee
) internal pure returns (uint256 _amountTo) {
uint256 _numerator = FeeMath.subtractFeeFromAmount(_swapFee, _amountFrom * _ratioFromTo);
_amountTo = _numerator / _fromTokenMagnitude;
// Note: we need to round up because we can't ask for less than what we actually need
if (_numerator % _fromTokenMagnitude != 0) _amountTo++;
}
function _getTimestamp() internal view virtual returns (uint32 _blockTimestamp) {
_blockTimestamp = uint32(block.timestamp);
}
function _getTotalAmountsToSwap(
address _tokenA,
address _tokenB,
bool _calculatePrivilegedAvailability
)
internal
view
virtual
returns (
uint256 _totalAmountToSwapTokenA,
uint256 _totalAmountToSwapTokenB,
bytes1 _intervalsInSwap
)
{
bytes1 _activeIntervals = activeSwapIntervals[_tokenA][_tokenB];
uint32 _blockTimestamp = _getTimestamp();
bytes1 _mask = 0x01;
while (_activeIntervals >= _mask && _mask > 0) {
if (_activeIntervals & _mask != 0) {
SwapData memory _swapDataMem = swapData[_tokenA][_tokenB][_mask];
uint32 _swapInterval = Intervals.maskToInterval(_mask);
uint32 _nextSwapAvailableAt = ((_swapDataMem.lastSwappedAt / _swapInterval) + 1) * _swapInterval;
if (!_calculatePrivilegedAvailability) {
// If the caller does not have privileges, then they will have to wait a little more to execute swaps
_nextSwapAvailableAt += _swapInterval / 3;
}
if (_nextSwapAvailableAt > _blockTimestamp) {
// Note: this 'break' is both an optimization and a search for more CoW. Since this loop starts with the smaller intervals, it is
// highly unlikely that if a small interval can't be swapped, a bigger interval can. It could only happen when a position was just
// created for a new swap interval. At the same time, by adding this check, we force intervals to be swapped together. Therefore
// increasing the chance of CoW (Coincidence of Wants), and reducing the need for external funds.
break;
}
_intervalsInSwap |= _mask;
_totalAmountToSwapTokenA += _swapDataMem.nextAmountToSwapAToB;
_totalAmountToSwapTokenB += _swapDataMem.nextAmountToSwapBToA;
}
_mask <<= 1;
}
if (_totalAmountToSwapTokenA == 0 && _totalAmountToSwapTokenB == 0) {
// Note: if there are no tokens to swap, then we don't want to execute any swaps for this pair
_intervalsInSwap = 0;
}
}
function _calculateRatio(
address _tokenA,
address _tokenB,
ITokenPriceOracle _oracle,
bytes calldata _oracleData
)
internal
view
virtual
returns (
uint256 _ratioAToB,
uint256 _ratioBToA,
PairMagnitudes memory _magnitudes
)
{
_magnitudes.magnitudeA = tokenMagnitude[_tokenA];
_magnitudes.magnitudeB = tokenMagnitude[_tokenB];
_ratioBToA = _oracle.quote(_tokenB, _magnitudes.magnitudeB, _tokenA, _oracleData);
_ratioAToB = (_magnitudes.magnitudeB * _magnitudes.magnitudeA) / _ratioBToA;
}
/// @inheritdoc IDCAHubSwapHandler
function getNextSwapInfo(
address[] calldata _tokens,
PairIndexes[] calldata _pairs,
bool _calculatePrivilegedAvailability,
bytes calldata _oracleData
) public view virtual returns (SwapInfo memory _swapInformation) {
// Note: we are caching these variables in memory so we can read storage only once (it's cheaper that way)
uint32 _swapFee = swapFee;
ITokenPriceOracle _oracle = oracle;
uint256[] memory _total = new uint256[](_tokens.length);
uint256[] memory _needed = new uint256[](_tokens.length);
_swapInformation.pairs = new PairInSwap[](_pairs.length);
for (uint256 i = 0; i < _pairs.length; ) {
uint8 indexTokenA = _pairs[i].indexTokenA;
uint8 indexTokenB = _pairs[i].indexTokenB;
if (
indexTokenA >= indexTokenB ||
(i > 0 &&
(indexTokenA < _pairs[i - 1].indexTokenA || (indexTokenA == _pairs[i - 1].indexTokenA && indexTokenB <= _pairs[i - 1].indexTokenB)))
) {
// Note: this confusing condition verifies that the pairs are sorted, first by token A, and then by token B
revert InvalidPairs();
}
PairInSwap memory _pairInSwap;
_pairInSwap.tokenA = _tokens[indexTokenA];
_pairInSwap.tokenB = _tokens[indexTokenB];
(_pairInSwap.totalAmountToSwapTokenA, _pairInSwap.totalAmountToSwapTokenB, _pairInSwap.intervalsInSwap) = _getTotalAmountsToSwap(
_pairInSwap.tokenA,
_pairInSwap.tokenB,
_calculatePrivilegedAvailability
);
_total[indexTokenA] += _pairInSwap.totalAmountToSwapTokenA;
_total[indexTokenB] += _pairInSwap.totalAmountToSwapTokenB;
// Note: it would be better to calculate the magnitudes here instead of inside `_calculateRatio`, but it throws a "stack too deep" error
PairMagnitudes memory _magnitudes;
(_pairInSwap.ratioAToB, _pairInSwap.ratioBToA, _magnitudes) = _calculateRatio(
_pairInSwap.tokenA,
_pairInSwap.tokenB,
_oracle,
_oracleData
);
_needed[indexTokenA] += _convertTo(_magnitudes.magnitudeB, _pairInSwap.totalAmountToSwapTokenB, _pairInSwap.ratioBToA, _swapFee);
_needed[indexTokenB] += _convertTo(_magnitudes.magnitudeA, _pairInSwap.totalAmountToSwapTokenA, _pairInSwap.ratioAToB, _swapFee);
_swapInformation.pairs[i] = _pairInSwap;
unchecked {
i++;
}
}
// Note: we are caching this variable in memory so we can read storage only once (it's cheaper that way)
uint16 _platformFeeRatio = platformFeeRatio;
_swapInformation.tokens = new TokenInSwap[](_tokens.length);
for (uint256 i = 0; i < _swapInformation.tokens.length; ) {
address _token = _tokens[i];
if (!allowedTokens[_token]) revert IDCAHubConfigHandler.UnallowedToken();
if (i > 0 && _token <= _tokens[i - 1]) {
revert IDCAHub.InvalidTokens();
}
TokenInSwap memory _tokenInSwap;
_tokenInSwap.token = _token;
uint256 _neededInSwap = _needed[i];
uint256 _totalBeingSwapped = _total[i];
if (_neededInSwap > 0 || _totalBeingSwapped > 0) {
uint256 _totalFee = FeeMath.calculateSubtractedFee(_swapFee, _neededInSwap);
int256 _platformFee = int256((_totalFee * _platformFeeRatio) / MAX_PLATFORM_FEE_RATIO);
// If diff is negative, we need tokens. If diff is positive, then we have more than is needed
int256 _diff = int256(_totalBeingSwapped) - int256(_neededInSwap);
// Instead of checking if diff is positive or not, we compare against the platform fee. This is to avoid any rounding issues
if (_diff > _platformFee) {
_tokenInSwap.reward = uint256(_diff - _platformFee);
} else if (_diff < _platformFee) {
_tokenInSwap.toProvide = uint256(_platformFee - _diff);
}
_tokenInSwap.platformFee = uint256(_platformFee);
}
_swapInformation.tokens[i] = _tokenInSwap;
unchecked {
i++;
}
}
}
/// @inheritdoc IDCAHubSwapHandler
function swap(
address[] calldata _tokens,
PairIndexes[] calldata _pairsToSwap,
address _rewardRecipient,
address _callbackHandler,
uint256[] calldata _borrow,
bytes calldata _callbackData,
bytes calldata _oracleData
) public nonReentrant whenNotPaused returns (SwapInfo memory _swapInformation) {
// Note: we are caching this variable in memory so we can read storage only once (it's cheaper that way)
uint32 _swapFee = swapFee;
{
_swapInformation = getNextSwapInfo(_tokens, _pairsToSwap, hasRole(PRIVILEGED_SWAPPER_ROLE, msg.sender), _oracleData);
uint32 _timestamp = _getTimestamp();
bool _executedAPair;
for (uint256 i = 0; i < _swapInformation.pairs.length; ) {
PairInSwap memory _pairInSwap = _swapInformation.pairs[i];
bytes1 _intervalsInSwap = _pairInSwap.intervalsInSwap;
bytes1 _mask = 0x01;
while (_intervalsInSwap >= _mask && _mask > 0) {
if (_intervalsInSwap & _mask != 0) {
_registerSwap(
_pairInSwap.tokenA,
_pairInSwap.tokenB,
_mask,
_subtractFeeFromAmount(_swapFee, _pairInSwap.ratioAToB),
_subtractFeeFromAmount(_swapFee, _pairInSwap.ratioBToA),
_timestamp
);
if (!_executedAPair) {
_executedAPair = true;
}
}
_mask <<= 1;
}
unchecked {
i++;
}
}
if (!_executedAPair) {
revert NoSwapsToExecute();
}
}
uint256[] memory _beforeBalances = new uint256[](_swapInformation.tokens.length);
for (uint256 i = 0; i < _swapInformation.tokens.length; ) {
TokenInSwap memory _tokenInSwap = _swapInformation.tokens[i];
uint256 _amountToBorrow = _borrow[i];
// Remember balances before callback
if (_tokenInSwap.toProvide > 0 || _amountToBorrow > 0) {
_beforeBalances[i] = _balanceOf(_tokenInSwap.token);
}
// Optimistically transfer tokens
if (_rewardRecipient == _callbackHandler) {
uint256 _amountToSend = _tokenInSwap.reward + _amountToBorrow;
_transfer(_tokenInSwap.token, _callbackHandler, _amountToSend);
} else {
_transfer(_tokenInSwap.token, _rewardRecipient, _tokenInSwap.reward);
_transfer(_tokenInSwap.token, _callbackHandler, _amountToBorrow);
}
unchecked {
i++;
}
}
// Make call
IDCAHubSwapCallee(_callbackHandler).DCAHubSwapCall(msg.sender, _swapInformation.tokens, _borrow, _callbackData);
// Checks and balance updates
for (uint256 i = 0; i < _swapInformation.tokens.length; ) {
TokenInSwap memory _tokenInSwap = _swapInformation.tokens[i];
uint256 _addToPlatformBalance = _tokenInSwap.platformFee;
if (_tokenInSwap.toProvide > 0 || _borrow[i] > 0) {
uint256 _amountToHave = _beforeBalances[i] + _tokenInSwap.toProvide - _tokenInSwap.reward;
uint256 _currentBalance = _balanceOf(_tokenInSwap.token);
// Make sure tokens were sent back
if (_currentBalance < _amountToHave) {
revert IDCAHub.LiquidityNotReturned();
}
// Any extra tokens that might have been received, are set as platform balance
_addToPlatformBalance += (_currentBalance - _amountToHave);
}
// Update platform balance
if (_addToPlatformBalance > 0) {
platformBalance[_tokenInSwap.token] += _addToPlatformBalance;
}
unchecked {
i++;
}
}
// Emit event
emit Swapped(msg.sender, _rewardRecipient, _callbackHandler, _swapInformation, _borrow, _swapFee);
}
// Note: This is almost exactly as FeeMath.subtractFeeFromAmount, but without dividing by FEE_PRECISION.
// We will make that division when calculating how much was swapped. By doing so, we don't lose precision which,
// in the case of tokens with a small amount of decimals (like USDC), can end up being a lot of funds
function _subtractFeeFromAmount(uint32 _fee, uint256 _amount) internal pure returns (uint256) {
return _amount * (FeeMath.FEE_PRECISION - _fee / 100);
}
function _markIntervalAsInactive(
address _tokenA,
address _tokenB,
bytes1 _swapIntervalMask
) internal {
activeSwapIntervals[_tokenA][_tokenB] &= ~_swapIntervalMask;
}
}
IERC20Metadata.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
DCAHubConfigHandler.sol 129 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/access/AccessControl.sol';
import '@openzeppelin/contracts/security/Pausable.sol';
import '../libraries/Intervals.sol';
import '../libraries/FeeMath.sol';
import './DCAHubParameters.sol';
abstract contract DCAHubConfigHandler is DCAHubParameters, AccessControl, Pausable, IDCAHubConfigHandler {
// Internal constants (all should be constants, but apparently the byte code size increases when they are)
// solhint-disable var-name-mixedcase
bytes32 public IMMEDIATE_ROLE = keccak256('IMMEDIATE_ROLE');
bytes32 public TIME_LOCKED_ROLE = keccak256('TIME_LOCKED_ROLE');
// solhint-enable var-name-mixedcase
bytes32 public constant PLATFORM_WITHDRAW_ROLE = keccak256('PLATFORM_WITHDRAW_ROLE');
bytes32 public constant PRIVILEGED_SWAPPER_ROLE = keccak256('PRIVILEGED_SWAPPER_ROLE');
/// @inheritdoc IDCAHubConfigHandler
uint32 public constant MAX_FEE = 100000; // 10%
/// @inheritdoc IDCAHubConfigHandler
uint16 public constant MAX_PLATFORM_FEE_RATIO = 10000;
/// @inheritdoc IDCAHubConfigHandler
ITokenPriceOracle public oracle;
/// @inheritdoc IDCAHubConfigHandler
uint32 public swapFee = 6000; // 0.6%
/// @inheritdoc IDCAHubConfigHandler
bytes1 public allowedSwapIntervals = 0xF0; // Start allowing weekly, daily, every 4 hours, hourly
/// @inheritdoc IDCAHubConfigHandler
uint16 public platformFeeRatio = 2500; // 25%
/// @inheritdoc IDCAHubConfigHandler
mapping(address => bool) public override allowedTokens;
/// @inheritdoc IDCAHubConfigHandler
mapping(address => uint120) public override tokenMagnitude;
constructor(
address _immediateGovernor,
address _timeLockedGovernor,
ITokenPriceOracle _oracle
) {
if (_immediateGovernor == address(0) || _timeLockedGovernor == address(0) || address(_oracle) == address(0)) revert IDCAHub.ZeroAddress();
_setupRole(IMMEDIATE_ROLE, _immediateGovernor);
_setupRole(TIME_LOCKED_ROLE, _timeLockedGovernor);
_setRoleAdmin(PLATFORM_WITHDRAW_ROLE, IMMEDIATE_ROLE);
_setRoleAdmin(PRIVILEGED_SWAPPER_ROLE, IMMEDIATE_ROLE);
// We set each role as its own admin, so they can assign new addresses with the same role
_setRoleAdmin(IMMEDIATE_ROLE, IMMEDIATE_ROLE);
_setRoleAdmin(TIME_LOCKED_ROLE, TIME_LOCKED_ROLE);
oracle = _oracle;
}
function setAllowedTokens(address[] calldata _tokens, bool[] calldata _allowed) external onlyRole(IMMEDIATE_ROLE) {
if (_tokens.length != _allowed.length) revert InvalidAllowedTokensInput();
for (uint256 i = 0; i < _tokens.length; ) {
address _token = _tokens[i];
allowedTokens[_token] = _allowed[i];
if (tokenMagnitude[_token] == 0) {
tokenMagnitude[_token] = uint120(10**IERC20Metadata(_token).decimals());
}
unchecked {
i++;
}
}
emit TokensAllowedUpdated(_tokens, _allowed);
}
/// @inheritdoc IDCAHubConfigHandler
function setOracle(ITokenPriceOracle _oracle) external onlyRole(TIME_LOCKED_ROLE) {
_assertNonZeroAddress(address(_oracle));
oracle = _oracle;
emit OracleSet(_oracle);
}
/// @inheritdoc IDCAHubConfigHandler
function setSwapFee(uint32 _swapFee) external onlyRole(TIME_LOCKED_ROLE) {
_validateFee(_swapFee);
swapFee = _swapFee;
emit SwapFeeSet(_swapFee);
}
/// @inheritdoc IDCAHubConfigHandler
function setPlatformFeeRatio(uint16 _platformFeeRatio) external onlyRole(TIME_LOCKED_ROLE) {
if (_platformFeeRatio > MAX_PLATFORM_FEE_RATIO) revert HighPlatformFeeRatio();
platformFeeRatio = _platformFeeRatio;
emit PlatformFeeRatioSet(_platformFeeRatio);
}
/// @inheritdoc IDCAHubConfigHandler
function addSwapIntervalsToAllowedList(uint32[] calldata _swapIntervals) external onlyRole(IMMEDIATE_ROLE) {
for (uint256 i = 0; i < _swapIntervals.length; ) {
allowedSwapIntervals |= Intervals.intervalToMask(_swapIntervals[i]);
unchecked {
i++;
}
}
emit SwapIntervalsAllowed(_swapIntervals);
}
/// @inheritdoc IDCAHubConfigHandler
function removeSwapIntervalsFromAllowedList(uint32[] calldata _swapIntervals) external onlyRole(IMMEDIATE_ROLE) {
for (uint256 i = 0; i < _swapIntervals.length; ) {
allowedSwapIntervals &= ~Intervals.intervalToMask(_swapIntervals[i]);
unchecked {
i++;
}
}
emit SwapIntervalsForbidden(_swapIntervals);
}
/// @inheritdoc IDCAHubConfigHandler
function pause() external onlyRole(IMMEDIATE_ROLE) {
_pause();
}
/// @inheritdoc IDCAHubConfigHandler
function unpause() external onlyRole(IMMEDIATE_ROLE) {
_unpause();
}
/// @inheritdoc IDCAHubConfigHandler
function paused() public view virtual override(IDCAHubConfigHandler, Pausable) returns (bool) {
return super.paused();
}
function _validateFee(uint32 _fee) internal pure {
if (_fee > MAX_FEE) revert HighFee();
if (_fee % 100 != 0) revert InvalidFee();
}
}
DCAHubPlatformHandler.sol 27 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import './DCAHubConfigHandler.sol';
abstract contract DCAHubPlatformHandler is ReentrancyGuard, DCAHubConfigHandler, IDCAHubPlatformHandler {
using SafeERC20 for IERC20Metadata;
/// @inheritdoc IDCAHubPlatformHandler
function withdrawFromPlatformBalance(IDCAHub.AmountOfToken[] calldata _amounts, address _recipient)
external
nonReentrant
onlyRole(PLATFORM_WITHDRAW_ROLE)
{
for (uint256 i = 0; i < _amounts.length; ) {
platformBalance[_amounts[i].token] -= _amounts[i].amount;
_transfer(_amounts[i].token, _recipient, _amounts[i].amount);
unchecked {
i++;
}
}
emit WithdrewFromPlatform(msg.sender, _recipient, _amounts);
}
}
DCAHubPositionHandler.sol 415 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
import '../libraries/Intervals.sol';
import './DCAHubConfigHandler.sol';
import '../libraries/FeeMath.sol';
abstract contract DCAHubPositionHandler is ReentrancyGuard, DCAHubConfigHandler, IDCAHubPositionHandler {
struct DCA {
uint32 swapWhereLastUpdated; // Includes both modify and withdraw
uint32 finalSwap;
bytes1 swapIntervalMask;
address from;
uint24 rateLower; // We are splitting the rate into two different uints, so that we can use only 2 storage slots
uint96 rateHigher;
address to;
}
using SafeERC20 for IERC20Metadata;
/// @inheritdoc IDCAHubPositionHandler
IDCAPermissionManager public permissionManager;
mapping(uint256 => DCA) internal _userPositions;
mapping(uint256 => uint256) internal _swappedBeforeModified;
/// @inheritdoc IDCAHubPositionHandler
uint256 public totalCreatedPositions;
constructor(IDCAPermissionManager _permissionManager) {
_assertNonZeroAddress(address(_permissionManager));
permissionManager = _permissionManager;
}
/// @inheritdoc IDCAHubPositionHandler
function userPosition(uint256 _positionId) external view returns (UserPosition memory _userPosition) {
DCA memory _position = _userPositions[_positionId];
uint32 _performedSwaps = _getPerformedSwaps(_position.from, _position.to, _position.swapIntervalMask);
uint32 _newestSwapToConsider = _min(_performedSwaps, _position.finalSwap);
_userPosition.from = IERC20Metadata(_position.from);
_userPosition.to = IERC20Metadata(_position.to);
_userPosition.swapsExecuted = _subtractIfPossible(_newestSwapToConsider, _position.swapWhereLastUpdated);
_userPosition.swapsLeft = _subtractIfPossible(_position.finalSwap, _performedSwaps);
_userPosition.remaining = _calculateUnswapped(_position, _performedSwaps);
_userPosition.rate = _mergeRate(_position);
if (_position.swapIntervalMask > 0) {
_userPosition.swapInterval = Intervals.maskToInterval(_position.swapIntervalMask);
_userPosition.swapped = _calculateSwapped(_positionId, _position, _performedSwaps);
}
}
/// @inheritdoc IDCAHubPositionHandler
function deposit(
address _from,
address _to,
uint256 _amount,
uint32 _amountOfSwaps,
uint32 _swapInterval,
address _owner,
IDCAPermissionManager.PermissionSet[] calldata _permissions
) public nonReentrant whenNotPaused returns (uint256) {
if (_from == address(0) || _to == address(0) || _owner == address(0)) revert IDCAHub.ZeroAddress();
if (_from == _to) revert InvalidToken();
if (_amount == 0) revert ZeroAmount();
if (_amountOfSwaps == 0) revert ZeroSwaps();
_assertTokensAreAllowed(_from, _to);
uint120 _rate = _calculateRate(_amount, _amountOfSwaps);
uint256 _positionId = ++totalCreatedPositions;
DCA memory _userPosition = _buildPosition(_from, _to, _amountOfSwaps, Intervals.intervalToMask(_swapInterval), _rate);
if (allowedSwapIntervals & _userPosition.swapIntervalMask == 0) revert IntervalNotAllowed();
permissionManager.mint(_positionId, _owner, _permissions);
_updateActiveIntervalsAndOracle(_from, _to, _userPosition.swapIntervalMask);
_addToDelta(_from, _to, _userPosition.swapIntervalMask, _userPosition.finalSwap, _rate);
_userPositions[_positionId] = _userPosition;
IERC20Metadata(_from).safeTransferFrom(msg.sender, address(this), _amount);
emit Deposited(
msg.sender,
_owner,
_positionId,
_from,
_to,
_swapInterval,
_rate,
_userPosition.swapWhereLastUpdated + 1,
_userPosition.finalSwap,
_permissions
);
return _positionId;
}
/// @inheritdoc IDCAHubPositionHandler
function deposit(
address _from,
address _to,
uint256 _amount,
uint32 _amountOfSwaps,
uint32 _swapInterval,
address _owner,
IDCAPermissionManager.PermissionSet[] calldata _permissions,
bytes calldata _miscellaneous
) external returns (uint256 _positionId) {
_positionId = deposit(_from, _to, _amount, _amountOfSwaps, _swapInterval, _owner, _permissions);
if (_miscellaneous.length > 0) {
emit Miscellaneous(_positionId, _miscellaneous);
}
}
/// @inheritdoc IDCAHubPositionHandler
function withdrawSwapped(uint256 _positionId, address _recipient) external nonReentrant returns (uint256) {
_assertNonZeroAddress(_recipient);
(uint256 _swapped, address _to) = _executeWithdraw(_positionId);
_transfer(_to, _recipient, _swapped);
emit Withdrew(msg.sender, _recipient, _positionId, _to, _swapped);
return _swapped;
}
/// @inheritdoc IDCAHubPositionHandler
function withdrawSwappedMany(PositionSet[] calldata _positions, address _recipient) external nonReentrant returns (uint256[] memory _swapped) {
_assertNonZeroAddress(_recipient);
_swapped = new uint256[](_positions.length);
for (uint256 i = 0; i < _positions.length; ) {
address _token = _positions[i].token;
uint256[] memory _positionIds = _positions[i].positionIds;
for (uint256 j = 0; j < _positionIds.length; ) {
(uint256 _swappedByPosition, address _to) = _executeWithdraw(_positionIds[j]);
if (_to != _token) revert PositionDoesNotMatchToken();
_swapped[i] += _swappedByPosition;
unchecked {
j++;
}
}
_transfer(_token, _recipient, _swapped[i]);
unchecked {
i++;
}
}
emit WithdrewMany(msg.sender, _recipient, _positions, _swapped);
}
/// @inheritdoc IDCAHubPositionHandler
function terminate(
uint256 _positionId,
address _recipientUnswapped,
address _recipientSwapped
) external nonReentrant returns (uint256 _unswapped, uint256 _swapped) {
if (_recipientUnswapped == address(0) || _recipientSwapped == address(0)) revert IDCAHub.ZeroAddress();
DCA memory _userPosition = _userPositions[_positionId];
_assertPositionExistsAndCallerHasPermission(_positionId, _userPosition, IDCAPermissionManager.Permission.TERMINATE);
uint32 _performedSwaps = _getPerformedSwaps(_userPosition.from, _userPosition.to, _userPosition.swapIntervalMask);
_swapped = _calculateSwapped(_positionId, _userPosition, _performedSwaps);
_unswapped = _calculateUnswapped(_userPosition, _performedSwaps);
_removeFromDelta(_userPosition, _performedSwaps);
delete _userPositions[_positionId];
delete _swappedBeforeModified[_positionId];
permissionManager.burn(_positionId);
_transfer(_userPosition.to, _recipientSwapped, _swapped);
_transfer(_userPosition.from, _recipientUnswapped, _unswapped);
emit Terminated(msg.sender, _recipientUnswapped, _recipientSwapped, _positionId, _unswapped, _swapped);
}
/// @inheritdoc IDCAHubPositionHandler
function increasePosition(
uint256 _positionId,
uint256 _amount,
uint32 _newAmountOfSwaps
) external nonReentrant whenNotPaused {
_modify(_positionId, _amount, _newAmountOfSwaps, address(0));
}
/// @inheritdoc IDCAHubPositionHandler
function reducePosition(
uint256 _positionId,
uint256 _amount,
uint32 _newAmountOfSwaps,
address _recipient
) external nonReentrant {
_assertNonZeroAddress(_recipient);
_modify(_positionId, _amount, _newAmountOfSwaps, _recipient);
}
function _modify(
uint256 _positionId,
uint256 _amount,
uint32 _newAmountOfSwaps,
address _recipient
) internal {
DCA memory _userPosition = _userPositions[_positionId];
bool _increase = _recipient == address(0);
_assertPositionExistsAndCallerHasPermission(
_positionId,
_userPosition,
_increase ? IDCAPermissionManager.Permission.INCREASE : IDCAPermissionManager.Permission.REDUCE
);
if (_increase) {
_assertTokensAreAllowed(_userPosition.from, _userPosition.to);
(address _tokenA, address _tokenB) = TokenSorting.sortTokens(_userPosition.from, _userPosition.to);
activeSwapIntervals[_tokenA][_tokenB] |= _userPosition.swapIntervalMask;
}
uint32 _performedSwaps = _getPerformedSwaps(_userPosition.from, _userPosition.to, _userPosition.swapIntervalMask);
uint256 _unswapped = _calculateUnswapped(_userPosition, _performedSwaps);
uint256 _total = _increase ? _unswapped + _amount : _unswapped - _amount;
if (_total != 0 && _newAmountOfSwaps == 0) revert ZeroSwaps();
if (_total == 0 && _newAmountOfSwaps > 0) _newAmountOfSwaps = 0;
uint120 _newRate = _newAmountOfSwaps == 0 ? 0 : _calculateRate(_total, _newAmountOfSwaps);
(_userPositions[_positionId].rateLower, _userPositions[_positionId].rateHigher) = _splitRate(_newRate);
uint32 _finalSwap = _performedSwaps + _newAmountOfSwaps;
_userPositions[_positionId].swapWhereLastUpdated = _performedSwaps;
_userPositions[_positionId].finalSwap = _finalSwap;
_swappedBeforeModified[_positionId] = _calculateSwapped(_positionId, _userPosition, _performedSwaps);
_removeFromDelta(_userPosition, _performedSwaps);
_addToDelta(_userPosition.from, _userPosition.to, _userPosition.swapIntervalMask, _finalSwap, _newRate);
if (_amount > 0) {
if (_increase) {
IERC20Metadata(_userPosition.from).safeTransferFrom(msg.sender, address(this), _amount);
} else {
_transfer(_userPosition.from, _recipient, _amount);
}
}
emit Modified(msg.sender, _positionId, _newRate, _performedSwaps + 1, _finalSwap);
}
function _assertTokensAreAllowed(address _tokenA, address _tokenB) internal view {
if (!allowedTokens[_tokenA] || !allowedTokens[_tokenB]) revert IDCAHubConfigHandler.UnallowedToken();
}
function _assertPositionExistsAndCallerHasPermission(
uint256 _positionId,
DCA memory _userPosition,
IDCAPermissionManager.Permission _permission
) internal view {
if (_userPosition.swapIntervalMask == 0) revert InvalidPosition();
if (!permissionManager.hasPermission(_positionId, msg.sender, _permission)) revert UnauthorizedCaller();
}
function _addToDelta(
address _from,
address _to,
bytes1 _swapIntervalMask,
uint32 _finalSwap,
uint120 _rate
) internal {
_modifyDelta(_from, _to, _swapIntervalMask, _finalSwap, _rate, true);
}
function _removeFromDelta(DCA memory _userPosition, uint32 _performedSwaps) internal {
if (_userPosition.finalSwap > _performedSwaps) {
_modifyDelta(
_userPosition.from,
_userPosition.to,
_userPosition.swapIntervalMask,
_userPosition.finalSwap,
_mergeRate(_userPosition),
false
);
}
}
function _modifyDelta(
address _from,
address _to,
bytes1 _swapIntervalMask,
uint32 _finalSwap,
uint120 _rate,
bool _add
) internal {
if (_from < _to) {
if (_add) {
swapData[_from][_to][_swapIntervalMask].nextAmountToSwapAToB += _rate;
swapAmountDelta[_from][_to][_swapIntervalMask][_finalSwap + 1].swapDeltaAToB += _rate;
} else {
swapData[_from][_to][_swapIntervalMask].nextAmountToSwapAToB -= _rate;
swapAmountDelta[_from][_to][_swapIntervalMask][_finalSwap + 1].swapDeltaAToB -= _rate;
}
} else {
if (_add) {
swapData[_to][_from][_swapIntervalMask].nextAmountToSwapBToA += _rate;
swapAmountDelta[_to][_from][_swapIntervalMask][_finalSwap + 1].swapDeltaBToA += _rate;
} else {
swapData[_to][_from][_swapIntervalMask].nextAmountToSwapBToA -= _rate;
swapAmountDelta[_to][_from][_swapIntervalMask][_finalSwap + 1].swapDeltaBToA -= _rate;
}
}
}
function _updateActiveIntervalsAndOracle(
address _from,
address _to,
bytes1 _mask
) internal {
(address _tokenA, address _tokenB) = TokenSorting.sortTokens(_from, _to);
bytes1 _activeIntervals = activeSwapIntervals[_tokenA][_tokenB];
if (_activeIntervals & _mask == 0) {
if (_activeIntervals == 0) {
oracle.addSupportForPairIfNeeded(_tokenA, _tokenB, '');
}
activeSwapIntervals[_tokenA][_tokenB] = _activeIntervals | _mask;
}
}
/** Returns the amount of tokens swapped in TO */
function _calculateSwapped(
uint256 _positionId,
DCA memory _userPosition,
uint32 _performedSwaps
) internal view returns (uint256 _swapped) {
uint32 _newestSwapToConsider = _min(_performedSwaps, _userPosition.finalSwap);
if (_userPosition.swapWhereLastUpdated > _newestSwapToConsider) {
// If last update happened after the position's final swap, then a withdraw was executed, and we just return 0
return 0;
} else if (_userPosition.swapWhereLastUpdated == _newestSwapToConsider) {
// If the last update matches the positions's final swap, then we can avoid all calculation below
return _swappedBeforeModified[_positionId];
}
uint256 _positionsAccumRatio;
if (_userPosition.from < _userPosition.to) {
mapping(uint32 => AccumRatio) storage _accumRatioRef = accumRatio[_userPosition.from][_userPosition.to][_userPosition.swapIntervalMask];
_positionsAccumRatio =
_accumRatioRef[_newestSwapToConsider].accumRatioAToB -
_accumRatioRef[_userPosition.swapWhereLastUpdated].accumRatioAToB;
} else {
mapping(uint32 => AccumRatio) storage _accumRatioRef = accumRatio[_userPosition.to][_userPosition.from][_userPosition.swapIntervalMask];
_positionsAccumRatio =
_accumRatioRef[_newestSwapToConsider].accumRatioBToA -
_accumRatioRef[_userPosition.swapWhereLastUpdated].accumRatioBToA;
}
uint256 _magnitude = tokenMagnitude[_userPosition.from];
uint120 _rate = _mergeRate(_userPosition);
(bool _ok, uint256 _mult) = SafeMath.tryMul(_positionsAccumRatio, _rate);
uint256 _swappedInCurrentPosition = (_ok ? _mult / _magnitude : (_positionsAccumRatio / _magnitude) * _rate) / FeeMath.FEE_PRECISION;
_swapped = _swappedInCurrentPosition + _swappedBeforeModified[_positionId];
}
/** Returns how many FROM remains unswapped */
function _calculateUnswapped(DCA memory _userPosition, uint32 _performedSwaps) internal pure returns (uint256 _unswapped) {
_unswapped = uint256(_subtractIfPossible(_userPosition.finalSwap, _performedSwaps)) * _mergeRate(_userPosition);
}
function _executeWithdraw(uint256 _positionId) internal returns (uint256 _swapped, address _to) {
DCA memory _userPosition = _userPositions[_positionId];
_assertPositionExistsAndCallerHasPermission(_positionId, _userPosition, IDCAPermissionManager.Permission.WITHDRAW);
uint32 _performedSwaps = _getPerformedSwaps(_userPosition.from, _userPosition.to, _userPosition.swapIntervalMask);
_swapped = _calculateSwapped(_positionId, _userPosition, _performedSwaps);
_to = _userPosition.to;
_userPositions[_positionId].swapWhereLastUpdated = _performedSwaps;
delete _swappedBeforeModified[_positionId];
}
function _getPerformedSwaps(
address _from,
address _to,
bytes1 _swapIntervalMask
) internal view returns (uint32) {
(address _tokenA, address _tokenB) = TokenSorting.sortTokens(_from, _to);
return swapData[_tokenA][_tokenB][_swapIntervalMask].performedSwaps;
}
function _buildPosition(
address _from,
address _to,
uint32 _amountOfSwaps,
bytes1 _mask,
uint120 _rate
) internal view returns (DCA memory _userPosition) {
uint32 _performedSwaps = _getPerformedSwaps(_from, _to, _mask);
(uint24 _lower, uint96 _higher) = _splitRate(_rate);
_userPosition = DCA({
swapWhereLastUpdated: _performedSwaps,
finalSwap: _performedSwaps + _amountOfSwaps,
swapIntervalMask: _mask,
rateLower: _lower,
rateHigher: _higher,
from: _from,
to: _to
});
}
function _calculateRate(uint256 _amount, uint32 _amountOfSwaps) internal pure returns (uint120) {
uint256 _rate = _amount / _amountOfSwaps;
if (_rate > type(uint120).max) revert AmountTooBig();
return uint120(_rate);
}
function _mergeRate(DCA memory _userPosition) internal pure returns (uint120) {
return (uint120(_userPosition.rateHigher) << 24) + _userPosition.rateLower;
}
function _splitRate(uint120 _rate) internal pure returns (uint24 _lower, uint96 _higher) {
_lower = uint24(_rate);
_higher = uint96(_rate >> 24);
}
function _min(uint32 _a, uint32 _b) internal pure returns (uint32) {
return _a > _b ? _b : _a;
}
function _subtractIfPossible(uint32 _a, uint32 _b) internal pure returns (uint32) {
return _a > _b ? _a - _b : 0;
}
}
IDCAHubSwapCallee.sol 19 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol';
import './IDCAHub.sol';
/**
* @title The interface for handling flash swaps
* @notice Users that want to execute flash swaps must implement this interface
*/
interface IDCAHubSwapCallee {
// solhint-disable-next-line func-name-mixedcase
function DCAHubSwapCall(
address sender,
IDCAHub.TokenInSwap[] calldata tokens,
uint256[] calldata borrowed,
bytes calldata data
) external;
}
draft-IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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);
}
IDCAPermissionManager.sol 270 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@mean-finance/nft-descriptors/solidity/interfaces/IDCAHubPositionDescriptor.sol';
interface IERC721BasicEnumerable {
/**
* @notice Count NFTs tracked by this contract
* @return A count of valid NFTs tracked by this contract, where each one of
* them has an assigned and queryable owner not equal to the zero address
*/
function totalSupply() external view returns (uint256);
}
/**
* @title The interface for all permission related matters
* @notice These methods allow users to set and remove permissions to their positions
*/
interface IDCAPermissionManager is IERC721, IERC721BasicEnumerable {
/// @notice Set of possible permissions
enum Permission {
INCREASE,
REDUCE,
WITHDRAW,
TERMINATE
}
/// @notice A set of permissions for a specific operator
struct PermissionSet {
// The address of the operator
address operator;
// The permissions given to the overator
Permission[] permissions;
}
/// @notice A collection of permissions sets for a specific position
struct PositionPermissions {
// The id of the token
uint256 tokenId;
// The permissions to assign to the position
PermissionSet[] permissionSets;
}
/**
* @notice Emitted when permissions for a token are modified
* @param tokenId The id of the token
* @param permissions The set of permissions that were updated
*/
event Modified(uint256 tokenId, PermissionSet[] permissions);
/**
* @notice Emitted when the address for a new descritor is set
* @param descriptor The new descriptor contract
*/
event NFTDescriptorSet(IDCAHubPositionDescriptor descriptor);
/// @notice Thrown when a user tries to set the hub, once it was already set
error HubAlreadySet();
/// @notice Thrown when a user provides a zero address when they shouldn't
error ZeroAddress();
/// @notice Thrown when a user calls a method that can only be executed by the hub
error OnlyHubCanExecute();
/// @notice Thrown when a user tries to modify permissions for a token they do not own
error NotOwner();
/// @notice Thrown when a user tries to execute a permit with an expired deadline
error ExpiredDeadline();
/// @notice Thrown when a user tries to execute a permit with an invalid signature
error InvalidSignature();
/**
* @notice The permit typehash used in the permit signature
* @return The typehash for the permit
*/
// solhint-disable-next-line func-name-mixedcase
function PERMIT_TYPEHASH() external pure returns (bytes32);
/**
* @notice The permit typehash used in the permission permit signature
* @return The typehash for the permission permit
*/
// solhint-disable-next-line func-name-mixedcase
function PERMISSION_PERMIT_TYPEHASH() external pure returns (bytes32);
/**
* @notice The permit typehash used in the multi permission permit signature
* @return The typehash for the multi permission permit
*/
// solhint-disable-next-line func-name-mixedcase
function MULTI_PERMISSION_PERMIT_TYPEHASH() external pure returns (bytes32);
/**
* @notice The permit typehash used in the permission permit signature
* @return The typehash for the permission set
*/
// solhint-disable-next-line func-name-mixedcase
function PERMISSION_SET_TYPEHASH() external pure returns (bytes32);
/**
* @notice The permit typehash used in the multi permission permit signature
* @return The typehash for the position permissions
*/
// solhint-disable-next-line func-name-mixedcase
function POSITION_PERMISSIONS_TYPEHASH() external pure returns (bytes32);
/**
* @notice The domain separator used in the permit signature
* @return The domain seperator used in encoding of permit signature
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
/**
* @notice Returns the NFT descriptor contract
* @return The contract for the NFT descriptor
*/
function nftDescriptor() external returns (IDCAHubPositionDescriptor);
/**
* @notice Returns the address of the DCA Hub
* @return The address of the DCA Hub
*/
function hub() external returns (address);
/**
* @notice Returns the next nonce to use for a given user
* @param user The address of the user
* @return nonce The next nonce to use
*/
function nonces(address user) external returns (uint256 nonce);
/**
* @notice Returns whether the given address has the permission for the given token
* @param id The id of the token to check
* @param account The address of the user to check
* @param permission The permission to check
* @return Whether the user has the permission or not
*/
function hasPermission(
uint256 id,
address account,
Permission permission
) external view returns (bool);
/**
* @notice Returns whether the given address has the permissions for the given token
* @param id The id of the token to check
* @param account The address of the user to check
* @param permissions The permissions to check
* @return hasPermissions Whether the user has each permission or not
*/
function hasPermissions(
uint256 id,
address account,
Permission[] calldata permissions
) external view returns (bool[] memory hasPermissions);
/**
* @notice Sets the address for the hub
* @dev Can only be successfully executed once. Once it's set, it can be modified again
* Will revert:
* - With ZeroAddress if address is zero
* - With HubAlreadySet if the hub has already been set
* @param hub The address to set for the hub
*/
function setHub(address hub) external;
/**
* @notice Mints a new NFT with the given id, and sets the permissions for it
* @dev Will revert with OnlyHubCanExecute if the caller is not the hub
* @param id The id of the new NFT
* @param owner The owner of the new NFT
* @param permissions Permissions to set for the new NFT
*/
function mint(
uint256 id,
address owner,
PermissionSet[] calldata permissions
) external;
/**
* @notice Burns the NFT with the given id, and clears all permissions
* @dev Will revert with OnlyHubCanExecute if the caller is not the hub
* @param id The token's id
*/
function burn(uint256 id) external;
/**
* @notice Sets new permissions for the given position
* @dev Will revert with NotOwner if the caller is not the token's owner.
* Operators that are not part of the given permission sets do not see their permissions modified.
* In order to remove permissions to an operator, provide an empty list of permissions for them
* @param id The token's id
* @param permissions A list of permission sets
*/
function modify(uint256 id, PermissionSet[] calldata permissions) external;
/**
* @notice Sets new permissions for the given positions
* @dev This is basically the same as executing multiple `modify`
* @param permissions A list of position permissions to set
*/
function modifyMany(PositionPermissions[] calldata permissions) external;
/**
* @notice Approves spending of a specific token ID by spender via signature
* @param spender The account that is being approved
* @param tokenId The ID of the token that is being approved for spending
* @param deadline The deadline timestamp by which the call must be mined for the approve to work
* @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
* @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
* @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
*/
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Sets permissions via signature
* @dev This method works similarly to `modifyMany`, but instead of being executed by the owner, it can be set by signature
* @param permissions The permissions to set for the different positions
* @param deadline The deadline timestamp by which the call must be mined for the approve to work
* @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
* @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
* @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
*/
function multiPermissionPermit(
PositionPermissions[] calldata permissions,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Sets permissions via signature
* @dev This method works similarly to `modify`, but instead of being executed by the owner, it can be set my signature
* @param permissions The permissions to set
* @param tokenId The token's id
* @param deadline The deadline timestamp by which the call must be mined for the approve to work
* @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
* @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
* @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
*/
function permissionPermit(
PermissionSet[] calldata permissions,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Sets a new NFT descriptor
* @dev Will revert with ZeroAddress if address is zero
* @param descriptor The new NFT descriptor contract
*/
function setNFTDescriptor(IDCAHubPositionDescriptor descriptor) external;
}
IDCAHubPositionDescriptor.sol 16 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.8.7 <0.9.0;
/**
* @title The interface for generating a description for a position in a DCA Hub
* @notice Contracts that implement this interface must return a base64 JSON with the entire description
*/
interface IDCAHubPositionDescriptor {
/**
* @notice Generates a positions's description, both the JSON and the image inside
* @param hub The address of the DCA Hub
* @param positionId The token/position id
* @return description The position's description
*/
function tokenURI(address hub, uint256 positionId) external view returns (string memory description);
}
Read Contract
DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
IMMEDIATE_ROLE 0x7d361dd3 → bytes32
MAX_FEE 0xbc063e1a → uint32
MAX_PLATFORM_FEE_RATIO 0x1b8b8c34 → uint16
PLATFORM_WITHDRAW_ROLE 0xfc448158 → bytes32
PRIVILEGED_SWAPPER_ROLE 0x64857370 → bytes32
TIME_LOCKED_ROLE 0x4eeeb3eb → bytes32
accumRatio 0x0b1aa984 → uint256, uint256
activeSwapIntervals 0x582cf84b → bytes1
allowedSwapIntervals 0x480e5da1 → bytes1
allowedTokens 0xe744092e → bool
getNextSwapInfo 0x6ca411e4 → tuple
getRoleAdmin 0x248a9ca3 → bytes32
hasRole 0x91d14854 → bool
oracle 0x7dc0d1d0 → address
paused 0x5c975abb → bool
permissionManager 0xcc7a2049 → address
platformBalance 0xc67e32e9 → uint256
platformFeeRatio 0x57ae1cec → uint16
supportsInterface 0x01ffc9a7 → bool
swapAmountDelta 0x4aa91aee → uint128, uint128
swapData 0x808ba8e0 → uint32, uint224, uint32, uint224
swapFee 0x54cf2aeb → uint32
tokenMagnitude 0x16cd7af8 → uint120
totalCreatedPositions 0x36639580 → uint256
userPosition 0x5b6fd01d → tuple
Write Contract 20 functions
These functions modify contract state and require a wallet transaction to execute.
addSwapIntervalsToAllowedList 0x3feb1493
uint32[] _swapIntervals
deposit 0xd99dfb1d
address _from
address _to
uint256 _amount
uint32 _amountOfSwaps
uint32 _swapInterval
address _owner
tuple[] _permissions
returns: uint256
deposit 0x8830d937
address _from
address _to
uint256 _amount
uint32 _amountOfSwaps
uint32 _swapInterval
address _owner
tuple[] _permissions
bytes _miscellaneous
returns: uint256
grantRole 0x2f2ff15d
bytes32 role
address account
increasePosition 0xded700a6
uint256 _positionId
uint256 _amount
uint32 _newAmountOfSwaps
pause 0x8456cb59
No parameters
reducePosition 0xf1accf39
uint256 _positionId
uint256 _amount
uint32 _newAmountOfSwaps
address _recipient
removeSwapIntervalsFromAllowedList 0x7d8e8603
uint32[] _swapIntervals
renounceRole 0x36568abe
bytes32 role
address account
revokeRole 0xd547741f
bytes32 role
address account
setAllowedTokens 0x74ae623b
address[] _tokens
bool[] _allowed
setOracle 0x7adbf973
address _oracle
setPlatformFeeRatio 0x6eefd134
uint16 _platformFeeRatio
setSwapFee 0xd6d788c3
uint32 _swapFee
swap 0xbe0cd37b
address[] _tokens
tuple[] _pairsToSwap
address _rewardRecipient
address _callbackHandler
uint256[] _borrow
bytes _callbackData
bytes _oracleData
returns: tuple
terminate 0x72ada4c5
uint256 _positionId
address _recipientUnswapped
address _recipientSwapped
returns: uint256, uint256
unpause 0x3f4ba83a
No parameters
withdrawFromPlatformBalance 0xd044082f
tuple[] _amounts
address _recipient
withdrawSwapped 0x17621890
uint256 _positionId
address _recipient
returns: uint256
withdrawSwappedMany 0x574ec04c
tuple[] _positions
address _recipient
returns: uint256[]
Token Balances (6)
View Transfers →Recent Transactions
No transactions found for this address