Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x816DDFA5DBC9f5236d2443B4b02E1a9e49cbbe30
Balance 0 ETH
Nonce 1
Code Size 14241 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

14241 bytes
0x60806040526004361061014f5760003560e01c80634d104adf116100b6578063b16a867c1161006f578063b16a867c146103ee578063b5dc454514610403578063d547741f14610423578063dc842ac414610443578063dddc2f6414610463578063ec87621c1461048357600080fd5b80634d104adf1461032057806354fd4d50146103545780636353586b146103845780638456cb59146103a457806391d14854146103b9578063a217fddf146103d957600080fd5b80632513e2b9116101085780632513e2b91461024a578063278ecde11461027e5780632f2ff15d1461029e57806336568abe146102be578063370158ea146102de57806338d074361461030057600080fd5b806301ffc9a71461015e578063046f7da21461019357806307da68f5146101aa57806315cfc405146101bf5780631e83409a146101ec578063248a9ca31461020c57600080fd5b3661015957600080fd5b600080fd5b34801561016a57600080fd5b5061017e610179366004612e95565b6104a5565b60405190151581526020015b60405180910390f35b34801561019f57600080fd5b506101a86104dc565b005b3480156101b657600080fd5b506101a861051a565b3480156101cb57600080fd5b506101df6101da366004612ed6565b6105d9565b60405161018a9190612ef1565b3480156101f857600080fd5b506101a8610207366004612ed6565b610674565b34801561021857600080fd5b5061023c610227366004612f1c565b6000908152600a602052604090206001015490565b60405190815260200161018a565b34801561025657600080fd5b5061023c7f2f049b28665abd79bc83d9aa564dba6b787ac439dba27b48e163a83befa9b26081565b34801561028a57600080fd5b506101a8610299366004612f1c565b610788565b3480156102aa57600080fd5b506101a86102b9366004612f35565b610954565b3480156102ca57600080fd5b506101a86102d9366004612f35565b61097e565b3480156102ea57600080fd5b506102f36109fd565b60405161018a9190612fb1565b34801561030c57600080fd5b506101a861031b366004613101565b610dad565b34801561032c57600080fd5b5061023c7fbb08418a67729a078f87bbc8d02a770929bb68f5bfdf134ae2ead6ed38e2f4ae81565b34801561036057600080fd5b5060408051808201825260018152603360f81b6020820152905161018a9190613131565b34801561039057600080fd5b506101a861039f366004612ed6565b61105a565b3480156103b057600080fd5b506101a8611189565b3480156103c557600080fd5b5061017e6103d4366004612f35565b6111ce565b3480156103e557600080fd5b5061023c600081565b3480156103fa57600080fd5b506101df6111f9565b34801561040f57600080fd5b506101a861041e36600461318c565b6112ed565b34801561042f57600080fd5b506101a861043e366004612f35565b6113de565b34801561044f57600080fd5b5061023c61045e366004613225565b611403565b34801561046f57600080fd5b506101a861047e36600461325f565b611457565b34801561048f57600080fd5b5061023c60008051602061374c83398151915281565b60006001600160e01b03198216637965db0b60e01b14806104d657506301ffc9a760e01b6001600160e01b03198316145b92915050565b60008051602061374c8339815191526104f481611827565b600e54600160401b900460ff1661050a57600080fd5b50600e805460ff60401b19169055565b60008051602061374c83398151915261053281611827565b6001600160401b037f0000000000000000000000000000000000000000000000000000000066827e2016426001600160401b0316101561057157600080fd5b600e546001600160401b0316426001600160401b03161061059157600080fd5b600e805467ffffffffffffffff1916426001600160401b03161790556040517f654d66e1d2e253351e9b6b83ca6f410eb33f5b849e7993b0bee7511cf05f65f990600090a150565b6106046040518060800160405280600081526020016000815260200160008152602001600081525090565b60008061061a84426001600160401b0316611834565b915091506040518060800160405280610648866001600160a01b031660009081526006602052604090205490565b815260200161065e8661065961199c565b6119d0565b8152602081019390935260409092015292915050565b60006106808242611a2a565b9050806000036106a35760405163614aac5b60e01b815260040160405180910390fd5b604080516001600160a01b0384168152602081018390527f47cee97cb7acd717b3c0aa1435d004cd5b3c8c57d70dbceb4e4458bbd60e39d4910160405180910390a160405163a9059cbb60e01b81526001600160a01b03838116600483015260248201839052610784917f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e9159091169063a9059cbb906044015b6020604051808303816000875af115801561075b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061077f91906132b7565b611c8d565b5050565b7f2f049b28665abd79bc83d9aa564dba6b787ac439dba27b48e163a83befa9b2606107b281611827565b600e546001600160401b0316426001600160401b031610156107e757604051639fc22d7960e01b815260040160405180910390fd5b60006107f96107f461199c565b611cab565b60095461080691906132ea565b6040516370a0823160e01b81523060048201529091506000906001600160a01b037f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e91516906370a0823190602401602060405180830381865afa158015610870573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061089491906132fd565b9050818110156108b7576040516302a4283160e61b815260040160405180910390fd5b60006108c38383613316565b9050846000036108d5578094506108f6565b808511156108f6576040516302a4283160e61b815260040160405180910390fd5b60405163a9059cbb60e01b81523360048201526024810186905261094d907f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e9156001600160a01b03169063a9059cbb9060440161073c565b5050505050565b6000828152600a602052604090206001015461096f81611827565b6109798383611cc9565b505050565b6001600160a01b03811633146109f35760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b60648201526084015b60405180910390fd5b6107848282611d4f565b604080516101a08101825260608082526020820181905291810182905260009181018290526080810182905260a0810182905260c0810182905260e081018290526101008101829052610120810182905261014081018290526101608101829052610180810191909152604051806101a00160405280600b8054610a8090613329565b80601f0160208091040260200160405190810160405280929190818152602001828054610aac90613329565b8015610af95780601f10610ace57610100808354040283529160200191610af9565b820191906000526020600020905b815481529060010190602001808311610adc57829003601f168201915b50505050508152602001600c8054610b1090613329565b80601f0160208091040260200160405190810160405280929190818152602001828054610b3c90613329565b8015610b895780601f10610b5e57610100808354040283529160200191610b89565b820191906000526020600020905b815481529060010190602001808311610b6c57829003601f168201915b50505050508152602001600d8054610ba090613329565b80601f0160208091040260200160405190810160405280929190818152602001828054610bcc90613329565b8015610c195780601f10610bee57610100808354040283529160200191610c19565b820191906000526020600020905b815481529060010190602001808311610bfc57829003601f168201915b50505091835250506001600160a01b037f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e9151660208201526001600160401b037f0000000000000000000000000000000000000000000000000001f25a6f54381c8116604083015263ffffffff7f0000000000000000000000000000000000000000000000000000000000015180811660608401527f00000000000000000000000000000000000000000000000000000000000d2f001660808301527f00000000000000000000000000000000000000000000152d02c7e14af67fffff60a08301527f00000000000000000000000000000000000000000000000000b1a2bc2ec50000811660c08301527f000000000000000000000000000000000000000000000000016345785d8a0000811660e083015260ff7f0000000000000000000000000000000000000000000000000000000000000001166101008301527f0000000000000000000000000000000000000000000000000000000066827e208116610120830152600e541661014090910152919050565b60008211610dba57600080fd5b600e546001600160401b0316426001600160401b0316108015610de65750600e54600160401b900460ff165b15610e0457604051636bea2ae560e01b815260040160405180910390fd5b610e163383610e1161199c565b611db6565b8015610f2d57600e546001600160401b0316426001600160401b031610610e5057604051631040858760e21b815260040160405180910390fd5b6000610e8d610e886001600160401b037f00000000000000000000000000000000000000000000000000b1a2bc2ec500001685613363565b611edb565b90506000610ec17f00000000000000000000000000000000000000000000000000000000000d2f0063ffffffff164261337a565b9050610ed733610ed18487613316565b83611f03565b60408051338152602081018690528082018490526001600160401b038316606082015290517f9aa7ca521b93e94aff8128438903669ce2d75baaa9e8ba595a0f53d3dac760b09181900360800190a15050611035565b600e546000906001600160401b0316426001600160401b03161015610f8557610f82610e886001600160401b037f000000000000000000000000000000000000000000000000016345785d8a00001685613363565b90505b610ff36001600160a01b037f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e9151663a9059cbb33610fc28588613316565b6040516001600160e01b031960e085901b1681526001600160a01b039092166004830152602482015260440161073c565b604080513381526020810185905280820183905290517fdf273cb619d95419a9cd0ec88123a0538c85064229baa6363788f743fff90deb9181900360600190a1505b61103d611f95565b610784576040516302a4283160e61b815260040160405180910390fd5b60008051602061374c83398151915261107281611827565b600e546001600160401b0316426001600160401b031610156110a75760405163049433bd60e51b815260040160405180910390fd5b60006110b58361065961199c565b90506110c08361203c565b604080516001600160a01b03851681526020810183905260008183015290517fdf273cb619d95419a9cd0ec88123a0538c85064229baa6363788f743fff90deb9181900360600190a160405163a9059cbb60e01b81526001600160a01b03848116600483015260248201839052611164917f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e9159091169063a9059cbb9060440161073c565b61116c611f95565b610979576040516302a4283160e61b815260040160405180910390fd5b60008051602061374c8339815191526111a181611827565b600e54600160401b900460ff16156111b857600080fd5b50600e805460ff60401b1916600160401b179055565b6000918252600a602090815260408084206001600160a01b0393909316845291905290205460ff1690565b6112246040518060800160405280600081526020016000815260200160008152602001600081525090565b604051806080016040528061123860075490565b81526020016112486107f461199c565b815260200161125660095490565b81526040516370a0823160e01b81523060048201526020909101906001600160a01b037f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e91516906370a0823190602401602060405180830381865afa1580156112c2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112e691906132fd565b9052919050565b60008051602061374c83398151915261130581611827565b868686868686604051602001611320969594939291906133ca565b60405160208183030381529060405280519060200120600b600c600d60405160200161134e93929190613490565b604051602081830303815290604052805190602001200361136e57600080fd5b868686868686600b6000600c81600d611388868883613525565b506113969050868883613525565b506113a49050868883613525565b50506040517f654d66e1d2e253351e9b6b83ca6f410eb33f5b849e7993b0bee7511cf05f65f995506000945092505050a150505050505050565b6000828152600a60205260409020600101546113f981611827565b6109798383611d4f565b600e546000906001600160401b03908116908316111561143057600e546001600160401b0316915061144e565b426001600160401b0316826001600160401b0316101561144e574291505b6104d682611cab565b6000861161146457600080fd5b83426001600160401b03161061148d57604051631d42701160e01b815260040160405180910390fd5b600e54600160401b900460ff16156114b857604051636bea2ae560e01b815260040160405180910390fd5b6001600160401b037f0000000000000000000000000000000000000000000000000000000066827e2016426001600160401b0316101561150b57604051638ea67c0f60e01b815260040160405180910390fd5b600e546001600160401b0316426001600160401b03161061153f576040516305cc621d60e41b815260040160405180910390fd5b60ff7f00000000000000000000000000000000000000000000000000000000000000011615611774573033600061161a8383898b60408051606095861b6bffffffffffffffffffffffff199081166020808401919091529590961b9095166034860152604885019290925260f81b6001600160f81b0319166068840152805160498185030181526069840182528051908301207f19457468657265756d205369676e6564204d6573736167653a0a333200000000608985015260a5808501919091528151808503909101815260c59093019052815191012090565b6040805160008082526020820180845284905260ff8a169282019290925260608101889052608081018790529192509060019060a0016020604051602081039080840390855afa158015611672573d6000803e3d6000fd5b5050604051601f19810151632474521560e21b82527fbb08418a67729a078f87bbc8d02a770929bb68f5bfdf134ae2ead6ed38e2f4ae60048301526001600160a01b038116602483015292503091506391d1485490604401602060405180830381865afa1580156116e7573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061170b91906132b7565b6117285760405163f24fa80560e01b815260040160405180910390fd5b7f000000000000000000000000000000000000000000000000000000000000000160ff168960ff16101561176f5760405163021d43e760e61b815260040160405180910390fd5b505050505b61177f3387426120c5565b7fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c33604080516001600160a01b039092168252602082018990520160405180910390a16040516323b872dd60e01b81523360048201523060248201526044810187905261181f907f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e9156001600160a01b0316906323b872dd9060640161073c565b505050505050565b61183181336121ba565b50565b6001600160a01b0382166000908152600860209081526040808320805482518185028101850190935280835284938493929190849084015b828210156118bb57600084815260209081902060408051808201909152908401546001600160c01b0381168252600160c01b90046001600160401b03168183015282526001909201910161186c565b50505050905060005b8151811080156118f95750848282815181106118e2576118e26135e4565b6020026020010151602001516001600160401b0316105b1561194457818181518110611910576119106135e4565b6020026020010151600001516001600160c01b03168361193091906132ea565b92508061193c816135fa565b9150506118c4565b81518110156119935781818151811061195f5761195f6135e4565b6020026020010151600001516001600160c01b03168461197f91906132ea565b93508061198b816135fa565b915050611944565b50509250929050565b600e5460009042906001600160401b03908116908216106119c857600e546001600160401b03166119ca565b805b91505090565b6001600160a01b0382166000908152600660205260408120547f00000000000000000000000000000000000000000000152d02c7e14af67fffff11611a2057611a198383612213565b90506104d6565b611a1983836122a9565b6001600160a01b038216600090815260086020908152604080832080548251818502810185019093528083528493849084015b82821015611aac57600084815260209081902060408051808201909152908401546001600160c01b0381168252600160c01b90046001600160401b031681830152825260019092019101611a5d565b5050505090506000805b825182108015611af55750828281518110611ad357611ad36135e4565b6020026020010151602001516001600160401b0316856001600160401b031610155b15611b4057828281518110611b0c57611b0c6135e4565b6020026020010151600001516001600160c01b031681611b2c91906132ea565b905081611b38816135fa565b925050611ab6565b81600003611b5457600093505050506104d6565b82518203611b82576001600160a01b0386166000908152600860205260408120611b7d91612e63565b611c6c565b60005b82811015611c6a5783611b9884836132ea565b81518110611ba857611ba86135e4565b602002602001015160086000896001600160a01b03166001600160a01b031681526020019081526020016000208281548110611be657611be66135e4565b600091825260208083208451948201516001600160401b0316600160c01b026001600160c01b039095169490941793909101929092556001600160a01b0389168152600890915260409020805480611c4057611c40613613565b60008281526020812082016000199081019190915501905580611c62816135fa565b915050611b85565b505b8060096000828254611c7e9190613316565b90915550909695505050505050565b806118315760405163022e258160e11b815260040160405180910390fd5b6000611cb682612364565b611cbf83612405565b6104d691906132ea565b611cd382826111ce565b610784576000828152600a602090815260408083206001600160a01b03851684529091529020805460ff19166001179055611d0b3390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b611d5982826111ce565b15610784576000828152600a602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6001600160a01b03831660009081526006602052604081205490818410611ddd5781611ddf565b835b6001600160a01b038616600090815260066020526040812080549293508392909190611e0c908490613316565b925050819055508060076000828254611e259190613316565b90915550507f00000000000000000000000000000000000000000000152d02c7e14af67fffff8210611ed0577f00000000000000000000000000000000000000000000152d02c7e14af67fffff611e7c8284613316565b1115611e9257611e8d85858561247f565b61094d565b6000611e9e8685612213565b90508015611eaf57611eaf866125ac565b808514611eca57611eca86611ec48784613316565b866125fd565b5061094d565b61094d85858561275e565b670de0b6b3a7640000808204906706f05b59d3b200009083061115611efe576001015b919050565b600160c01b8210611f1657611f1661363f565b6001600160a01b038316600090815260086020908152604080832081518083019092526001600160c01b0380871683526001600160401b0380871684860190815283546001810185559387529486209351945116600160c01b0293169290921791015560098054849290611f8b9084906132ea565b9091555050505050565b6000611fa060095490565b600754611fad91906132ea565b6040516370a0823160e01b81523060048201527f000000000000000000000000a02120696c7b8fe16c09c749e4598819b2b0e9156001600160a01b0316906370a0823190602401602060405180830381865afa158015612011573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061203591906132fd565b1015905090565b6001600160a01b0381166000908152600660205260409020547f00000000000000000000000000000000000000000000152d02c7e14af67fffff811061208a57612085826125ac565b612093565b61209382612961565b80600760008282546120a59190613316565b9091555050506001600160a01b0316600090815260066020526040812055565b6001600160a01b03831660009081526006602052604081208054918491906120ed83856132ea565b92505081905550826007600082825461210691906132ea565b90915550507f00000000000000000000000000000000000000000000152d02c7e14af67fffff81106121425761213d848484612a03565b6121b4565b7f00000000000000000000000000000000000000000000152d02c7e14af67fffff61216d84836132ea565b106121a957600061217e85846122a9565b9050801561218f5761218f85612961565b6121a38561219d86846132ea565b85612a03565b506121b4565b6121b48484846125fd565b50505050565b6121c482826111ce565b610784576121d181612ac7565b6121dc836020612ad9565b6040516020016121ed929190613655565b60408051601f198184030181529082905262461bcd60e51b82526109ea91600401613131565b6001600160a01b0382166000908152600460205260408120546122a2906001600160401b037f0000000000000000000000000000000000000000000000000001f25a6f54381c167f00000000000000000000000000000000000000000000000000000000677317e0857f0000000000000000000000000000000000000000000000000000000000015180612c74565b9392505050565b6001600160a01b038216600090815260208181526040808320546002909252822054826123177f00000000000000000000000000000000000000000000000000000000667fdb20867f0000000000000000000000000000000000000000000000000000000000015180612d50565b6001600160401b03169050600061232e8383613363565b61233890856136ca565b905060008112156123505760009450505050506104d6565b61235981611edb565b9450505050506104d6565b60015460035460009190826123ba7f00000000000000000000000000000000000000000000000000000000667fdb20867f0000000000000000000000000000000000000000000000000000000000015180612d50565b6001600160401b0316905060006123d18383613363565b6123db90856136ca565b905060008112156123f25750600095945050505050565b6123fb81611edb565b9695505050505050565b60006104d66005547f0000000000000000000000000000000000000000000000000001f25a6f54381c6001600160401b03167f00000000000000000000000000000000000000000000000000000000677317e0857f0000000000000000000000000000000000000000000000000000000000015180612c74565b600061248b84836119d0565b9050808311156124ae5760405163a6f373d560e01b815260040160405180910390fd5b8083036124be5761213d8461203c565b6000612536847f0000000000000000000000000000000000000000000000000001f25a6f54381c6001600160401b0316857f00000000000000000000000000000000000000000000000000000000677317e07f0000000000000000000000000000000000000000000000000000000000015180612c74565b6001600160a01b0386166000908152600460205260409020549091508082111561255e578091505b6001600160a01b03861660009081526004602052604081208054849290612586908490613316565b92505081905550816005600082825461259f9190613316565b9091555050505050505050565b6001600160a01b03811660009081526004602052604090205480156107845780600560008282546125dd9190613316565b9091555050506001600160a01b0316600090815260046020526040812055565b61260f670de0b6b3a764000083613363565b91506000670de0b6b3a764000061264f6001600160401b037f0000000000000000000000000000000000000000000000000001f25a6f54381c1685613363565b61265991906136f2565b905060006126a87f00000000000000000000000000000000000000000000000000000000667fdb20847f0000000000000000000000000000000000000000000000000000000000015180612d50565b6001600160401b0316905060006126bf8284613363565b6126c99086613714565b905080600080886001600160a01b03166001600160a01b0316815260200190815260200160002060008282546126ff91906136ca565b90915550506001600160a01b0386166000908152600260205260408120805485929061272c9084906132ea565b92505081905550826003600082825461274591906132ea565b92505081905550806001600082825461259f91906136ca565b600061276a84836119d0565b90508083111561278d5760405163a6f373d560e01b815260040160405180910390fd5b80830361279d5761213d8461203c565b6001600160a01b038416600090815260026020526040812054906128027f00000000000000000000000000000000000000000000000000000000667fdb20857f0000000000000000000000000000000000000000000000000000000000015180612d50565b9050600083612820876ec097ce7bc90715b34b9f1000000000613363565b61282a91906136f2565b9050670de0b6b3a76400008111156128475750670de0b6b3a76400005b6000670de0b6b3a764000061285c8382613316565b6128669086613363565b61287091906136f2565b90506000670de0b6b3a76400006128878482613316565b61289a6001600160401b03871688613363565b6128a49190613363565b6128ae91906136f2565b6128c089670de0b6b3a7640000613363565b6128ca9190613714565b905080600160008282546128de9190613714565b9250508190555081600360008282546128f79190613316565b90915550506001600160a01b03891660009081526020819052604081208054839290612924908490613714565b90915550506001600160a01b03891660009081526002602052604081208054849290612951908490613316565b9091555050505050505050505050565b6001600160a01b03811660009081526020819052604090205480156129b15780600160008282546129929190613714565b90915550506001600160a01b0382166000908152602081905260408120555b6001600160a01b03821660009081526002602052604090205480156109795780600360008282546129e29190613316565b909155505050506001600160a01b0316600090815260026020526040812055565b6000612a7b837f0000000000000000000000000000000000000000000000000001f25a6f54381c6001600160401b0316847f00000000000000000000000000000000000000000000000000000000677317e07f0000000000000000000000000000000000000000000000000000000000015180612c74565b90508060056000828254612a8f91906132ea565b90915550506001600160a01b03841660009081526004602052604081208054839290612abc9084906132ea565b909155505050505050565b60606104d66001600160a01b03831660145b60606000612ae8836002613363565b612af39060026132ea565b6001600160401b03811115612b0a57612b0a6134c9565b6040519080825280601f01601f191660200182016040528015612b34576020820181803683370190505b509050600360fc1b81600081518110612b4f57612b4f6135e4565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110612b7e57612b7e6135e4565b60200101906001600160f81b031916908160001a9053506000612ba2846002613363565b612bad9060016132ea565b90505b6001811115612c25576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110612be157612be16135e4565b1a60f81b828281518110612bf757612bf76135e4565b60200101906001600160f81b031916908160001a90535060049490941c93612c1e81613734565b9050612bb0565b5083156122a25760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e7460448201526064016109ea565b600080612c82858585612d50565b9050806001600160401b0316600003612c9e5786915050612d47565b600066038d7ea4c68000612cdc612cb58983613363565b612ccd906d314dc6448d9338c15b0a000000006132ea565b846001600160401b0316612df3565b612ce691906136f2565b90506000866001600160401b0316866001600160401b031610612d1257612d0d828a613363565b612d36565b81612d2c8a6ec097ce7bc90715b34b9f1000000000613363565b612d3691906136f2565b9050612d4181611edb565b93505050505b95945050505050565b6000826001600160401b0316846001600160401b03161115612d70579192915b8163ffffffff168484036001600160401b031681612d9057612d90613629565b0490508163ffffffff16836001600160401b031681612db157612db1613629565b066001600160401b03168263ffffffff16856001600160401b031681612dd957612dd9613629565b066001600160401b031611156122a2576001019392505050565b6000808260011611612e13576d314dc6448d9338c15b0a00000000612e15565b825b9050600182901c91505b81156104d6576d314dc6448d9338c15b0a000000008380020492506001821615612e57576d314dc6448d9338c15b0a00000000908302045b600182901c9150612e1f565b508054600082559060005260206000209081019061183191905b80821115612e915760008155600101612e7d565b5090565b600060208284031215612ea757600080fd5b81356001600160e01b0319811681146122a257600080fd5b80356001600160a01b0381168114611efe57600080fd5b600060208284031215612ee857600080fd5b6122a282612ebf565b81518152602080830151908201526040808301519082015260608083015190820152608081016104d6565b600060208284031215612f2e57600080fd5b5035919050565b60008060408385031215612f4857600080fd5b82359150612f5860208401612ebf565b90509250929050565b60005b83811015612f7c578181015183820152602001612f64565b50506000910152565b60008151808452612f9d816020860160208601612f61565b601f01601f19169290920160200192915050565b60208152600082516101a0806020850152612fd06101c0850183612f85565b91506020850151601f1980868503016040870152612fee8483612f85565b935060408701519150808685030160608701525061300c8382612f85565b925050606085015161302960808601826001600160a01b03169052565b5060808501516001600160401b03811660a08601525060a085015163ffffffff811660c08601525060c085015163ffffffff811660e08601525060e08501516101008581019190915285015161012061308c818701836001600160401b03169052565b86015190506101406130a8868201836001600160401b03169052565b86015190506101606130be8682018360ff169052565b86015190506101806130da868201836001600160401b03169052565b909501516001600160401b031693019290925250919050565b801515811461183157600080fd5b6000806040838503121561311457600080fd5b823591506020830135613126816130f3565b809150509250929050565b6020815260006122a26020830184612f85565b60008083601f84011261315657600080fd5b5081356001600160401b0381111561316d57600080fd5b60208301915083602082850101111561318557600080fd5b9250929050565b600080600080600080606087890312156131a557600080fd5b86356001600160401b03808211156131bc57600080fd5b6131c88a838b01613144565b909850965060208901359150808211156131e157600080fd5b6131ed8a838b01613144565b9096509450604089013591508082111561320657600080fd5b5061321389828a01613144565b979a9699509497509295939492505050565b60006020828403121561323757600080fd5b81356001600160401b03811681146122a257600080fd5b803560ff81168114611efe57600080fd5b60008060008060008060c0878903121561327857600080fd5b863595506132886020880161324e565b94506040870135935061329d6060880161324e565b92506080870135915060a087013590509295509295509295565b6000602082840312156132c957600080fd5b81516122a2816130f3565b634e487b7160e01b600052601160045260246000fd5b808201808211156104d6576104d66132d4565b60006020828403121561330f57600080fd5b5051919050565b818103818111156104d6576104d66132d4565b600181811c9082168061333d57607f821691505b60208210810361335d57634e487b7160e01b600052602260045260246000fd5b50919050565b80820281158282048414176104d6576104d66132d4565b6001600160401b0381811683821601908082111561339a5761339a6132d4565b5092915050565b81835281816020850137506000828201602090810191909152601f909101601f19169091010190565b6060815260006133de60608301888a6133a1565b82810360208401526133f18187896133a1565b905082810360408401526134068185876133a1565b9998505050505050505050565b6000815461342081613329565b80855260206001838116801561343d576001811461345757613485565b60ff1985168884015283151560051b880183019550613485565b866000528260002060005b8581101561347d5781548a8201860152908301908401613462565b890184019650505b505050505092915050565b6060815260006134a36060830186613413565b82810360208401526134b58186613413565b905082810360408401526123fb8185613413565b634e487b7160e01b600052604160045260246000fd5b601f82111561097957600081815260208120601f850160051c810160208610156135065750805b601f850160051c820191505b8181101561181f57828155600101613512565b6001600160401b0383111561353c5761353c6134c9565b6135508361354a8354613329565b836134df565b6000601f841160018114613584576000851561356c5750838201355b600019600387901b1c1916600186901b17835561094d565b600083815260209020601f19861690835b828110156135b55786850135825560209485019460019092019101613595565b50868210156135d25760001960f88860031b161c19848701351681555b505060018560011b0183555050505050565b634e487b7160e01b600052603260045260246000fd5b60006001820161360c5761360c6132d4565b5060010190565b634e487b7160e01b600052603160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b634e487b7160e01b600052600160045260246000fd5b7f416363657373436f6e74726f6c3a206163636f756e742000000000000000000081526000835161368d816017850160208801612f61565b7001034b99036b4b9b9b4b733903937b6329607d1b60179184019182015283516136be816028840160208801612f61565b01602801949350505050565b80820182811260008312801582168215821617156136ea576136ea6132d4565b505092915050565b60008261370f57634e487b7160e01b600052601260045260246000fd5b500490565b818103600083128015838313168383128216171561339a5761339a6132d4565b600081613743576137436132d4565b50600019019056fe241ecf16d79d0f8dbfb92cbc07fe17840425976cf0667f022fe9877caa831b08a26469706673582212201ac9b7e3f624a509d97a2897dcd062f2104aa76eec28dc088e0068610dbb3a1e64736f6c63430008110033

Verified Source Code Full Match

Compiler: v0.8.17+commit.8df45f5f EVM: london Optimization: Yes (200 runs)
Staking.sol 266 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import {TransferDelayer} from "./abstract/TransferDelayer.sol";
import {FlexibleInterest} from "./abstract/FlexibleInterest.sol";
import {CommonInterest} from "./abstract/CommonInterest.sol";
import {CompoundInterest} from "./abstract/CompoundInterest.sol";
import {SimpleInterest} from "./abstract/SimpleInterest.sol";
import {LimeRank} from "./lib/LimeRank.sol";
import {Math} from "./lib/Math.sol";
import {TimeContext} from "./abstract/TimeContext.sol";
import {AccessControl} from "@openzeppelin/contracts/access/AccessControl.sol";
import {IStakingCore} from "./IStakingCore.sol";
import {IStakingInfo} from "./IStakingInfo.sol";
import {IStakingPredictable} from "./IStakingPredictable.sol";
import {IStakingStatistics} from "./IStakingStatistics.sol";
import {IStakingPausable} from "./IStakingPausable.sol";

/**
    @title Staking
    @author iMe Lab

    @notice Implementation of iMe staking version 2
 */
contract Staking is
    IStakingCore,
    IStakingInfo,
    IStakingPredictable,
    IStakingStatistics,
    IStakingPausable,
    FlexibleInterest,
    TransferDelayer,
    TimeContext,
    AccessControl
{
    constructor(
        StakingInfo memory blueprint
    )
        FlexibleInterest(blueprint.compoundAccrualThreshold)
        SimpleInterest(blueprint.startsAt - blueprint.accrualPeriod * 2)
        CompoundInterest((blueprint.startsAt + blueprint.endsAt) / 2)
        CommonInterest(blueprint.interestRate, blueprint.accrualPeriod)
    {
        require(blueprint.startsAt < blueprint.endsAt);
        require(blueprint.prematureWithdrawalFee < 1e18);
        require(blueprint.delayedWithdrawalFee < 1e18);

        _name = blueprint.name;
        _author = blueprint.author;
        _website = blueprint.website;
        _token = IERC20(blueprint.token);
        _minimalRank = blueprint.minimalRank;
        _delayedWithdrawalDuration = blueprint.delayedWithdrawalDuration;
        _startsAt = blueprint.startsAt;
        _endsAt = blueprint.endsAt;
        _delayedWithdrawalFee = blueprint.delayedWithdrawalFee;
        _prematureWithdrawalFee = blueprint.prematureWithdrawalFee;
        _isPaused = false;

        _grantRole(MANAGER_ROLE, _msgSender());
        _grantRole(PARTNER_ROLE, _msgSender());

        _setRoleAdmin(MANAGER_ROLE, MANAGER_ROLE);
        _setRoleAdmin(ARBITER_ROLE, MANAGER_ROLE);
        _setRoleAdmin(PARTNER_ROLE, PARTNER_ROLE);
    }

    bytes32 public constant MANAGER_ROLE = keccak256("MANAGER_ROLE");
    bytes32 public constant PARTNER_ROLE = keccak256("PARTNER_ROLE");
    bytes32 public constant ARBITER_ROLE = keccak256("ARBITER_ROLE");

    string private _name;
    string private _author;
    string private _website;
    IERC20 private immutable _token;
    uint8 private immutable _minimalRank;
    uint32 private immutable _delayedWithdrawalDuration;
    uint64 private immutable _startsAt;
    uint64 private _endsAt;
    uint64 private immutable _delayedWithdrawalFee;
    uint64 private immutable _prematureWithdrawalFee;

    bool private _isPaused;

    function version() external pure override returns (string memory) {
        return "3";
    }

    function info() external view override returns (StakingInfo memory) {
        return
            StakingInfo(
                _name,
                _author,
                _website,
                address(_token),
                _interestRate,
                _accrualPeriod,
                _delayedWithdrawalDuration,
                _compoundThreshold,
                _delayedWithdrawalFee,
                _prematureWithdrawalFee,
                _minimalRank,
                _startsAt,
                _endsAt
            );
    }

    function summary() external view override returns (StakingSummary memory) {
        return
            StakingSummary(
                _totalImpact(),
                _totalDebt(_accrualNow()),
                _totalDelayed(),
                _token.balanceOf(address(this))
            );
    }

    function totalDebt(uint64 at) external view override returns (uint256) {
        if (at > _endsAt) at = _endsAt;
        else if (at < _now()) at = _now();
        return _totalDebt(at);
    }

    function statsOf(
        address investor
    ) external view override returns (StakingStatistics memory) {
        (uint256 pending, uint256 ready) = _delayedTokensFor(investor, _now());

        return
            StakingStatistics(
                _impactOf(investor),
                _debt(investor, _accrualNow()),
                pending,
                ready
            );
    }

    function deposit(
        uint256 amount,
        uint8 rank,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external override {
        require(amount > 0);
        if (_now() >= deadline) revert DepositDeadlineIsReached();
        if (_isPaused) revert StakingIsPaused();
        if (_now() < _startsAt) revert DepositIsTooEarly();
        if (_now() >= _endsAt) revert DepositIsTooLate();
        if (_minimalRank != 0) {
            address subject = address(this);
            address sender = _msgSender();
            bytes32 proof = LimeRank.proof(subject, sender, deadline, rank);
            address signer = ecrecover(proof, v, r, s);
            if (!this.hasRole(ARBITER_ROLE, signer))
                revert DepositRankIsUntrusted();
            if (rank < _minimalRank) revert DepositRankIsTooLow();
        }
        _deposit(_msgSender(), amount, _now());
        emit Deposit(_msgSender(), amount);
        _safe(_token.transferFrom(_msgSender(), address(this), amount));
    }

    function withdraw(uint256 amount, bool delayed) external override {
        require(amount > 0);
        if (_now() < _endsAt && _isPaused) revert StakingIsPaused();

        _withdrawal(_msgSender(), amount, _accrualNow());

        if (delayed) {
            if (_now() >= _endsAt) revert WithdrawalDelayIsUnwanted();
            uint256 fee = Math.fromX18(amount * _delayedWithdrawalFee);
            uint64 unlockAt = _now() + _delayedWithdrawalDuration;
            _delayTransfer(_msgSender(), amount - fee, unlockAt);
            emit DelayedWithdrawal(_msgSender(), amount, fee, unlockAt);
        } else {
            uint256 fee;
            if (_now() < _endsAt)
                fee = Math.fromX18(amount * _prematureWithdrawalFee);

            _safe(_token.transfer(_msgSender(), amount - fee));
            emit Withdrawal(_msgSender(), amount, fee);
        }

        if (!_hasEnoughFunds()) revert WithdrawalIsOffensive();
    }

    function reward(address to) external override onlyRole(MANAGER_ROLE) {
        if (_now() < _endsAt) revert RewardIsTooEarly();
        uint256 prize = _debt(to, _accrualNow());
        _withdrawal(to);
        emit Withdrawal(to, prize, 0);
        _safe(_token.transfer(to, prize));
        if (!_hasEnoughFunds()) revert WithdrawalIsOffensive();
    }

    function refund(uint256 amount) external override onlyRole(PARTNER_ROLE) {
        if (_now() < _endsAt) revert RefundIsTooEarly();
        uint256 tokensToGive = _totalDelayed() + _totalDebt(_accrualNow());
        uint256 balance = _token.balanceOf(address(this));
        if (balance < tokensToGive) revert WithdrawalIsOffensive();

        uint256 freeTokens = balance - tokensToGive;
        if (amount == 0) amount = freeTokens;
        else if (amount > freeTokens) revert WithdrawalIsOffensive();

        _safe(_token.transfer(_msgSender(), amount));
    }

    function claim(address recipient) external override {
        uint256 amount = _finalizeDelayedTransfers(recipient, _now());
        if (amount == 0) revert NoTokensReadyForClaim();
        emit Claim(recipient, amount);
        _safe(_token.transfer(recipient, amount));
    }

    function pause() external override onlyRole(MANAGER_ROLE) {
        require(!_isPaused);
        _isPaused = true;
    }

    function resume() external override onlyRole(MANAGER_ROLE) {
        require(_isPaused);
        _isPaused = false;
    }

    function stop() external onlyRole(MANAGER_ROLE) {
        require(_now() >= _startsAt);
        require(_now() < _endsAt);
        _endsAt = _now();
        emit StakingInfoChanged();
    }

    function setRequisites(
        string calldata name,
        string calldata author,
        string calldata website
    ) external onlyRole(MANAGER_ROLE) {
        require(
            keccak256(abi.encode(_name, _author, _website)) !=
                keccak256(abi.encode(name, author, website))
        );
        (_name, _author, _website) = (name, author, website);
        emit StakingInfoChanged();
    }

    function _hasEnoughFunds() private view returns (bool) {
        return
            _token.balanceOf(address(this)) >= _totalImpact() + _totalDelayed();
    }

    function _safe(bool transfer) private pure {
        if (!transfer) revert TokenTransferFailed();
    }

    function _accrualNow() internal view returns (uint64) {
        uint64 time = _now();
        return time < _endsAt ? time : _endsAt;
    }

    receive() external payable {
        revert();
    }
}
Math.sol 44 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title Math
    @author iMe Lab

    @notice Maths library. Generally, for financial computations.
 */
library Math {
    /**
        @notice Yields integer exponent of fixed-point number

        @dev Implementation of Exponintiation by squaring algorightm.
        Highly inspired by PRBMath library. Uses x33 precision instead
        of x18 in order to make financial computations more accurate.

        @param x Exponent base, 33x33 fixed number close to 1.0
        @param y Exponentiation parameter, integer
     */
    function powerX33(
        uint256 x,
        uint256 y
    ) internal pure returns (uint256 power) {
        unchecked {
            power = y & 1 > 0 ? x : 1e33;

            for (y >>= 1; y > 0; y >>= 1) {
                x = (x * x) / 1e33;
                if (y & 1 > 0) power = (power * x) / 1e33;
            }
        }
    }

    /**
        @notice Round x18 fixed number to an integer
     */
    function fromX18(uint256 fixedX18) internal pure returns (uint256 round) {
        unchecked {
            round = fixedX18 / 1e18;
            if (fixedX18 % 1e18 > 5e17) round += 1;
        }
    }
}
IStakingCore.sol 98 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title IStakingCore
    @author iMe Lab

    @notice General interface for iMe Staking v2
 */
interface IStakingCore {
    error TokenTransferFailed();
    error DepositIsTooEarly();
    error DepositIsTooLate();
    error DepositRankIsUntrusted();
    error DepositRankIsTooLow();
    error DepositDeadlineIsReached();
    error WithdrawalDelayIsUnwanted();
    error WithdrawalIsOffensive();
    error NoTokensReadyForClaim();
    error RewardIsTooEarly();
    error RefundIsTooEarly();

    event Deposit(address from, uint256 amount);
    event Withdrawal(address to, uint256 amount, uint256 fee);
    event DelayedWithdrawal(
        address to, uint256 amount, uint256 fee, uint64 until
    );
    event Claim(address to, uint256 amount);

    /**
        @notice Yields internal staking version

        @dev Version is needed to distinguish staking v1/v2 interfaces
     */
    function version() external pure returns (string memory);

    /**
       @notice Make a deposit

       @dev Should fire StakingDeposit event

       @param amount Amount of token to deposit. Should be approved in advance.
       @param rank Depositor's LIME rank
       @param deadline Deadline for deposit transaction
       @param v V part of the signature, proofing depositor's rank
       @param r R part of the signature, proofing depositor's rank
       @param s S part of the signature, proofing depositor's rank
     */
    function deposit(
        uint256 amount,
        uint8 rank,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external;

    /**
        @notice Withdraw staked and prize tokens

        @dev should fire StakingWithdrawal or StakingDelayedWithdrawal event

        @param amount Amount of tokens to withdraw
        @param delayed Whether withdrawal is delayed
     */
    function withdraw(uint256 amount, bool delayed) external;

    /**
        @notice Claim delayed withdrawn tokens

        @dev Actually doesn't matter who run this method: claimer address
        is passed as a parameter. So, anyone can pay gas to perform claim for
        a friend.

        Should fire StakingClaim event.

        @param depositor Depositor who performs claim
     */
    function claim(address depositor) external;

    /**
        @notice Force withdrawal for specified investor

        @dev Force withdrawals should be available after staking finish only.

        @param depositor Depositor to perform delay for
     */
    function reward(address depositor) external;

    /**
        @notice Take tokens which doesn't participate in staking. Should be
        available only after staking finish and only for tokens owner (partner)

        @param amount Amount of tokens to take. Should not be above free
        tokens. if amount = 0, all free tokens will be withdrawn
     */
    function refund(uint256 amount) external;
}
IStakingInfo.sol 86 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title IStakingInfo
    @author iMe Lab
    @notice Staking contract v2 extension, allowing clients to retrieve 
    staking programme information.

    Generally, needed for building better UX by allowing users to see staking
    requisites, lifespan, fees, etc.
 */
interface IStakingInfo {
    /**
        @notice General staking information
     */
    struct StakingInfo {
        /**
            @notice Staking name to be displayed everywhere
         */
        string name;
        /**
            @notice Partner name. As example, iMe Lab
         */
        string author;
        /**
            @notice Partner website. As example, https://imem.app
         */
        string website;
        /**
            @notice Address of token for staking
         */
        address token;
        /**
            @notice Interest per accrual period
            @dev Represented as fixed 2x18 number
         */
        uint64 interestRate;
        /**
            @notice Interest accrual period in seconds
         */
        uint32 accrualPeriod;
        /**
            @notice Duration of withdrawn tokens lock, in seconds
         */
        uint32 delayedWithdrawalDuration;
        /**
            @notice Impact needed to enable compound accrual
         */
        uint256 compoundAccrualThreshold;
        /**
            @notice Fee taken for delayed withdrawn tokens
            @dev Represented as fixed 2x18 number
         */
        uint64 delayedWithdrawalFee;
        /**
            @notice Fee taken for premature withdrawn tokens
            @dev Represented as fixed 2x18 number
         */
        uint64 prematureWithdrawalFee;
        /**
            @notice Minimal LIME rank needed to make deposits
         */
        uint8 minimalRank;
        /**
            @notice Staking start moment
         */
        uint64 startsAt;
        /**
            @notice Staking end moment. May change if staking stops
         */
        uint64 endsAt;
    }

    /**
        @notice Event, typically fired when staking info changes
     */
    event StakingInfoChanged();

    /**
        @notice Retrieve staking information

        @dev Information shouldn't change frequently
     */
    function info() external view returns (StakingInfo memory);
}
Calendar.sol 38 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/**
    @title Calendar
    @author iMe Lab

    @notice Small date & time library
 */
library Calendar {
    /**
        @notice Count round periods over time interval
        
        @dev Example case, where function should return 3:
        
         duration = |-----|
        
             start               end
               |                  |
               V                  V
        -----|-----|-----|-----|-----|-----|---
    
        @param start Interval start
        @param end Interval end
        @param duration Period duration
     */
    function periods(
        uint64 start,
        uint64 end,
        uint32 duration
    ) internal pure returns (uint64 count) {
        unchecked {
            if (start > end) (start, end) = (end, start);
            count = (end - start) / duration;
            if (start % duration > end % duration) count += 1;
        }
    }
}
LimeRank.sol 46 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title LimeRank
    @author iMe Lab

    @notice Library for working with LIME ranks
 */
library LimeRank {
    /**
        @notice Yields proof for **subject** that **issuer** has LIME **rank**
        in a timespan, not later than **deadline**

        @dev "Proofs" make sense only if they are signed. Signing example:

        ```typescript
          const hash = ethers.utils.solidityKeccak256(
            ["address", "address", "uint256", "uint8"],
            [subject, issuer, deadline, rank]
          );
          const proof = ethers.utils.arrayify(hash);
          const sig = await arbiter.signMessage(proof);
          const { v, r, s } = ethers.utils.splitSignature(sig);
        ```

        @param subject Address of entity that performs check
        @param issuer Address of account who proofs his rank
        @param deadline Proof expiration timestamp
        @param rank LIME rank that being proofed
    */
    function proof(
        address subject,
        address issuer,
        uint256 deadline,
        uint8 rank
    ) internal pure returns (bytes32) {
        return
            keccak256(
                abi.encodePacked(
                    "\x19Ethereum Signed Message:\n32",
                    keccak256(abi.encodePacked(subject, issuer, deadline, rank))
                )
            );
    }
}
IStakingPausable.sol 26 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title IStakingPausable
    @author iMe Lab

    @notice Staking v2 extension, allowing managers to stop programmes.
 */
interface IStakingPausable {
    /**
        @notice Error, typically fired on attempt to do something during pause
     */
    error StakingIsPaused();

    /**
        @notice Temporary forbid user deposits/withdrawals
        Makes no sense after staking finish.
     */
    function pause() external;

    /**
        @notice Resume paused staking
     */
    function resume() external;
}
IStakingStatistics.sol 28 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title IStakingStatistics
    @author iMe Lab
    @notice Staking contract v2 extension, allowing clients to
    see their own statistics

    Generally, needed to improve UX by showing users their staked, accrued
    and delayed token amounts.
 */
interface IStakingStatistics {
    /**
        @notice Staking stats, related to a certain investor
     */
    struct StakingStatistics {
        uint256 impact;
        uint256 debt;
        uint256 pendingWithdrawnTokens;
        uint256 readyWithdrawnTokens;
    }

    /**
        @notice Yields personal stats for a certain investor
     */
    function statsOf(address) external view returns (StakingStatistics memory);
}
IStakingPredictable.sol 34 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title IStakingPredictable
    @author iMe Lab
    @notice Staking contract v2 extension, allowing clients to retrieve
    staking current statistics and predict debt in future.

    Generally, needed to predict staking solvency.
 */
interface IStakingPredictable {
    /**
        @notice Totals in this staking
     */
    struct StakingSummary {
        uint256 totalImpact;
        uint256 totalDebt;
        uint256 totalDelayed;
        uint256 balance;
    }

    /**
        @notice Populate staking summary for the present moment
     */
    function summary() external view returns (StakingSummary memory);

    /**
        @notice Predict total debt for a certain point in time

        @param at Unit in time to make a prediction. Shouldn't be in the past.
     */
    function totalDebt(uint64 at) external view returns (uint256);
}
TimeContext.sol 23 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title TimeContext
    @author iMe Lab

    @notice Contract fragment, providing context of present moment
 */
abstract contract TimeContext {
    /**
        @notice Get present moment timestamp
        
        @dev It should be overridden in mock contracts
        Any implementation of this function should follow a rule:
        sequential calls of _now() should give non-decreasing sequence of numbers.
        It's forbidden to travel back in time.
     */
    function _now() internal view virtual returns (uint64) {
        // solhint-disable-next-line not-rely-on-time
        return uint64(block.timestamp);
    }
}
CommonInterest.sol 78 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title CommonInterest
    @author iMe Lab

    @notice Base contract for interest accrual contracts
 */
abstract contract CommonInterest {
    constructor(uint64 interestRate, uint32 accrualPeriod) {
        _interestRate = interestRate;
        _accrualPeriod = accrualPeriod;
    }

    /**
        @notice Error, typically fired on attempt to withdraw over balance
     */
    error WithdrawalOverDebt();

    uint64 internal immutable _interestRate;
    uint32 internal immutable _accrualPeriod;

    /**
        @notice Make a logical deposit

        @param depositor Account who makes a deposit
        @param amount Amount of deposited tokens (integer)
        @param at Timestamp of deposit
     */
    function _deposit(
        address depositor,
        uint256 amount,
        uint64 at
    ) internal virtual;

    /**
        @notice Make a logical withdrawal

        @dev Should revert with WithdrawalOverDebt on balance exceed

        @param depositor Account who makes a withdrawal
        @param amount Amount of withdrawn tokens (integer)
        @param at Timestamp of withdrawal
     */
    function _withdrawal(
        address depositor,
        uint256 amount,
        uint64 at
    ) internal virtual;

    /**
        @notice Make full withdrawal (logical)

        @dev It' a gase-efficient equivalent of
        `_withdrawal(address, uint256, uint65)`, as it shouldn't care
        about previous depositor balance
     */
    function _withdrawal(address depositor) internal virtual;

    /**
        @notice Predicts debt for an investor

        @param depositor The depositor
        @param at Timestamp for debt calculation
     */
    function _debt(
        address depositor,
        uint64 at
    ) internal view virtual returns (uint256);

    /**
        @notice Predict total debt accross all investors

        @param at Timestamp to make a prediction for. Shouldn't be in the past.
     */
    function _totalDebt(uint64 at) internal view virtual returns (uint256);
}
SimpleInterest.sol 105 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import {CommonInterest} from "./CommonInterest.sol";
import {Math} from "../lib/Math.sol";
import {Calendar} from "../lib/Calendar.sol";

/**
    @title SimpleInterest
    @author iMe Lab

    @notice Implementation of simple interest accrual
    @dev https://en.wikipedia.org/wiki/Interest#Types_of_interest
 */
abstract contract SimpleInterest is CommonInterest {
    constructor(uint64 anchor) {
        _simpleAnchor = anchor;
    }

    uint64 private immutable _simpleAnchor;
    mapping(address => int256) private _simpleDeposit;
    int256 private _totalSimpleDeposit;
    mapping(address => uint256) private _simpleGrowth;
    uint256 private _totalSimpleGrowth;

    function _deposit(
        address depositor,
        uint256 amount,
        uint64 at
    ) internal virtual override(CommonInterest) {
        amount *= 1e18;
        uint256 growthIncrease = (amount * _interestRate) / 1e18;
        uint256 elapsed = Calendar.periods(_simpleAnchor, at, _accrualPeriod);
        int256 depoDiff = int256(amount) - int256(growthIncrease * elapsed);
        _simpleDeposit[depositor] += depoDiff;
        _simpleGrowth[depositor] += growthIncrease;
        _totalSimpleGrowth += growthIncrease;
        _totalSimpleDeposit += depoDiff;
    }

    function _withdrawal(
        address depositor,
        uint256 amount,
        uint64 at
    ) internal virtual override(CommonInterest) {
        uint256 debt = _debt(depositor, at);
        if (amount > debt) {
            revert WithdrawalOverDebt();
        } else if (amount == debt) {
            _withdrawal(depositor);
        } else {
            uint256 growth = _simpleGrowth[depositor];
            uint64 periods = Calendar.periods(
                _simpleAnchor,
                at,
                _accrualPeriod
            );
            uint256 percent = (amount * 1e36) / debt;
            if (percent > 1e18) percent = 1e18;
            uint256 growthDecrease = (growth * (1e18 - percent)) / 1e18;
            int256 depoDecrease = int256(amount * 1e18) -
                int256((growth * periods * (1e18 - percent)) / 1e18);
            _totalSimpleDeposit -= depoDecrease;
            _totalSimpleGrowth -= growthDecrease;
            _simpleDeposit[depositor] -= depoDecrease;
            _simpleGrowth[depositor] -= growthDecrease;
        }
    }

    function _withdrawal(address depositor) internal virtual override {
        int256 deposit = _simpleDeposit[depositor];
        if (deposit != 0) {
            _totalSimpleDeposit -= deposit;
            _simpleDeposit[depositor] = 0;
        }
        uint256 growth = _simpleGrowth[depositor];
        if (growth != 0) {
            _totalSimpleGrowth -= growth;
            _simpleGrowth[depositor] = 0;
        }
    }

    function _debt(
        address depositor,
        uint64 at
    ) internal view virtual override(CommonInterest) returns (uint256) {
        int256 deposit = _simpleDeposit[depositor];
        uint256 growth = _simpleGrowth[depositor];
        uint256 periods = Calendar.periods(_simpleAnchor, at, _accrualPeriod);
        int256 debt = int256(deposit) + int256(periods * growth);
        if (debt < 0) return 0;
        else return Math.fromX18(uint256(debt));
    }

    function _totalDebt(
        uint64 at
    ) internal view virtual override returns (uint256) {
        int256 deposit = _totalSimpleDeposit;
        uint256 growth = _totalSimpleGrowth;
        uint256 periods = Calendar.periods(_simpleAnchor, at, _accrualPeriod);
        int256 debt = int256(deposit) + int256(periods * growth);
        if (debt < 0) return 0;
        else return Math.fromX18(uint256(debt));
    }
}
TransferDelayer.sol 89 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/**
    @title TransferDelayer
    @author iMe Lab

    @notice Contract fragment, responsible for token transfer delay
 */
abstract contract TransferDelayer {
    struct DelayedTransfer {
        /**
            @notice Amount of tokens to send, integer

            @dev uint192 is used in order to optimize gas costs
         */
        uint192 amount;
        /**
            @notice Timestamp to perform the transfer
         */
        uint64 notBefore;
    }

    mapping(address => DelayedTransfer[]) private _transfers;
    uint256 private _delayedValue = 0;

    function _delayTransfer(
        address recipient,
        uint256 amount,
        uint64 notBefore
    ) internal {
        assert(amount < 2 ** 192);
        _transfers[recipient].push(DelayedTransfer(uint192(amount), notBefore));
        _delayedValue += amount;
    }

    /**
        @notice Finalize transfers, which are ready, for certain user

        @dev Be sure to perform a real token transfer
     */
    function _finalizeDelayedTransfers(
        address recipient,
        uint64 moment
    ) internal returns (uint256) {
        DelayedTransfer[] memory transfers = _transfers[recipient];
        uint256 i = 0; // Index of the last transfer to perform
        uint256 tokensToSend = 0;

        for (; i < transfers.length && moment >= transfers[i].notBefore; i++)
            tokensToSend += transfers[i].amount;

        if (i == 0) {
            return 0;
        } else if (i == transfers.length) {
            delete _transfers[recipient];
        } else {
            for (uint256 k = 0; k < i; k++) {
                _transfers[recipient][k] = transfers[k + i];
                _transfers[recipient].pop();
            }
        }

        _delayedValue -= tokensToSend;
        return tokensToSend;
    }

    /**
        @notice Yields amount of delayed tokens for a certain user

        @return pending Amount of tokens, which cannot be transferred yet
        @return ready Amount of tokens, ready to be transferred
     */
    function _delayedTokensFor(
        address recipient,
        uint256 moment
    ) internal view returns (uint256 pending, uint256 ready) {
        DelayedTransfer[] memory transfers = _transfers[recipient];
        uint256 i = 0;
        for (; i < transfers.length && transfers[i].notBefore < moment; i++)
            ready += transfers[i].amount;

        for (; i < transfers.length; i++) pending += transfers[i].amount;
    }

    function _totalDelayed() internal view returns (uint256) {
        return _delayedValue;
    }
}
CompoundInterest.sol 120 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import {CommonInterest} from "./CommonInterest.sol";
import {Math} from "../lib/Math.sol";
import {Calendar} from "../lib/Calendar.sol";

/**
    @title CompoundInterest
    @author iMe Lab

    @notice Implementation of compound interest accrual
    @dev https://en.wikipedia.org/wiki/Compound_interest
 */
abstract contract CompoundInterest is CommonInterest {
    constructor(uint64 anchor) {
        _compoundAnchor = anchor;
    }

    uint64 private immutable _compoundAnchor;
    mapping(address => uint256) private _compoundDeposit;
    uint256 private _totalCompoundDeposit;

    function _deposit(
        address depositor,
        uint256 amount,
        uint64 at
    ) internal virtual override(CommonInterest) {
        uint256 effect = _converge(
            amount,
            _interestRate,
            at,
            _compoundAnchor,
            _accrualPeriod
        );

        _totalCompoundDeposit += effect;
        _compoundDeposit[depositor] += effect;
    }

    function _withdrawal(
        address recipient,
        uint256 amount,
        uint64 at
    ) internal virtual override(CommonInterest) {
        uint256 debt = _debt(recipient, at);

        if (amount > debt) {
            revert WithdrawalOverDebt();
        } else if (amount == debt) {
            _withdrawal(recipient);
        } else {
            uint256 diff = _converge(
                amount,
                _interestRate,
                at,
                _compoundAnchor,
                _accrualPeriod
            );
            uint256 deposit = _compoundDeposit[recipient];
            if (diff > deposit) diff = deposit;
            _compoundDeposit[recipient] -= diff;
            _totalCompoundDeposit -= diff;
        }
    }

    function _withdrawal(address recipient) internal virtual override {
        uint256 deposit = _compoundDeposit[recipient];
        if (deposit != 0) {
            _totalCompoundDeposit -= deposit;
            _compoundDeposit[recipient] = 0;
        }
    }

    function _debt(
        address recipient,
        uint64 at
    ) internal view virtual override returns (uint256) {
        return
            _converge(
                _compoundDeposit[recipient],
                _interestRate,
                _compoundAnchor,
                at,
                _accrualPeriod
            );
    }

    function _totalDebt(
        uint64 at
    ) internal view virtual override returns (uint256) {
        return
            _converge(
                _totalCompoundDeposit,
                _interestRate,
                _compoundAnchor,
                at,
                _accrualPeriod
            );
    }

    /**
        @notice Yields money value, converged to specified point in time

        @return Converged amount of money [fixed]
     */
    function _converge(
        uint256 sum,
        uint256 interest,
        uint64 from,
        uint64 to,
        uint32 period
    ) private pure returns (uint256) {
        uint64 periods = Calendar.periods(from, to, period);
        if (periods == 0) return sum;
        uint256 lever = Math.powerX33(1e33 + interest * 1e15, periods) / 1e15;
        uint256 converged = to < from ? (sum * 1e36) / lever : sum * lever;
        return Math.fromX18(converged);
    }
}
FlexibleInterest.sol 113 lines
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import {CommonInterest} from "./CommonInterest.sol";
import {SimpleInterest} from "./SimpleInterest.sol";
import {CompoundInterest} from "./CompoundInterest.sol";

/**
    @title FlexibleInterest
    @author iMe Lab

    @notice Contract fragment, implementing flexible interest accrual.
    "Flexible" means actual accrual strategy of an investor may change.
 */
abstract contract FlexibleInterest is SimpleInterest, CompoundInterest {
    constructor(uint256 compoundThreshold) {
        _compoundThreshold = compoundThreshold;
    }

    uint256 internal immutable _compoundThreshold;
    mapping(address => uint256) private _impact;
    uint256 private _accumulatedImpact;

    function _deposit(
        address depositor,
        uint256 amount,
        uint64 at
    ) internal override(SimpleInterest, CompoundInterest) {
        uint256 impact = _impact[depositor];
        _impact[depositor] += amount;
        _accumulatedImpact += amount;

        if (impact >= _compoundThreshold) {
            CompoundInterest._deposit(depositor, amount, at);
        } else {
            if (impact + amount >= _compoundThreshold) {
                uint256 debt = SimpleInterest._debt(depositor, at);
                if (debt != 0) SimpleInterest._withdrawal(depositor);
                CompoundInterest._deposit(depositor, debt + amount, at);
            } else {
                SimpleInterest._deposit(depositor, amount, at);
            }
        }
    }

    function _withdrawal(
        address depositor,
        uint256 amount,
        uint64 at
    ) internal override(SimpleInterest, CompoundInterest) {
        uint256 impact = _impact[depositor];
        uint256 decrease = (amount < impact) ? amount : impact;
        _impact[depositor] -= decrease;
        _accumulatedImpact -= decrease;

        if (impact >= _compoundThreshold) {
            if (impact - decrease > _compoundThreshold) {
                CompoundInterest._withdrawal(depositor, amount, at);
            } else {
                uint256 debt = CompoundInterest._debt(depositor, at);
                if (debt != 0) CompoundInterest._withdrawal(depositor);
                if (amount != debt)
                    SimpleInterest._deposit(depositor, debt - amount, at);
            }
        } else {
            SimpleInterest._withdrawal(depositor, amount, at);
        }
    }

    function _withdrawal(
        address depositor
    ) internal override(SimpleInterest, CompoundInterest) {
        uint256 impact = _impact[depositor];
        if (impact >= _compoundThreshold)
            CompoundInterest._withdrawal(depositor);
        else SimpleInterest._withdrawal(depositor);
        _accumulatedImpact -= impact;
        _impact[depositor] = 0;
    }

    function _debt(
        address depositor,
        uint64 at
    )
        internal
        view
        override(SimpleInterest, CompoundInterest)
        returns (uint256)
    {
        if (_impact[depositor] >= _compoundThreshold)
            return CompoundInterest._debt(depositor, at);
        else return SimpleInterest._debt(depositor, at);
    }

    function _totalDebt(
        uint64 at
    )
        internal
        view
        override(SimpleInterest, CompoundInterest)
        returns (uint256)
    {
        return CompoundInterest._totalDebt(at) + SimpleInterest._totalDebt(at);
    }

    function _totalImpact() internal view returns (uint256) {
        return _accumulatedImpact;
    }

    function _impactOf(address investor) internal view returns (uint256) {
        return _impact[investor];
    }
}
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 70 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

import "./math/Math.sol";

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        unchecked {
            uint256 length = Math.log10(value) + 1;
            string memory buffer = new string(length);
            uint256 ptr;
            /// @solidity memory-safe-assembly
            assembly {
                ptr := add(buffer, add(32, length))
            }
            while (true) {
                ptr--;
                /// @solidity memory-safe-assembly
                assembly {
                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
                }
                value /= 10;
                if (value == 0) break;
            }
            return buffer;
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        unchecked {
            return toHexString(value, Math.log256(value) + 1);
        }
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}
Math.sol 345 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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. If the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        //
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
        //
        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
        //
        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1 << (log2(a) >> 1);

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = sqrt(a);
            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 2, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 128;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 64;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 32;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 16;
            }
            if (value >> 8 > 0) {
                value >>= 8;
                result += 8;
            }
            if (value >> 4 > 0) {
                value >>= 4;
                result += 4;
            }
            if (value >> 2 > 0) {
                value >>= 2;
                result += 2;
            }
            if (value >> 1 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log2(value);
            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 10, rounded down, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >= 10**64) {
                value /= 10**64;
                result += 64;
            }
            if (value >= 10**32) {
                value /= 10**32;
                result += 32;
            }
            if (value >= 10**16) {
                value /= 10**16;
                result += 16;
            }
            if (value >= 10**8) {
                value /= 10**8;
                result += 8;
            }
            if (value >= 10**4) {
                value /= 10**4;
                result += 4;
            }
            if (value >= 10**2) {
                value /= 10**2;
                result += 2;
            }
            if (value >= 10**1) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log10(value);
            return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);
        }
    }

    /**
     * @dev Return the log in base 256, rounded down, of a positive value.
     * Returns 0 if given 0.
     *
     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
     */
    function log256(uint256 value) internal pure returns (uint256) {
        uint256 result = 0;
        unchecked {
            if (value >> 128 > 0) {
                value >>= 128;
                result += 16;
            }
            if (value >> 64 > 0) {
                value >>= 64;
                result += 8;
            }
            if (value >> 32 > 0) {
                value >>= 32;
                result += 4;
            }
            if (value >> 16 > 0) {
                value >>= 16;
                result += 2;
            }
            if (value >> 8 > 0) {
                result += 1;
            }
        }
        return result;
    }

    /**
     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.
     * Returns 0 if given 0.
     */
    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
        unchecked {
            uint256 result = log256(value);
            return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);
        }
    }
}
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);
}
AccessControl.sol 247 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.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(account),
                        " 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());
        }
    }
}
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;
}
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;
    }
}
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);
}

Read Contract

ARBITER_ROLE 0x4d104adf → bytes32
DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
MANAGER_ROLE 0xec87621c → bytes32
PARTNER_ROLE 0x2513e2b9 → bytes32
getRoleAdmin 0x248a9ca3 → bytes32
hasRole 0x91d14854 → bool
info 0x370158ea → tuple
statsOf 0x15cfc405 → tuple
summary 0xb16a867c → tuple
supportsInterface 0x01ffc9a7 → bool
totalDebt 0xdc842ac4 → uint256
version 0x54fd4d50 → string

Write Contract 12 functions

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

claim 0x1e83409a
address recipient
deposit 0xdddc2f64
uint256 amount
uint8 rank
uint256 deadline
uint8 v
bytes32 r
bytes32 s
grantRole 0x2f2ff15d
bytes32 role
address account
pause 0x8456cb59
No parameters
refund 0x278ecde1
uint256 amount
renounceRole 0x36568abe
bytes32 role
address account
resume 0x046f7da2
No parameters
revokeRole 0xd547741f
bytes32 role
address account
reward 0x6353586b
address to
setRequisites 0xb5dc4545
string name
string author
string website
stop 0x07da68f5
No parameters
withdraw 0x38d07436
uint256 amount
bool delayed

Recent Transactions

No transactions found for this address