Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x033f339f704C4C9273BE9D84a9dcAa33E947BbC6
Balance 0 ETH
Nonce 1
Code Size 12217 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

12217 bytes
0x608060405234801561001057600080fd5b50600436106103d05760003560e01c806391d14854116101ff578063d547741f1161011a578063ecef6cff116100ad578063f87507d71161007c578063f87507d7146108aa578063f9724c70146108e3578063fae7e9c9146108ec578063fb8d81011461094357600080fd5b8063ecef6cff14610855578063f045a2b414610885578063f1a640f81461088d578063f5b541a61461089557600080fd5b8063e3ce0307116100e9578063e3ce030714610831578063e6a69ab814610839578063eb91d37e14610844578063ebf886d21461084c57600080fd5b8063d547741f146107f5578063d62886be14610808578063e1525fbb1461081f578063e1f06f541461082957600080fd5b8063b212748711610192578063c42a737911610161578063c42a7379146107c9578063c93c5880146107d2578063cae91300146107e5578063d4631a8a146107ed57600080fd5b8063b212748714610782578063b29310961461078b578063b6783393146107b9578063b72a3248146107c157600080fd5b80639b7d02ad116101ce5780639b7d02ad146106f45780639de707101461071d578063a217fddf1461073d578063aa33fedb1461074557600080fd5b806391d14854146106c357806396c82e57146106d657806399fb15d2146106df5780639b5655dc146106ec57600080fd5b80634626402b116102ef57806370902a4511610282578063845380a211610251578063845380a2146106835780638456cb59146106aa5780638a735659146106b25780638bcdfe79146106bb57600080fd5b806370902a45146105e957806378da5728146105fc578063809d458d1461065d578063838edebf1461067057600080fd5b806369a69e29116102be57806369a69e29146105a85780636db74283146105bb5780636e27d889146105ce5780636f9fb98a146105e157600080fd5b80634626402b1461055f5780635c975abb146105725780635dc993641461057d5780635e2c19db1461058557600080fd5b806322ca68fe1161036757806336568abe1161033657806336568abe14610531578063372500ab14610544578063378191871461054c5780633f4ba83a1461055757600080fd5b806322ca68fe146104a6578063248a9ca3146104e85780632f2ff15d1461050b57806334c8d7111461051e57600080fd5b80630b5ab26c116103a35780630b5ab26c1461044a57806319beb249146104605780631cb44dfc1461048057806322607c611461049357600080fd5b806301ffc9a7146103d557806303142cf0146103fd57806303b8b9111461041257806304d34f641461041a575b600080fd5b6103e86103e3366004612cb2565b61096a565b60405190151581526020015b60405180910390f35b61041061040b366004612cdc565b6109a1565b005b610410610a26565b6002546104329061010090046001600160a01b031681565b6040516001600160a01b0390911681526020016103f4565b610452610a74565b6040519081526020016103f4565b61045261046e366004612d0c565b60076020526000908152604090205481565b61041061048e366004612d0c565b610b04565b6104526104a1366004612d0c565b610b89565b6104b96104b4366004612cdc565b610c1e565b6040805196875260208701959095529385019290925215156060840152608083015260a082015260c0016103f4565b6104526104f6366004612cdc565b60009081526020819052604090206001015490565b610410610519366004612d27565b610c6a565b6103e861052c366004612d53565b610c95565b61041061053f366004612d27565b610d0d565b610410610d40565b6104526305f5e10081565b610410610f87565b600354610432906001600160a01b031681565b60025460ff166103e8565b610452610faa565b6103e8610593366004612d0c565b60086020526000908152604090205460ff1681565b6104526105b6366004612d0c565b610fde565b6104526105c9366004612d0c565b61117a565b6104106105dc366004612cdc565b6112de565b600b54610452565b6104106105f7366004612d86565b611571565b61060f61060a366004612cdc565b61180c565b6040516103f49190600060c0820190508251825260208301516020830152604083015160408301526060830151151560608301526080830151608083015260a083015160a083015292915050565b61041061066b366004612d0c565b6118ba565b61041061067e366004612cdc565b611937565b6104327f000000000000000000000000419d0d8bdd9af5e606ae2232ed285aff190e711b81565b6104106119a2565b61045260045481565b6104106119c2565b6103e86106d1366004612d27565b611c94565b610452600c5481565b6011546103e89060ff1681565b610452611cbd565b610452610702366004612d0c565b6001600160a01b031660009081526006602052604090205490565b61045261072b366004612cdc565b6000908152600a602052604090205490565b610452600081565b610758610753366004612dbb565b611d53565b6040805195865260208601949094529284019190915215156060830152608082015260a0016103f4565b610452600d5481565b6103e8610799366004612dbb565b600960209081526000928352604080842090915290825290205460ff1681565b610452600881565b610410611da4565b610452600f5481565b6104106107e0366004612cdc565b611e6a565b610410611ef7565b610452611f48565b610410610803366004612d27565b611f85565b610810611faa565b6040516103f493929190612e21565b61045262093a8081565b610410612178565b6104526123d6565b6104526301e1338081565b601054610452565b610452600e5481565b61085d612430565b604080519586526020860194909452928401919091526060830152608082015260a0016103f4565b600554610452565b610452600681565b610452600080516020612f6483398151915281565b6103e86108b8366004612dbb565b6001600160a01b03919091166000908152600960209081526040808320938352929052205460ff1690565b61045261546081565b6108ff6108fa366004612dbb565b6124ab565b6040516103f49190600060a0820190508251825260208301516020830152604083015160408301526060830151151560608301526080830151608083015292915050565b6104527fd96ba01d6560c2ab35f2940dd8d70c5f5fe06236c72674237120515918198fb081565b60006001600160e01b03198216637965db0b60e01b148061099b57506301ffc9a760e01b6001600160e01b03198316145b92915050565b600080516020612f648339815191526109b981612561565b600082156109c85750816109d3565b6109d0610a74565b90505b601081905542600d8190556040805183815260208101929092527f945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd696838910160405180910390a1610a218161256b565b505050565b600080516020612f64833981519152610a3e81612561565b6011805460ff191690556040517fc756aa3ca97a640620220b1301d884be827ac9aa1a9430d6836f692b7cd1fbb590600090a150565b60025460405163907f238360e01b81526305f5e100600482015260009161010090046001600160a01b03169063907f238390602401602060405180830381865afa925050508015610ae2575060408051601f3d908101601f19168201909252610adf91810190612e90565b60015b610aff5760405163fa80e24f60e01b815260040160405180910390fd5b919050565b6000610b0f81612561565b6001600160a01b038216610b365760405163d92e233d60e01b815260040160405180910390fd5b60028054610100600160a81b0319166101006001600160a01b038516908102919091179091556040517f3df77beb5db05fcdd70a30fc8adf3f83f9501b68579455adbd100b818094039490600090a25050565b6001600160a01b03811660009081526006602052604081208190815b8154811015610c1557818181548110610bc057610bc0612ea9565b600091825260209091206003600590920201015460ff16610c0d57818181548110610bed57610bed612ea9565b90600052602060002090600502016000015483610c0a9190612ed5565b92505b600101610ba5565b50909392505050565b60058181548110610c2e57600080fd5b60009182526020909120600690910201805460018201546002830154600384015460048501546005909501549395509193909260ff9092169186565b600082815260208190526040902060010154610c8581612561565b610c8f8383612718565b50505050565b6001600160a01b0383166000908152600660205260408120548310610cbc57506000610d06565b6001600160a01b038416600090815260066020526040902080546001841b919085908110610cec57610cec612ea9565b906000526020600020906005020160040154166000141590505b9392505050565b6001600160a01b0381163314610d365760405163334bd91960e11b815260040160405180910390fd5b610a2182826127aa565b610d48612815565b610d5061283f565b60115460ff16610d73576040516384426c9560e01b815260040160405180910390fd5b336000908152600660205260408120815b600f54811015610f025760058181548110610da157610da1612ea9565b600091825260209091206003600690920201015460ff1615610efa5733600090815260096020908152604080832084845290915290205460ff16610efa576000805b8354811015610e5757826001901b848281548110610e0357610e03612ea9565b90600052602060002090600502016004015416600014610e4f57838181548110610e2f57610e2f612ea9565b90600052602060002090600502016002015482610e4c9190612ed5565b91505b600101610de3565b508015801590610e7457506000828152600a602052604090205415155b15610ef8576000828152600a60205260408120546005805485908110610e9c57610e9c612ea9565b90600052602060002090600602016001015483610eb99190612ee8565b610ec39190612eff565b9050610ecf8186612ed5565b3360009081526009602090815260408083208784529091529020805460ff191660011790559450505b505b600101610d84565b508115610f7a57600354610f44906001600160a01b037f000000000000000000000000419d0d8bdd9af5e606ae2232ed285aff190e711b811691163385612863565b60405182815233907fdf29796aad820e4bb192f3a8d631b76519bcd2cbe77cc85af20e9df53cece0869060200160405180910390a25b5050610f8560018055565b565b600080516020612f64833981519152610f9f81612561565b610fa76128bd565b50565b600080615460600d54610fbd9190612ed5565b9050804210610fce57600091505090565b610fd84282612f21565b91505090565b6001600160a01b0381166000908152600660205260408120805482036110075750600092915050565b6000805b600f54811015611172576005818154811061102857611028612ea9565b600091825260209091206003600690920201015460ff16801561106f57506001600160a01b038516600090815260096020908152604080832084845290915290205460ff16155b1561116a576000805b84548110156110ec57826001901b85828154811061109857611098612ea9565b906000526020600020906005020160040154166000146110e4578481815481106110c4576110c4612ea9565b906000526020600020906005020160020154826110e19190612ed5565b91505b600101611078565b50801580159061110957506000828152600a602052604090205415155b15611168576000828152600a6020526040812054600580548590811061113157611131612ea9565b9060005260206000209060060201600101548361114e9190612ee8565b6111589190612eff565b90506111648185612ed5565b9350505b505b60010161100b565b509392505050565b6001600160a01b0381166000908152600660205260408120805482036111a35750600092915050565b6000805b600f5481101561117257600581815481106111c4576111c4612ea9565b600091825260209091206003600690920201015460ff16156112d6576000805b845481101561125857826001901b85828154811061120457611204612ea9565b906000526020600020906005020160040154166000146112505784818154811061123057611230612ea9565b9060005260206000209060050201600201548261124d9190612ed5565b91505b6001016111e4565b50801580159061127557506000828152600a602052604090205415155b156112d4576000828152600a6020526040812054600580548590811061129d5761129d612ea9565b906000526020600020906006020160010154836112ba9190612ee8565b6112c49190612eff565b90506112d08185612ed5565b9350505b505b6001016111a7565b6112e6612815565b6112ee61283f565b8060000361130f5760405163162908e360e11b815260040160405180910390fd5b600560008154811061132357611323612ea9565b90600052602060002090600602016002015442106113545760405163559895a360e01b815260040160405180910390fd5b600354611390906001600160a01b037f000000000000000000000000419d0d8bdd9af5e606ae2232ed285aff190e711b81169133911684612863565b60004260056000815481106113a7576113a7612ea9565b9060005260206000209060060201600201546113c39190612f21565b905060006113d18284612ee8565b90506000805b60055481101561144857600581815481106113f4576113f4612ea9565b906000526020600020906006020160050154600003611440576000818152600a60205260409020546001821b9290921791611430908490612ed5565b6000828152600a60205260409020555b6001016113d7565b50336000908152600660209081526040808320815160a0810183528881524281850190815292810187815260608201868152608083018881528454600180820187559589529690972092516005909602909201948555925191840191909155905160028301555160038201805460ff19169115159190911790559051600490910155600b546114d8908590612ed5565b600b55600c546114e9908390612ed5565b600c5533600090815260076020526040902054611507908390612ed5565b336000818152600760209081526040918290209390935580518781524293810193909352820184905260608201839052907fa2e3c0f7de988ae3bbc6bbd90484543ee1f08d1534bb75c6cf1337a7da7d9c519060800160405180910390a2505050610fa760018055565b600061157c81612561565b600554831061159e5760405163162908e360e11b815260040160405180910390fd5b600583815481106115b1576115b1612ea9565b600091825260209091206003600690920201015460ff161561161a5760405162461bcd60e51b815260206004820152601b60248201527f4d696c6573746f6e6520616c726561647920747269676765726564000000000060448201526064015b60405180910390fd5b81801561164b57506005838154811061163557611635612ea9565b9060005260206000209060060201600501546000145b156116e157426005848154811061166457611664612ea9565b906000526020600020906006020160050181905550827f9e636185da326992ff9f34ddf29e5373fe1891d8a95409625ac5228b9cba7378600585815481106116ae576116ae612ea9565b906000526020600020906006020160000154426040516116d8929190918252602082015260400190565b60405180910390a25b6001600584815481106116f6576116f6612ea9565b906000526020600020906006020160030160006101000a81548160ff021916908315150217905550426005848154811061173257611732612ea9565b906000526020600020906006020160040181905550600f54830361175f5761175b836001612ed5565b600f555b60115460ff166117a0576011805460ff191660011790556040517fa27d966b6927fa787f5d772151a349be295f020fc0f5ca20b6015bb17f6c321e90600090a15b827f9c7b2c20873cfc7ad90f08eec0d0b1705e688bfb2861270384e820f44e97cd64600585815481106117d5576117d5612ea9565b906000526020600020906006020160000154426040516117ff929190918252602082015260400190565b60405180910390a2505050565b6118476040518060c0016040528060008152602001600081526020016000815260200160001515815260200160008152602001600081525090565b6005828154811061185a5761185a612ea9565b60009182526020918290206040805160c081018252600690930290910180548352600181015493830193909352600283015490820152600382015460ff16151560608201526004820154608082015260059091015460a082015292915050565b60006118c581612561565b6001600160a01b0382166118ec5760405163d92e233d60e01b815260040160405180910390fd5b600380546001600160a01b0319166001600160a01b0384169081179091556040517f97c79b3848e51f57983ac89e4403452655c8d83ceba8199011de63a74f60d1a790600090a25050565b600080516020612f6483398151915261194f81612561565b60005b828111610a21576005818154811061196c5761196c612ea9565b600091825260209091206003600690920201015460ff16611990576119908161290f565b8061199a81612f34565b915050611952565b600080516020612f648339815191526119ba81612561565b610fa7612a3d565b6119ca612815565b6119d261283f565b3360009081526008602052604090205460ff1615611a0357604051636507689f60e01b815260040160405180910390fd5b6005600081548110611a1757611a17612ea9565b906000526020600020906006020160020154421015611a4957604051633376277360e11b815260040160405180910390fd5b60115460ff1615611a6d57604051630327064560e51b815260040160405180910390fd5b3360009081526006602052604081208190815b8154811015611bce57818181548110611a9b57611a9b612ea9565b600091825260209091206003600590920201015460ff16611bc6576000828281548110611aca57611aca612ea9565b90600052602060002090600502016001015442611ae79190612f21565b9050600454811115611af857506004545b6000611b096301e133806064612ee8565b826008868681548110611b1e57611b1e612ea9565b906000526020600020906005020160000154611b3a9190612ee8565b611b449190612ee8565b611b4e9190612eff565b9050838381548110611b6257611b62612ea9565b90600052602060002090600502016000015486611b7f9190612ed5565b9550611b8b8186612ed5565b94506001848481548110611ba157611ba1612ea9565b60009182526020909120600590910201600301805460ff191691151591909117905550505b600101611a80565b50336000908152600860205260409020805460ff191660011790558215611c885782600b54611bfd9190612f21565b600b556000611c0c8385612ed5565b600354909150611c4a906001600160a01b037f000000000000000000000000419d0d8bdd9af5e606ae2232ed285aff190e711b811691163384612863565b604080518281526020810185905233917fffe903c0abe6b2dbb2f3474ef43d7a3c1fca49e5a774453423ca8e1952aabffa91015b60405180910390a2505b505050610f8560018055565b6000918252602082815260408084206001600160a01b0393909316845291905290205460ff1690565b6003546040516370a0823160e01b81526001600160a01b0391821660048201526000917f000000000000000000000000419d0d8bdd9af5e606ae2232ed285aff190e711b16906370a08231906024015b602060405180830381865afa158015611d2a573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d4e9190612e90565b905090565b60066020528160005260406000208181548110611d6f57600080fd5b6000918252602090912060059091020180546001820154600283015460038401546004909401549295509093509160ff169085565b611dac61283f565b7fd96ba01d6560c2ab35f2940dd8d70c5f5fe06236c72674237120515918198fb0611dd681612561565b615460600d54611de69190612ed5565b421015611e0657604051637bb7b97d60e11b815260040160405180910390fd5b6000611e10610a74565b601081905542600d8190556040519192507f945c1c4e99aa89f648fbfe3df471b916f719e16d960fcec0737d4d56bd69683891611e5591848252602082015260400190565b60405180910390a1611e668161256b565b5050565b6000611e7581612561565b81600003611e965760405163162908e360e11b815260040160405180910390fd5b636955b8ff821015611ebb5760405163064e567360e51b815260040160405180910390fd5b60048290556040518281527f6f90eab8034fc5abf7cd2e26176224b00e353ab38bdea6ebb0af5c58d974a46c9060200160405180910390a15050565b600080516020612f64833981519152611f0f81612561565b6011805460ff191660011790556040517fa27d966b6927fa787f5d772151a349be295f020fc0f5ca20b6015bb17f6c321e90600090a150565b6005546000908103611f5a5750600090565b6005600081548110611f6e57611f6e612ea9565b906000526020600020906006020160020154905090565b600082815260208190526040902060010154611fa081612561565b610c8f83836127aa565b600554606090819081908067ffffffffffffffff811115611fcd57611fcd612f4d565b604051908082528060200260200182016040528015611ff6578160200160208202803683370190505b5093508067ffffffffffffffff81111561201257612012612f4d565b60405190808252806020026020018201604052801561203b578160200160208202803683370190505b5092508067ffffffffffffffff81111561205757612057612f4d565b604051908082528060200260200182016040528015612080578160200160208202803683370190505b50915060005b8181101561217157600581815481106120a1576120a1612ea9565b906000526020600020906006020160030160009054906101000a900460ff168582815181106120d2576120d2612ea9565b602002602001019015159081151581525050600581815481106120f7576120f7612ea9565b90600052602060002090600602016005015484828151811061211b5761211b612ea9565b6020026020010181815250506005818154811061213a5761213a612ea9565b90600052602060002090600602016004015483828151811061215e5761215e612ea9565b6020908102919091010152600101612086565b5050909192565b612180612815565b61218861283f565b3360009081526008602052604090205460ff16156121b957604051636507689f60e01b815260040160405180910390fd5b600060056000815481106121cf576121cf612ea9565b6000918252602082206002600690920201015442101591506001905b600554811015612234576005818154811061220857612208612ea9565b600091825260209091206003600690920201015460ff1661222c5760009150612234565b6001016121eb565b5080158015612241575081155b1561225f57604051633376277360e11b815260040160405180910390fd5b336000908152600660205260408120815b81548110156123165781818154811061228b5761228b612ea9565b600091825260209091206003600590920201015460ff1661230e578181815481106122b8576122b8612ea9565b906000526020600020906005020160000154836122d59190612ed5565b925060018282815481106122eb576122eb612ea9565b60009182526020909120600590910201600301805460ff19169115159190911790555b600101612270565b50816000036123385760405163ce7731bd60e01b815260040160405180910390fd5b336000908152600860205260409020805460ff19166001179055600b54612360908390612f21565b600b5560035461239e906001600160a01b037f000000000000000000000000419d0d8bdd9af5e606ae2232ed285aff190e711b811691163385612863565b604080518381526000602082015233917fffe903c0abe6b2dbb2f3474ef43d7a3c1fca49e5a774453423ca8e1952aabffa9101611c7e565b600354604051636eb1769f60e11b81526001600160a01b0391821660048201523060248201526000917f000000000000000000000000419d0d8bdd9af5e606ae2232ed285aff190e711b169063dd62ed3e90604401611d0d565b600f54601054600554600090819081908510156124a4576005600f548154811061245c5761245c612ea9565b9060005260206000209060060201600001549250600e546000146124a457600e546124879042612f21565b915062093a808210156124a4576124a18262093a80612f21565b90505b9091929394565b6124df6040518060a00160405280600081526020016000815260200160008152602001600015158152602001600081525090565b6001600160a01b038316600090815260066020526040902080548390811061250957612509612ea9565b60009182526020918290206040805160a081018252600590930290910180548352600181015493830193909352600283015490820152600382015460ff16151560608201526004909101546080820152905092915050565b610fa78133612a7a565b60008060005b60055481101561267c576005818154811061258e5761258e612ea9565b906000526020600020906006020160000154841061266f5780925060019150600581815481106125c0576125c0612ea9565b90600052602060002090600602016005015460000361266a5742600582815481106125ed576125ed612ea9565b906000526020600020906006020160050181905550807f9e636185da326992ff9f34ddf29e5373fe1891d8a95409625ac5228b9cba73786005838154811061263757612637612ea9565b90600052602060002090600602016000015442604051612661929190918252602082015260400190565b60405180910390a25b612674565b61267c565b600101612571565b5080156126cb57600e546000036126925742600e555b62093a80600e546126a39190612ed5565b42106126c6576126b282612ab3565b6126bd826001612ed5565b600f556000600e555b6126d1565b6000600e555b600f546040805185815260208101929092524282820152517f8bd43f2e7fe173e0cf0d4de31c3f51093e9cf54de11151f2554ccb91939586879181900360600190a1505050565b60006127248383611c94565b6127a2576000838152602081815260408083206001600160a01b03861684529091529020805460ff1916600117905561275a3390565b6001600160a01b0316826001600160a01b0316847f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a450600161099b565b50600061099b565b60006127b68383611c94565b156127a2576000838152602081815260408083206001600160a01b0386168085529252808320805460ff1916905551339286917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a450600161099b565b60026001540361283857604051633ee5aeb560e01b815260040160405180910390fd5b6002600155565b60025460ff1615610f855760405163d93c066560e01b815260040160405180910390fd5b604080516001600160a01b0385811660248301528416604482015260648082018490528251808303909101815260849091019091526020810180516001600160e01b03166323b872dd60e01b179052610c8f908590612c1e565b6128c5612c8f565b6002805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b600554811061291b5750565b6005818154811061292e5761292e612ea9565b600091825260209091206003600690920201015460ff161561294d5750565b60016005828154811061296257612962612ea9565b906000526020600020906006020160030160006101000a81548160ff021916908315150217905550426005828154811061299e5761299e612ea9565b60009182526020909120600460069092020101556011805460ff191660019081179091556129cd908290612ed5565b600f81905550807f9c7b2c20873cfc7ad90f08eec0d0b1705e688bfb2861270384e820f44e97cd6460058381548110612a0857612a08612ea9565b90600052602060002090600602016000015442604051612a32929190918252602082015260400190565b60405180910390a250565b612a4561283f565b6002805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586128f23390565b612a848282611c94565b611e665760405163e2517d3f60e01b81526001600160a01b038216600482015260248101839052604401611611565b60005b818111158015612ac7575060055481105b15612bda5760058181548110612adf57612adf612ea9565b600091825260209091206003600690920201015460ff16612bc857600160058281548110612b0f57612b0f612ea9565b906000526020600020906006020160030160006101000a81548160ff0219169083151502179055504260058281548110612b4b57612b4b612ea9565b906000526020600020906006020160040181905550807f9c7b2c20873cfc7ad90f08eec0d0b1705e688bfb2861270384e820f44e97cd6460058381548110612b9557612b95612ea9565b90600052602060002090600602016000015442604051612bbf929190918252602082015260400190565b60405180910390a25b80612bd281612f34565b915050612ab6565b5060115460ff16610fa7576011805460ff191660011790556040517fa27d966b6927fa787f5d772151a349be295f020fc0f5ca20b6015bb17f6c321e90600090a150565b600080602060008451602086016000885af180612c41576040513d6000823e3d81fd5b50506000513d91508115612c59578060011415612c66565b6001600160a01b0384163b155b15610c8f57604051635274afe760e01b81526001600160a01b0385166004820152602401611611565b60025460ff16610f8557604051638dfc202b60e01b815260040160405180910390fd5b600060208284031215612cc457600080fd5b81356001600160e01b031981168114610d0657600080fd5b600060208284031215612cee57600080fd5b5035919050565b80356001600160a01b0381168114610aff57600080fd5b600060208284031215612d1e57600080fd5b610d0682612cf5565b60008060408385031215612d3a57600080fd5b82359150612d4a60208401612cf5565b90509250929050565b600080600060608486031215612d6857600080fd5b612d7184612cf5565b95602085013595506040909401359392505050565b60008060408385031215612d9957600080fd5b8235915060208301358015158114612db057600080fd5b809150509250929050565b60008060408385031215612dce57600080fd5b612dd783612cf5565b946020939093013593505050565b600081518084526020840193506020830160005b82811015612e17578151865260209586019590910190600101612df9565b5093949350505050565b6060808252845190820181905260009060208601906080840190835b81811015612e5d5783511515835260209384019390920191600101612e3d565b50508381036020850152612e718187612de5565b9150508281036040840152612e868185612de5565b9695505050505050565b600060208284031215612ea257600080fd5b5051919050565b634e487b7160e01b600052603260045260246000fd5b634e487b7160e01b600052601160045260246000fd5b8082018082111561099b5761099b612ebf565b808202811582820484141761099b5761099b612ebf565b600082612f1c57634e487b7160e01b600052601260045260246000fd5b500490565b8181038181111561099b5761099b612ebf565b600060018201612f4657612f46612ebf565b5060010190565b634e487b7160e01b600052604160045260246000fdfe97667070c54ef182b0f5858b034beac1b6f3089aa2d3188bb1e8929f4fa9b929a2646970667358221220ee72277ce615d4eb617576b4ee126d64bc7af51b9ebb4a08de0e8da0013876ae64736f6c634300081e0033

Verified Source Code Full Match

Compiler: v0.8.30+commit.73712a01 EVM: paris Optimization: Yes (200 runs)
AccessControl.sol 209 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/AccessControl.sol)

pragma solidity ^0.8.20;

import {IAccessControl} from "./IAccessControl.sol";
import {Context} from "../utils/Context.sol";
import {ERC165} from "../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:
 *
 * ```solidity
 * 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}:
 *
 * ```solidity
 * 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. We recommend using {AccessControlDefaultAdminRules}
 * to enforce additional security measures for this role.
 */
abstract contract AccessControl is Context, IAccessControl, ERC165 {
    struct RoleData {
        mapping(address account => bool) hasRole;
        bytes32 adminRole;
    }

    mapping(bytes32 role => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with an {AccessControlUnauthorizedAccount} error including the required role.
     */
    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 returns (bool) {
        return _roles[role].hasRole[account];
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `_msgSender()`
     * is missing `role`. Overriding this function changes the behavior of the {onlyRole} modifier.
     */
    function _checkRole(bytes32 role) internal view virtual {
        _checkRole(role, _msgSender());
    }

    /**
     * @dev Reverts with an {AccessControlUnauthorizedAccount} error if `account`
     * is missing `role`.
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert AccessControlUnauthorizedAccount(account, role);
        }
    }

    /**
     * @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 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 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 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 `callerConfirmation`.
     *
     * May emit a {RoleRevoked} event.
     */
    function renounceRole(bytes32 role, address callerConfirmation) public virtual {
        if (callerConfirmation != _msgSender()) {
            revert AccessControlBadConfirmation();
        }

        _revokeRole(role, callerConfirmation);
    }

    /**
     * @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 Attempts to grant `role` to `account` and returns a boolean indicating if `role` was granted.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleGranted} event.
     */
    function _grantRole(bytes32 role, address account) internal virtual returns (bool) {
        if (!hasRole(role, account)) {
            _roles[role].hasRole[account] = true;
            emit RoleGranted(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Attempts to revoke `role` from `account` and returns a boolean indicating if `role` was revoked.
     *
     * Internal function without access restriction.
     *
     * May emit a {RoleRevoked} event.
     */
    function _revokeRole(bytes32 role, address account) internal virtual returns (bool) {
        if (hasRole(role, account)) {
            _roles[role].hasRole[account] = false;
            emit RoleRevoked(role, account, _msgSender());
            return true;
        } else {
            return false;
        }
    }
}
IAccessControl.sol 98 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (access/IAccessControl.sol)

pragma solidity ^0.8.20;

/**
 * @dev External interface of AccessControl declared to support ERC-165 detection.
 */
interface IAccessControl {
    /**
     * @dev The `account` is missing a role.
     */
    error AccessControlUnauthorizedAccount(address account, bytes32 neededRole);

    /**
     * @dev The caller of a function is not the expected one.
     *
     * NOTE: Don't confuse with {AccessControlUnauthorizedAccount}.
     */
    error AccessControlBadConfirmation();

    /**
     * @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 to signal this.
     */
    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. This account bears the admin role (for the granted role).
     * Expected in cases where the role was granted using the internal {AccessControl-_grantRole}.
     */
    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 `callerConfirmation`.
     */
    function renounceRole(bytes32 role, address callerConfirmation) external;
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/IERC1363.sol)

pragma solidity ^0.8.20;

import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";

/**
 * @title IERC1363
 * @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
 *
 * Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
 * after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
 */
interface IERC1363 is IERC20, IERC165 {
    /*
     * Note: the ERC-165 identifier for this interface is 0xb0202a11.
     * 0xb0202a11 ===
     *   bytes4(keccak256('transferAndCall(address,uint256)')) ^
     *   bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
     *   bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256)')) ^
     *   bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
     */

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from the caller's account to `to`
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
     * and then calls {IERC1363Receiver-onTransferReceived} on `to`.
     * @param from The address which you want to send tokens from.
     * @param to The address which you want to transfer to.
     * @param value The amount of tokens to be transferred.
     * @param data Additional data with no specified format, sent in call to `to`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value) external returns (bool);

    /**
     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the
     * caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
     * @param spender The address which will spend the funds.
     * @param value The amount of tokens to be spent.
     * @param data Additional data with no specified format, sent in call to `spender`.
     * @return A boolean value indicating whether the operation succeeded unless throwing.
     */
    function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "../utils/introspection/IERC165.sol";
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../token/ERC20/IERC20.sol";
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-20 standard as defined in the ERC.
 */
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 value of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns the value of tokens owned by `account`.
     */
    function balanceOf(address account) external view returns (uint256);

    /**
     * @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);

    /**
     * @dev Moves a `value` amount of tokens from `from` to `to` using the
     * allowance mechanism. `value` 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 value) external returns (bool);
}
SafeERC20.sol 212 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.20;

import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC-20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    /**
     * @dev An operation with an ERC-20 token failed.
     */
    error SafeERC20FailedOperation(address token);

    /**
     * @dev Indicates a failed `decreaseAllowance` request.
     */
    error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);

    /**
     * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     */
    function safeTransfer(IERC20 token, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
     * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
     */
    function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
        _callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
    }

    /**
     * @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
     */
    function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
        return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, value)));
    }

    /**
     * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
        uint256 oldAllowance = token.allowance(address(this), spender);
        forceApprove(token, spender, oldAllowance + value);
    }

    /**
     * @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
     * value, non-reverting calls are assumed to be successful.
     *
     * IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
     * smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
     * this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
     * that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
     */
    function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
        unchecked {
            uint256 currentAllowance = token.allowance(address(this), spender);
            if (currentAllowance < requestedDecrease) {
                revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
            }
            forceApprove(token, spender, currentAllowance - requestedDecrease);
        }
    }

    /**
     * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
     * non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
     * to be set to zero before setting it to a non-zero value, such as USDT.
     *
     * NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
     * only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
     * set here.
     */
    function forceApprove(IERC20 token, address spender, uint256 value) internal {
        bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));

        if (!_callOptionalReturnBool(token, approvalCall)) {
            _callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
            _callOptionalReturn(token, approvalCall);
        }
    }

    /**
     * @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            safeTransfer(token, to, value);
        } else if (!token.transferAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
     * has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * Reverts if the returned value is other than `true`.
     */
    function transferFromAndCallRelaxed(
        IERC1363 token,
        address from,
        address to,
        uint256 value,
        bytes memory data
    ) internal {
        if (to.code.length == 0) {
            safeTransferFrom(token, from, to, value);
        } else if (!token.transferFromAndCall(from, to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
     * code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
     * targeting contracts.
     *
     * NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
     * Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
     * once without retrying, and relies on the returned value to be true.
     *
     * Reverts if the returned value is other than `true`.
     */
    function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
        if (to.code.length == 0) {
            forceApprove(token, to, value);
        } else if (!token.approveAndCall(to, value, data)) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            // bubble errors
            if iszero(success) {
                let ptr := mload(0x40)
                returndatacopy(ptr, 0, returndatasize())
                revert(ptr, returndatasize())
            }
            returnSize := returndatasize()
            returnValue := mload(0)
        }

        if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
            revert SafeERC20FailedOperation(address(token));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     *
     * This is a variant of {_callOptionalReturn} that silently catches all reverts and returns a bool instead.
     */
    function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
        bool success;
        uint256 returnSize;
        uint256 returnValue;
        assembly ("memory-safe") {
            success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
            returnSize := returndatasize()
            returnValue := mload(0)
        }
        return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
    }
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)

pragma solidity ^0.8.20;

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

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

    function _contextSuffixLength() internal view virtual returns (uint256) {
        return 0;
    }
}
ERC165.sol 27 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/ERC165.sol)

pragma solidity ^0.8.20;

import {IERC165} from "./IERC165.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC-165 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);
 * }
 * ```
 */
abstract contract ERC165 is IERC165 {
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
        return interfaceId == type(IERC165).interfaceId;
    }
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/introspection/IERC165.sol)

pragma solidity ^0.8.20;

/**
 * @dev Interface of the ERC-165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[ERC].
 *
 * 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[ERC 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);
}
Pausable.sol 112 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/Pausable.sol)

pragma solidity ^0.8.20;

import {Context} from "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    bool private _paused;

    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    /**
     * @dev The operation failed because the contract is paused.
     */
    error EnforcedPause();

    /**
     * @dev The operation failed because the contract is not paused.
     */
    error ExpectedPause();

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        _requireNotPaused();
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        _requirePaused();
        _;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Throws if the contract is paused.
     */
    function _requireNotPaused() internal view virtual {
        if (paused()) {
            revert EnforcedPause();
        }
    }

    /**
     * @dev Throws if the contract is not paused.
     */
    function _requirePaused() internal view virtual {
        if (!paused()) {
            revert ExpectedPause();
        }
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}
ReentrancyGuard.sol 87 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/ReentrancyGuard.sol)

pragma solidity ^0.8.20;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If EIP-1153 (transient storage) is available on the chain you're deploying at,
 * consider using {ReentrancyGuardTransient} instead.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant NOT_ENTERED = 1;
    uint256 private constant ENTERED = 2;

    uint256 private _status;

    /**
     * @dev Unauthorized reentrant call.
     */
    error ReentrancyGuardReentrantCall();

    constructor() {
        _status = NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        _nonReentrantBefore();
        _;
        _nonReentrantAfter();
    }

    function _nonReentrantBefore() private {
        // On the first call to nonReentrant, _status will be NOT_ENTERED
        if (_status == ENTERED) {
            revert ReentrancyGuardReentrantCall();
        }

        // Any calls to nonReentrant after this point will fail
        _status = ENTERED;
    }

    function _nonReentrantAfter() private {
        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = NOT_ENTERED;
    }

    /**
     * @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
     * `nonReentrant` function in the call stack.
     */
    function _reentrancyGuardEntered() internal view returns (bool) {
        return _status == ENTERED;
    }
}
FUNGiveaway.sol 1019 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30; 

import "./interfaces/IFUNGiveaway.sol";
import "@openzeppelin/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";

/**
 * @title IFUNOracle
 * @author SolidityDevNL - Devon Martens
 * @notice Interface for the FUN Oracle contract
 */
interface IFUNOracle {
    function getPriceInUSDT(uint256 tokenAmount) external view returns (uint256 usdAmount);
}

/**
 * @title FUN Token Giveaway Contract
 * @author @SolidityDevNL
 * @notice A contract for locking FUN tokens with time-weighted rewards based on price milestones
 * @dev Implements a giveaway system where rewards are distributed based on FUN/USDT price targets
 * @dev Anti-abuse: Users can only get rewards for milestones not yet hit when they lock tokens
 */
contract FUNGiveaway is IFUNGiveaway, AccessControl, ReentrancyGuard, Pausable {
    using SafeERC20 for IERC20;

    // =============================================================
    //                      CONSTRACT VARIABLES
    // =============================================================

    // Role definitions
    bytes32 public constant OPERATOR_ROLE = keccak256("OPERATOR_ROLE");
    bytes32 public constant PRICE_UPDATER_ROLE = keccak256("PRICE_UPDATER_ROLE");

    // Price milestone structure

    // Contract state variables
    IERC20 public immutable funToken;
    IFUNOracle public funOracle;
    address public treasuryWallet; // Central wallet holding reward funds
    uint256 public maxInterestDuration;
    
    // Constants
    uint256 public constant ANNUAL_INTEREST_RATE = 8; // 8% annual interest
    uint256 public constant PRICE_HOLD_DURATION = 7 days; // Price must hold for 7 days
    uint256 public constant PRICE_CHECK_INTERVAL = 6 hours; // Price checks every 6 hours
    uint256 public constant SECONDS_PER_YEAR = 365 days;
    uint256 public constant PRICE_DECIMALS = 6; // USDT has 6 decimals
    uint256 public constant FUN_UNIT = 1 * 10**8; // 1 FUN token for price calculation
    
    // Price milestones
    PriceMilestone[] public priceMilestones;
    
    // User data
    mapping(address => UserLock[]) public userLocks;
    mapping(address => uint256) public userTotalWeight;
    mapping(address => bool) public hasWithdrawn;
    
    mapping(address => mapping(uint256 => bool)) public hasClaimed; // user => milestone => claimed

    mapping(uint256 => uint256) private milestoneEligibleWeight; // milestone index => total eligible weight
    
    // Global state
    uint256 private totalLockedTokens;
    uint256 public totalWeight;
    uint256 public lastPriceCheckTime;
    uint256 public lastValidPriceTime; // When current price level was first achieved
    uint256 public currentPriceLevel; // Index of current price level achieved
    uint256 private currentPrice; // Current FUN/USDT price from oracle
    bool public distributionActive;

    
    // =============================================================
    //                          CONSTRUCTOR
    // =============================================================

     /**
     * @notice Initializes the FUN giveaway contract with required addresses and settings
     * @dev Sets up roles, initializes price milestones, and configures contract state
     * @param _funToken Address of the FUN token contract
     * @param _funOracle Address of the FUN oracle contract (can be FUNPriceAdapter)
     * @param _treasuryWallet Address of the treasury wallet holding reward funds
     * @param _admin Address to be granted DEFAULT_ADMIN_ROLE
     * @param _maxInterestDuration Maximum duration for interest calculation in seconds
     * @custom:requirements All addresses must be non-zero, _maxInterestDuration > 0 and <= 2 years
     * @custom:effects Grants admin roles, initializes price milestones, sets deployment time
     */
    constructor(
        address _funToken,
        address _funOracle,
        address _treasuryWallet,
        address _admin,
        uint256 _maxInterestDuration
    ) {
        if (_funToken == address(0) || _funOracle == address(0) || 
            _treasuryWallet == address(0) || _admin == address(0)) {
            revert ZeroAddress();
        }
        if (_maxInterestDuration == 0) revert InvalidAmount();
        
        funToken = IERC20(_funToken);
        funOracle = IFUNOracle(_funOracle);
        treasuryWallet = _treasuryWallet;
        lastPriceCheckTime = block.timestamp;
        maxInterestDuration = _maxInterestDuration;
        
        // Set up roles
        _grantRole(DEFAULT_ADMIN_ROLE, _admin);
        _grantRole(OPERATOR_ROLE, _admin);
        _grantRole(PRICE_UPDATER_ROLE, _admin);
        
        // Initialize price milestones
        _initializePriceMilestones();
    }


    // =============================================================
    //                      EXTERNAL FUNCTIONS
    // =============================================================

    /**
     * @notice Locks FUN tokens in the contract for participation in milestone rewards
     * @dev Transfers tokens to treasury, calculates time-weighted rewards, tracks milestone eligibility
     * @param _amount Amount of FUN tokens to lock (must be > 0)
     * @custom:requirements Contract not paused, amount > 0, deadline not reached, sufficient allowance
     * @custom:effects Transfers tokens to treasury, creates user lock entry, updates contract totals
     * @custom:emits TokensLocked
     * @custom:modifiers nonReentrant, whenNotPaused
     */
    function lockTokens(uint256 _amount) external nonReentrant whenNotPaused  {
        if (_amount == 0) revert InvalidAmount();
        if (block.timestamp >= priceMilestones[0].deadline) revert DeadlineExceeded();

        // Transfer tokens from user to treasury wallet for locking
        funToken.safeTransferFrom(msg.sender, treasuryWallet, _amount);
        
        // Calculate weight based on time until deadline
        uint256 timeRemaining = priceMilestones[0].deadline - block.timestamp;
        uint256 weight = _amount * timeRemaining;
        

        uint256 eligibleMilestones = 0;
        for (uint256 i = 0; i < priceMilestones.length; i++) {
            if (priceMilestones[i].priceFirstHit == 0) { // Price threshold not yet reached
                eligibleMilestones |= (1 << i); // Set bit for this milestone
                milestoneEligibleWeight[i] =  milestoneEligibleWeight[i] + weight; // Add to milestone-specific weight
            }
        }
        
        // Create new lock entry
        userLocks[msg.sender].push(UserLock({
            amount: _amount,
            lockTime: block.timestamp,
            weight: weight,
            withdrawn: false,
            eligibleMilestones: eligibleMilestones 
        }));
        
        // Update totals
        totalLockedTokens = totalLockedTokens + _amount;
        totalWeight = totalWeight + weight;
        userTotalWeight[msg.sender] =  userTotalWeight[msg.sender] + weight;
        
        emit TokensLocked(msg.sender, _amount, block.timestamp, weight, eligibleMilestones);
    }

     /**
     * @notice Withdraws original locked tokens (principal only) when conditions are met
     * @dev Only allowed if all milestones triggered OR December 31st deadline passed
     * @custom:requirements Not already withdrawn, (all milestones triggered OR deadline passed)
     * @custom:effects Marks locks as withdrawn, transfers principal from treasury to user
     * @custom:emits TokensWithdrawn
     * @custom:modifiers nonReentrant, whenNotPaused
     */
    function withdrawPrincipal() external nonReentrant whenNotPaused {
        if (hasWithdrawn[msg.sender]) revert AlreadyWithdrawn();
        
        bool deadlinePassed = block.timestamp >= priceMilestones[0].deadline; // Dec 31, 2025
        
        // Check if all milestones have been triggered (max milestone reached)
        bool allMilestonesTriggered = true;
        for (uint256 i = 0; i < priceMilestones.length; i++) {
            if (!priceMilestones[i].triggered) {
                allMilestonesTriggered = false;
                break;
            }
        }
        
        // Can only withdraw if either:
        // 1. All milestones have been triggered (program completed successfully), OR
        // 2. December 31st deadline has passed (program ended by time limit)
        if (!allMilestonesTriggered && !deadlinePassed) {
            revert DeadlineNotReached(); // Program still active, must wait
        }
        
        uint256 totalAmount = 0;
        UserLock[] storage locks = userLocks[msg.sender];
        
        for (uint256 i = 0; i < locks.length; i++) {
            if (!locks[i].withdrawn) {
                totalAmount = totalAmount + locks[i].amount;
                locks[i].withdrawn = true;
            }
        }
        
        if (totalAmount == 0) revert NoLockedTokens();
        
        hasWithdrawn[msg.sender] = true;
        totalLockedTokens = totalLockedTokens - totalAmount;
        
        // Transfer principal back from treasury
        funToken.safeTransferFrom(treasuryWallet, msg.sender, totalAmount);
        
       
     emit TokensWithdrawn(msg.sender, totalAmount, 0);
    }

    /**
     * @notice Claims available rewards for triggered milestones the user is eligible for
     * @dev Calculates and distributes rewards based on milestone-specific eligible weight
     * @custom:requirements Distribution active, user has eligible locks for triggered milestones
     * @custom:effects Marks milestones as claimed, transfers rewards from treasury to user
     * @custom:emits RewardsDistributed
     * @custom:modifiers nonReentrant, whenNotPaused
     */
    function claimRewards() external nonReentrant whenNotPaused {
        if (!distributionActive) revert DistributionNotActive();
        
        uint256 totalRewards = 0;
        UserLock[] storage locks = userLocks[msg.sender];
        
        // Calculate rewards for all triggered milestones
        for (uint256 i = 0; i < currentPriceLevel; i++) {
            if (priceMilestones[i].triggered) {
                if (hasClaimed[msg.sender][i]) {
                    continue; // Skip already claimed milestones
                }
                
                // Calculate user's eligible weight for this specific milestone
                uint256 userEligibleWeight = 0;
                for (uint256 j = 0; j < locks.length; j++) {
                    if ((locks[j].eligibleMilestones & (1 << i)) != 0) {
                        userEligibleWeight = userEligibleWeight + locks[j].weight;
                    }
                }
                
                // Calculate user's share for this milestone
                if (userEligibleWeight != 0 && milestoneEligibleWeight[i] != 0) {
                    uint256 userShare = (userEligibleWeight * priceMilestones[i].rewardAmount) / milestoneEligibleWeight[i];
                    totalRewards = totalRewards + userShare;
                    
                    hasClaimed[msg.sender][i] = true;
                }
            }
        }
        
        if (totalRewards != 0) {
            // Transfer rewards from treasury wallet to user
            funToken.safeTransferFrom(treasuryWallet, msg.sender, totalRewards);
            emit RewardsDistributed(msg.sender, totalRewards);
        }
    }

    /**
     * @notice Withdraws locked tokens with 8% annual interest if milestones not met by deadline
     * @dev Only available after deadline if no milestones were triggered (distribution inactive)
     * @custom:requirements Not already withdrawn, deadline passed, distribution not active
     * @custom:effects Calculates interest, transfers principal + interest from treasury
     * @custom:emits TokensWithdrawn
     * @custom:modifiers  nonReentrant, whenNotPaused
     */
    function withdrawWithInterest() external nonReentrant whenNotPaused {
        if (hasWithdrawn[msg.sender]) revert AlreadyWithdrawn();
        if (block.timestamp < priceMilestones[0].deadline) revert DeadlineNotReached();
        
        if (distributionActive) {
            revert DistributionActive();
        }
        
        uint256 totalAmount = 0;
        uint256 totalInterest = 0;
        
        UserLock[] storage locks = userLocks[msg.sender];
        
        for (uint256 i = 0; i < locks.length; i++) {
        if (!locks[i].withdrawn) {
            uint256 lockDuration = block.timestamp - locks[i].lockTime;
            
            // Cap the duration BEFORE interest calculation
            if (lockDuration > maxInterestDuration) {
                lockDuration = maxInterestDuration;
            }
            
            uint256 interest = (locks[i].amount * ANNUAL_INTEREST_RATE * lockDuration) / 
                            (100 * SECONDS_PER_YEAR);
            
            totalAmount = totalAmount + locks[i].amount;
            totalInterest = totalInterest + interest;
            locks[i].withdrawn = true;
        }
    }
        hasWithdrawn[msg.sender] = true;
        
        if (totalAmount != 0) {
            totalLockedTokens = totalLockedTokens  - totalAmount;
            uint256 totalPayout = totalAmount + totalInterest;
            
            // Transfer principal + interest from treasury
            funToken.safeTransferFrom(treasuryWallet, msg.sender, totalPayout);
            
            emit TokensWithdrawn(msg.sender, totalPayout, totalInterest);
        }
    }

    /**
     * @notice Performs automated price check and milestone evaluation (called every 6 hours)
     * @dev Gets price from oracle, updates milestones, checks trigger conditions
     * @custom:requirements Minimum time passed since last check, valid oracle response
     * @custom:effects Updates current price, checks milestone triggers, updates price tracking
     * @custom:emits PriceUpdated, potentially PriceMilestoneTriggered
     * @custom:modifiers whenNotPaused, onlyRole(PRICE_UPDATER_ROLE)
     */
        function performScheduledPriceCheck() external whenNotPaused onlyRole(PRICE_UPDATER_ROLE) {
        // Ensure minimum time has passed since last check
        if (block.timestamp < lastPriceCheckTime + PRICE_CHECK_INTERVAL) {
            revert PriceCheckTooEarly();
        }
        
        // Get current price from oracle
        uint256 newPrice = getCurrentPriceFromOracle();
        
        // Update stored price and check time
        currentPrice = newPrice;
        lastPriceCheckTime = block.timestamp;
        
        emit PriceUpdated(newPrice, block.timestamp);
        
        // Check if we can trigger any milestones
        _checkAndTriggerMilestones(newPrice);
    }

     /**
     * @notice Pauses all contract operations except view functions
     * @dev Emergency function to halt contract operations
     * @custom:modifiers onlyRole(OPERATOR_ROLE)
     * @custom:effects Sets contract to paused state
     */
      function pause() external onlyRole(OPERATOR_ROLE) {
        _pause();
    }

    /**
     * @notice Unpauses contract operations
     * @dev Resumes normal contract functionality
     * @custom:modifiers onlyRole(OPERATOR_ROLE) 
     * @custom:effects Removes paused state
     */
        function unpause() external onlyRole(OPERATOR_ROLE) {
        _unpause();
    }

    /**
     * @notice Manually triggers a specific price milestone (emergency function)
     * @dev Bypasses normal price checking mechanism for emergency situations
     * @param _level Milestone level to trigger (must be valid index)
     * @custom:requirements Valid milestone level, milestone not already triggered
     * @custom:effects Triggers milestone, activates distribution if needed
     * @custom:emits PriceMilestoneTriggered, potentially DistributionActivated
     * @custom:modifiers onlyRole(OPERATOR_ROLE)
     */
    function manuallyTriggerMilestone(uint256 _level) external onlyRole(OPERATOR_ROLE) {
          // Auto-trigger all previous milestones up to the target level
            // This ensures users don't lose rewards from skipped milestones
            for (uint256 i = 0; i <= _level; i++) {
                if (!priceMilestones[i].triggered) {
                    _triggerPriceMilestone(i);
                }
            }
    }

    /**
     * @notice Manually unlocks a specific milestone with optional price tracking
     * @dev Admin function to unlock milestones outside normal price mechanism
     * @param _milestoneIndex Index of milestone to unlock (must be valid)
     * @param _setFirstHitTime Whether to set the priceFirstHit timestamp for tracking
     * @custom:requirements Valid milestone index, milestone not already triggered
     * @custom:effects Sets milestone as triggered, optionally sets first hit time, activates distribution
     * @custom:emits PriceMilestoneTriggered, potentially PriceThresholdFirstHit, DistributionActivated
     * @custom:modifiers onlyRole(DEFAULT_ADMIN_ROLE)
     */
    function manuallyUnlockMilestone(uint256 _milestoneIndex, bool _setFirstHitTime) 
        external 
        onlyRole(DEFAULT_ADMIN_ROLE) 
    {
        if (_milestoneIndex >= priceMilestones.length) revert InvalidAmount();
        if (priceMilestones[_milestoneIndex].triggered) revert("Milestone already triggered");
        
        // Set priceFirstHit if requested and not already set
        if (_setFirstHitTime && priceMilestones[_milestoneIndex].priceFirstHit == 0) {
            priceMilestones[_milestoneIndex].priceFirstHit = block.timestamp;
            emit PriceThresholdFirstHit(_milestoneIndex, priceMilestones[_milestoneIndex].priceThreshold, block.timestamp);
        }
        
        // Trigger the milestone
        priceMilestones[_milestoneIndex].triggered = true;
        priceMilestones[_milestoneIndex].triggeredAt = block.timestamp;
        
        // Update current price level if this milestone is sequential
        if (_milestoneIndex == currentPriceLevel) {
            currentPriceLevel = _milestoneIndex + 1;
        }
        
        // Activate distribution if not already active
        if (!distributionActive) {
            distributionActive = true;
            emit DistributionActivated();
        }
        
        emit PriceMilestoneTriggered(_milestoneIndex, priceMilestones[_milestoneIndex].priceThreshold, block.timestamp);
    }

     /**
     * @notice Updates the treasury wallet address
     * @dev Changes where locked tokens are stored and rewards are distributed from
     * @param _newTreasury New treasury wallet address (must be non-zero)
     * @custom:requirements Address not zero
     * @custom:effects Updates treasury wallet address
     * @custom:emits TreasuryWalletUpdated
     * @custom:modifiers onlyRole(DEFAULT_ADMIN_ROLE)
     */
    function updateTreasuryWallet(address _newTreasury) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_newTreasury == address(0)) revert ZeroAddress();
        treasuryWallet = _newTreasury;
        emit TreasuryWalletUpdated(_newTreasury);
    }

    /**
     * @notice Updates the oracle contract address
     * @dev Changes the price feed source for FUN/USDT price data
     * @param _newOracle New oracle contract address (must be non-zero)
     * @custom:requirements Address not zero, new oracle must implement IFUNOracle
     * @custom:effects Updates oracle contract reference
     * @custom:emits OracleUpdated
     * @custom:modifiers onlyRole(DEFAULT_ADMIN_ROLE)
     */
    function updateOracle(address _newOracle) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_newOracle == address(0)) revert ZeroAddress();
        funOracle = IFUNOracle(_newOracle);
        emit OracleUpdated(_newOracle);
    }

    /**
     * @notice Emergency price check that bypasses time restrictions
     * @dev Allows immediate price check with optional manual price override
     * @param _manualPrice Optional manual price override (0 to use oracle)
     * @custom:effects Updates current price, performs milestone checks
     * @custom:emits PriceUpdated, potentially milestone events
     * @custom:modifiers onlyRole(OPERATOR_ROLE)
     */
    function emergencyPriceCheck(uint256 _manualPrice) external onlyRole(OPERATOR_ROLE) {
        uint256 priceToUse;
        
        if (_manualPrice != 0) {
            // Use manual price override
            priceToUse = _manualPrice;
        } else {
            // Get from oracle
            priceToUse = getCurrentPriceFromOracle();
        }
        
        currentPrice = priceToUse;
        lastPriceCheckTime = block.timestamp;
        
        emit PriceUpdated(priceToUse, block.timestamp);
        _checkAndTriggerMilestones(priceToUse);
    }

    /**
     * @notice Updates the maximum duration for interest calculation
     * @dev Changes the cap on interest accrual period
     * @param _newMaxDuration New maximum duration in seconds
     */
    function updateMaxInterestDuration(uint256 _newMaxDuration) external onlyRole(DEFAULT_ADMIN_ROLE) {
        if (_newMaxDuration == 0) revert InvalidAmount();
        if (_newMaxDuration < 1767225599) revert DurationLessThanDeadline();
        
        maxInterestDuration = _newMaxDuration;
        
        emit MaxInterestDurationUpdated(_newMaxDuration);
    }

    /**
     * @notice Emergency function to activate distribution manually
     * @dev Bypasses normal milestone triggering to enable reward distribution
     * @custom:effects Sets distributionActive to true
     * @custom:emits DistributionActivated
     * @custom:modifiers onlyRole(OPERATOR_ROLE)
     */
    function activateDistribution() external onlyRole(OPERATOR_ROLE) {
        distributionActive = true;
        emit DistributionActivated();
    }

    /**
     * @notice Emergency function to deactivate distribution
     * @dev Disables reward distribution (emergency use only)
     * @custom:effects Sets distributionActive to false
     * @custom:emits DistributionDeactivated
     * @custom:modifiers onlyRole(OPERATOR_ROLE)
     */
    function deactivateDistribution() external onlyRole(OPERATOR_ROLE) {
        distributionActive = false;
        emit DistributionDeactivated();
    }


    // =============================================================
    //                      EXTERNAL VIEW FUNCTIONS
    // =============================================================

    /**
     * @notice Checks if user has claimed rewards for a specific milestone
     * @dev Returns claim status for milestone-specific rewards
     * @param _user User address to check
     * @param _milestoneIndex Milestone index to check
     * @return claimed Whether user has claimed rewards for this milestone
     */
      function hasClaimedMilestone(address _user, uint256 _milestoneIndex) external view returns (bool  claimed) {
        return hasClaimed[_user][_milestoneIndex];
    }

    /**
     * @notice Gets unclaimed rewards for a user across all triggered milestones
     * @dev Calculates total available rewards that haven't been claimed yet
     * @param _user User address to check
     * @return _totalRewards Total unclaimed reward amount in FUN tokens
     */
    function getUnclaimedRewards(address _user) external view returns (uint256 _totalRewards) {
        UserLock[] storage locks = userLocks[_user];
        if (locks.length == 0) return 0;
        
        uint256 totalRewards = 0;
        
        for (uint256 i = 0; i < currentPriceLevel; i++) {
            if (priceMilestones[i].triggered && !hasClaimed[_user][i]) {
                // Calculate user's eligible weight for this specific milestone
                uint256 userEligibleWeight = 0;
                for (uint256 j = 0; j < locks.length; j++) {
                    if ((locks[j].eligibleMilestones & (1 << i)) != 0) {
                        userEligibleWeight = userEligibleWeight + locks[j].weight;
                    }
                }
                
                // Calculate user's share for unclaimed milestone
                if (userEligibleWeight != 0 && milestoneEligibleWeight[i] != 0) {
                    uint256 userShare = (userEligibleWeight * priceMilestones[i].rewardAmount) / milestoneEligibleWeight[i];
                    totalRewards = totalRewards + userShare;
                }
            }
        }
        
        return totalRewards;
    }

    /**
     * @notice Gets comprehensive milestone status overview for monitoring
     * @dev Returns arrays of milestone trigger status and timing information
     * @return triggered Array indicating which milestones are triggered
     * @return firstHitTimes Array of priceFirstHit timestamps
     * @return triggeredTimes Array of triggeredAt timestamps
     */
    function getMilestoneStatusOverview() 
        external 
        view 
        returns (
            bool[] memory triggered,
            uint256[] memory firstHitTimes,
            uint256[] memory triggeredTimes
        ) 
    {
        uint256 length = priceMilestones.length;
        triggered = new bool[](length);
        firstHitTimes = new uint256[](length);
        triggeredTimes = new uint256[](length);
        
        for (uint256 i = 0; i < length; i++) {
            triggered[i] = priceMilestones[i].triggered;
            firstHitTimes[i] = priceMilestones[i].priceFirstHit;
            triggeredTimes[i] = priceMilestones[i].triggeredAt;
        }
    }

    /**
     * @notice Gets the current deadline for all milestones
     * @dev Returns the unified deadline timestamp for the program
     * @return deadline Current deadline timestamp (0 if no milestones exist)
     */
    function getCurrentDeadline() external view returns (uint256 deadline) {
        return priceMilestones.length != 0 ? priceMilestones[0].deadline : 0;
    }

    /**
     * @notice Gets user's total locked amount across all locks
     * @dev Sums all non-withdrawn lock amounts for the user
     * @param _user User address to check
     * @return _total Total amount locked by user in FUN tokens
     */
    function getUserTotalLocked(address _user) external view returns (uint256 _total) {
        uint256 total = 0;
        UserLock[] storage locks = userLocks[_user];
        
        for (uint256 i = 0; i < locks.length; i++) {
            if (!locks[i].withdrawn) {
                total = total +  locks[i].amount;
            }
        }
        
        return total;
    }

    /**
     * @notice Gets user's total number of lock entries
     * @dev Returns count of lock transactions made by user
     * @param _user User address to check
     * @return lockCount Number of lock entries for user
     */
       function getUserLockCount(address _user) external view returns (uint256 lockCount) {
        return userLocks[_user].length;
    }

    /**
     * @notice Gets specific lock information for a user
     * @dev Returns detailed information about a specific user lock
     * @param _user User address
     * @param _index Lock index (must be valid)
     * @return lock UserLock struct containing lock details
     */
    function getUserLock(address _user, uint256 _index) external view returns (UserLock memory lock) {
        return userLocks[_user][_index];
    }


    /**
     * @notice Gets the last stored/updated price from the contract
     * @dev Returns cached price from last successful oracle update
     * @return _currentPrice Last updated price in USDT (6 decimals)
     */
    function getCurrentPrice() external view returns (uint256 _currentPrice) {
        return currentPrice;
    }


    /**
     * @notice Gets time remaining until next scheduled price check is allowed
     * @dev Calculates seconds until PRICE_CHECK_INTERVAL has passed
     * @return timeRemaining Seconds until next price check (0 if check is allowed now)
     */
    function getTimeUntilNextPriceCheck() external view returns (uint256 timeRemaining) {
        uint256 nextCheckTime = lastPriceCheckTime + PRICE_CHECK_INTERVAL;
        if (block.timestamp >= nextCheckTime) {
            return 0;
        }
        return nextCheckTime - block.timestamp;
    }

    /**
     * @notice Gets comprehensive price status and milestone progress information
     * @dev Returns detailed information about current price tracking state
     * @return priceLevel Current price level being tracked
     * @return currentPriceValue Current stored price value
     * @return targetPrice Target price for current level
     * @return timeHeld How long current price has been held
     * @return timeRemaining Time remaining to trigger milestone
     */
    function getPriceStatus() external view returns (
        uint256 priceLevel,
        uint256 currentPriceValue,
        uint256 targetPrice,
        uint256 timeHeld,
        uint256 timeRemaining
    ) {
        priceLevel = currentPriceLevel;
        currentPriceValue = currentPrice;
        
        if (currentPriceLevel < priceMilestones.length) {
            targetPrice = priceMilestones[currentPriceLevel].priceThreshold;
            
            if (lastValidPriceTime != 0) {
                timeHeld = block.timestamp - lastValidPriceTime;
                if (timeHeld < PRICE_HOLD_DURATION) {
                    timeRemaining = PRICE_HOLD_DURATION - timeHeld;
                }
            }
        }
    }

    /**
     * @notice Gets estimated total rewards for a user based on current milestone status
     * @dev Calculates potential rewards from all triggered milestones user is eligible for
     * @param _user User address to check
     * @return _totalRewards Estimated total reward amount in FUN tokens
     */
    function getEstimatedRewards(address _user) external view returns (uint256 _totalRewards) {
        UserLock[] storage locks = userLocks[_user];
        if (locks.length == 0) return 0;
        
        uint256 totalRewards = 0;
        
        for (uint256 i = 0; i < currentPriceLevel; i++) {
            if (priceMilestones[i].triggered) {
                uint256 userEligibleWeight = 0;
                for (uint256 j = 0; j < locks.length; j++) {
                    if ((locks[j].eligibleMilestones & (1 << i)) != 0) {
                        userEligibleWeight = userEligibleWeight + locks[j].weight;
                    }
                }
                
                if (userEligibleWeight != 0 && milestoneEligibleWeight[i] != 0) {
                    uint256 userShare = (userEligibleWeight * priceMilestones[i].rewardAmount) / milestoneEligibleWeight[i];
                    totalRewards = totalRewards + userShare;
                }
            }
        }
        
        return totalRewards;
    }

    /**
     * @notice Gets the total number of price milestones configured
     * @dev Returns length of priceMilestones array
     * @return milestoneCount Total number of milestones
     */
    function getPriceMilestoneCount() external view returns (uint256 milestoneCount) {
        return priceMilestones.length;
    }

       /**
     * @notice Gets detailed information about a specific price milestone
     * @dev Returns complete milestone configuration and status
     * @param _index Milestone index (must be valid)
     * @return milestone PriceMilestone struct containing all milestone data
     */
    function getPriceMilestone(uint256 _index) external view returns (PriceMilestone memory milestone) {
        return priceMilestones[_index];
    }
    
    /**
     * @notice Gets total eligible weight for a specific milestone
     * @dev Returns sum of weights from users eligible for the milestone
     * @param _milestoneIndex Milestone index to check
     * @return eligibleWeight Total eligible weight for reward distribution
     */
    function getMilestoneEligibleWeight(uint256 _milestoneIndex) external view returns (uint256 eligibleWeight) {
        return milestoneEligibleWeight[_milestoneIndex];
    }

    /**
     * @notice Checks if a user's specific lock is eligible for a milestone
     * @dev Verifies milestone eligibility using bitmap stored in user lock
     * @param _user User address
     * @param _lockIndex Lock index (must be valid)
     * @param _milestoneIndex Milestone index to check
     * @return isEligible Whether the lock is eligible for the milestone
     */
    function isLockEligibleForMilestone(address _user, uint256 _lockIndex, uint256 _milestoneIndex) external view returns (bool isEligible) {
        if (_lockIndex >= userLocks[_user].length) return false;
        return (userLocks[_user][_lockIndex].eligibleMilestones & (1 << _milestoneIndex)) != 0;
    }
 

      /**
     * @notice Gets current FUN token balance of the treasury wallet
     * @dev Returns available balance for token operations
     * @return balance Treasury wallet FUN token balance
     */
    function getTreasuryBalance() external view returns (uint256 balance) {
        return funToken.balanceOf(treasuryWallet);
    }

        /**
     * @notice Gets treasury wallet's token allowance to this contract
     * @dev Returns amount treasury has approved for contract operations
     * @return allowance Treasury allowance amount for this contract
     */
    function getTreasuryAllowance() external view returns (uint256 allowance) {
        return funToken.allowance(treasuryWallet, address(this));
    }

    
    /**
     * @notice Gets total amount of FUN tokens locked by all users
     * @dev Returns sum of all active user locks
     * @return _totalLockedTokens Total locked token amount across all users
     */
    function getContractBalance() external view returns (uint256 _totalLockedTokens) {
        return totalLockedTokens;  
    }

       // =============================================================
    //                      PUBLIC VIEW FUNCTIONS
    // =============================================================

    /**
     * @notice Gets current FUN/USDT price from oracle (public version)
     * @dev Public function that queries oracle for current price
     * @return _priceInUSDT Current price in USDT (6 decimals)
     * @custom:reverts OraclePriceError if oracle call fails
     */
    function getCurrentPriceFromOracle() public view returns (uint256 _priceInUSDT) {
        try funOracle.getPriceInUSDT(FUN_UNIT) returns (uint256 priceInUSDT) {
            return priceInUSDT;
        } catch {
            revert OraclePriceError();
        }
    }

    // =============================================================
    //                      PRIVATE FUNCTIONS
    // =============================================================

    /**
     * @notice Initializes the price milestones with predefined values
     * @dev Sets up 8 milestones from $0.03 to $0.10 with 10M FUN rewards each
     * @custom:effects Populates priceMilestones array with milestone configurations
     */
    function _initializePriceMilestones() private {
        uint256 deadline = 1769877226; // 31 Jan 2026
        
        // Updated milestones starting from $0.01
        priceMilestones.push(PriceMilestone({
            priceThreshold: 10000, // $0.01
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
        
        priceMilestones.push(PriceMilestone({
            priceThreshold: 20000, // $0.02
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
        
        priceMilestones.push(PriceMilestone({
            priceThreshold: 30000, // $0.03
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
        
        priceMilestones.push(PriceMilestone({
            priceThreshold: 40000, // $0.04
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
        
        priceMilestones.push(PriceMilestone({
            priceThreshold: 50000, // $0.05
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
        
        priceMilestones.push(PriceMilestone({
            priceThreshold: 60000, // $0.06
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
        
        priceMilestones.push(PriceMilestone({
            priceThreshold: 70000, // $0.07
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
        
        priceMilestones.push(PriceMilestone({
            priceThreshold: 80000, // $0.08
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
    
        priceMilestones.push(PriceMilestone({
            priceThreshold: 90000, // $0.09
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
        
        priceMilestones.push(PriceMilestone({
            priceThreshold: 100000, // $0.10
            rewardAmount: 9500000 * 10**8, // 9.5M FUN tokens
            deadline: deadline,
            triggered: false,
            triggeredAt: 0,
            priceFirstHit: 0 
        }));
    }

    /**
     * @notice Checks current price against milestones and triggers if conditions met
     * @dev Evaluates price hold duration and triggers eligible milestones
     * @param _currentPrice Current FUN/USDT price from oracle
     * @custom:effects May trigger milestones, update price tracking, activate distribution
     * @custom:emits PriceThresholdFirstHit, PriceMilestoneTriggered, DistributionActivated, PriceCheckPerformed
     */
        function _checkAndTriggerMilestones(uint256 _currentPrice) private {
        // Find the highest milestone that current price satisfies
        uint256 highestSatisfiedLevel = 0;
        bool foundSatisfiedLevel = false;
        
        for (uint256 i = 0; i < priceMilestones.length; i++) {
            if (_currentPrice >= priceMilestones[i].priceThreshold) {
                highestSatisfiedLevel = i;
                foundSatisfiedLevel = true;
                
                // Mark price as first hit if not already marked
                if (priceMilestones[i].priceFirstHit == 0) {
                    priceMilestones[i].priceFirstHit = block.timestamp;
                    emit PriceThresholdFirstHit(i, priceMilestones[i].priceThreshold, block.timestamp);
                }
            } else {
                break; // Since milestones are in ascending order, no need to check higher ones
            }
        }
        
        if (foundSatisfiedLevel) {
            // Price meets or exceeds at least one milestone threshold
            if (lastValidPriceTime == 0) {
                // First time reaching this price level
                lastValidPriceTime = block.timestamp;
            }
            
            // Check if price has been held for required duration
            if (block.timestamp >= lastValidPriceTime + PRICE_HOLD_DURATION) {
                // Trigger all milestones up to the highest satisfied level
                _triggerMilestonesUpTo(highestSatisfiedLevel);
                
                // Update current price level to the next untriggered milestone
                currentPriceLevel = highestSatisfiedLevel + 1;
                lastValidPriceTime = 0; // Reset for next level
            }
        } else {
            // Price doesn't satisfy any milestones, reset timer
            lastValidPriceTime = 0;
        }
        
        emit PriceCheckPerformed(_currentPrice, currentPriceLevel, block.timestamp);
    }

    /**
     * @notice Triggers all milestones up to and including specified level
     * @dev Marks milestones as triggered and activates distribution
     * @param _maxLevel Maximum milestone level to trigger (inclusive)
     * @custom:effects Sets milestones as triggered, activates distribution if needed
     * @custom:emits PriceMilestoneTriggered, DistributionActivated
     */
    function _triggerMilestonesUpTo(uint256 _maxLevel) private {
        for (uint256 i = 0; i <= _maxLevel && i < priceMilestones.length; i++) {
            if (!priceMilestones[i].triggered) {
                priceMilestones[i].triggered = true;
                priceMilestones[i].triggeredAt = block.timestamp;
                emit PriceMilestoneTriggered(i, priceMilestones[i].priceThreshold, block.timestamp);
            }
        }
        
        // Activate distribution if any milestone is triggered
        if (!distributionActive) {
            distributionActive = true;
            emit DistributionActivated();
        }
    }

    /**
     * @notice Triggers a specific price milestone and enables distribution
     * @dev Internal function to handle individual milestone triggering
     * @param _level Milestone level to trigger
     * @custom:effects Marks milestone as triggered, updates price level, activates distribution
     * @custom:emits PriceMilestoneTriggered
     */
    function _triggerPriceMilestone(uint256 _level) private {
        if (_level >= priceMilestones.length) return;
        if (priceMilestones[_level].triggered) return;
        
        priceMilestones[_level].triggered = true;
        priceMilestones[_level].triggeredAt = block.timestamp;
        
        // Activate distribution for this level and all previous levels
        distributionActive = true;
        currentPriceLevel = _level + 1;
        
        emit PriceMilestoneTriggered(_level, priceMilestones[_level].priceThreshold, block.timestamp);
    }

}
IFUNGiveaway.sol 430 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.30;

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

/**
 * @title IFUNGiveaway
 * @author SolidityDevNL - Devon Martens
 * @notice Interface for FUN Token Giveaway Contract with time-weighted rewards based on price milestones
 * @dev Implements a giveaway system where rewards are distributed based on FUN/USDT price targets
 * @dev Anti-abuse: Users can only get rewards for milestones not yet hit when they lock tokens
 */
interface IFUNGiveaway {
    
    // =============================================================
    //                           STRUCTS
    // =============================================================

    /**
     * @notice Price milestone structure for tracking reward thresholds
     * @param priceThreshold Price in 6 decimals (e.g., 0.03 = 30000)
     * @param rewardAmount Amount of FUN tokens to distribute
     * @param deadline Deadline timestamp for the milestone
     * @param triggered Whether this milestone has been triggered
     * @param triggeredAt When the milestone was triggered
     * @param priceFirstHit When the price threshold was first reached
     */
    struct PriceMilestone {
        uint256 priceThreshold;
        uint256 rewardAmount;
        uint256 deadline;
        bool triggered;
        uint256 triggeredAt;
        uint256 priceFirstHit;
    }

    /**
     * @notice User lock information for tracking individual stakes
     * @param amount Amount of tokens locked
     * @param lockTime When tokens were locked
     * @param weight Calculated weight (amount * time)
     * @param withdrawn Whether tokens have been withdrawn
     * @param eligibleMilestones Bitmap of milestones this lock is eligible for
     */
    struct UserLock {
        uint256 amount;
        uint256 lockTime;
        uint256 weight;
        bool withdrawn;
        uint256 eligibleMilestones;
    }

    // =============================================================
    //                           EVENTS
    // =============================================================

    /// @notice Emitted when the max interest duration is changed
    event MaxInterestDurationUpdated(uint256 newDuration);

    /// @notice Emitted when user locks FUN tokens
    event TokensLocked(address indexed user, uint256 amount, uint256 lockTime, uint256 weight, uint256 eligibleMilestones);
    
    /// @notice Emitted when user withdraws tokens (principal and/or interest)
    event TokensWithdrawn(address indexed user, uint256 amount, uint256 interest);
    
    /// @notice Emitted when rewards are distributed to a user
    event RewardsDistributed(address indexed user, uint256 amount);
    
    /// @notice Emitted when a price milestone is triggered
    event PriceMilestoneTriggered(uint256 indexed level, uint256 price, uint256 timestamp);
    
    /// @notice Emitted when price threshold is first hit (before 7-day hold requirement)
    event PriceThresholdFirstHit(uint256 indexed level, uint256 price, uint256 timestamp);
    
    /// @notice Emitted when price is updated from oracle
    event PriceUpdated(uint256 newPrice, uint256 timestamp);
    
    /// @notice Emitted during scheduled price checks
    event PriceCheckPerformed(uint256 price, uint256 level, uint256 timestamp);
    
    /// @notice Emitted when oracle address is updated
    event OracleUpdated(address indexed newOracle);
    
    /// @notice Emitted when treasury wallet address is updated
    event TreasuryWalletUpdated(address indexed newTreasury);
    
    /// @notice Emitted when distribution is activated
    event DistributionActivated();
    
    /// @notice Emitted when distribution is deactivated
    event DistributionDeactivated();
    
    /// @notice Emitted during emergency withdrawals by admin
    event EmergencyWithdrawal(address indexed admin, uint256 amount);
    
    /// @notice Emitted when deadline is updated
    event DeadlineUpdated(uint256 newDeadline);

    // =============================================================
    //                           ERRORS
    // =============================================================

    /// @notice Thrown when an invalid deadline is entered
    error DurationLessThanDeadline();

    /// @notice Thrown when an invalid amount is provided
    error InvalidAmount();
    
    /// @notice Thrown when an invalid oracle address is provided
    error InvalidOracle();
    
    /// @notice Thrown when user has already withdrawn
    error AlreadyWithdrawn();
    
    /// @notice Thrown when distribution is not active
    error DistributionNotActive();
    
    /// @notice Thrown when price requirement is not met
    error PriceNotMet();
    
    /// @notice Thrown when deadline has not been reached
    error DeadlineNotReached();

    /// @notice Thrown when deadline has been exceeded
    error DeadlineExceeded();
    
    /// @notice Thrown when user has no locked tokens
    error NoLockedTokens();
    
    /// @notice Thrown when token transfer fails
    error TransferFailed();
    
    /// @notice Thrown when unauthorized access is attempted
    error UnauthorizedAccess();
    
    /// @notice Thrown when invalid role operation is attempted
    error InvalidRole();
    
    /// @notice Thrown when zero address is provided
    error ZeroAddress();
    
    /// @notice Thrown when price check is attempted too early
    error PriceCheckTooEarly();
    
    /// @notice Thrown when oracle price query fails
    error OraclePriceError();
    
    /// @notice Thrown when invalid deadline is provided
    error InvalidDeadline();

    /// @notice Thrown when a user cannot withdraw intrest because distribution is active
    error DistributionActive();

    // =============================================================
    //                         CONSTANTS
    // =============================================================

    /// @notice Annual interest rate (8%)
    function ANNUAL_INTEREST_RATE() external view returns (uint256);
    
    /// @notice Duration price must be held (7 days)
    function PRICE_HOLD_DURATION() external view returns (uint256);
    
    /// @notice Interval between price checks (6 hours)
    function PRICE_CHECK_INTERVAL() external view returns (uint256);
    
    /// @notice Seconds per year constant
    function SECONDS_PER_YEAR() external view returns (uint256);
    
    /// @notice Price decimals (6 for USDT)
    function PRICE_DECIMALS() external view returns (uint256);
    
    /// @notice One FUN token unit (18 decimals)
    function FUN_UNIT() external view returns (uint256);
    
    /// @notice Operator role identifier
    function OPERATOR_ROLE() external view returns (bytes32);
    
    /// @notice Price updater role identifier
    function PRICE_UPDATER_ROLE() external view returns (bytes32);

    // =============================================================
    //                    CORE FUNCTIONALITY
    // =============================================================

    /**
     * @notice Lock FUN tokens in the contract
     * @param _amount Amount of FUN tokens to lock
     */
    function lockTokens(uint256 _amount) external;

    /**
     * @notice Claim rewards for triggered milestones
     */
    function claimRewards() external;

    /**
     * @notice Withdraw original locked tokens (principal only)
     */
    function withdrawPrincipal() external;

    /**
     * @notice Withdraw locked tokens with interest if milestones not met by deadline
     */
    function withdrawWithInterest() external;

    // =============================================================
    //                    PRICE MANAGEMENT
    // =============================================================

    /**
     * @notice Automated price check function to be called every 6 hours
     */
    function performScheduledPriceCheck() external;

    /**
     * @notice Emergency price check (bypasses time restriction)
     * @param _manualPrice Optional manual price override
     */
    function emergencyPriceCheck(uint256 _manualPrice) external;

    /**
     * @notice Manually trigger a price milestone (emergency function)
     * @param _level Milestone level to trigger
     */
    function manuallyTriggerMilestone(uint256 _level) external;

    // =============================================================
    //                    ADMIN FUNCTIONS
    // =============================================================

    /**
     * @notice Updates the maximum duration for interest calculation
     * @dev Changes the cap on interest accrual period
     * @param _newMaxDuration New maximum duration in seconds 
     */
    function updateMaxInterestDuration(uint256 _newMaxDuration) external;

    /**
     * @notice Update treasury wallet address
     * @param _newTreasury New treasury wallet address
     */
    function updateTreasuryWallet(address _newTreasury) external;

    /**
     * @notice Update oracle address
     * @param _newOracle New oracle address
     */
    function updateOracle(address _newOracle) external;

    /**
     * @notice Pause the contract
     */
    function pause() external;

    /**
     * @notice Unpause the contract
     */
    function unpause() external;

    /**
     * @notice Emergency function to activate distribution manually
     */
    function activateDistribution() external;

    /**
     * @notice Emergency function to deactivate distribution
     */
    function deactivateDistribution() external;

    // =============================================================
    //                      VIEW FUNCTIONS
    // =============================================================

    /**
     * @notice Check if user has claimed rewards for a specific milestone
     * @param _user User address
     * @param _milestoneIndex Milestone index
     * @return Whether user has claimed rewards for this milestone
     */
    function hasClaimedMilestone(address _user, uint256 _milestoneIndex) external view returns (bool);

    /**
     * @notice Get unclaimed rewards for a user
     * @param _user User address
     * @return Unclaimed reward amount
     */
    function getUnclaimedRewards(address _user) external view returns (uint256);

    /**
     * @notice Get the current deadline for all milestones
     * @return Current deadline timestamp
     */
    function getCurrentDeadline() external view returns (uint256);

    /**
     * @notice Get user's total locked amount across all locks
     * @param _user User address
     * @return Total amount locked by user
     */
    function getUserTotalLocked(address _user) external view returns (uint256);

    /**
     * @notice Get user's lock count
     * @param _user User address
     * @return Number of lock entries for user
     */
    function getUserLockCount(address _user) external view returns (uint256);

    /**
     * @notice Get specific lock information for a user
     * @param _user User address
     * @param _index Lock index
     * @return Lock information
     */
    function getUserLock(address _user, uint256 _index) external view returns (UserLock memory);

    /**
     * @notice Get current FUN/USDT price from oracle
     * @return Current price in USDT (6 decimals)
     */
    function getCurrentPriceFromOracle() external view returns (uint256);

    /**
     * @notice Get stored current price (last updated price)
     * @return Last updated price in USDT (6 decimals)
     */
    function getCurrentPrice() external view returns (uint256);

    /**
     * @notice Get time remaining until next allowed price check
     * @return Seconds until next price check is allowed
     */
    function getTimeUntilNextPriceCheck() external view returns (uint256);

    /**
     * @notice Get detailed price status information
     * @return priceLevel Current price level being tracked
     * @return currentPriceValue Current stored price
     * @return targetPrice Target price for current level
     * @return timeHeld How long current price has been held
     * @return timeRemaining Time remaining to trigger milestone
     */
    function getPriceStatus() external view returns (
        uint256 priceLevel,
        uint256 currentPriceValue,
        uint256 targetPrice,
        uint256 timeHeld,
        uint256 timeRemaining
    );

    /**
     * @notice Get estimated rewards for a user
     * @param _user User address
     * @return Estimated reward amount
     */
    function getEstimatedRewards(address _user) external view returns (uint256);

    /**
     * @notice Get number of price milestones
     * @return Number of milestones
     */
    function getPriceMilestoneCount() external view returns (uint256);

    /**
     * @notice Get price milestone information
     * @param _index Milestone index
     * @return Milestone information
     */
    function getPriceMilestone(uint256 _index) external view returns (PriceMilestone memory);

    /**
     * @notice Get eligible weight for a specific milestone
     * @param _milestoneIndex Milestone index
     * @return Total eligible weight for the milestone
     */
    function getMilestoneEligibleWeight(uint256 _milestoneIndex) external view returns (uint256);

    /**
     * @notice Check if a user's lock is eligible for a specific milestone
     * @param _user User address
     * @param _lockIndex Lock index
     * @param _milestoneIndex Milestone index
     * @return Whether the lock is eligible for the milestone
     */
    function isLockEligibleForMilestone(address _user, uint256 _lockIndex, uint256 _milestoneIndex) external view returns (bool);

    /**
     * @notice Get treasury wallet balance
     * @return Current FUN token balance of treasury wallet
     */
    function getTreasuryBalance() external view returns (uint256);

    /**
     * @notice Get treasury allowance to this contract
     * @return Amount treasury wallet has approved for this contract to spend
     */
    function getTreasuryAllowance() external view returns (uint256);

    /**
     * @notice Get total locked tokens by all users
     * @return Total amount of FUN tokens locked by users
     */
    function getContractBalance() external view returns (uint256);

    // =============================================================
    //                    STATE VARIABLES
    // =============================================================

    /// @notice The FUN token contract
    function funToken() external view returns (IERC20);
    
    /// @notice Treasury wallet holding reward funds
    function treasuryWallet() external view returns (address);
    
    /// @notice Total weight of all locks
    function totalWeight() external view returns (uint256);
    
    /// @notice Last price check timestamp
    function lastPriceCheckTime() external view returns (uint256);
    
    /// @notice When current price level was first achieved
    function lastValidPriceTime() external view returns (uint256);
    
    /// @notice Index of current price level achieved
    function currentPriceLevel() external view returns (uint256);
    
    /// @notice Whether distribution is currently active
    function distributionActive() external view returns (bool);
}

Read Contract

ANNUAL_INTEREST_RATE 0xb6783393 → uint256
DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
FUN_UNIT 0x37819187 → uint256
OPERATOR_ROLE 0xf5b541a6 → bytes32
PRICE_CHECK_INTERVAL 0xf9724c70 → uint256
PRICE_DECIMALS 0xf1a640f8 → uint256
PRICE_HOLD_DURATION 0xe1525fbb → uint256
PRICE_UPDATER_ROLE 0xfb8d8101 → bytes32
SECONDS_PER_YEAR 0xe6a69ab8 → uint256
currentPriceLevel 0xc42a7379 → uint256
distributionActive 0x99fb15d2 → bool
funOracle 0x04d34f64 → address
funToken 0x845380a2 → address
getContractBalance 0x6f9fb98a → uint256
getCurrentDeadline 0xd4631a8a → uint256
getCurrentPrice 0xeb91d37e → uint256
getCurrentPriceFromOracle 0x0b5ab26c → uint256
getEstimatedRewards 0x6db74283 → uint256
getMilestoneEligibleWeight 0x9de70710 → uint256
getMilestoneStatusOverview 0xd62886be → bool[], uint256[], uint256[]
getPriceMilestone 0x78da5728 → tuple
getPriceMilestoneCount 0xf045a2b4 → uint256
getPriceStatus 0xecef6cff → uint256, uint256, uint256, uint256, uint256
getRoleAdmin 0x248a9ca3 → bytes32
getTimeUntilNextPriceCheck 0x5dc99364 → uint256
getTreasuryAllowance 0xe3ce0307 → uint256
getTreasuryBalance 0x9b5655dc → uint256
getUnclaimedRewards 0x69a69e29 → uint256
getUserLock 0xfae7e9c9 → tuple
getUserLockCount 0x9b7d02ad → uint256
getUserTotalLocked 0x22607c61 → uint256
hasClaimed 0xb2931096 → bool
hasClaimedMilestone 0xf87507d7 → bool
hasRole 0x91d14854 → bool
hasWithdrawn 0x5e2c19db → bool
isLockEligibleForMilestone 0x34c8d711 → bool
lastPriceCheckTime 0xb2127487 → uint256
lastValidPriceTime 0xebf886d2 → uint256
maxInterestDuration 0x8a735659 → uint256
paused 0x5c975abb → bool
priceMilestones 0x22ca68fe → uint256, uint256, uint256, bool, uint256, uint256
supportsInterface 0x01ffc9a7 → bool
totalWeight 0x96c82e57 → uint256
treasuryWallet 0x4626402b → address
userLocks 0xaa33fedb → uint256, uint256, uint256, bool, uint256
userTotalWeight 0x19beb249 → uint256

Write Contract 18 functions

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

activateDistribution 0xcae91300
No parameters
claimRewards 0x372500ab
No parameters
deactivateDistribution 0x03b8b911
No parameters
emergencyPriceCheck 0x03142cf0
uint256 _manualPrice
grantRole 0x2f2ff15d
bytes32 role
address account
lockTokens 0x6e27d889
uint256 _amount
manuallyTriggerMilestone 0x838edebf
uint256 _level
manuallyUnlockMilestone 0x70902a45
uint256 _milestoneIndex
bool _setFirstHitTime
pause 0x8456cb59
No parameters
performScheduledPriceCheck 0xb72a3248
No parameters
renounceRole 0x36568abe
bytes32 role
address callerConfirmation
revokeRole 0xd547741f
bytes32 role
address account
unpause 0x3f4ba83a
No parameters
updateMaxInterestDuration 0xc93c5880
uint256 _newMaxDuration
updateOracle 0x1cb44dfc
address _newOracle
updateTreasuryWallet 0x809d458d
address _newTreasury
withdrawPrincipal 0xe1f06f54
No parameters
withdrawWithInterest 0x8bcdfe79
No parameters

Recent Transactions

No transactions found for this address