Forkchoice Ethereum Mainnet

Address Contract Partially Verified

Address 0xc377a8fe7c5F4143C2cf4c9e5040eFb04127ef7C
Balance 0 ETH
Nonce 2
Code Size 23375 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

23375 bytes
0x6080604052600436106101c05760003560e01c806301b75440146101c557806303a3f2ab146101f057806312d7b2c41461021e578063150b7a021461024d5780631a4774c71461027a578063247884a01461029a57806326bfee04146102ba57806337200f96146102dc5780633c423f0b146102fc5780633dc0714b1461031c57806359851e0d1461033157806359f3f952146103515780635bbcefc214610371578063607777951461039157806363a4282c146103c457806368b6e033146103e45780636dee201214610404578063715018a6146104265780637d86e66d1461043b5780637f3c73a91461045b578063883ce8b21461047b5780638da5cb5b1461049b5780638e106865146104b05780639261a0bf146104d05780639be8fc99146104f0578063a61ea93c14610505578063ac9650d814610525578063b02c43d014610545578063b44a272214610576578063ba3296ff1461058b578063c36c1ea5146105a0578063c45a0155146105cf578063cbcb9746146105e4578063ccafa5b4146105f9578063ccc00d491461060e578063d5053e111461063d578063e07974b71461065d578063f2fde38b14610672578063fa25cc2d14610692575b600080fd5b3480156101d157600080fd5b506101da6106b2565b6040516101e791906150ea565b60405180910390f35b3480156101fc57600080fd5b5061021061020b366004614cd7565b6106b8565b6040516101e79291906157e1565b34801561022a57600080fd5b5061023e610239366004614d41565b610765565b6040516101e793929190615734565b34801561025957600080fd5b5061026d61026836600461482a565b610819565b6040516101e79190615186565b34801561028657600080fd5b506101da6102953660046148c3565b610c05565b3480156102a657600080fd5b506101da6102b53660046148ee565b610c30565b3480156102c657600080fd5b506102da6102d5366004614bc5565b610c67565b005b3480156102e857600080fd5b506102da6102f7366004614b63565b610e07565b34801561030857600080fd5b506102da610317366004614bf4565b610e34565b34801561032857600080fd5b506101da61100e565b34801561033d57600080fd5b506101da61034c366004614a3e565b611014565b34801561035d57600080fd5b5061021061036c366004614c85565b611029565b34801561037d57600080fd5b506101da61038c366004614b47565b6110d3565b34801561039d57600080fd5b506103b16103ac366004614a3e565b6111e4565b6040516101e797969594939291906156b9565b3480156103d057600080fd5b506102da6103df366004614b63565b6114db565b3480156103f057600080fd5b506102da6103ff366004614a3e565b611511565b34801561041057600080fd5b506104196115f3565b6040516101e79190614ffc565b34801561043257600080fd5b506102da611602565b34801561044757600080fd5b506101da6104563660046147f2565b61169c565b34801561046757600080fd5b506102da610476366004614b47565b6116bd565b34801561048757600080fd5b506101da6104963660046148c3565b611dd6565b3480156104a757600080fd5b50610419611e02565b3480156104bc57600080fd5b506101da6104cb366004614a56565b611e11565b3480156104dc57600080fd5b506101da6104eb366004614a3e565b611e29565b3480156104fc57600080fd5b506101da611e36565b34801561051157600080fd5b506102da610520366004614b63565b611e47565b610538610533366004614922565b611f08565b6040516101e7919061507f565b34801561055157600080fd5b50610565610560366004614a3e565b612047565b6040516101e7959493929190615043565b34801561058257600080fd5b50610419612095565b34801561059757600080fd5b506104196120a4565b3480156105ac57600080fd5b506105c06105bb366004614a56565b6120c8565b6040516101e793929190615755565b3480156105db57600080fd5b50610419612130565b3480156105f057600080fd5b506101da61213f565b34801561060557600080fd5b506101da612146565b34801561061a57600080fd5b5061062e610629366004614b63565b612152565b6040516101e7939291906157ef565b34801561064957600080fd5b506102da610658366004614a3e565b6126f4565b34801561066957600080fd5b506101da6127b6565b34801561067e57600080fd5b506102da61068d3660046147f2565b6127bc565b34801561069e57600080fd5b506101da6106ad366004614a3e565b6128ad565b60045481565b60008060006107407f0000000000000000000000005f505a62d375239f9af611bfe21579d16f35242b89898989896040516024016106fa9594939291906157b5565b60408051601f19818403018152918152602080830180516001600160e01b03166303a3f2ab60e01b179052815160608101909252602380835290615b20908301396128c4565b9050808060200190518101906107569190614d1e565b92509250509550959350505050565b6000806000806107f07f0000000000000000000000005f505a62d375239f9af611bfe21579d16f35242b8b8b8b8b8b8b6040516024016107aa96959493929190615893565b60408051601f19818403018152918152602080830180516001600160e01b03166304b5ecb160e21b179052815160608101909252602380835290615b20908301396128c4565b9050808060200190518101906108069190614b8f565b9350935093505096509650969350505050565b6001546000906001600160a01b0316331461084f5760405162461bcd60e51b8152600401610846906153c0565b60405180910390fd5b60015460405163133f757160e31b815260009182916001600160a01b03909116906399fbab88906108849089906004016150ea565b6101806040518083038186803b15801561089d57600080fd5b505afa1580156108b1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108d59190614d83565b50505050509650965050505050506040518060a00160405280886001600160a01b03168152602001600065ffffffffffff1681526020018360020b81526020018260020b8152602001600015158152506008600088815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160000160146101000a81548165ffffffffffff021916908365ffffffffffff160217905550604082015181600001601a6101000a81548162ffffff021916908360020b62ffffff160217905550606082015181600001601d6101000a81548162ffffff021916908360020b62ffffff16021790555060808201518160010160006101000a81548160ff021916908315150217905550905050866001600160a01b031660006001600160a01b031687600080516020615b0083398151915260405160405180910390a46001600160a01b0387166000908152600a60205260409020610a5590876129c6565b508315610bf157610280841415610b01576000610a7485870187614b47565b90506000610a81826129d2565b60008181526007602052604090206011015490915060ff1615610af05760008881526008602052604090206001908101805460ff19169091179055610ac7600d896129c6565b50876000805160206159ba8339815191526001604051610ae791906150df565b60405180910390a25b610afa8289612a02565b5050610bf1565b6000610b0f85870187614990565b905060005b8151811015610bee576000610b3b838381518110610b2e57fe5b60200260200101516129d2565b60008a81526008602052604090206001015490915060ff16158015610b71575060008181526007602052604090206011015460ff165b15610bc85760008981526008602052604090206001908101805460ff19169091179055610b9f600d8a6129c6565b50886000805160206159ba8339815191526001604051610bbf91906150df565b60405180910390a25b610be5838381518110610bd757fe5b60200260200101518a612a02565b50600101610b14565b50505b50630a85bd0160e11b979650505050505050565b6001600160a01b0382166000908152600a60205260408120610c279083613002565b90505b92915050565b6001600160a01b0383166000908152600b602090815260408083208584529091528120610c5d9083613002565b90505b9392505050565b6001600160a01b038116610c8d5760405162461bcd60e51b815260040161084690615366565b6001600160a01b038116301415610cb65760405162461bcd60e51b8152600401610846906153de565b6000828152600860205260409020546001600160a01b0316338114610ced5760405162461bcd60e51b8152600401610846906155f4565b600083815260086020908152604080832080546001600160a01b0319166001600160a01b038781169190911790915584168352600a9091529020610d31908461300e565b506001600160a01b0382166000908152600a60205260409020610d5490846129c6565b506001600160a01b038082166000908152600b60208181526040808420888552825280842094871684529181528183208784529052812090610d958361301a565b905060005b81811015610dcf576000610dae8582613002565b9050610dba858261300e565b50610dc584826129c6565b5050600101610d9a565b50846001600160a01b0316846001600160a01b031687600080516020615b0083398151915260405160405180910390a4505050505050565b333014610e265760405162461bcd60e51b815260040161084690615474565b610e308282612a02565b5050565b6001600160a01b038216301415610e5d5760405162461bcd60e51b815260040161084690615456565b600083815260086020908152604091829020825160a08101845281546001600160a01b038116825265ffffffffffff600160a01b820416938201849052600160d01b8104600290810b810b810b95830195909552600160e81b9004840b840b90930b60608401526001015460ff161515608083015215610eef5760405162461bcd60e51b81526004016108469061523a565b80516001600160a01b03163314610f185760405162461bcd60e51b8152600401610846906153a2565b806080015115610f3a5760405162461bcd60e51b8152600401610846906151e0565b80516001600160a01b03166000908152600a60205260409020610f5d908561300e565b50600084815260086020526040808220828155600101805460ff19169055825190516001600160a01b03909116908690600080516020615b00833981519152908490a4600154604051635c46a7ef60e11b81526001600160a01b039091169063b88d4fde90610fd6903090879089908890600401615010565b600060405180830381600087803b158015610ff057600080fd5b505af1158015611004573d6000803e3d6000fd5b5050505050505050565b60055481565b6000611021600283613002565b90505b919050565b60008060006110af7f0000000000000000000000005f505a62d375239f9af611bfe21579d16f35242b888888886040516024016110699493929190615785565b60408051601f19818403018152918152602080830180516001600160e01b0316632cf9fca960e11b179052815160608101909252602380835290615b20908301396128c4565b9050808060200190518101906110c59190614d1e565b925092505094509492505050565b600081608001514210156110f95760405162461bcd60e51b815260040161084690615438565b6000611104836129d2565b60008181526007602052604090206004810154919250906111375760405162461bcd60e51b81526004016108469061541a565b600e810154600160a01b90046001600160601b0316156111695760405162461bcd60e51b815260040161084690615504565b600d81018054600c83018054600091829055925501925061118b60028361300e565b5082156111a5576111a584600001518560c0015185613025565b817f65124e6175aa9904f40735e87e2a37c76e87a609b855287bb4d1aba8257d9763846040516111d591906150ea565b60405180910390a25050919050565b60076020818152600092835260409283902083516101408101855281546001600160a01b0390811682526001808401548216838601526002840154838801526003840154606084015260048401546080840152600584015460a0840152600684015490911660c0830152855160e0818101909752948301805460ff80821615158852949793968896948801959094929392850192610100909204169081111561128957fe5b600181111561129457fe5b81528154620100008104600290810b810b810b602080850191909152600160281b8304820b820b820b604080860191909152600160401b90930460ff9081161515606086015260018601546080860152948201548516151560a0948501529486528151928301909152600a8601805495909401949193928492169081111561131857fe5b600281111561132357fe5b815290546001600160401b0361010082048116602080850191909152600160481b830482166040850152600160881b8304909116606084015260ff600160c81b90920482161515608090930192909252918352600b84015492019116600181111561138a57fe5b600181111561139557fe5b905250600c820154600d830154600e8401546040805160e08101909152600f8601805460ff808216151584529697959694956001600160a01b03851695600160a01b9095046001600160601b0316949093929160208401916101009091041660018111156113ff57fe5b600181111561140a57fe5b81528154620100008104600290810b810b810b6020840152600160281b8204810b810b810b60408085019190915260ff600160401b90930483161515606085015260018501546080850152938101548216151560a0938401528351928301909352601285018054949594929390928492169081111561148557fe5b600281111561149057fe5b815290546001600160401b03610100820481166020840152600160481b820481166040840152600160881b820416606083015260ff600160c81b909104161515608090910152905087565b6000818152600860205260409020546001600160a01b03163314610e265760405162461bcd60e51b815260040161084690615258565b61151961307d565b6001600160a01b031661152a611e02565b6001600160a01b031614611573576040805162461bcd60e51b81526020600482018190526024820152600080516020615a5c833981519152604482015290519081900360640190fd5b60008181526008602052604090206001015460ff166115a45760405162461bcd60e51b81526004016108469061564e565b6000818152600860205260409020600101805460ff191690556115c8600d8261300e565b50806000805160206159ba83398151915260006040516115e891906150df565b60405180910390a250565b6006546001600160a01b031681565b61160a61307d565b6001600160a01b031661161b611e02565b6001600160a01b031614611664576040805162461bcd60e51b81526020600482018190526024820152600080516020615a5c833981519152604482015290519081900360640190fd5b6012546040516000916001600160a01b031690600080516020615a7c833981519152908390a3601280546001600160a01b0319169055565b6001600160a01b0381166000908152600a602052604081206110219061301a565b6116c561307d565b6001600160a01b03166116d6611e02565b6001600160a01b03161461171f576040805162461bcd60e51b81526020600482018190526024820152600080516020615a5c833981519152604482015290519081900360640190fd5b60008160400151116117435760405162461bcd60e51b8152600401610846906152ee565b80606001514211156117675760405162461bcd60e51b815260040161084690615348565b60045442826060015103111561178f5760405162461bcd60e51b815260040161084690615276565b80608001518160600151106117b65760405162461bcd60e51b815260040161084690615294565b600554816060015182608001510311156117e25760405162461bcd60e51b8152600401610846906155b8565b80606001518160800151038160a0015111156118105760405162461bcd60e51b81526004016108469061566c565b60c08101516001600160a01b031661183a5760405162461bcd60e51b8152600401610846906151c2565b6118478160200151613081565b60e08101515115611887578060e001516060015160020b8160e001516040015160020b126118875760405162461bcd60e51b81526004016108469061532a565b8060e0015160800151156118d45760008160e0015160a001511180156118b85750621b13d08160e0015160a0015111155b6118d45760405162461bcd60e51b8152600401610846906153fc565b60006101008201515160028111156118e857fe5b146119cd576000816101000151602001516001600160401b03161161191f5760405162461bcd60e51b815260040161084690615522565b6303c26700816101000151602001516001600160401b031611156119555760405162461bcd60e51b81526004016108469061557c565b806101000151602001516001600160401b0316816101000151604001516001600160401b0316106119985760405162461bcd60e51b815260040161084690615612565b62278d00816101000151606001516001600160401b031611156119cd5760405162461bcd60e51b815260040161084690615492565b60006119d8826129d2565b600081815260076020818152604092839020865181546001600160a01b03199081166001600160a01b039283161783558884015160018085018054841692851692909217909155958901516002840155606089015160038401556080890151600484015560a0890151600584015560c0890151600684018054909216921691909117905560e08701518051938201805460ff191694151594909417808555928101519596509094879486949293839161ff001990911690610100908490811115611a9e57fe5b021790555060408201518154606084015160808501511515600160401b0260ff60401b19600292830b62ffffff908116600160281b0262ffffff60281b1996850b909116620100000264ffffff0000199095169490941794909416929092179290921617825560a083015160018084019190915560c090930151918101805492151560ff199384161790556101008501518051600a860180549295909491938593909216918490811115611b4e57fe5b021790555060208201518154604084015160608501516080909501511515600160c81b0260ff60c81b196001600160401b03968716600160881b02600160881b600160c81b0319938816600160481b02600160481b600160881b03199890961661010002610100600160481b0319909516949094179690961693909317161792909216919091179055610120820151600b8201805460ff191660018381811115611bf457fe5b02179055505050604080840151600c83018054909101905560e084015160c081015160118401805491151560ff1992831617905591810151600f84018054606084015184511515600291820b62ffffff908116600160281b0262ffffff60281b199690930b16620100000264ffffff00001990931692909217939093169290921790931617808355602090910151919061ff001916610100836001811115611c9857fe5b021790555060e08301516080810151600f83018054911515600160401b0260ff60401b1990921691909117905560a0015160108201556101008301515160128201805460ff19166001836002811115611ced57fe5b0217905550610100808401516020810151601284018054604084015160608501516080909501511515600160c81b0260ff60c81b196001600160401b03968716600160881b02600160881b600160c81b0319938816600160481b02600160481b600160881b031998909716909802610100600160481b031990941693909317959095169390931792909216939093171617905560018361012001516001811115611d9357fe5b1415611da357611da3838361315b565b611db783600001513330866040015161323b565b611dc26002836129c6565b50611dd1836040015184613294565b505050565b6001600160a01b0382166000908152600b602090815260408083208484529091528120610c279061301a565b6012546001600160a01b031690565b6000828152600c60205260408120610c279083613002565b6000611021600d83613002565b6000611e42600d61301a565b905090565b600081815260086020908152604091829020825160a08101845281546001600160a01b038116825265ffffffffffff600160a01b82041693820193909352600160d01b8304600290810b810b810b94820194909452600160e81b909204830b830b90920b606082015260019091015460ff161515608080830191909152830151421015611ef75780516001600160a01b03163314611ef75760405162461bcd60e51b8152600401610846906155d6565b611f02838383613349565b50505050565b6060816001600160401b0381118015611f2057600080fd5b50604051908082528060200260200182016040528015611f5457816020015b6060815260200190600190039081611f3f5790505b50905060005b828110156120405760008030868685818110611f7257fe5b9050602002810190611f8491906158bb565b604051611f92929190614fec565b600060405180830381855af49150503d8060008114611fcd576040519150601f19603f3d011682016040523d82523d6000602084013e611fd2565b606091505b50915091508161201e57604481511015611feb57600080fd5b600481019050808060200190518101906120059190614ad0565b60405162461bcd60e51b815260040161084691906151af565b8084848151811061202b57fe5b60209081029190910101525050600101611f5a565b5092915050565b600860205260009081526040902080546001909101546001600160a01b0382169165ffffffffffff600160a01b82041691600160d01b8204600290810b92600160e81b9004900b9060ff1685565b6001546001600160a01b031681565b7f0000000000000000000000005f505a62d375239f9af611bfe21579d16f35242b81565b6000828152600960209081526040808320848452909152902080546001600160a01b0381169163ffffffff600160a01b830416916001600160401b03600160c01b909104811691908214156121285760018101546001600160801b031691505b509250925092565b6000546001600160a01b031681565b62278d0081565b6000611e42600261301a565b600080600080612161866129d2565b90506001866101200151600181111561217657fe5b14156121d6576000858152601160209081526040808320848452909152902080546001600160801b03166121bc5760405162461bcd60e51b815260040161084690615540565b60009350600092506121ce86836134f7565b945050612128565b60008060006121e588856120c8565b9250925092506000816001600160801b0316116122145760405162461bcd60e51b815260040161084690615540565b6000888152600860209081526040808320815160a08101835281546001600160a01b03808216835265ffffffffffff600160a01b83041683870152600160d01b8204600290810b810b810b84870152600160e81b909204820b820b820b606084015260019384015460ff908116151560808501528b885260078088528689208751610220810189528154851660e0808301918252838a01548716610100848101919091529784015461012084015260038401546101408401526004840154610160840152600584015461018084015260068401549096166101a08301528951958601909952918101805480851615158652969a99929891978997929689966101c08a0196909593949386019391909104169081111561232f57fe5b600181111561233a57fe5b81528154620100008104600290810b810b810b602080850191909152600160281b8304820b820b820b604080860191909152600160401b90930460ff9081161515606086015260018601546080860152948201548516151560a0948501529486528151928301909152600a860180549590940194919392849216908111156123be57fe5b60028111156123c957fe5b815290546001600160401b0361010082048116602080850191909152600160481b830482166040850152600160881b8304909116606084015260ff600160c81b90920482161515608090930192909252918352600b84015492019116600181111561243057fe5b600181111561243b57fe5b9052508152600c820154602080830191909152600d830154604080840191909152600e8401546001600160a01b0381166060850152600160a01b90046001600160601b03166080840152805160e08101909152600f8401805460ff8082161515845260a09095019492939192918401916101009091041660018111156124bd57fe5b60018111156124c857fe5b81528154620100008104600290810b810b810b602080850191909152600160281b8304820b820b820b604080860191909152600160401b90930460ff9081161515606086015260018601546080860152948201548516151560a094850152948652815192830190915260128601805495909401949193928492169081111561254c57fe5b600281111561255757fe5b8152905461010081046001600160401b03908116602080850191909152600160481b83048216604080860191909152600160881b8404909216606080860191909152600160c81b90930460ff161515608090940193909352929093528f0151868201519287015191516351c403f960e11b81529495506000948594506001600160a01b039091169263a38807f2926125f19260040161519b565b60606040518083038186803b15801561260957600080fd5b505afa15801561261d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126419190614a77565b92509250506126de6040518061016001604052808560200151815260200185606001516001600160a01b031681526020018f6060015181526020018f6080015181526020018f60a001518152602001876001600160801b03168152602001896001600160a01b03168152602001846001600160a01b031681526020018863ffffffff1681526020018363ffffffff1681526020014281525061356d565b919c509a50985050505050505050509250925092565b6126fc61307d565b6001600160a01b031661270d611e02565b6001600160a01b031614612756576040805162461bcd60e51b81526020600482018190526024820152600080516020615a5c833981519152604482015290519081900360640190fd5b600081116127765760405162461bcd60e51b815260040161084690615630565b600f8190556040517fcb4f422769239d11c770c6857247498f2ee242ad1787266c86efe6ab908e69d6906127ab9083906150ea565b60405180910390a150565b600f5481565b6127c461307d565b6001600160a01b03166127d5611e02565b6001600160a01b03161461281e576040805162461bcd60e51b81526020600482018190526024820152600080516020615a5c833981519152604482015290519081900360640190fd5b6001600160a01b0381166128635760405162461bcd60e51b8152600401808060200182810382526026815260200180615a366026913960400191505060405180910390fd5b6012546040516001600160a01b03808416921690600080516020615a7c83398151915290600090a3601280546001600160a01b0319166001600160a01b0392909216919091179055565b6000818152600c602052604081206110219061301a565b60606128cf8461363d565b61290a5760405162461bcd60e51b8152600401808060200182810382526026815260200180615a9c6026913960400191505060405180910390fd5b600080856001600160a01b0316856040518082805190602001908083835b602083106129475780518252601f199092019160209182019101612928565b6001836020036101000a038019825116818451168082178552505050505050905001915050600060405180830381855af49150503d80600081146129a7576040519150601f19603f3d011682016040523d82523d6000602084013e6129ac565b606091505b50915091506129bc828286613643565b9695505050505050565b6000610c2783836136e7565b6000816040516020016129e591906156aa565b604051602081830303815290604052805190602001209050919050565b8160600151421015612a265760405162461bcd60e51b81526004016108469061530c565b81608001514210612a495760405162461bcd60e51b81526004016108469061555e565b6000612a54836129d2565b6000818152600760205260409020600c81015491925090612a875760405162461bcd60e51b81526004016108469061541a565b600083815260086020908152604080832054600f546001600160a01b03909116808552600b84528285208886529093529220909190612ac59061301a565b10612ae25760405162461bcd60e51b8152600401610846906154b0565b6001600160a01b0381166000908152600b602090815260408083208784529091529020612b0f90846129c6565b506000838152600c60205260409020612b2890856129c6565b5060008054600154829182918291612b4d916001600160a01b0391821691168a613731565b935093509350935088602001516001600160a01b0316846001600160a01b031614612b8a5760405162461bcd60e51b8152600401610846906152b2565b6000816001600160801b031611612bb35760405162461bcd60e51b81526004016108469061559a565b612bbe878484613820565b612bda5760405162461bcd60e51b8152600401610846906152d0565b601186015460ff168015612c00575060008881526008602052604090206001015460ff16155b15612c575760008881526008602052604090206001908101805460ff19169091179055612c2e600d896129c6565b50876000805160206159ba8339815191526001604051612c4e91906150df565b60405180910390a25b60008881526008602052604090208054600165ffffffffffff600160a01b80840482168301909116810265ffffffffffff60a01b1990931692909217909255600e880180546001600160601b0383820481168501169092026001600160a01b039092169190911790558961012001516001811115612cd157fe5b1415612d555760008781526010602090815260408083208b8452601183528184208b855290925290912080546001600160801b031615612d235760405162461bcd60e51b8152600401610846906151fe565b612d2d8a8a613918565b81546001600160801b03841690810190925580546001600160801b0319169091179055612fbe565b60008881526009602090815260408083208a8452909152902054600160c01b90046001600160401b031615612d9c5760405162461bcd60e51b8152600401610846906151fe565b600080856001600160a01b031663a38807f286866040518363ffffffff1660e01b8152600401612dcd92919061519b565b60606040518083038186803b158015612de557600080fd5b505afa158015612df9573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190612e1d9190614a77565b9093509150506001600160401b036001600160801b03841610612f56576040518060800160405280836001600160a01b031681526020018263ffffffff1681526020016001600160401b0380168152602001846001600160801b0316815250600960008c815260200190815260200160002060008b815260200190815260200160002060008201518160000160006101000a8154816001600160a01b0302191690836001600160a01b0316021790555060208201518160000160146101000a81548163ffffffff021916908363ffffffff16021790555060408201518160000160186101000a8154816001600160401b0302191690836001600160401b0316021790555060608201518160010160006101000a8154816001600160801b0302191690836001600160801b03160217905550905050612fbb565b60008a81526009602090815260408083208c8452909152902080546001600160a01b0319166001600160a01b0384161763ffffffff60a01b1916600160a01b63ffffffff841602176001600160c01b0316600160c01b6001600160401b038616021790555b50505b86887f3fe90ccd0a34e28f2b4b7a1e8323415ed9dd595f4eec5dfd461d18c2df336dbd83604051612fef9190615720565b60405180910390a3505050505050505050565b6000610c27838361399a565b6000610c2783836139fe565b600061102182613ac4565b613037836001600160a01b031661363d565b6130725760405162461bcd60e51b815260040180806020018281038252603a8152602001806159fc603a913960400191505060405180910390fd5b611dd1838383613ac8565b3390565b61308a8161363d565b6130a65760405162461bcd60e51b815260040161084690615384565b806001600160a01b031663c45a01556040518163ffffffff1660e01b815260040160206040518083038186803b1580156130df57600080fd5b505afa92505050801561310f575060408051601f3d908101601f1916820190925261310c9181019061480e565b60015b61312b5760405162461bcd60e51b815260040161084690615384565b6000546001600160a01b03828116911614610e305760405162461bcd60e51b815260040161084690615384565b50565b60e0820151518015613180575060008260e0015160200151600181111561317e57fe5b145b61319c5760405162461bcd60e51b81526004016108469061521c565b600082606001518360800151039050600081676765c793fa10079d601b1b856040015102816131c757fe5b049050600081116131ea5760405162461bcd60e51b8152600401610846906154ce565b60408051608081018252600080825260208083019485528284018281526060988901519884019889529682526010905291909120905181559051600182015591516002830155509051600390910155565b61324d846001600160a01b031661363d565b6132885760405162461bcd60e51b815260040180806020018281038252603e815260200180615ac2603e913960400191505060405180910390fd5b611f0284848484613c16565b80602001516001600160a01b031681600001516001600160a01b03167f35e6e5d41fc13a520ef12bc9a13a02cef3468dc98ea27579ab30d06f939809eb836060015184608001518560a001518660c00151888860e00151600001518960e00151602001518a60e00151604001518b60e00151606001518c60e00151608001518d60e0015160a001518e60e0015160c0015160405161333d9c9b9a9998979695949392919061580e565b60405180910390a35050565b600080613355856129d2565b9050600080600061336787858a613d6e565b9250925092506133778785613e33565b85516001600160a01b03166000908152600b602090815260408083208a845290915290206133a5908561300e565b506000848152600c602052604090206133be908861300e565b506133ca878583613eaf565b600188610120015160018111156133dd57fe5b14156134ae5760008481526010602090815260408083208a8452601183528184208885529092529091206134118987613918565b600281015482546001600160801b038516900383556000878152600760205260409020600c0154909750871115613457576000868152600760205260409020600c015496505b6000868152600760205260408120600c018054899003905581546001600160801b0319168255600282015586156134a757600086815260076020526040902088516134a7918c918991908b613ef8565b50506134bf565b6134bc888786868686614011565b94505b604051849088907fe1ba67e807ae0efa0a9549f9520ddc15c27f0a4dae2bc045e800ca66a940778f90600090a3505050509392505050565b6000828152601160209081526040808320848452909152812080546001600160801b0316613529576000915050610c2a565b600061353484614062565b60018301548354600290940154676765c793fa10079d601b1b6001600160801b0390951691909203029290920491909101949350505050565b60008060008360400151846101400151101561358557fe5b8360a001516001600160801b03168460c001518560e0015103029050600084602001516001600160a01b0316608086604001516135cb88606001518961014001516140ea565b03901b0390506135e98560000151836001600160a01b031683614101565b92508461010001518561012001510363ffffffff1685608001511161361057829350613635565b84608001518561010001518661012001510363ffffffff1684028161363157fe5b0493505b509193909250565b3b151590565b60608315613652575081610c60565b8251156136625782518084602001fd5b8160405162461bcd60e51b81526004018080602001828103825283818151815260200191508051906020019080838360005b838110156136ac578181015183820152602001613694565b50505050905090810190601f1680156136d95780820380516001836020036101000a031916815260200191505b509250505060405180910390fd5b60006136f383836141b0565b61372957508154600181810184556000848152602080822090930184905584548482528286019093526040902091909155610c2a565b506000610c2a565b6000806000806000806000886001600160a01b03166399fbab88896040518263ffffffff1660e01b8152600401808281526020019150506101806040518083038186803b15801561378157600080fd5b505afa158015613795573d6000803e3d6000fd5b505050506040513d6101808110156137ac57600080fd5b50604080820151606080840151608085015160a086015160c087015160e090970151865194850187526001600160a01b0380871686528416602086015262ffffff8316968501969096529b50949950929750909550909350909150613812908b906141c8565b965050505093509350935093565b6000838152600760205260408120600f810154600160401b900460ff161561386757601081015484840390600290810b9082900b121561386557600092505050610c60565b505b600f81015460ff1661387d576001915050610c60565b6000600f820154610100900460ff16600181111561389757fe5b14156138da57600f810154600285810b62010000909204810b900b1480156138d25750600f810154600284810b600160281b909204810b900b145b915050610c60565b600f810154620100009004600290810b810b9085900b128015906138d25750600f0154600160281b9004600290810b810b9083900b13159050610c60565b6000818152601060209081526040808320600790925290912061393a83614062565b600283015560048101544210613954576004810154613956565b425b60038301556000848152601160209081526040808320868452909152902061397e85856134f7565b8160020181905550826002015481600101819055505050505050565b815460009082106139dc5760405162461bcd60e51b81526004018080602001828103825260228152602001806159da6022913960400191505060405180910390fd5b8260000182815481106139eb57fe5b9060005260206000200154905092915050565b60008181526001830160205260408120548015613aba5783546000198083019190810190600090879083908110613a3157fe5b9060005260206000200154905080876000018481548110613a4e57fe5b600091825260208083209091019290925582815260018981019092526040902090840190558654879080613a7e57fe5b60019003818190600052602060002001600090559055866001016000878152602001908152602001600020600090556001945050505050610c2a565b6000915050610c2a565b5490565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663a9059cbb60e01b1781529251825160009485949389169392918291908083835b60208310613b445780518252601f199092019160209182019101613b25565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613ba6576040519150601f19603f3d011682016040523d82523d6000602084013e613bab565b606091505b5091509150818015613bd9575080511580613bd95750808060200190516020811015613bd657600080fd5b50515b613c0f576040805162461bcd60e51b815260206004820152600260248201526114d560f21b604482015290519081900360640190fd5b5050505050565b604080516001600160a01b0385811660248301528481166044830152606480830185905283518084039091018152608490920183526020820180516001600160e01b03166323b872dd60e01b178152925182516000948594938a169392918291908083835b60208310613c9a5780518252601f199092019160209182019101613c7b565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114613cfc576040519150601f19603f3d011682016040523d82523d6000602084013e613d01565b606091505b5091509150818015613d2f575080511580613d2f5750808060200190516020811015613d2c57600080fd5b50515b613d66576040805162461bcd60e51b815260206004820152600360248201526229aa2360e91b604482015290519081900360640190fd5b505050505050565b6000808060018461012001516001811115613d8557fe5b1415613de3576000868152601160209081526040808320888452909152902080546001600160801b0316613dcb5760405162461bcd60e51b81526004016108469061568a565b54600093508392506001600160801b03169050613e2a565b6000806000613df289896120c8565b925092509250806001600160801b031660001415613e225760405162461bcd60e51b81526004016108469061568a565b919450925090505b93509350939050565b6000918252600860209081526040808420805460001965ffffffffffff600160a01b80840482168301909116810265ffffffffffff60a01b19909316929092179092559385526007909252909220600e0180546001600160601b0383820481169094019093169091026001600160a01b03909216919091179055565b600083815260096020908152604080832085845290915281209081556001600160401b036001600160801b03831610611f025760010180546001600160801b0319169055505050565b80613f0257613c0f565b6000601284015460ff166002811115613f1757fe5b1415613f7e578451613f2a908383613025565b816001600160a01b031685600001516001600160a01b03167f0aa4d283470c904c551d18bb894d37e17674920f3261a7f854be501e25f421b783604051613f7191906150ea565b60405180910390a3613c0f565b8451600654613f9791906001600160a01b0316836142a7565b600654855160c087015160405163369e53d160e01b81526001600160a01b039093169263369e53d192613fd89289928891889160128c0191906004016150f3565b600060405180830381600087803b158015613ff257600080fd5b505af1158015614006573d6000803e3d6000fd5b505050505050505050565b60008481526007602052604081208180806140308b858c8b8a8c6143ee565b92509250925061404284828486614544565b6140538b8a868d6000015187613ef8565b50909998505050505050505050565b6000818152601060205260408120805461408157600201549050611024565b6000838152600760205260408120600481015490919042106140a75760048201546140a9565b425b9050826003015481116140c3575050600201549050611024565b825460018401546003850154830302816140d957fe5b048360020154019350505050919050565b6000818310156140fa5781610c27565b5090919050565b6000808060001985870986860292508281109083900303905080614137576000841161412c57600080fd5b508290049050610c60565b80841161414357600080fd5b6000848688096000868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b60009081526001919091016020526040902054151590565b600081602001516001600160a01b031682600001516001600160a01b0316106141f057600080fd5b50805160208083015160409384015184516001600160a01b0394851681850152939091168385015262ffffff166060808401919091528351808403820181526080840185528051908301206001600160f81b031960a085015294901b6001600160601b03191660a183015260b58201939093527fe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b5460d5808301919091528251808303909101815260f5909101909152805191012090565b604080516001600160a01b038481166024830152604480830185905283518084039091018152606490920183526020820180516001600160e01b031663095ea7b360e01b1781529251825160009485949389169392918291908083835b602083106143235780518252601f199092019160209182019101614304565b6001836020036101000a0380198251168184511680821785525050505050509050019150506000604051808303816000865af19150503d8060008114614385576040519150601f19603f3d011682016040523d82523d6000602084013e61438a565b606091505b50915091508180156143b85750805115806143b857508080602001905160208110156143b557600080fd5b50515b613c0f576040805162461bcd60e51b8152602060048201526002602482015261534160f01b604482015290519081900360640190fd5b60008060008060008a602001516001600160a01b031663a38807f28a604001518b606001516040518363ffffffff1660e01b815260040161443092919061519b565b60606040518083038186803b15801561444857600080fd5b505afa15801561445c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906144809190614a77565b92509250506145306040518061016001604052808c600c015481526020018c600e0160009054906101000a90046001600160a01b03166001600160a01b031681526020018d6060015181526020018d6080015181526020018d60a001518152602001896001600160801b031681526020018a6001600160a01b03168152602001846001600160a01b031681526020018863ffffffff1681526020018363ffffffff1681526020014281525061356d565b945094509450505096509650969350505050565b600e840180546001600160a01b038082168601166001600160a01b0319909116179055600c84018054839003905580821115611f0257600d8401805482840301905550505050565b803561102481615980565b805161102481615980565b8035801515811461102457600080fd5b80356002811061102457600080fd5b803561102481615995565b805161102481615995565b600060a082840312156145e8578081fd5b60405160a081016001600160401b038111828210171561460457fe5b60405290508082356003811061461957600080fd5b8152614627602084016147db565b6020820152614638604084016147db565b6040820152614649606084016147db565b606082015261465a608084016145a2565b60808201525092915050565b60006102808284031215614678578081fd5b614683610140615906565b905061468e8261458c565b815261469c6020830161458c565b602082015260408201356040820152606082013560608201526080820135608082015260a082013560a08201526146d560c0830161458c565b60c08201526146e78360e08401614719565b60e08201526146fa836101c084016145d7565b61010082015261470d61026083016145b2565b61012082015292915050565b600060e0828403121561472a578081fd5b60405160e081016001600160401b038111828210171561474657fe5b604052905080614755836145a2565b8152614763602084016145b2565b6020820152614774604084016145c1565b6040820152614785606084016145c1565b6060820152614796608084016145a2565b608082015260a083013560a08201526147b160c084016145a2565b60c08201525092915050565b8051611024816159a4565b805162ffffff8116811461102457600080fd5b80356001600160401b038116811461102457600080fd5b600060208284031215614803578081fd5b8135610c6081615980565b60006020828403121561481f578081fd5b8151610c6081615980565b600080600080600060808688031215614841578081fd5b853561484c81615980565b9450602086013561485c81615980565b93506040860135925060608601356001600160401b038082111561487e578283fd5b818801915088601f830112614891578283fd5b81358181111561489f578384fd5b8960208285010111156148b0578384fd5b9699959850939650602001949392505050565b600080604083850312156148d5578182fd5b82356148e081615980565b946020939093013593505050565b600080600060608486031215614902578081fd5b833561490d81615980565b95602085013595506040909401359392505050565b60008060208385031215614934578182fd5b82356001600160401b038082111561494a578384fd5b818501915085601f83011261495d578384fd5b81358181111561496b578485fd5b866020808302850101111561497e578485fd5b60209290920196919550909350505050565b600060208083850312156149a2578182fd5b82356001600160401b03808211156149b8578384fd5b818501915085601f8301126149cb578384fd5b8135818111156149d757fe5b6149e48485830201615906565b8181528481019250838501610280808402860187018a1015614a04578788fd5b8795505b83861015614a3057614a1a8a83614666565b8552600195909501949386019390810190614a08565b509098975050505050505050565b600060208284031215614a4f578081fd5b5035919050565b60008060408385031215614a68578182fd5b50508035926020909101359150565b600080600060608486031215614a8b578081fd5b83518060060b8114614a9b578182fd5b6020850151909350614aac81615980565b604085015190925063ffffffff81168114614ac5578182fd5b809150509250925092565b600060208284031215614ae1578081fd5b81516001600160401b03811115614af6578182fd5b8201601f81018413614b06578182fd5b8051614b19614b1482615929565b615906565b818152856020838501011115614b2d578384fd5b614b3e82602083016020860161594a565b95945050505050565b60006102808284031215614b59578081fd5b610c278383614666565b6000806102a08385031215614b76578182fd5b614b808484614666565b94610280939093013593505050565b600080600060608486031215614ba3578081fd5b8351614bae816159a4565b602085015160409095015190969495509392505050565b60008060408385031215614bd7578182fd5b823591506020830135614be981615980565b809150509250929050565b600080600060608486031215614c08578081fd5b833592506020840135614c1a81615980565b915060408401356001600160401b03811115614c34578182fd5b8401601f81018613614c44578182fd5b8035614c52614b1482615929565b818152876020838501011115614c66578384fd5b8160208401602083013783602083830101528093505050509250925092565b60008060008060808587031215614c9a578182fd5b843593506020850135614cac81615980565b92506040850135614cbc816159a4565b91506060850135614ccc816159a4565b939692955090935050565b600080600080600060a08688031215614cee578283fd5b853594506020860135614d00816159a4565b94979496505050506040830135926060810135926080909101359150565b60008060408385031215614d30578182fd5b505080516020909101519092909150565b60008060008060008060c08789031215614d59578384fd5b505084359660208601359650604086013595606081013595506080810135945060a0013592509050565b6000806000806000806000806000806000806101808d8f031215614da557898afd5b8c516001600160601b0381168114614dbb578a8bfd5b9b50614dc960208e01614597565b9a50614dd760408e01614597565b9950614de560608e01614597565b9850614df360808e016147c8565b9750614e0160a08e016145cc565b9650614e0f60c08e016145cc565b9550614e1d60e08e016147bd565b94506101008d015193506101208d01519250614e3c6101408e016147bd565b9150614e4b6101608e016147bd565b90509295989b509295989b509295989b565b6001600160a01b03169052565b15159052565b60008151808452614e8881602086016020860161594a565b601f01601f19169290920160200192915050565b60038110614ea657fe5b9052565b614ea681615976565b614ebe828251614e9c565b6020818101516001600160401b0390811691840191909152604080830151821690840152606080830151909116908301526080908101511515910152565b614f07828251614e5d565b6020810151614f196020840182614e5d565b5060408101516040830152606081015160608301526080810151608083015260a081015160a083015260c0810151614f5460c0840182614e5d565b5060e0810151614f6760e0840182614f91565b50610100810151614f7c6101c0840182614eb3565b50610120810151611dd1610260840182614eaa565b8051151582526020810151614fa581615976565b80602084015250604081015160020b6040830152606081015160020b606083015260808101511515608083015260a081015160a083015260c0810151151560c08301525050565b6000828483379101908152919050565b6001600160a01b0391909116815260200190565b6001600160a01b03858116825284166020820152604081018390526080606082018190526000906129bc90830184614e70565b6001600160a01b0395909516855265ffffffffffff939093166020850152600291820b6040850152900b60608301521515608082015260a00190565b6000602080830181845280855180835260408601915060408482028701019250838701855b828110156150d257603f198886030184526150c0858351614e70565b945092850192908501906001016150a4565b5092979650505050505050565b901515815260200190565b90815260200190565b8681526001600160a01b0386811660208301528516604082015260608101849052825461014082019061512c6080840160ff8316614e9c565b6001600160401b03600882901c811660a0850152604882901c811660c0850152608882901c1660e084015261516c610100840160ff60c884901c16614e6a565b5061517b610120830184614e5d565b979650505050505050565b6001600160e01b031991909116815260200190565b600292830b8152910b602082015260400190565b600060208252610c276020830184614e70565b6020808252600490820152634530303760e01b604082015260600190565b602080825260049082015263114c0c8d60e21b604082015260600190565b6020808252600490820152634530333160e01b604082015260600190565b6020808252600490820152634530343560e01b604082015260600190565b6020808252600490820152632298191960e11b604082015260600190565b6020808252600490820152634530323560e01b604082015260600190565b6020808252600490820152634530303360e01b604082015260600190565b602080825260049082015263114c0c0d60e21b604082015260600190565b6020808252600490820152632298199960e11b604082015260600190565b602080825260049082015263114c0ccd60e21b604082015260600190565b6020808252600490820152634530303160e01b604082015260600190565b60208082526004908201526308a6064760e31b604082015260600190565b60208082526004908201526308a6060760e31b604082015260600190565b6020808252600490820152632298181960e11b604082015260600190565b60208082526004908201526308a6062760e31b604082015260600190565b602080825260049082015263114c0d0d60e21b604082015260600190565b6020808252600490820152634530323360e01b604082015260600190565b6020808252600490820152634530313760e01b604082015260600190565b6020808252600490820152634530313960e01b604082015260600190565b6020808252600490820152634530303960e01b604082015260600190565b6020808252600490820152630453033360e41b604082015260600190565b602080825260049082015263114c0c4d60e21b604082015260600190565b6020808252600490820152634530323160e01b604082015260600190565b6020808252600490820152630453034360e41b604082015260600190565b6020808252600490820152632298189960e11b604082015260600190565b6020808252600490820152634530343160e01b604082015260600190565b6020808252601c908201527b5265776172642072617465206d75737420626520706f73697469766560201b604082015260600190565b6020808252600490820152632298189b60e11b604082015260600190565b6020808252600490820152630453031360e41b604082015260600190565b6020808252600490820152634530323760e01b604082015260600190565b6020808252600490820152634530323960e01b604082015260600190565b6020808252600490820152634530343360e01b604082015260600190565b6020808252600490820152634530333360e01b604082015260600190565b6020808252600490820152634530303560e01b604082015260600190565b6020808252600490820152632298191b60e11b604082015260600190565b6020808252600490820152630453032360e41b604082015260600190565b6020808252600490820152634530313160e01b604082015260600190565b60208082526004908201526322981a1960e11b604082015260600190565b6020808252600490820152634530313360e01b604082015260600190565b6020808252600490820152632298181b60e11b604082015260600190565b602080825260069082015265453032372e3160d01b604082015260600190565b6102808101610c2a8284614efc565b61048081016156c8828a614efc565b61028082018890526102a082018790526001600160a01b0386166102c08301526001600160601b0385166102e0830152615706610300830185614f91565b6157146103e0830184614eb3565b98975050505050505050565b6001600160801b0391909116815260200190565b6001600160801b039390931683526020830191909152604082015260600190565b6001600160a01b0393909316835263ffffffff9190911660208301526001600160801b0316604082015260600190565b9384526001600160a01b039290921660208401526001600160801b03908116604084015216606082015260800190565b9485526001600160801b0393909316602085015260408401919091526060830152608082015260a00190565b918252602082015260400190565b92835260208301919091526001600160a01b0316604082015260600190565b8c8152602081018c9052604081018b90526001600160a01b038a1660608201526080810189905287151560a0820152610180810161584b88615976565b8760c08301528660020b60e08301528560020b61010083015284151561012083015283610140830152615882610160830184614e6a565b9d9c50505050505050505050505050565b958652602086019490945260408501929092526060840152608083015260a082015260c00190565b6000808335601e198436030181126158d1578283fd5b8301803591506001600160401b038211156158ea578283fd5b6020019150368190038213156158ff57600080fd5b9250929050565b6040518181016001600160401b038111828210171561592157fe5b604052919050565b60006001600160401b0382111561593c57fe5b50601f01601f191660200190565b60005b8381101561596557818101518382015260200161594d565b83811115611f025750506000910152565b6002811061315857fe5b6001600160a01b038116811461315857600080fd5b8060020b811461315857600080fd5b6001600160801b038116811461315857600080fdfeda2a809cdb3c0db5541ecefe88d0162a40822b5e7c7b5e7cdb1cfe38266c8fcc456e756d657261626c655365743a20696e646578206f7574206f6620626f756e64735472616e7366657248656c706572457874656e6465643a3a736166655472616e736665723a2063616c6c20746f206e6f6e2d636f6e74726163744f776e61626c653a206e6577206f776e657220697320746865207a65726f20616464726573734f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65728be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0416464726573733a2064656c65676174652063616c6c20746f206e6f6e2d636f6e74726163745472616e7366657248656c706572457874656e6465643a3a736166655472616e7366657246726f6d3a2063616c6c20746f206e6f6e2d636f6e7472616374cdfc765b85e1048bee3c6a0f9d1c91fc7c4631f5fe5745a55fc6843db5c3260f4c69717569646974792068616e646c65722064656c65676174696f6e206661696c6564a164736f6c6343000706000a

Verified Source Code Partial Match

Compiler: v0.7.6+commit.7338295f EVM: istanbul Optimization: Yes (10 runs)
Ownable.sol 68 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

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

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor () {
        address msgSender = _msgSender();
        _owner = msgSender;
        emit OwnershipTransferred(address(0), msgSender);
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}
IERC165.sol 24 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165 {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
Math.sol 31 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow, so we distribute
        return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
    }
}
SafeMath.sol 214 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
    /**
     * @dev Returns the addition of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        uint256 c = a + b;
        if (c < a) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the substraction of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b > a) return (false, 0);
        return (true, a - b);
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, with an overflow flag.
     *
     * _Available since v3.4._
     */
    function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
        // benefit is lost if 'b' is also tested.
        // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
        if (a == 0) return (true, 0);
        uint256 c = a * b;
        if (c / a != b) return (false, 0);
        return (true, c);
    }

    /**
     * @dev Returns the division of two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a / b);
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
     *
     * _Available since v3.4._
     */
    function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
        if (b == 0) return (false, 0);
        return (true, a % b);
    }

    /**
     * @dev Returns the addition of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `+` operator.
     *
     * Requirements:
     *
     * - Addition cannot overflow.
     */
    function add(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 c = a + b;
        require(c >= a, "SafeMath: addition overflow");
        return c;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting on
     * overflow (when the result is negative).
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b <= a, "SafeMath: subtraction overflow");
        return a - b;
    }

    /**
     * @dev Returns the multiplication of two unsigned integers, reverting on
     * overflow.
     *
     * Counterpart to Solidity's `*` operator.
     *
     * Requirements:
     *
     * - Multiplication cannot overflow.
     */
    function mul(uint256 a, uint256 b) internal pure returns (uint256) {
        if (a == 0) return 0;
        uint256 c = a * b;
        require(c / a == b, "SafeMath: multiplication overflow");
        return c;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting on
     * division by zero. The result is rounded towards zero.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: division by zero");
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting when dividing by zero.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b) internal pure returns (uint256) {
        require(b > 0, "SafeMath: modulo by zero");
        return a % b;
    }

    /**
     * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
     * overflow (when the result is negative).
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {trySub}.
     *
     * Counterpart to Solidity's `-` operator.
     *
     * Requirements:
     *
     * - Subtraction cannot overflow.
     */
    function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b <= a, errorMessage);
        return a - b;
    }

    /**
     * @dev Returns the integer division of two unsigned integers, reverting with custom message on
     * division by zero. The result is rounded towards zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryDiv}.
     *
     * Counterpart to Solidity's `/` operator. Note: this function uses a
     * `revert` opcode (which leaves remaining gas untouched) while Solidity
     * uses an invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a / b;
    }

    /**
     * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
     * reverting with custom message when dividing by zero.
     *
     * CAUTION: This function is deprecated because it requires allocating memory for the error
     * message unnecessarily. For custom revert reasons use {tryMod}.
     *
     * Counterpart to Solidity's `%` operator. This function uses a `revert`
     * opcode (which leaves remaining gas untouched) while Solidity uses an
     * invalid opcode to revert (consuming all remaining gas).
     *
     * Requirements:
     *
     * - The divisor cannot be zero.
     */
    function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
        require(b > 0, errorMessage);
        return a % b;
    }
}
ERC20.sol 306 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin guidelines: functions revert instead
 * of returning `false` on failure. This behavior is nonetheless conventional
 * and does not conflict with the expectations of ERC20 applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20 {
    using SafeMath for uint256;

    mapping (address => uint256) private _balances;

    mapping (address => mapping (address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;
    uint8 private _decimals;

    /**
     * @dev Sets the values for {name} and {symbol}, initializes {decimals} with
     * a default value of 18.
     *
     * To select a different value for {decimals}, use {_setupDecimals}.
     *
     * All three of these values are immutable: they can only be set once during
     * construction.
     */
    constructor (string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
        _decimals = 18;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5,05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
     * called.
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual returns (uint8) {
        return _decimals;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);
        _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
        return true;
    }

    /**
     * @dev Moves tokens `amount` from `sender` to `recipient`.
     *
     * This is internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(address sender, address recipient, uint256 amount) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
        _balances[recipient] = _balances[recipient].add(amount);
        emit Transfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply = _totalSupply.add(amount);
        _balances[account] = _balances[account].add(amount);
        emit Transfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
        _totalSupply = _totalSupply.sub(amount);
        emit Transfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Sets {decimals} to a value other than the default one of 18.
     *
     * WARNING: This function should only be called from the constructor. Most
     * applications that interact with token contracts will not expect
     * {decimals} to ever change, and may work incorrectly if it does.
     */
    function _setupDecimals(uint8 decimals_) internal virtual {
        _decimals = decimals_;
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be to transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
IERC20.sol 77 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);

    /**
     * @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);
}
IERC721.sol 129 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "../../introspection/IERC165.sol";

/**
 * @dev Required interface of an ERC721 compliant contract.
 */
interface IERC721 is IERC165 {
    /**
     * @dev Emitted when `tokenId` token is transferred from `from` to `to`.
     */
    event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
     */
    event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);

    /**
     * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
     */
    event ApprovalForAll(address indexed owner, address indexed operator, bool approved);

    /**
     * @dev Returns the number of tokens in ``owner``'s account.
     */
    function balanceOf(address owner) external view returns (uint256 balance);

    /**
     * @dev Returns the owner of the `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function ownerOf(uint256 tokenId) external view returns (address owner);

    /**
     * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
     * are aware of the ERC721 protocol to prevent tokens from being forever locked.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must exist and be owned by `from`.
     * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
     * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
     *
     * Emits a {Transfer} event.
     */
    function safeTransferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Transfers `tokenId` token from `from` to `to`.
     *
     * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `tokenId` token must be owned by `from`.
     * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 tokenId) external;

    /**
     * @dev Gives permission to `to` to transfer `tokenId` token to another account.
     * The approval is cleared when the token is transferred.
     *
     * Only a single account can be approved at a time, so approving the zero address clears previous approvals.
     *
     * Requirements:
     *
     * - The caller must own the token or be an approved operator.
     * - `tokenId` must exist.
     *
     * Emits an {Approval} event.
     */
    function approve(address to, uint256 tokenId) external;

    /**
     * @dev Returns the account approved for `tokenId` token.
     *
     * Requirements:
     *
     * - `tokenId` must exist.
     */
    function getApproved(uint256 tokenId) external view returns (address operator);

    /**
     * @dev Approve or remove `operator` as an operator for the caller.
     * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
     *
     * Requirements:
     *
     * - The `operator` cannot be the caller.
     *
     * Emits an {ApprovalForAll} event.
     */
    function setApprovalForAll(address operator, bool _approved) external;

    /**
     * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
     *
     * See {setApprovalForAll}
     */
    function isApprovedForAll(address owner, address operator) external view returns (bool);

    /**
      * @dev Safely transfers `tokenId` token from `from` to `to`.
      *
      * Requirements:
      *
      * - `from` cannot be the zero address.
      * - `to` cannot be the zero address.
      * - `tokenId` token must exist and be owned by `from`.
      * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
      * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
      *
      * Emits a {Transfer} event.
      */
    function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
IERC721Enumerable.sol 29 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Enumerable is IERC721 {

    /**
     * @dev Returns the total amount of tokens stored by the contract.
     */
    function totalSupply() external view returns (uint256);

    /**
     * @dev Returns a token ID owned by `owner` at a given `index` of its token list.
     * Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
     */
    function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);

    /**
     * @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
     * Use along with {totalSupply} to enumerate all tokens.
     */
    function tokenByIndex(uint256 index) external view returns (uint256);
}
IERC721Metadata.sol 27 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

import "./IERC721.sol";

/**
 * @title ERC-721 Non-Fungible Token Standard, optional metadata extension
 * @dev See https://eips.ethereum.org/EIPS/eip-721
 */
interface IERC721Metadata is IERC721 {

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

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

    /**
     * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
     */
    function tokenURI(uint256 tokenId) external view returns (string memory);
}
IERC721Receiver.sol 21 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

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

pragma solidity ^0.7.0;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize, which returns 0 for contracts in
        // construction, since the code is only stored at the end of the
        // constructor execution.

        uint256 size;
        // solhint-disable-next-line no-inline-assembly
        assembly { size := extcodesize(account) }
        return size > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        // solhint-disable-next-line avoid-low-level-calls, avoid-call-value
        (bool success, ) = recipient.call{ value: amount }("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain`call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
      return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.call{ value: value }(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.staticcall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        // solhint-disable-next-line avoid-low-level-calls
        (bool success, bytes memory returndata) = target.delegatecall(data);
        return _verifyCallResult(success, returndata, errorMessage);
    }

    function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                // solhint-disable-next-line no-inline-assembly
                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
Context.sol 24 lines
// SPDX-License-Identifier: MIT

pragma solidity >=0.6.0 <0.8.0;

/*
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with GSN 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 payable) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes memory) {
        this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
        return msg.data;
    }
}
EnumerableSet.sol 297 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.7.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;

        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping (bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) { // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
            // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.

            bytes32 lastvalue = set._values[lastIndex];

            // Move the last value to the index where the value to delete is
            set._values[toDeleteIndex] = lastvalue;
            // Update the index for the moved value
            set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        require(set._values.length > index, "EnumerableSet: index out of bounds");
        return set._values[index];
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }


    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

   /**
    * @dev Returns the value stored at position `index` in the set. O(1).
    *
    * Note that there are no guarantees on the ordering of values inside the
    * array, and it may change when more values are added or removed.
    *
    * Requirements:
    *
    * - `index` must be strictly less than {length}.
    */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }
}
IERC20Minimal.sol 52 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Minimal ERC20 interface for Uniswap
/// @notice Contains a subset of the full ERC20 interface that is used in Uniswap V3
interface IERC20Minimal {
    /// @notice Returns the balance of a token
    /// @param account The account for which to look up the number of tokens it has, i.e. its balance
    /// @return The number of tokens held by the account
    function balanceOf(address account) external view returns (uint256);

    /// @notice Transfers the amount of token from the `msg.sender` to the recipient
    /// @param recipient The account that will receive the amount transferred
    /// @param amount The number of tokens to send from the sender to the recipient
    /// @return Returns true for a successful transfer, false for an unsuccessful transfer
    function transfer(address recipient, uint256 amount) external returns (bool);

    /// @notice Returns the current allowance given to a spender by an owner
    /// @param owner The account of the token owner
    /// @param spender The account of the token spender
    /// @return The current allowance granted by `owner` to `spender`
    function allowance(address owner, address spender) external view returns (uint256);

    /// @notice Sets the allowance of a spender from the `msg.sender` to the value `amount`
    /// @param spender The account which will be allowed to spend a given amount of the owners tokens
    /// @param amount The amount of tokens allowed to be used by `spender`
    /// @return Returns true for a successful approval, false for unsuccessful
    function approve(address spender, uint256 amount) external returns (bool);

    /// @notice Transfers `amount` tokens from `sender` to `recipient` up to the allowance given to the `msg.sender`
    /// @param sender The account from which the transfer will be initiated
    /// @param recipient The recipient of the transfer
    /// @param amount The amount of the transfer
    /// @return Returns true for a successful transfer, false for unsuccessful
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /// @notice Event emitted when tokens are transferred from one address to another, either via `#transfer` or `#transferFrom`.
    /// @param from The account from which the tokens were sent, i.e. the balance decreased
    /// @param to The account to which the tokens were sent, i.e. the balance increased
    /// @param value The amount of tokens that were transferred
    event Transfer(address indexed from, address indexed to, uint256 value);

    /// @notice Event emitted when the approval amount for the spender of a given owner's tokens changes.
    /// @param owner The account that approved spending of its tokens
    /// @param spender The account for which the spending allowance was modified
    /// @param value The new allowance from the owner to the spender
    event Approval(address indexed owner, address indexed spender, uint256 value);
}
IUniswapV3Factory.sol 78 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title The interface for the Uniswap V3 Factory
/// @notice The Uniswap V3 Factory facilitates creation of Uniswap V3 pools and control over the protocol fees
interface IUniswapV3Factory {
    /// @notice Emitted when the owner of the factory is changed
    /// @param oldOwner The owner before the owner was changed
    /// @param newOwner The owner after the owner was changed
    event OwnerChanged(address indexed oldOwner, address indexed newOwner);

    /// @notice Emitted when a pool is created
    /// @param token0 The first token of the pool by address sort order
    /// @param token1 The second token of the pool by address sort order
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks
    /// @param pool The address of the created pool
    event PoolCreated(
        address indexed token0,
        address indexed token1,
        uint24 indexed fee,
        int24 tickSpacing,
        address pool
    );

    /// @notice Emitted when a new fee amount is enabled for pool creation via the factory
    /// @param fee The enabled fee, denominated in hundredths of a bip
    /// @param tickSpacing The minimum number of ticks between initialized ticks for pools created with the given fee
    event FeeAmountEnabled(uint24 indexed fee, int24 indexed tickSpacing);

    /// @notice Returns the current owner of the factory
    /// @dev Can be changed by the current owner via setOwner
    /// @return The address of the factory owner
    function owner() external view returns (address);

    /// @notice Returns the tick spacing for a given fee amount, if enabled, or 0 if not enabled
    /// @dev A fee amount can never be removed, so this value should be hard coded or cached in the calling context
    /// @param fee The enabled fee, denominated in hundredths of a bip. Returns 0 in case of unenabled fee
    /// @return The tick spacing
    function feeAmountTickSpacing(uint24 fee) external view returns (int24);

    /// @notice Returns the pool address for a given pair of tokens and a fee, or address 0 if it does not exist
    /// @dev tokenA and tokenB may be passed in either token0/token1 or token1/token0 order
    /// @param tokenA The contract address of either token0 or token1
    /// @param tokenB The contract address of the other token
    /// @param fee The fee collected upon every swap in the pool, denominated in hundredths of a bip
    /// @return pool The pool address
    function getPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external view returns (address pool);

    /// @notice Creates a pool for the given two tokens and fee
    /// @param tokenA One of the two tokens in the desired pool
    /// @param tokenB The other of the two tokens in the desired pool
    /// @param fee The desired fee for the pool
    /// @dev tokenA and tokenB may be passed in either order: token0/token1 or token1/token0. tickSpacing is retrieved
    /// from the fee. The call will revert if the pool already exists, the fee is invalid, or the token arguments
    /// are invalid.
    /// @return pool The address of the newly created pool
    function createPool(
        address tokenA,
        address tokenB,
        uint24 fee
    ) external returns (address pool);

    /// @notice Updates the owner of the factory
    /// @dev Must be called by the current owner
    /// @param _owner The new owner of the factory
    function setOwner(address _owner) external;

    /// @notice Enables a fee amount with the given tickSpacing
    /// @dev Fee amounts may never be removed once enabled
    /// @param fee The fee amount to enable, denominated in hundredths of a bip (i.e. 1e-6)
    /// @param tickSpacing The spacing between ticks to be enforced for all pools created with the given fee amount
    function enableFeeAmount(uint24 fee, int24 tickSpacing) external;
}
IUniswapV3Pool.sol 24 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';

/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
    IUniswapV3PoolImmutables,
    IUniswapV3PoolState,
    IUniswapV3PoolDerivedState,
    IUniswapV3PoolActions,
    IUniswapV3PoolOwnerActions,
    IUniswapV3PoolEvents
{

}
IUniswapV3PoolActions.sol 103 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;

    /// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
    /// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
    /// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
    /// on tickLower, tickUpper, the amount of liquidity, and the current price.
    /// @param recipient The address for which the liquidity will be created
    /// @param tickLower The lower tick of the position in which to add liquidity
    /// @param tickUpper The upper tick of the position in which to add liquidity
    /// @param amount The amount of liquidity to mint
    /// @param data Any data that should be passed through to the callback
    /// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
    /// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
    function mint(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount,
        bytes calldata data
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Collects tokens owed to a position
    /// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
    /// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
    /// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
    /// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
    /// @param recipient The address which should receive the fees collected
    /// @param tickLower The lower tick of the position for which to collect fees
    /// @param tickUpper The upper tick of the position for which to collect fees
    /// @param amount0Requested How much token0 should be withdrawn from the fees owed
    /// @param amount1Requested How much token1 should be withdrawn from the fees owed
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(
        address recipient,
        int24 tickLower,
        int24 tickUpper,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);

    /// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
    /// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
    /// @dev Fees must be collected separately via a call to #collect
    /// @param tickLower The lower tick of the position for which to burn liquidity
    /// @param tickUpper The upper tick of the position for which to burn liquidity
    /// @param amount How much liquidity to burn
    /// @return amount0 The amount of token0 sent to the recipient
    /// @return amount1 The amount of token1 sent to the recipient
    function burn(
        int24 tickLower,
        int24 tickUpper,
        uint128 amount
    ) external returns (uint256 amount0, uint256 amount1);

    /// @notice Swap token0 for token1, or token1 for token0
    /// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
    /// @param recipient The address to receive the output of the swap
    /// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
    /// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
    /// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
    /// value after the swap. If one for zero, the price cannot be greater than this value after the swap
    /// @param data Any data to be passed through to the callback
    /// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
    /// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
    function swap(
        address recipient,
        bool zeroForOne,
        int256 amountSpecified,
        uint160 sqrtPriceLimitX96,
        bytes calldata data
    ) external returns (int256 amount0, int256 amount1);

    /// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
    /// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
    /// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
    /// with 0 amount{0,1} and sending the donation amount(s) from the callback
    /// @param recipient The address which will receive the token0 and token1 amounts
    /// @param amount0 The amount of token0 to send
    /// @param amount1 The amount of token1 to send
    /// @param data Any data to be passed through to the callback
    function flash(
        address recipient,
        uint256 amount0,
        uint256 amount1,
        bytes calldata data
    ) external;

    /// @notice Increase the maximum number of price and liquidity observations that this pool will store
    /// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
    /// the input observationCardinalityNext.
    /// @param observationCardinalityNext The desired minimum number of observations for the pool to store
    function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
IUniswapV3PoolDerivedState.sol 40 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
    /// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
    /// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
    /// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
    /// you must call it with secondsAgos = [3600, 0].
    /// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
    /// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
    /// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
    /// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
    /// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
    /// timestamp
    function observe(uint32[] calldata secondsAgos)
        external
        view
        returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);

    /// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
    /// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
    /// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
    /// snapshot is taken and the second snapshot is taken.
    /// @param tickLower The lower tick of the range
    /// @param tickUpper The upper tick of the range
    /// @return tickCumulativeInside The snapshot of the tick accumulator for the range
    /// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
    /// @return secondsInside The snapshot of seconds per liquidity for the range
    function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
        external
        view
        returns (
            int56 tickCumulativeInside,
            uint160 secondsPerLiquidityInsideX128,
            uint32 secondsInside
        );
}
IUniswapV3PoolEvents.sol 121 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
    /// @notice Emitted exactly once by a pool when #initialize is first called on the pool
    /// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
    /// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
    /// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
    event Initialize(uint160 sqrtPriceX96, int24 tick);

    /// @notice Emitted when liquidity is minted for a given position
    /// @param sender The address that minted the liquidity
    /// @param owner The owner of the position and recipient of any minted liquidity
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity minted to the position range
    /// @param amount0 How much token0 was required for the minted liquidity
    /// @param amount1 How much token1 was required for the minted liquidity
    event Mint(
        address sender,
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted when fees are collected by the owner of a position
    /// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
    /// @param owner The owner of the position for which fees are collected
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount0 The amount of token0 fees collected
    /// @param amount1 The amount of token1 fees collected
    event Collect(
        address indexed owner,
        address recipient,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount0,
        uint128 amount1
    );

    /// @notice Emitted when a position's liquidity is removed
    /// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
    /// @param owner The owner of the position for which liquidity is removed
    /// @param tickLower The lower tick of the position
    /// @param tickUpper The upper tick of the position
    /// @param amount The amount of liquidity to remove
    /// @param amount0 The amount of token0 withdrawn
    /// @param amount1 The amount of token1 withdrawn
    event Burn(
        address indexed owner,
        int24 indexed tickLower,
        int24 indexed tickUpper,
        uint128 amount,
        uint256 amount0,
        uint256 amount1
    );

    /// @notice Emitted by the pool for any swaps between token0 and token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the output of the swap
    /// @param amount0 The delta of the token0 balance of the pool
    /// @param amount1 The delta of the token1 balance of the pool
    /// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
    /// @param liquidity The liquidity of the pool after the swap
    /// @param tick The log base 1.0001 of price of the pool after the swap
    event Swap(
        address indexed sender,
        address indexed recipient,
        int256 amount0,
        int256 amount1,
        uint160 sqrtPriceX96,
        uint128 liquidity,
        int24 tick
    );

    /// @notice Emitted by the pool for any flashes of token0/token1
    /// @param sender The address that initiated the swap call, and that received the callback
    /// @param recipient The address that received the tokens from flash
    /// @param amount0 The amount of token0 that was flashed
    /// @param amount1 The amount of token1 that was flashed
    /// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
    /// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
    event Flash(
        address indexed sender,
        address indexed recipient,
        uint256 amount0,
        uint256 amount1,
        uint256 paid0,
        uint256 paid1
    );

    /// @notice Emitted by the pool for increases to the number of observations that can be stored
    /// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
    /// just before a mint/swap/burn.
    /// @param observationCardinalityNextOld The previous value of the next observation cardinality
    /// @param observationCardinalityNextNew The updated value of the next observation cardinality
    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    /// @notice Emitted when the protocol fee is changed by the pool
    /// @param feeProtocol0Old The previous value of the token0 protocol fee
    /// @param feeProtocol1Old The previous value of the token1 protocol fee
    /// @param feeProtocol0New The updated value of the token0 protocol fee
    /// @param feeProtocol1New The updated value of the token1 protocol fee
    event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);

    /// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
    /// @param sender The address that collects the protocol fees
    /// @param recipient The address that receives the collected protocol fees
    /// @param amount0 The amount of token0 protocol fees that is withdrawn
    /// @param amount0 The amount of token1 protocol fees that is withdrawn
    event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
IUniswapV3PoolImmutables.sol 35 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
    /// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
    /// @return The contract address
    function factory() external view returns (address);

    /// @notice The first of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token0() external view returns (address);

    /// @notice The second of the two tokens of the pool, sorted by address
    /// @return The token contract address
    function token1() external view returns (address);

    /// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
    /// @return The fee
    function fee() external view returns (uint24);

    /// @notice The pool tick spacing
    /// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
    /// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
    /// This value is an int24 to avoid casting even though it is always positive.
    /// @return The tick spacing
    function tickSpacing() external view returns (int24);

    /// @notice The maximum amount of position liquidity that can use any tick in the range
    /// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
    /// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
    /// @return The max amount of liquidity per tick
    function maxLiquidityPerTick() external view returns (uint128);
}
IUniswapV3PoolOwnerActions.sol 23 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
    /// @notice Set the denominator of the protocol's % share of the fees
    /// @param feeProtocol0 new protocol fee for token0 of the pool
    /// @param feeProtocol1 new protocol fee for token1 of the pool
    function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;

    /// @notice Collect the protocol fee accrued to the pool
    /// @param recipient The address to which collected protocol fees should be sent
    /// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
    /// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
    /// @return amount0 The protocol fee collected in token0
    /// @return amount1 The protocol fee collected in token1
    function collectProtocol(
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint128 amount0, uint128 amount1);
}
IUniswapV3PoolState.sol 116 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
    /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
    /// when accessed externally.
    /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
    /// tick The current tick of the pool, i.e. according to the last tick transition that was run.
    /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
    /// boundary.
    /// observationIndex The index of the last oracle observation that was written,
    /// observationCardinality The current maximum number of observations stored in the pool,
    /// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
    /// feeProtocol The protocol fee for both tokens of the pool.
    /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
    /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
    /// unlocked Whether the pool is currently locked to reentrancy
    function slot0()
        external
        view
        returns (
            uint160 sqrtPriceX96,
            int24 tick,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext,
            uint8 feeProtocol,
            bool unlocked
        );

    /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal0X128() external view returns (uint256);

    /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
    /// @dev This value can overflow the uint256
    function feeGrowthGlobal1X128() external view returns (uint256);

    /// @notice The amounts of token0 and token1 that are owed to the protocol
    /// @dev Protocol fees will never exceed uint128 max in either token
    function protocolFees() external view returns (uint128 token0, uint128 token1);

    /// @notice The currently in range liquidity available to the pool
    /// @dev This value has no relationship to the total liquidity across all ticks
    function liquidity() external view returns (uint128);

    /// @notice Look up information about a specific tick in the pool
    /// @param tick The tick to look up
    /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
    /// tick upper,
    /// liquidityNet how much liquidity changes when the pool price crosses the tick,
    /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
    /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
    /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
    /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
    /// secondsOutside the seconds spent on the other side of the tick from the current tick,
    /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
    /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
    /// In addition, these values are only relative and must be used only in comparison to previous snapshots for
    /// a specific position.
    function ticks(int24 tick)
        external
        view
        returns (
            uint128 liquidityGross,
            int128 liquidityNet,
            uint256 feeGrowthOutside0X128,
            uint256 feeGrowthOutside1X128,
            int56 tickCumulativeOutside,
            uint160 secondsPerLiquidityOutsideX128,
            uint32 secondsOutside,
            bool initialized
        );

    /// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
    function tickBitmap(int16 wordPosition) external view returns (uint256);

    /// @notice Returns the information about a position by the position's key
    /// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
    /// @return _liquidity The amount of liquidity in the position,
    /// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
    /// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
    /// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
    /// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
    function positions(bytes32 key)
        external
        view
        returns (
            uint128 _liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    /// @notice Returns data about a specific observation index
    /// @param index The element of the observations array to fetch
    /// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
    /// ago, rather than at a specific index in the array.
    /// @return blockTimestamp The timestamp of the observation,
    /// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
    /// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
    /// Returns initialized whether the observation has been initialized and the values are safe to use
    function observations(uint256 index)
        external
        view
        returns (
            uint32 blockTimestamp,
            int56 tickCumulative,
            uint160 secondsPerLiquidityCumulativeX128,
            bool initialized
        );
}
FullMath.sol 124 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;

/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
    /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
    function mulDiv(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        // 512-bit multiply [prod1 prod0] = a * b
        // Compute the product mod 2**256 and mod 2**256 - 1
        // then use the Chinese Remainder Theorem to reconstruct
        // the 512 bit result. The result is stored in two 256
        // variables such that product = prod1 * 2**256 + prod0
        uint256 prod0; // Least significant 256 bits of the product
        uint256 prod1; // Most significant 256 bits of the product
        assembly {
            let mm := mulmod(a, b, not(0))
            prod0 := mul(a, b)
            prod1 := sub(sub(mm, prod0), lt(mm, prod0))
        }

        // Handle non-overflow cases, 256 by 256 division
        if (prod1 == 0) {
            require(denominator > 0);
            assembly {
                result := div(prod0, denominator)
            }
            return result;
        }

        // Make sure the result is less than 2**256.
        // Also prevents denominator == 0
        require(denominator > prod1);

        ///////////////////////////////////////////////
        // 512 by 256 division.
        ///////////////////////////////////////////////

        // Make division exact by subtracting the remainder from [prod1 prod0]
        // Compute remainder using mulmod
        uint256 remainder;
        assembly {
            remainder := mulmod(a, b, denominator)
        }
        // Subtract 256 bit number from 512 bit number
        assembly {
            prod1 := sub(prod1, gt(remainder, prod0))
            prod0 := sub(prod0, remainder)
        }

        // Factor powers of two out of denominator
        // Compute largest power of two divisor of denominator.
        // Always >= 1.
        uint256 twos = -denominator & denominator;
        // Divide denominator by power of two
        assembly {
            denominator := div(denominator, twos)
        }

        // Divide [prod1 prod0] by the factors of two
        assembly {
            prod0 := div(prod0, twos)
        }
        // Shift in bits from prod1 into prod0. For this we need
        // to flip `twos` such that it is 2**256 / twos.
        // If twos is zero, then it becomes one
        assembly {
            twos := add(div(sub(0, twos), twos), 1)
        }
        prod0 |= prod1 * twos;

        // Invert denominator mod 2**256
        // Now that denominator is an odd number, it has an inverse
        // modulo 2**256 such that denominator * inv = 1 mod 2**256.
        // Compute the inverse by starting with a seed that is correct
        // correct for four bits. That is, denominator * inv = 1 mod 2**4
        uint256 inv = (3 * denominator) ^ 2;
        // Now use Newton-Raphson iteration to improve the precision.
        // Thanks to Hensel's lifting lemma, this also works in modular
        // arithmetic, doubling the correct bits in each step.
        inv *= 2 - denominator * inv; // inverse mod 2**8
        inv *= 2 - denominator * inv; // inverse mod 2**16
        inv *= 2 - denominator * inv; // inverse mod 2**32
        inv *= 2 - denominator * inv; // inverse mod 2**64
        inv *= 2 - denominator * inv; // inverse mod 2**128
        inv *= 2 - denominator * inv; // inverse mod 2**256

        // Because the division is now exact we can divide by multiplying
        // with the modular inverse of denominator. This will give us the
        // correct result modulo 2**256. Since the precoditions guarantee
        // that the outcome is less than 2**256, this is the final result.
        // We don't need to compute the high bits of the result and prod1
        // is no longer required.
        result = prod0 * inv;
        return result;
    }

    /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
    /// @param a The multiplicand
    /// @param b The multiplier
    /// @param denominator The divisor
    /// @return result The 256-bit result
    function mulDivRoundingUp(
        uint256 a,
        uint256 b,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        result = mulDiv(a, b, denominator);
        if (mulmod(a, b, denominator) > 0) {
            require(result < type(uint256).max);
            result++;
        }
    }
}
IUniswapV3SwapCallback.sol 21 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
    /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
    /// @dev In the implementation you must pay the pool tokens owed for the swap.
    /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
    /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
    /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
    /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
    /// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
    /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
    function uniswapV3SwapCallback(
        int256 amount0Delta,
        int256 amount1Delta,
        bytes calldata data
    ) external;
}
Multicall.sol 28 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '../interfaces/IMulticall.sol';

/// @title Multicall
/// @notice Enables calling multiple methods in a single call to the contract
abstract contract Multicall is IMulticall {
    /// @inheritdoc IMulticall
    function multicall(bytes[] calldata data) public payable override returns (bytes[] memory results) {
        results = new bytes[](data.length);
        for (uint256 i = 0; i < data.length; i++) {
            (bool success, bytes memory result) = address(this).delegatecall(data[i]);

            if (!success) {
                // Next 5 lines from https://ethereum.stackexchange.com/a/83577
                if (result.length < 68) revert();
                assembly {
                    result := add(result, 0x04)
                }
                revert(abi.decode(result, (string)));
            }

            results[i] = result;
        }
    }
}
IERC721Permit.sol 32 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

import '@openzeppelin/contracts/token/ERC721/IERC721.sol';

/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
    /// @notice The permit typehash used in the permit signature
    /// @return The typehash for the permit
    function PERMIT_TYPEHASH() external pure returns (bytes32);

    /// @notice The domain separator used in the permit signature
    /// @return The domain seperator used in encoding of permit signature
    function DOMAIN_SEPARATOR() external view returns (bytes32);

    /// @notice Approve of a specific token ID for spending by spender via signature
    /// @param spender The account that is being approved
    /// @param tokenId The ID of the token that is being approved for spending
    /// @param deadline The deadline timestamp by which the call must be mined for the approve to work
    /// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
    /// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
    /// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
    function permit(
        address spender,
        uint256 tokenId,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) external payable;
}
IMulticall.sol 13 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Multicall interface
/// @notice Enables calling multiple methods in a single call to the contract
interface IMulticall {
    /// @notice Call multiple functions in the current contract and return the data from all of them if they all succeed
    /// @dev The `msg.value` should not be trusted for any method callable from multicall.
    /// @param data The encoded function data for each of the calls to make to this contract
    /// @return results The results from each of the calls passed in via data
    function multicall(bytes[] calldata data) external payable returns (bytes[] memory results);
}
INonfungiblePositionManager.sol 180 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

import '@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol';

import './IPoolInitializer.sol';
import './IERC721Permit.sol';
import './IPeripheryPayments.sol';
import './IPeripheryImmutableState.sol';
import '../libraries/PoolAddress.sol';

/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
    IPoolInitializer,
    IPeripheryPayments,
    IPeripheryImmutableState,
    IERC721Metadata,
    IERC721Enumerable,
    IERC721Permit
{
    /// @notice Emitted when liquidity is increased for a position NFT
    /// @dev Also emitted when a token is minted
    /// @param tokenId The ID of the token for which liquidity was increased
    /// @param liquidity The amount by which liquidity for the NFT position was increased
    /// @param amount0 The amount of token0 that was paid for the increase in liquidity
    /// @param amount1 The amount of token1 that was paid for the increase in liquidity
    event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when liquidity is decreased for a position NFT
    /// @param tokenId The ID of the token for which liquidity was decreased
    /// @param liquidity The amount by which liquidity for the NFT position was decreased
    /// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
    /// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
    event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
    /// @notice Emitted when tokens are collected for a position NFT
    /// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
    /// @param tokenId The ID of the token for which underlying tokens were collected
    /// @param recipient The address of the account that received the collected tokens
    /// @param amount0 The amount of token0 owed to the position that was collected
    /// @param amount1 The amount of token1 owed to the position that was collected
    event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);

    /// @notice Returns the position information associated with a given token ID.
    /// @dev Throws if the token ID is not valid.
    /// @param tokenId The ID of the token that represents the position
    /// @return nonce The nonce for permits
    /// @return operator The address that is approved for spending
    /// @return token0 The address of the token0 for a specific pool
    /// @return token1 The address of the token1 for a specific pool
    /// @return fee The fee associated with the pool
    /// @return tickLower The lower end of the tick range for the position
    /// @return tickUpper The higher end of the tick range for the position
    /// @return liquidity The liquidity of the position
    /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
    /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
    /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
    /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
    function positions(uint256 tokenId)
        external
        view
        returns (
            uint96 nonce,
            address operator,
            address token0,
            address token1,
            uint24 fee,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity,
            uint256 feeGrowthInside0LastX128,
            uint256 feeGrowthInside1LastX128,
            uint128 tokensOwed0,
            uint128 tokensOwed1
        );

    struct MintParams {
        address token0;
        address token1;
        uint24 fee;
        int24 tickLower;
        int24 tickUpper;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        address recipient;
        uint256 deadline;
    }

    /// @notice Creates a new position wrapped in a NFT
    /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
    /// a method does not exist, i.e. the pool is assumed to be initialized.
    /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
    /// @return tokenId The ID of the token that represents the minted position
    /// @return liquidity The amount of liquidity for this position
    /// @return amount0 The amount of token0
    /// @return amount1 The amount of token1
    function mint(MintParams calldata params)
        external
        payable
        returns (
            uint256 tokenId,
            uint128 liquidity,
            uint256 amount0,
            uint256 amount1
        );

    struct IncreaseLiquidityParams {
        uint256 tokenId;
        uint256 amount0Desired;
        uint256 amount1Desired;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
    /// @param params tokenId The ID of the token for which liquidity is being increased,
    /// amount0Desired The desired amount of token0 to be spent,
    /// amount1Desired The desired amount of token1 to be spent,
    /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
    /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return liquidity The new liquidity amount as a result of the increase
    /// @return amount0 The amount of token0 to acheive resulting liquidity
    /// @return amount1 The amount of token1 to acheive resulting liquidity
    function increaseLiquidity(IncreaseLiquidityParams calldata params)
        external
        payable
        returns (
            uint128 liquidity,
            uint256 amount0,
            uint256 amount1
        );

    struct DecreaseLiquidityParams {
        uint256 tokenId;
        uint128 liquidity;
        uint256 amount0Min;
        uint256 amount1Min;
        uint256 deadline;
    }

    /// @notice Decreases the amount of liquidity in a position and accounts it to the position
    /// @param params tokenId The ID of the token for which liquidity is being decreased,
    /// amount The amount by which liquidity will be decreased,
    /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
    /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
    /// deadline The time by which the transaction must be included to effect the change
    /// @return amount0 The amount of token0 accounted to the position's tokens owed
    /// @return amount1 The amount of token1 accounted to the position's tokens owed
    function decreaseLiquidity(DecreaseLiquidityParams calldata params)
        external
        payable
        returns (uint256 amount0, uint256 amount1);

    struct CollectParams {
        uint256 tokenId;
        address recipient;
        uint128 amount0Max;
        uint128 amount1Max;
    }

    /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
    /// @param params tokenId The ID of the NFT for which tokens are being collected,
    /// recipient The account that should receive the tokens,
    /// amount0Max The maximum amount of token0 to collect,
    /// amount1Max The maximum amount of token1 to collect
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);

    /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
    /// must be collected first.
    /// @param tokenId The ID of the token that is being burned
    function burn(uint256 tokenId) external payable;
}
IPeripheryImmutableState.sol 12 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
    /// @return Returns the address of the Uniswap V3 factory
    function factory() external view returns (address);

    /// @return Returns the address of WETH9
    function WETH9() external view returns (address);
}
IPeripheryPayments.sol 28 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
    /// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
    /// @param amountMinimum The minimum amount of WETH9 to unwrap
    /// @param recipient The address receiving ETH
    function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;

    /// @notice Refunds any ETH balance held by this contract to the `msg.sender`
    /// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
    /// that use ether for the input amount
    function refundETH() external payable;

    /// @notice Transfers the full amount of a token held by this contract to recipient
    /// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
    /// @param token The contract address of the token which will be transferred to `recipient`
    /// @param amountMinimum The minimum amount of token required for a transfer
    /// @param recipient The destination address of the token
    function sweepToken(
        address token,
        uint256 amountMinimum,
        address recipient
    ) external payable;
}
IPoolInitializer.sol 22 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
    /// @notice Creates a new pool if it does not exist, then initializes if not initialized
    /// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
    /// @param token0 The contract address of token0 of the pool
    /// @param token1 The contract address of token1 of the pool
    /// @param fee The fee amount of the v3 pool for the specified token pair
    /// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
    /// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
    function createAndInitializePoolIfNecessary(
        address token0,
        address token1,
        uint24 fee,
        uint160 sqrtPriceX96
    ) external payable returns (address pool);
}
IQuoter.sol 51 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

/// @title Quoter Interface
/// @notice Supports quoting the calculated amounts from exact input or exact output swaps
/// @dev These functions are not marked view because they rely on calling non-view functions and reverting
/// to compute the result. They are also not gas efficient and should not be called on-chain.
interface IQuoter {
    /// @notice Returns the amount out received for a given exact input swap without executing the swap
    /// @param path The path of the swap, i.e. each token pair and the pool fee
    /// @param amountIn The amount of the first token to swap
    /// @return amountOut The amount of the last token that would be received
    function quoteExactInput(bytes memory path, uint256 amountIn) external returns (uint256 amountOut);

    /// @notice Returns the amount out received for a given exact input but for a swap of a single pool
    /// @param tokenIn The token being swapped in
    /// @param tokenOut The token being swapped out
    /// @param fee The fee of the token pool to consider for the pair
    /// @param amountIn The desired input amount
    /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountOut The amount of `tokenOut` that would be received
    function quoteExactInputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountIn,
        uint160 sqrtPriceLimitX96
    ) external returns (uint256 amountOut);

    /// @notice Returns the amount in required for a given exact output swap without executing the swap
    /// @param path The path of the swap, i.e. each token pair and the pool fee. Path must be provided in reverse order
    /// @param amountOut The amount of the last token to receive
    /// @return amountIn The amount of first token required to be paid
    function quoteExactOutput(bytes memory path, uint256 amountOut) external returns (uint256 amountIn);

    /// @notice Returns the amount in required to receive the given exact output amount but for a swap of a single pool
    /// @param tokenIn The token being swapped in
    /// @param tokenOut The token being swapped out
    /// @param fee The fee of the token pool to consider for the pair
    /// @param amountOut The desired output amount
    /// @param sqrtPriceLimitX96 The price limit of the pool that cannot be exceeded by the swap
    /// @return amountIn The amount required as the input for the swap in order to receive `amountOut`
    function quoteExactOutputSingle(
        address tokenIn,
        address tokenOut,
        uint24 fee,
        uint256 amountOut,
        uint160 sqrtPriceLimitX96
    ) external returns (uint256 amountIn);
}
ISwapRouter.sol 67 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3SwapCallback.sol';

/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
    struct ExactInputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);

    struct ExactInputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountIn;
        uint256 amountOutMinimum;
    }

    /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
    /// @return amountOut The amount of the received token
    function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);

    struct ExactOutputSingleParams {
        address tokenIn;
        address tokenOut;
        uint24 fee;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
        uint160 sqrtPriceLimitX96;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another token
    /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);

    struct ExactOutputParams {
        bytes path;
        address recipient;
        uint256 deadline;
        uint256 amountOut;
        uint256 amountInMaximum;
    }

    /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
    /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
    /// @return amountIn The amount of the input token
    function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
PoolAddress.sol 48 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;

/// @title Provides functions for deriving a pool address from the factory, tokens, and the fee
library PoolAddress {
    bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;

    /// @notice The identifying key of the pool
    struct PoolKey {
        address token0;
        address token1;
        uint24 fee;
    }

    /// @notice Returns PoolKey: the ordered tokens with the matched fee levels
    /// @param tokenA The first token of a pool, unsorted
    /// @param tokenB The second token of a pool, unsorted
    /// @param fee The fee level of the pool
    /// @return Poolkey The pool details with ordered token0 and token1 assignments
    function getPoolKey(
        address tokenA,
        address tokenB,
        uint24 fee
    ) internal pure returns (PoolKey memory) {
        if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
        return PoolKey({token0: tokenA, token1: tokenB, fee: fee});
    }

    /// @notice Deterministically computes the pool address given the factory and PoolKey
    /// @param factory The Uniswap V3 factory contract address
    /// @param key The PoolKey
    /// @return pool The contract address of the V3 pool
    function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
        require(key.token0 < key.token1);
        pool = address(
            uint256(
                keccak256(
                    abi.encodePacked(
                        hex'ff',
                        factory,
                        keccak256(abi.encode(key.token0, key.token1, key.fee)),
                        POOL_INIT_CODE_HASH
                    )
                )
            )
        );
    }
}
TransferHelper.sol 60 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

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

library TransferHelper {
    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) =
            token.call(abi.encodeWithSelector(IERC20.transferFrom.selector, from, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'STF');
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.transfer.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'ST');
    }

    /// @notice Approves the stipulated contract to spend the given allowance in the given token
    /// @dev Errors with 'SA' if transfer fails
    /// @param token The contract address of the token to be approved
    /// @param to The target of the approval
    /// @param value The amount of the given token the target will be allowed to spend
    function safeApprove(
        address token,
        address to,
        uint256 value
    ) internal {
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(IERC20.approve.selector, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'SA');
    }

    /// @notice Transfers ETH to the recipient address
    /// @dev Fails with `STE`
    /// @param to The destination of the transfer
    /// @param value The value to be transferred
    function safeTransferETH(address to, uint256 value) internal {
        (bool success, ) = to.call{value: value}(new bytes(0));
        require(success, 'STE');
    }
}
ERC20Staker.sol 664 lines
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol';
import '@openzeppelin/contracts/utils/EnumerableSet.sol';
import '@openzeppelin/contracts/math/SafeMath.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import './libraries/TransferHelperExtended.sol';
import './EmissionController.sol';

/// @title ERC20 Staking Manager
/// @notice Manages the staking of ERC20 tokens with various reward distribution mechanisms and locks vs unlocked incentives
contract ERC20Staker is Ownable {
    using EnumerableSet for EnumerableSet.Bytes32Set;
    using SafeMath for uint;

    struct ERC20IncentiveKey {
        IERC20Minimal rewardToken;
        IERC20Minimal stakingToken;
        uint256 reward;
        uint256 startTime;
        uint256 endTime;
        address refundee;
        IEmissionController.EmissionSettings emissionSettings;
        bool isLocked;  // If entered, the tokens must remain in the incentive for the entire duration. Rewards can be claimed.
    }

    struct ERC20Incentive {
        ERC20IncentiveKey key;
        uint256 totalRewardUnclaimed;
        uint256 totalStaked;
        uint256 rewardPerTokenStored;
        uint256 lastUpdateTime;
        uint256 rewardRate;
    }

    struct ERC20Stake {
        uint256 amount;
        uint256 rewardPerTokenPaid;
        uint256 rewards;
    }

    /// @dev External view of stake state
    struct StakeInfo {
        bytes32 incentiveId;
        IERC20Minimal stakingToken;
        IERC20Minimal rewardToken;
        uint256 stakeAmount;
        uint256 earnedReward;
        bool isLocked;
        uint256 startTime;
        uint256 endTime;
    }

    IEmissionController public immutable emissionController;
    uint256 public immutable maxIncentiveStartLeadTime;
    uint256 public immutable maxIncentiveDuration;
    uint256 public constant MAX_STAGING_DURATION = 30 days;
    uint256 public immutable END_GRACE_PERIOD;
    uint256 private constant PRECISION = 1e27;

    // Maps user address and incentive ID to their stake
    mapping(address => mapping(bytes32 => ERC20Stake)) private _erc20Stakes;
    // Maps incentive IDs to their mutable state
    mapping(bytes32 => ERC20Incentive) public erc20Incentives;
    // Maps users to set of incentive IDs they've staked in
    mapping(address => EnumerableSet.Bytes32Set) private _userERC20IncentiveIds;
    // All currently active erc20 incentive programmes
    EnumerableSet.Bytes32Set private _activeIncentives;
    // Tracks if a locked user has been unlocked from an incentive
    mapping(address => mapping(bytes32 => bool)) public userLockReleased;

    event ERC20IncentiveCreated(
        bytes32 indexed incentiveId,
        IERC20Minimal indexed rewardToken,
        IERC20Minimal indexed stakingToken,
        uint256 startTime,
        uint256 endTime,
        address refundee,
        uint256 reward,
        IEmissionController.EmissionStyle emissionStyle,
        bool isLocked
    );
    event ERC20Staked(bytes32 indexed incentiveId, address indexed user, uint256 amount);
    event ERC20Unstaked(bytes32 indexed incentiveId, address indexed user, uint256 amount, uint256 reward);
    event ERC20RewardClaimed(bytes32 indexed incentiveId, address indexed user, uint256 reward);
    event ERC20IncentiveEnded(bytes32 indexed incentiveId, uint256 refund);
    event ERC20LockReleased(address indexed user, bytes32 indexed incentiveId);
    event ERC20LockReset(address indexed user, bytes32 indexed incentiveId);
    event RewardClaimed(IERC20Minimal indexed rewardToken, address indexed to, uint256 amount);
    event ERC20IncentiveUnlocked(bytes32 indexed incentiveId);

    /// @notice Constructs a new ERC20Staker contract with given parameters
    /// @param _maxIncentiveStartLeadTime The max seconds into the future incentives can be scheduled
    /// @param _maxIncentiveDuration The max duration of an incentive in seconds
    constructor(
        uint256 _maxIncentiveStartLeadTime,
        uint256 _maxIncentiveDuration,
        uint256 _endGracePeriod
    ) {
        emissionController = new EmissionController();
        maxIncentiveStartLeadTime = _maxIncentiveStartLeadTime;
        maxIncentiveDuration = _maxIncentiveDuration;
        END_GRACE_PERIOD = _endGracePeriod;
    }

    /// @notice Creates a deterministic incentive ID
    function computeERC20IncentiveId(ERC20IncentiveKey memory key) public pure returns (bytes32 incentiveId) {
        return keccak256(abi.encode(
            key.rewardToken,
            key.stakingToken,
            key.reward,
            key.startTime,
            key.endTime,
            key.refundee,
            key.isLocked,
            key.emissionSettings.emissionStyle,
            key.emissionSettings.period,
            key.emissionSettings.cliff,
            key.emissionSettings.stagingDuration,
            key.emissionSettings.isForfeitable
        ));
    }

    /// @notice Returns the current reward per token value for an incentive
    function rewardPerToken(bytes32 incentiveId) public view returns (uint256) {
        ERC20Incentive storage incentive = erc20Incentives[incentiveId];

        if (incentive.totalStaked == 0) {
            return incentive.rewardPerTokenStored;
        }

        // Calculate the correct last update time based on incentive boundaries
        uint256 lastTimeRewardApplicable = block.timestamp < incentive.key.endTime
            ? block.timestamp
            : incentive.key.endTime;

        if (lastTimeRewardApplicable <= incentive.lastUpdateTime) {
            // It's fine to return this early, as per block, we're only incrementing the rewardPerTokenStored once.
            // It doesn't matter how many stakes happen happen in that block, since on the first update, incentive.totalStaked is read
            // before adjusting to account for the new stake.  And, on subsequent updates,
            // the time between lastTimeRewardApplicable and incentive.lastUpdateTime when subtracted will always be zero
            return incentive.rewardPerTokenStored;
        }

        // Calculate additional reward per token since last update
        // Note: rewardRate already includes PRECISION scaling
        return incentive.rewardPerTokenStored.add(
            lastTimeRewardApplicable
            .sub(incentive.lastUpdateTime)
            .mul(incentive.rewardRate)
            .div(incentive.totalStaked)
        );
    }

    /// @notice Returns the amount of cumulative reward tokens a user has earned
    function earned(address user, bytes32 incentiveId) public view returns (uint256) {
        ERC20Stake storage stake = _erc20Stakes[user][incentiveId];
        if (stake.amount == 0) {
            return 0;
        }

        uint256 currentRewardPerToken = rewardPerToken(incentiveId);
        uint256 rewardsSinceLastCalculation = stake.amount
            .mul(currentRewardPerToken.sub(stake.rewardPerTokenPaid))
            .div(PRECISION);

        return stake.rewards.add(rewardsSinceLastCalculation);
    }

    /// @notice Updates the reward accounting for a specific user
    function _updateReward(address user, bytes32 incentiveId) private {
        ERC20Stake storage stake = _erc20Stakes[user][incentiveId];
        ERC20Incentive storage incentive = erc20Incentives[incentiveId];

        // Update incentive-level reward tracking
        incentive.rewardPerTokenStored = rewardPerToken(incentiveId);
        incentive.lastUpdateTime = block.timestamp < incentive.key.endTime
            ? block.timestamp
            : incentive.key.endTime;

        // Update user-level reward tracking
        stake.rewards = earned(user, incentiveId);
        stake.rewardPerTokenPaid = incentive.rewardPerTokenStored;
    }


    /// @notice Creates a new incentive for ERC20 token staking
    function createERC20Incentive(ERC20IncentiveKey memory key) external onlyOwner returns (bytes32 incentiveId) {
        require(
            key.reward > 0,
            'ERC20Staker::createERC20Incentive: reward must be positive'
        );

        require(
            block.timestamp <= key.startTime,
            'ERC20Staker::createERC20Incentive: start time must be now or in the future'
        );

        require(
            key.startTime - block.timestamp <= maxIncentiveStartLeadTime,
            'ERC20Staker::createERC20Incentive: start time too far into future'
        );

        require(
            key.startTime < key.endTime,
            'ERC20Staker::createERC20Incentive: start time must be before end time'
        );

        require(
            key.endTime - key.startTime <= maxIncentiveDuration,
            'ERC20Staker::createERC20Incentive: incentive duration is too long'
        );

        require(
            key.refundee != address(0),
            'ERC20Staker::createERC20Incentive: refundee must be a valid address'
        );

        // Check emission settings
        if (key.emissionSettings.emissionStyle != IEmissionController.EmissionStyle.Regular) {
            require(
                key.emissionSettings.period > 0,
                'ERC20Staker::createERC20Incentive: period must be positive when using Dripped/Vested emission style'
            );

            require(
                key.emissionSettings.period <= 730 days,
                'ERC20Staker::createERC20Incentive: period cannot exceed 2 years'
            );

            require(
                key.emissionSettings.cliff < key.emissionSettings.period,
                'ERC20Staker::createERC20Incentive: cliff must be less than period'
            );

            require(
                key.emissionSettings.stagingDuration <= MAX_STAGING_DURATION,
                'ERC20Staker::createERC20Incentive: invalid staging duration'
            );
        }

        // Generate a unique incentive ID
        incentiveId = computeERC20IncentiveId(key);

        // Make sure this incentive doesn't already exist
        require(
            erc20Incentives[incentiveId].totalRewardUnclaimed == 0,
            'ERC20Staker::createERC20Incentive: incentive already exists'
        );

        // Calculate reward rate with precision (rewards per second * PRECISION)
        uint256 duration = key.endTime.sub(key.startTime);
        uint256 rewardRate = key.reward.mul(PRECISION).div(duration);

        require(
            rewardRate > 0,
            'ERC20Staker::createERC20Incentive: reward rate must be positive'
        );

        // Create the incentive
        erc20Incentives[incentiveId] = ERC20Incentive({
            key: key,
            totalRewardUnclaimed: key.reward,
            totalStaked: 0,
            rewardPerTokenStored: 0,
            lastUpdateTime: key.startTime,
            rewardRate: rewardRate
        });

        // Add the incentive ID to the active incentives set
        _activeIncentives.add(incentiveId);

        // Transfer the reward tokens to this contract
        TransferHelperExtended.safeTransferFrom(address(key.rewardToken), msg.sender, address(this), key.reward);
        emit ERC20IncentiveCreated(
            incentiveId,
            key.rewardToken,
            key.stakingToken,
            key.startTime,
            key.endTime,
            key.refundee,
            key.reward,
            key.emissionSettings.emissionStyle,
            key.isLocked
        );

        return incentiveId;
    }

    /// @notice Stake ERC20 tokens in an incentive
    /// @dev User can stake in multiple incentives for the same token
    function stakeERC20(bytes32 incentiveId, uint256 amount) external {
        require(
            amount > 0,
            'ERC20Staker::stakeERC20: amount must be positive'
        );

        ERC20Incentive storage incentive = erc20Incentives[incentiveId];

        require(
            incentive.totalRewardUnclaimed > 0,
            'ERC20Staker::stakeERC20: non-existent incentive'
        );

        require(
            block.timestamp >= incentive.key.startTime,
            'ERC20Staker::stakeERC20: incentive not started'
        );

        require(
            block.timestamp < incentive.key.endTime,
            'ERC20Staker::stakeERC20: incentive ended'
        );

        // Get the user's current stake for this incentive
        ERC20Stake storage stake = _erc20Stakes[msg.sender][incentiveId];

        // Update rewards before changing stake
        _updateReward(msg.sender, incentiveId);

        // If this is a new stake for this incentive, add to the user's incentive list
        if (stake.amount == 0) {
            _userERC20IncentiveIds[msg.sender].add(incentiveId);
        }

        // Update stake amount
        stake.amount = stake.amount.add(amount);

        // Update total staked amount in the incentive
        incentive.totalStaked = incentive.totalStaked.add(amount);

        // Transfer tokens from user to contract
        TransferHelperExtended.safeTransferFrom(
            address(incentive.key.stakingToken),
            msg.sender,
            address(this),
            amount
        );

        emit ERC20Staked(incentiveId, msg.sender, amount);
    }

    /// @notice Unstake ERC20 tokens from a specific incentive
    /// @param incentiveId The ID of the incentive to unstake from
    /// @param amount The amount to unstake (0 to unstake all)
    /// @return reward The amount of reward earned
    function unstakeERC20(bytes32 incentiveId, uint256 amount) external returns (uint256 reward) {
        ERC20Stake storage stake = _erc20Stakes[msg.sender][incentiveId];

        require(
            stake.amount > 0,
            'ERC20Staker::unstakeERC20: no stake found'
        );

        ERC20Incentive storage incentive = erc20Incentives[incentiveId];

        // For locked incentives, only allow unstaking after incentive has ended, or unlocked via exception
        if (incentive.key.isLocked && !userLockReleased[msg.sender][incentiveId]) {
            require(
                block.timestamp >= incentive.key.endTime,
                'ERC20Staker::unstakeERC20: cannot unstake from locked incentive before end time'
            );
        }

        // If amount is 0 or greater than staked amount, unstake all
        uint256 amountToUnstake = (amount == 0 || amount > stake.amount) ? stake.amount : amount;

        // Update rewards before changing stake
        _updateReward(msg.sender, incentiveId);

        // Get earned rewards
        reward = stake.rewards;

        // Reset rewards since we're distributing them
        stake.rewards = 0;

        // Update stake data
        stake.amount = stake.amount.sub(amountToUnstake);
        incentive.totalStaked = incentive.totalStaked.sub(amountToUnstake);

        // If completely unstaked, clean up
        if (stake.amount == 0) {
            _userERC20IncentiveIds[msg.sender].remove(incentiveId);
        }

        // Transfer tokens back to user
        TransferHelperExtended.safeTransfer(
            address(incentive.key.stakingToken),
            msg.sender,
            amountToUnstake
        );

        // Distribute rewards
        uint256 actualReward = _distributeERC20Reward(incentiveId, msg.sender, reward);
        emit ERC20Unstaked(incentiveId, msg.sender, amountToUnstake, actualReward);
        return actualReward;
    }

    /// @notice Claims rewards without unstaking tokens
    /// @param incentiveId The ID of the incentive to claim rewards from
    /// @return reward The amount of reward claimed
    function claimERC20Reward(bytes32 incentiveId) external returns (uint256 reward) {
        ERC20Stake storage stake = _erc20Stakes[msg.sender][incentiveId];

        require(
            stake.amount > 0,
            'ERC20Staker::claimERC20Reward: no stake found'
        );

        // Update rewards before claiming
        _updateReward(msg.sender, incentiveId);

        // Get the current reward amount
        reward = stake.rewards;

        // Reset rewards
        stake.rewards = 0;

        // Distribute rewards based on emission style
        uint256 actualReward = _distributeERC20Reward(incentiveId, msg.sender, reward);
        emit ERC20RewardClaimed(incentiveId, msg.sender, actualReward);
        return actualReward;
    }

    /// @notice Distributes rewards for ERC20 staking, to either be claimed directly, or sent to EmissionController
    function _distributeERC20Reward(
        bytes32 incentiveId,
        address user,
        uint256 reward
    ) private returns (uint256) {
        ERC20Incentive storage incentive = erc20Incentives[incentiveId];

        // Cap reward at available unclaimed amount
        if (reward > incentive.totalRewardUnclaimed) {
            reward = incentive.totalRewardUnclaimed;
        }

        if (reward == 0) {
            return 0;
        }

        // Update incentive accounting
        incentive.totalRewardUnclaimed = incentive.totalRewardUnclaimed.sub(reward);

        // Distribute according to emission style
        if (incentive.key.emissionSettings.emissionStyle == IEmissionController.EmissionStyle.Regular) {
            TransferHelperExtended.safeTransfer(address(incentive.key.rewardToken), user, reward);
            emit RewardClaimed(incentive.key.rewardToken, user, reward);
        } else {
            // For dripped/vested rewards, use the emission controller
            TransferHelper.safeApprove(address(incentive.key.rewardToken), address(emissionController), reward);

            emissionController.createEmission(
                incentiveId,
                incentive.key.rewardToken,
                user,
                reward,
                incentive.key.emissionSettings,
                incentive.key.refundee
            );
        }

        return reward;
    }

    /// @notice Get the current reward info for an ERC20 stake
    function getERC20RewardInfo(
        address user,
        bytes32 incentiveId
    ) external view returns (
        uint256 stakeAmount,
        uint256 earnedReward,
        bool isLocked,
        uint256 endTime,
        IERC20Minimal stakingToken,
        IERC20Minimal rewardToken
    ) {
        ERC20Stake storage stake = _erc20Stakes[user][incentiveId];

        // If no stake, return zeroes
        if (stake.amount == 0) {
            return (0, 0, false, 0, IERC20Minimal(address(0)), IERC20Minimal(address(0)));
        }

        ERC20Incentive storage incentive = erc20Incentives[incentiveId];

        stakeAmount = stake.amount;
        earnedReward = incentive.totalRewardUnclaimed == 0 ? 0 : earned(user, incentiveId);
        isLocked = incentive.key.isLocked;
        endTime = incentive.key.endTime;
        stakingToken = incentive.key.stakingToken;
        rewardToken = incentive.key.rewardToken;

        return (stakeAmount, earnedReward, isLocked, endTime, stakingToken, rewardToken);
    }

    /// @notice End an ERC20 incentive and reclaim remaining rewards
    function endERC20Incentive(bytes32 incentiveId) external onlyOwner returns (uint256 refund) {
        ERC20Incentive storage incentive = erc20Incentives[incentiveId];

        require(
            incentive.key.endTime > 0,
            'ERC20Staker::endERC20Incentive: non-existent incentive'
        );

        require(
            block.timestamp >= incentive.key.endTime,
            'ERC20Staker::endERC20Incentive: incentive not ended'
        );

        require(
            block.timestamp >= (incentive.key.endTime + END_GRACE_PERIOD),
            'ERC20Staker::endERC20Incentive: User claim grace period not elapsed'
        );

        // Refund is the remaining unclaimed amount
        refund = incentive.totalRewardUnclaimed;

        // Reset incentive data
        incentive.totalRewardUnclaimed = 0;

        // Remove tracking
        _activeIncentives.remove(incentiveId);

        if (refund > 0) {
            TransferHelperExtended.safeTransfer(address(incentive.key.rewardToken), incentive.key.refundee, refund);
        }

        emit ERC20IncentiveEnded(incentiveId, refund);

        return refund;
    }

    /// @notice Get the total number of active incentives
    /// @return The total count of active incentives
    function getActiveIncentivesCount() external view returns (uint256) {
        return _activeIncentives.length();
    }

    /// @notice Get active incentive IDs with pagination
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return incentiveIds Array of active incentive IDs
    /// @return total Total number of active incentives
    function getActiveIncentivesPaginated(uint256 offset, uint256 limit) external view returns (bytes32[] memory incentiveIds, uint256 total) {
        total = _activeIncentives.length();
        
        if (offset >= total || limit == 0) {
            return (new bytes32[](0), total);
        }
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        incentiveIds = new bytes32[](count);
        
        for (uint256 i = 0; i < count; i++) {
            incentiveIds[i] = _activeIncentives.at(offset + i);
        }
        
        return (incentiveIds, total);
    }

    /// @notice Release lock for a user's staked tokens in an incentive
    function releaseERC20Lock(address user, bytes32 incentiveId) external onlyOwner {
        require(_erc20Stakes[user][incentiveId].amount > 0, "ERC20Staker::releaseERC20Lock: no stake found");
        require(erc20Incentives[incentiveId].key.isLocked, "ERC20Staker::releaseERC20Lock: not a locked incentive");

        userLockReleased[user][incentiveId] = true;
        emit ERC20LockReleased(user, incentiveId);
    }

    /// @notice Reset lock for a user's staked tokens in an incentive, revoking previous unlock
    function resetERC20Lock(address user, bytes32 incentiveId) external onlyOwner {
        require(_erc20Stakes[user][incentiveId].amount > 0, "ERC20Staker::resetERC20Lock: no stake found");
        require(erc20Incentives[incentiveId].key.isLocked, "ERC20Staker::resetERC20Lock: not a locked incentive");
        require(userLockReleased[user][incentiveId], "ERC20Staker::resetERC20Lock: lock not previously released");

        userLockReleased[user][incentiveId] = false;
        emit ERC20LockReset(user, incentiveId);
    }

    /// @notice Get the total number of incentives a user has staked in
    /// @param user The user address
    /// @return The total count of incentives the user has staked in
    function getUserERC20IncentiveIdsCount(address user) external view returns (uint256) {
        return _userERC20IncentiveIds[user].length();
    }

    /// @notice Get incentive IDs a user has staked in with pagination
    /// @param user The user address
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return incentiveIds Array of incentive IDs the user has staked in
    /// @return total Total number of incentives the user has staked in
    function getUserERC20IncentiveIdsPaginated(address user, uint256 offset, uint256 limit) external view returns (bytes32[] memory incentiveIds, uint256 total) {
        total = _userERC20IncentiveIds[user].length();
        
        if (offset >= total || limit == 0) {
            return (new bytes32[](0), total);
        }
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        incentiveIds = new bytes32[](count);
        
        for (uint256 i = 0; i < count; i++) {
            incentiveIds[i] = _userERC20IncentiveIds[user].at(offset + i);
        }
        
        return (incentiveIds, total);
    }

    /// @notice Get the total number of ERC20 stakes for a user
    /// @param account The user address
    /// @return The total count of stakes
    function getERC20StakesCount(address account) external view returns (uint256) {
        return _userERC20IncentiveIds[account].length();
    }

    /// @notice Paginated view of a user's ERC20 stakes
    /// @param account The user address
    /// @param offset Starting index for pagination
    /// @param limit Maximum number of entries to return
    /// @return stakeEntries Array of stake entries
    /// @return total Total number of stakes
    function getERC20StakesPaginated(
        address account,
        uint256 offset,
        uint256 limit
    ) external view returns (StakeInfo[] memory stakeEntries, uint256 total) {
        total = _userERC20IncentiveIds[account].length();

        // Handle pagination boundaries
        if (offset >= total) {
            return (new StakeInfo[](0), total);
        }

        uint256 endIdx = offset + limit;
        if (endIdx > total) {
            endIdx = total;
        }

        stakeEntries = new StakeInfo[](endIdx - offset);

        // Populate entries
        for (uint256 i = offset; i < endIdx; i++) {
            bytes32 incentiveId = _userERC20IncentiveIds[account].at(i);
            ERC20Stake storage stake = _erc20Stakes[account][incentiveId];
            ERC20Incentive storage incentive = erc20Incentives[incentiveId];

            stakeEntries[i - offset] = StakeInfo({
                incentiveId: incentiveId,
                stakingToken: incentive.key.stakingToken,
                rewardToken: incentive.key.rewardToken,
                stakeAmount: stake.amount,
                earnedReward: incentive.totalRewardUnclaimed == 0 ? 0: earned(account, incentiveId),
                isLocked: incentive.key.isLocked,
                startTime: incentive.key.startTime,
                endTime: incentive.key.endTime
            });
        }

        return (stakeEntries, total);
    }
}
EmissionController.sol 573 lines
pragma solidity =0.7.6;
pragma abicoder v2;

import "@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol";
import "./libraries/TransferHelperExtended.sol";
import "./interfaces/IEmissionController.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";

/**
 * @title EmissionController
 * @dev Contract for managing token emission schedules with different styles: Dripped, and Vested.
 *      When Dripped, tokens are released linearly.
 *      When Vested, tokens are release in an exponential fashion
 *      Both types may have a Staging duration, and a Cliff duration.
 *      When a Cliff is specified, unlocks are prevented until after the Cliff duration.
 *      When a Staging duration is specified, then claimed tokens will move into a
 *      staging period before being mintable after being claimed.
 *      All types of claims, may be forfeitable.  If marked as isOneShot, then the
 *      first touch of the emission will cause the remaining to flow back
 *      to the refundee.
 * Glossary:
 *      Incentive: A staking program which rewards NFT/ERC20 depositors with rewards
 *      Reward: A token allocation, which was earned by staking a UniV3 NFT or ERC20 in an incentive program
 *      Emission: A Reward which was claimed from a staked NFT/ERC20, and sent to this contract to be vested
 *      StagedReward: An Emission which was claimed, but which has a staging period before being mintable
 */
contract EmissionController is IEmissionController {
    using EnumerableSet for EnumerableSet.UintSet;

    /// @dev Stores all data associated with a single emission
    struct EmissionEntry {
        bytes32 incentiveId;          // The ID of the incentive this emission is associated with
        address owner;                // The address that owns this emission and can claim rewards
        address rewardToken;          // The token that will be distributed as rewards
        EmissionStyle style;          // The emission style (Dripped, or Vested), since regular should never be sent here
        uint256 totalAmount;          // The total amount of tokens allocated to this emission
        uint256 claimed;              // The amount of tokens already claimed from this emission
        uint64 startTime;             // Timestamp when the emission starts
        uint64 endTime;               // Timestamp when the emission ends
        uint64 cliffDuration;         // Duration of the cliff period in seconds
        uint64 vestingPeriod;         // Total duration of the vesting period in seconds, including cliff
        uint64 stagingDuration;       // Duration of the staging period before claiming in seconds
        bool isActive;                // Whether the emission is still active (or even created at all)
        bool isOneShot;               // If true, still vesting/dripping rewards are forfeit after first touch/claim
        address refundee;             // Address to receive forfeited rewards
    }

    /// @dev Stores data for emissions that are claimed but not yet transferable to users
    struct StagedReward {
        bytes32 incentiveId;          // The ID of the incentive this staged reward is associated with
        uint256 emissionId;           // The ID of the emission this staged reward came from
        address owner;                // The address that owns this staged reward
        address rewardToken;          // The token that will be distributed
        uint256 amount;               // The amount of tokens in this staged reward
        uint64 stagedAt;              // Timestamp when the reward was staged
        uint64 stagingDuration;       // Duration of the staging period in seconds
        bool isActive;                // Whether the staged reward is still active, or created at all
    }

    /// @dev Counter for generating unique IDs
    uint256 private _idCounter = 1;

    /// @dev Maps emission IDs to their emission entries
    mapping(uint256 => EmissionEntry) public emissions;

    /// @dev Maps staged IDs to their staged reward entries
    mapping(uint256 => StagedReward) public stagedRewards;

    /// @dev Maps users to their emission IDs which are still to be claimed
    mapping(address => EnumerableSet.UintSet) private _accountEmissionIds;

    /// @dev Maps users to their staged reward IDs
    mapping(address => EnumerableSet.UintSet) private _accountStagedRewardIds;

    /// @dev Used to track how many tokens are locked in the staging period for each incentive
    mapping(bytes32 => uint256) public totalStagedByIncentive;

    /// @dev Used for access control to ensure only the staker can create emissions
    address public immutable staker;

    /**
     * @notice Emitted when a new emission is created
     * @param emissionId Unique identifier for the emission
     * @param incentiveId ID of the incentive this emission belongs to
     * @param beneficiary Address that will receive the rewards
     * @param rewardToken Address of the token to be rewarded
     * @param style The emission style (Dripped, Vested)
     * @param amount Total amount of tokens to be distributed
     * @param cliff Duration of the cliff period in seconds
     * @param period Total duration of the vesting period in seconds
     * @param stagingDuration Duration of the staging period in seconds
     * @param isOneShot Whether pending rewards are forfeit after first claim
     */
    event EmissionCreated(
        uint256 indexed emissionId,
        bytes32 indexed incentiveId,
        address indexed beneficiary,
        address rewardToken,
        EmissionStyle style,
        uint256 amount,
        uint64 cliff,
        uint64 period,
        uint64 stagingDuration,
        bool isOneShot
    );

    /**
     * @notice Emitted when rewards are claimed from an emission
     * @param emissionId ID of the emission from which rewards are claimed
     * @param incentiveId ID of the incentive this emission belongs to
     * @param claimer Address that claimed the rewards
     * @param amount Amount of tokens claimed
     */
    event RewardClaimed(
        uint256 indexed emissionId,
        bytes32 indexed incentiveId,
        address indexed claimer,
        uint256 amount
    );

    /**
     * @notice Emitted when rewards are staged
     * @param emissionId ID of the emission from which rewards were claimed
     * @param stagedRewardId ID of the created staged reward
     * @param incentiveId ID of the incentive this emission belongs to
     * @param beneficiary Address that will receive the staged rewards
     * @param amount Amount of tokens staged
     * @param availableTime Timestamp when the staged rewards will be claimable
     */
    event RewardStaged(
        uint256 indexed emissionId,
        uint256 indexed stagedRewardId,
        bytes32 indexed incentiveId,
        address beneficiary,
        uint256 amount,
        uint64 availableTime
    );

    /**
     * @notice Emitted when staged rewards are claimed
     * @param stagedRewardId ID of the staged reward being claimed
     * @param incentiveId ID of the incentive this reward belongs to
     * @param claimer Address claiming the staged rewards
     * @param amount Amount of tokens claimed
     */
    event StagedRewardClaimed(
        uint256 indexed stagedRewardId,
        bytes32 indexed incentiveId,
        address indexed claimer,
        uint256 amount
    );

    /**
    * @notice Initializes the emission controller
     * @dev Sets the staker contract address for access control
     */
    constructor() {
        staker = msg.sender;
    }

    /**
     * @notice Restricts function access to only the staker contract
     * @dev Modifier for access control to prevent unauthorized emission creation
     */
    modifier onlyStaker() {
        require(msg.sender == staker, "EmissionController: caller is not the staker");
        _;
    }

    /**
     * @notice Creates a new emission for a specific incentive, according to the input parameters.
     * @dev Called by the staker contract when rewards are distributed
     * @param incentiveId ID of the incentive this emission belongs to
     * @param rewardToken Token to be distributed as rewards
     * @param onBehalfOf Address that will own this emission and can claim rewards
     * @param amount Amount of tokens to be distributed
     * @param emissionSettings Vesting and emission parameters
     * @param refundee Address to receive forfeited or unclaimed rewards
     */
    function createEmission(
        bytes32 incentiveId,
        IERC20Minimal rewardToken,
        address onBehalfOf,
        uint256 amount,
        EmissionSettings memory emissionSettings,
        address refundee
    ) external onlyStaker override {
        TransferHelperExtended.safeTransferFrom(address(rewardToken), msg.sender, address(this), amount);

        uint emissionId = _idCounter++;
        uint64 startTime = uint64(block.timestamp);
        uint64 endTime = uint64(block.timestamp + emissionSettings.period);

        emissions[emissionId] = EmissionEntry({
            incentiveId: incentiveId,
            owner: onBehalfOf,
            rewardToken: address(rewardToken),
            style: emissionSettings.emissionStyle,
            totalAmount: amount,
            claimed: 0,
            startTime: startTime,
            endTime: endTime,
            cliffDuration: emissionSettings.cliff,
            vestingPeriod: emissionSettings.period,
            stagingDuration: emissionSettings.stagingDuration,
            isActive: true,
            isOneShot: emissionSettings.isForfeitable,
            refundee: refundee
        });

        _accountEmissionIds[onBehalfOf].add(emissionId);

        emit EmissionCreated(
            emissionId,
            incentiveId,
            onBehalfOf,
            address(rewardToken),
            emissionSettings.emissionStyle,
            amount,
            emissionSettings.cliff,
            emissionSettings.period,
            emissionSettings.stagingDuration,
            emissionSettings.isForfeitable
        );
    }

    /**
     * @notice Claims rewards from an emission based on its vesting schedule
     * @dev Transfers tokens immediately if no staging period, otherwise creates a staged reward
     * @param emissionId ID of the emission to claim rewards from
     * @return reward Amount of tokens claimed or staged
     */
    function claimReward(uint256 emissionId) external override returns (uint256 reward) {
        EmissionEntry storage entry = emissions[emissionId];

        require(entry.isActive, "Emission not active");
        require(entry.owner == msg.sender, "Not emission owner");

        uint256 claimable = calculateClaimable(emissionId);
        require(claimable > 0, "Nothing to claim");
        entry.claimed += claimable;

        assert(entry.claimed <= entry.totalAmount);

        if (entry.stagingDuration == 0) {
            TransferHelperExtended.safeTransfer(entry.rewardToken, entry.owner, claimable);

            emit RewardClaimed(
                emissionId,
                entry.incentiveId,
                entry.owner,
                claimable
            );
        } else {
            uint256 stagedRewardId = _idCounter++;

            stagedRewards[stagedRewardId] = StagedReward({
                incentiveId: entry.incentiveId,
                emissionId: emissionId,
                owner: entry.owner,
                rewardToken: entry.rewardToken,
                amount: claimable,
                stagedAt: uint64(block.timestamp),
                stagingDuration: entry.stagingDuration,
                isActive: true
            });

            _accountStagedRewardIds[entry.owner].add(stagedRewardId);
            totalStagedByIncentive[entry.incentiveId] += claimable;

            emit RewardStaged(
                emissionId,
                stagedRewardId,
                entry.incentiveId,
                entry.owner,
                claimable,
                uint64(block.timestamp + entry.stagingDuration)
            );
        }

        uint256 remainingToClaim = entry.totalAmount - entry.claimed;

        if (entry.isOneShot || remainingToClaim == 0) {
            if (remainingToClaim > 0) {
                TransferHelperExtended.safeTransfer(entry.rewardToken, entry.refundee, remainingToClaim);
            }
            _accountEmissionIds[entry.owner].remove(emissionId);
            delete emissions[emissionId];
        }

        return claimable;
    }

    /**
     * @notice Claims rewards that have passed their staging period
     * @dev Transfers tokens to the owner after the staging period has passed
     * @param stagedRewardId ID of the staged reward to claim
     */
    function claimStagedReward(uint256 stagedRewardId) external override {
        StagedReward storage stagedReward = stagedRewards[stagedRewardId];

        require(stagedReward.isActive, "Reward not active or already claimed");
        require(stagedReward.owner == msg.sender, "Not staged reward owner");
        require(block.timestamp >= stagedReward.stagedAt + stagedReward.stagingDuration, "Staging period not over");

        uint256 amount = stagedReward.amount;
        bytes32 incentiveId = stagedReward.incentiveId;
        address rewardToken = stagedReward.rewardToken;
        address owner = stagedReward.owner;
        
        // Update state before external call to prevent reentrancy
        totalStagedByIncentive[incentiveId] -= amount;
        _accountStagedRewardIds[owner].remove(stagedRewardId);
        delete stagedRewards[stagedRewardId];
        
        TransferHelperExtended.safeTransfer(rewardToken, owner, amount);

        emit StagedRewardClaimed(
            stagedRewardId,
            incentiveId,
            owner,
            amount
        );
    }

    /// @dev Used as input for the calculateClaimableAmount function to avoid stack-too-deep
    struct ClaimableParams {
        EmissionStyle style;       // The emission style (Dripped, Vested)
        uint256 totalAmount;       // Total amount of tokens allocated
        uint256 claimed;           // Amount already claimed
        uint64 startTime;          // Start time of the emission
        uint64 endTime;            // End time of the emission
        uint64 cliffDuration;      // Duration of the cliff period
        uint64 vestingPeriod;      // Total duration of the vesting period
        uint256 currentTime;       // Current timestamp for calculation
    }

    /**
     * @notice Calculates the amount of tokens claimable based on vesting schedule
     * @dev Implements different vesting algorithms based on emission style
     * @param params Vesting parameters and time information
     * @return claimable The amount of tokens that can be claimed
     */
    function calculateClaimableAmount(ClaimableParams memory params) public pure returns (uint256 claimable) {
        if (params.claimed >= params.totalAmount) {
            return 0; // Entirely claimed emissions are deleted in claimReward(), but just in case...
        }

        uint256 vestedAmount;

        if (params.currentTime >= params.endTime) {
            vestedAmount = params.totalAmount;
        } else if (params.currentTime < params.startTime + params.cliffDuration) {
            vestedAmount = 0;
        } else {
            uint256 vestingDuration = params.endTime - params.startTime - params.cliffDuration;
            uint256 timeVested = params.currentTime - params.startTime - params.cliffDuration;

            if (params.style == EmissionStyle.Dripped) {
                // Dripped emissions are vested linearly over time
                vestedAmount = params.totalAmount * timeVested / vestingDuration;
            } else /** if (params.style == EmissionStyle.Vested) **/ {
                // it must be Vested, if not Dripped, as Staker never creates an emission if EmissionStyle.Regular
                uint256 vestHalfDuration = vestingDuration / 2;
                uint256 maxFirstHalfVested = params.totalAmount * 10 / 100;

                if (timeVested <= vestHalfDuration) {
                    // Slow linear increase up to 10% for the first half of the term
                    vestedAmount = maxFirstHalfVested * timeVested / vestHalfDuration;
                } else {
                    // Exponential increase for the second half of the term
                    uint256 secondHalfElapsed = timeVested - vestHalfDuration;
                    // It's ok that second half initially vests slower than linear vest, because it makes up for it on tail end.
                    uint256 exponentialFactor = ((secondHalfElapsed ** 2) * 1e18) / (vestHalfDuration ** 2);
                    uint256 maxSecondHalfVested = params.totalAmount - maxFirstHalfVested;
                    vestedAmount = maxFirstHalfVested + ((maxSecondHalfVested * exponentialFactor) / 1e18);
                }
            }
        }

        // Calculate claimable as vested minus already claimed
        claimable = vestedAmount > params.claimed ? vestedAmount - params.claimed : 0;
    }

    /**
    * @notice Calculates the amount of tokens claimable for a specific emission
    * @dev Constructs parameters and calls calculateClaimableAmount
    * @param emissionId ID of the emission to calculate claimable amount for
    * @return claimable The amount of tokens that can be claimed
    */
    function calculateClaimable(uint256 emissionId) public view returns (uint256 claimable) {
        EmissionEntry storage entry = emissions[emissionId];

        if (!entry.isActive) {
            return 0;
        }

        ClaimableParams memory params = ClaimableParams({
            style: entry.style,
            totalAmount: entry.totalAmount,
            claimed: entry.claimed,
            startTime: entry.startTime,
            endTime: entry.endTime,
            cliffDuration: entry.cliffDuration,
            vestingPeriod: entry.vestingPeriod,
            currentTime: block.timestamp
        });

        return calculateClaimableAmount(params);
    }

    /**
   * @notice Gets the total amount of tokens staged for a specific incentive
     * @param incentiveId The ID of the incentive to check
     * @return The total amount of tokens in staged rewards for this incentive
     */
    function getTotalStagedForIncentive(bytes32 incentiveId) external view returns (uint256) {
        return totalStagedByIncentive[incentiveId];
    }

/**
 * @notice Gets the total number of emissions for a specific account
     * @param account The address to check
     * @return The number of emissions owned by the account
     */
    function getEmissionsCount(address account) external view returns (uint256) {
        return _accountEmissionIds[account].length();
    }

/**
 * @notice Gets the total number of staged rewards for a specific account
     * @param account The address to check
     * @return The number of staged rewards owned by the account
     */
    function getStagedRewardsCount(address account) external view returns (uint256) {
        return _accountStagedRewardIds[account].length();
    }

/**
 * @notice Extended emission entry struct for external display
     * @dev Includes calculated claimable amount for UI display
     */
    struct External_EmissionEntry {
        uint emissionId;
        bytes32 incentiveId;
        address owner;
        address rewardToken;
        EmissionStyle style;
        uint256 totalAmount;
        uint256 claimed;
        uint64 startTime;
        uint64 endTime;
        uint64 cliffDuration;
        uint64 vestingPeriod;
        uint64 stagingDuration;
        bool isActive;
        bool isOneShot;
        uint256 claimable;
    }

/**
 * @notice Extended staged reward struct for external display
     * @dev Includes calculated isClaimable flag for UI display
     */
    struct External_StagedRewardEntry {
        uint stagedRewardId;
        bytes32 incentiveId;
        uint256 emissionId;
        address owner;
        address rewardToken;
        uint256 amount;
        uint64 stagedAt;
        uint64 stagingDuration;
        bool isActive;
        bool isClaimable;
    }

/**
 * @notice Gets paginated emission entries for a specific account with additional UI information
     * @dev Includes calculated claimable amounts for each emission
     * @param account The address to get emissions for
     * @param offset Starting index for pagination
     * @param limit Maximum number of entries to return
     * @return entries Array of emission entries with UI display information
     */
    function getEmissionsPaginated(address account, uint256 offset, uint256 limit)
    external view returns (External_EmissionEntry[] memory entries) {
        uint256 totalEmissions = _accountEmissionIds[account].length();

        if (offset >= totalEmissions) {
            // Paged to the end
            return new External_EmissionEntry[](0);
        }

        uint256 endIdx = offset + limit;
        if (endIdx > totalEmissions) {
            endIdx = totalEmissions;
        }

        entries = new External_EmissionEntry[](endIdx - offset);

        for (uint256 i = offset; i < endIdx; i++) {
            uint emissionId = _accountEmissionIds[account].at(i);
            EmissionEntry storage entry = emissions[emissionId];

            entries[i - offset] = External_EmissionEntry({
                emissionId: emissionId,
                incentiveId: entry.incentiveId,
                owner: entry.owner,
                rewardToken: entry.rewardToken,
                style: entry.style,
                totalAmount: entry.totalAmount,
                claimed: entry.claimed,
                startTime: entry.startTime,
                endTime: entry.endTime,
                cliffDuration: entry.cliffDuration,
                vestingPeriod: entry.vestingPeriod,
                stagingDuration: entry.stagingDuration,
                isActive: entry.isActive,
                isOneShot: entry.isOneShot,
                claimable: calculateClaimable(emissionId)
            });
        }

        return entries;
    }

/**
 * @notice Gets paginated staged reward entries for a specific account with additional UI information
     * @dev Includes calculated isClaimable flag for each reward
     * @param account The address to get staged rewards for
     * @param offset Starting index for pagination
     * @param limit Maximum number of entries to return
     * @return entries Array of staged reward entries with UI display information
     */
    function getStagedRewardsPaginated(address account, uint256 offset, uint256 limit)
    external view returns (External_StagedRewardEntry[] memory entries)
    {
        uint256 totalStagedRewards = _accountStagedRewardIds[account].length();

        if (offset >= totalStagedRewards) {
            // Paged to the end
            return new External_StagedRewardEntry[](0);
        }

        uint256 endIdx = offset + limit;
        if (endIdx > totalStagedRewards) {
            endIdx = totalStagedRewards;
        }

        entries = new External_StagedRewardEntry[](endIdx - offset);

        for (uint256 i = offset; i < endIdx; i++) {
            uint stagedRewardId = _accountStagedRewardIds[account].at(i);
            StagedReward storage reward = stagedRewards[stagedRewardId];

            entries[i - offset] = External_StagedRewardEntry({
                stagedRewardId: stagedRewardId,
                incentiveId: reward.incentiveId,
                emissionId: reward.emissionId,
                owner: reward.owner,
                rewardToken: reward.rewardToken,
                amount: reward.amount,
                stagedAt: reward.stagedAt,
                stagingDuration: reward.stagingDuration,
                isActive: reward.isActive,
                isClaimable: block.timestamp >= reward.stagedAt + reward.stagingDuration
            });
        }

        return entries;
    }
}
UniswapV3Staker.sol 616 lines
pragma solidity =0.7.6;
pragma abicoder v2;

/* ERROR CODE MAPPING
E001:           'reward must be positive'
E002:           'start time must be now or in the future'
E003:           'start time too far into future'
E004:           'start time must be before end time'
E005:           'incentive duration is too long'
E006:           'vesting time must be lte incentive duration'
E007:           'refundee must be a valid address'
E008:           'tick lower must be less than tick upper'
E009:           'min width must be greater than 0, and less than 1,774,544'
E010:           'period must be positive when using Dripped/Vested emission style'
E011:           'cliff must be less than period'
E012:           'invalid staging duration'
E013:           'not a POL token'
E014:           'cannot end incentive before end time'
E015:           'no refund available'
E016:           'cannot end incentive while deposits are staked'
E017:           'not a univ3 nft'
E018:           'invalid transfer recipient: (address 0)'
E019:           'invalid transfer recipient (staker address)'
E020:           'can only be called by deposit owner'
E021:           'cannot withdraw to staker'
E022:           'cannot withdraw token while staked'
E023:           'only owner can withdraw token'
E024:           'cannot withdraw POL token'
E025:           'only owner can stake token'
E026:           'only owner can withdraw token before incentive end time'
E027/E027.1:    'stake does not exist'
E028:           'incentive not started'
E029:           'incentive ended'
E030:           'non-existent incentive'
E031:           'token already staked'
E032:           'token pool is not the incentive pool'
E033:           'cannot stake token with 0 liquidity'
E034:           'token tick range does not match required range'
E035:           'invalid page start index'
E040:           'only callable by this contract'
E041:           'maximum incentives per position reached'
E042:           'max incentives per position must be greater than 0'
E043:           'period cannot exceed 2 years'
E044:           'pool is not a valid Uniswap V3 pool'
E045:           'share based rewards require all users to share a common range'
*/

import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import '@openzeppelin/contracts/access/Ownable.sol';
import './EmissionController.sol';

import './libraries/IncentiveId.sol';
import './libraries/NFTPositionInfo.sol';
import './libraries/RewardMath.sol';
import './libraries/TransferHelperExtended.sol';

import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-periphery/contracts/base/Multicall.sol';
import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import "./UniswapV3StakerLiquidityHandler.sol";
import "./UniswapV3StakerState.sol";

/// @title Uniswap V3 canonical staking interface, altered to introduce additional permissioned liquidity constraints.
/// @notice Manages the staking of Uniswap V3 NFT positions, distributing rewards according to various emission strategies
/// @dev Extends the standard Uniswap V3 staking with protocol-owned liquidity and restricted tick range features, with inclusion of revert.finances vesting period.
contract UniswapV3Staker is UniswapV3StakerState, Multicall, Ownable {
    // Use EnumerableSet for efficient set operations
    using EnumerableSet for EnumerableSet.UintSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;
    
    /// @notice The address of the liquidity handler implementation
    address public immutable liquidityHandlerImplementation;

    /// @notice Updates the maximum number of incentives per position
    /// @param _maxIncentivesPerPosition The new maximum
    /// @dev Only callable by owner
    function setMaxIncentivesPerPosition(uint256 _maxIncentivesPerPosition) external onlyOwner {
        require(_maxIncentivesPerPosition > 0, 'E042');
        maxIncentivesPerPosition = _maxIncentivesPerPosition;
        emit MaxIncentivesPerPositionUpdated(_maxIncentivesPerPosition);
    }

    // ========== STORAGE ACCESS FOR VIEWS ==========

    /// @notice Get an active incentive by index
    function getActiveIncentiveAt(uint256 index) external view override returns (bytes32) {
        return activeIncentives.at(index);
    }

    /// @notice Get the count of active incentives
    function getActiveIncentivesLength() external view override returns (uint256) {
        return activeIncentives.length();
    }

    /// @notice Get a user's ERC721 deposit by index
    function getUserERC721DepositAt(address user, uint256 index) external view override returns (uint256) {
        return userERC721Deposits[user].at(index);
    }

    /// @notice Get the count of a user's ERC721 deposits
    function getUserERC721DepositsLength(address user) external view override returns (uint256) {
        return userERC721Deposits[user].length();
    }

    /// @notice Get a user's ERC721 stake by index
    function getUserERC721StakeAt(address user, uint256 tokenId, uint256 index) external view override returns (bytes32) {
        return userERC721Stakes[user][tokenId].at(index);
    }

    /// @notice Get the count of a user's ERC721 stakes for a token
    function getUserERC721StakesLength(address user, uint256 tokenId) external view override returns (uint256) {
        return userERC721Stakes[user][tokenId].length();
    }

    /// @notice Get a POL token ID by index
    function getPOLTokenIdAt(uint256 index) external view override returns (uint256) {
        return polTokenIds.at(index);
    }

    /// @notice Get the count of POL token IDs
    function getPOLTokenIdsLength() external view override returns (uint256) {
        return polTokenIds.length();
    }

    /// @inheritdoc IUniswapV3Staker
    function getIncentiveTokenAt(bytes32 incentiveId, uint256 index) external view override returns (uint256) {
        return incentiveTokens[incentiveId].at(index);
    }

    /// @inheritdoc IUniswapV3Staker
    function getIncentiveTokensLength(bytes32 incentiveId) external view override returns (uint256) {
        return incentiveTokens[incentiveId].length();
    }

    /// @notice Constructs a new UniswapV3Staker contract with given parameters
    /// @param _factory the Uniswap V3 factory
    /// @param _nonfungiblePositionManager the NFT position manager contract address
    /// @param _maxIncentiveStartLeadTime the max duration of an incentive in seconds
    /// @param _maxIncentiveDuration the max amount of seconds into the future the incentive startTime can be set
    constructor(
        IUniswapV3Factory _factory,
        INonfungiblePositionManager _nonfungiblePositionManager,
        uint256 _maxIncentiveStartLeadTime,
        uint256 _maxIncentiveDuration,
        address _liquidityHandlerImplementation
    ) UniswapV3StakerState(
        _factory,
        _nonfungiblePositionManager,
        _maxIncentiveStartLeadTime,
        _maxIncentiveDuration
    ) {
        liquidityHandlerImplementation = _liquidityHandlerImplementation;
    }

    /// @notice Creates a new incentive with optional parameters for POL, tick range, minimum width, and emission style
    /// @param key The incentive key (pool, reward token, timestamps, etc) with emission style parameters
    function createIncentive(IncentiveKey memory key) external override onlyOwner {
        require(
            key.reward > 0,
            'E001'
        );

        require(
            block.timestamp <= key.startTime,
            'E002'
        );

        require(
            key.startTime - block.timestamp <= maxIncentiveStartLeadTime,
            'E003'
        );

        require(
            key.startTime < key.endTime,
            'E004'
        );

        require(
            key.endTime - key.startTime <= maxIncentiveDuration,
            'E005'
        );

        require(
            key.vestingPeriod <= key.endTime - key.startTime,
            'E006'
        );

        require(
            key.refundee != address(0),
            'E007'
        );

        _validatePool(key.pool);

        if (key.rangeSettings.hasTickRange) {
            require(
                key.rangeSettings.requiredTickLower < key.rangeSettings.requiredTickUpper,
                'E008'
            );
        }

        if (key.rangeSettings.hasMinWidth) {
            require(
                key.rangeSettings.minTickWidth > 0 &&
                key.rangeSettings.minTickWidth <= 1_774_544, // (887,272) - (-887,272) == 1,774,544, range of a UniswapV3 full range position
                'E009'
            );
        }

        if (key.emissionSettings.emissionStyle != IEmissionController.EmissionStyle.Regular) {
            require(
                key.emissionSettings.period > 0,
                'E010'
            );

            require(
                key.emissionSettings.period <= 730 days,
                'E043' // period cannot exceed 2 years
            );

            require(
                key.emissionSettings.cliff < key.emissionSettings.period,
                'E011'
            );

            require(
                key.emissionSettings.stagingDuration <= MAX_STAGING_DURATION,
                'E012'
            );
        }

        bytes32 incentiveId = IncentiveId.compute(key);
        Incentive storage incentive = incentives[incentiveId];

        incentive.key = key;
        incentive.totalRewardUnclaimed += key.reward;
        incentive.rangeSettings.buildsPOL = key.rangeSettings.buildsPOL;
        incentive.rangeSettings.requiredTickLower = key.rangeSettings.requiredTickLower;
        incentive.rangeSettings.requiredTickUpper = key.rangeSettings.requiredTickUpper;
        incentive.rangeSettings.hasTickRange = key.rangeSettings.hasTickRange;
        incentive.rangeSettings.rangeType = key.rangeSettings.rangeType;
        incentive.rangeSettings.hasMinWidth = key.rangeSettings.hasMinWidth;
        incentive.rangeSettings.minTickWidth = key.rangeSettings.minTickWidth;

        // Set emission strategy parameters
        incentive.emissionSettings.emissionStyle = key.emissionSettings.emissionStyle;
        incentive.emissionSettings.period = key.emissionSettings.period;
        incentive.emissionSettings.cliff = key.emissionSettings.cliff;
        incentive.emissionSettings.stagingDuration = key.emissionSettings.stagingDuration;
        incentive.emissionSettings.isForfeitable = key.emissionSettings.isForfeitable;

        if (key.accrualMechanism == RewardAccrualMechanism.ShareWeighted) {
            _initializeShareBasedIncentive(key, incentiveId);
        }

        TransferHelperExtended.safeTransferFrom(address(key.rewardToken), msg.sender, address(this), key.reward);
        activeIncentives.add(incentiveId);
        _emitCreationEvent(key.reward, key);
    }

    function _initializeShareBasedIncentive(IncentiveKey memory key, bytes32 incentiveId) private {
        require(
            key.rangeSettings.hasTickRange && key.rangeSettings.rangeType == RangeType.Fixed,
            'E045'
        );

        // Calculate reward rate (rewards per second * PRECISION)
        uint256 duration = key.endTime - key.startTime;
        uint256 rewardRate = (key.reward * PRECISION) / duration;
        require(rewardRate > 0, 'Reward rate must be positive');
        
        // Initialize share-weighted state
        shareWeightedStates[incentiveId] = ShareWeightedState({
            // totalRewardUnclaimed in incentive.totalRewardUnclaimed
            totalStaked: 0,
            rewardRate: rewardRate,
            rewardPerTokenStored: 0,
            lastUpdateTime: key.startTime
        });
    }

    /// @notice Function to release a POL NFT, only callable by owner
    /// @param tokenId The ID of the NFT to release from POL status
    function releasePOL(uint256 tokenId) external onlyOwner {
        require(deposits[tokenId].buildsPOL, "E013");
        deposits[tokenId].buildsPOL = false;
        polTokenIds.remove(tokenId);
        emit POLStatusChanged(tokenId, false);
    }

    /// @inheritdoc IUniswapV3Staker
    function endIncentive(IncentiveKey memory key) external override returns (uint256 refund) {
        require(block.timestamp >= key.endTime, 'E014');

        bytes32 incentiveId = IncentiveId.compute(key);
        Incentive storage incentive = incentives[incentiveId];

        // Check if incentive exists by verifying it has been created
        require(incentive.key.endTime > 0, 'E030');
        require(incentive.numberOfStakes == 0, 'E016');

        refund = incentive.totalRewardUnclaimed + incentive.totalRewardLocked;

        // Reset incentive data
        incentive.totalRewardUnclaimed = 0;
        incentive.totalRewardLocked = 0;

        // Remove from active incentives tracking
        activeIncentives.remove(incentiveId);

        // Transfer refund only if there are funds to refund
        if (refund > 0) {
            TransferHelperExtended.safeTransfer(address(key.rewardToken), key.refundee, refund);
        }

        // note we never clear totalSecondsClaimedX128

        emit IncentiveEnded(incentiveId, refund);
    }

    /// @notice Upon receiving a Uniswap V3 ERC721, creates the token deposit setting owner to `from`. Also stakes token
    /// in one or more incentives if properly formatted `data` has a length > 0.
    /// @inheritdoc IERC721Receiver
    function onERC721Received(
        address,
        address from,
        uint256 tokenId,
        bytes calldata data
    ) external override returns (bytes4) {
        require(msg.sender == address(nonfungiblePositionManager), 'E017');
        (, , , , , int24 tickLower, int24 tickUpper, , , , ,) = nonfungiblePositionManager.positions(tokenId);

        deposits[tokenId] = Deposit({owner: from, numberOfStakes: 0, tickLower: tickLower, tickUpper: tickUpper, buildsPOL: false});
        emit DepositTransferred(tokenId, address(0), from);
        userERC721Deposits[from].add(tokenId);

        if (data.length > 0) {
            if (data.length == 640) { // Single incentive case
                IncentiveKey memory key = abi.decode(data, (IncentiveKey));
                bytes32 incentiveId = IncentiveId.compute(key);
                if (incentives[incentiveId].rangeSettings.buildsPOL) {
                    deposits[tokenId].buildsPOL = true;
                    polTokenIds.add(tokenId);
                    emit POLStatusChanged(tokenId, true);
                }
                _stakeToken(key, tokenId);
            } else { // Multiple incentives case
                IncentiveKey[] memory keys = abi.decode(data, (IncentiveKey[]));
                for (uint256 i = 0; i < keys.length; i++) {
                    bytes32 incentiveId = IncentiveId.compute(keys[i]);
                    if (!deposits[tokenId].buildsPOL && incentives[incentiveId].rangeSettings.buildsPOL) {
                        deposits[tokenId].buildsPOL = true;
                        polTokenIds.add(tokenId);
                        emit POLStatusChanged(tokenId, true);
                    }
                    _stakeToken(keys[i], tokenId);
                }
            }
        }

        return this.onERC721Received.selector;
    }

    /// @inheritdoc IUniswapV3Staker
    function transferDeposit(uint256 tokenId, address to) external override {
        require(to != address(0), 'E018');
        require(to != address(this), 'E019');
        address owner = deposits[tokenId].owner;
        require(owner == msg.sender, 'E020');
        deposits[tokenId].owner = to;

        // Use EnumerableSet methods to safely remove and add
        userERC721Deposits[owner].remove(tokenId);
        userERC721Deposits[to].add(tokenId);

        // Transfer all stakes from old owner to new owner
        EnumerableSet.Bytes32Set storage oldOwnerStakes = userERC721Stakes[owner][tokenId];
        EnumerableSet.Bytes32Set storage newOwnerStakes = userERC721Stakes[to][tokenId];
        
        uint256 stakesCount = oldOwnerStakes.length();
        for (uint256 i = 0; i < stakesCount; i++) {
            // Always get the first element since we're removing it
            bytes32 incentiveId = oldOwnerStakes.at(0);
            oldOwnerStakes.remove(incentiveId);
            newOwnerStakes.add(incentiveId);
        }

        emit DepositTransferred(tokenId, owner, to);
    }

    /// @inheritdoc IUniswapV3Staker
    function withdrawToken(
        uint256 tokenId,
        address to,
        bytes memory data
    ) external override {
        require(to != address(this), 'E021');
        Deposit memory deposit = deposits[tokenId];
        require(deposit.numberOfStakes == 0, 'E022');
        require(deposit.owner == msg.sender, 'E023');
        require(!deposit.buildsPOL, 'E024');

        // Use EnumerableSet to safely remove the token
        userERC721Deposits[deposit.owner].remove(tokenId);

        delete deposits[tokenId];
        emit DepositTransferred(tokenId, deposit.owner, address(0));

        nonfungiblePositionManager.safeTransferFrom(address(this), to, tokenId, data);
    }

    /// @inheritdoc IUniswapV3Staker
    function stakeToken(IncentiveKey memory key, uint256 tokenId) external override {
        require(deposits[tokenId].owner == msg.sender, 'E025');

        _stakeToken(key, tokenId);
    }

    /// @inheritdoc IUniswapV3Staker
    function unstakeToken(IncentiveKey memory key, uint256 tokenId) external override {
        Deposit memory deposit = deposits[tokenId];

        // anyone can call unstakeToken if the block time is after the end time of the incentive
        if (block.timestamp < key.endTime) {
            require(deposit.owner == msg.sender, 'E026');
        }

        _unstakeToken(key, tokenId, deposit);
    }

    /// @notice Collects the fees earned by a deposited position without withdrawing it from the contract
    /// @param tokenId The ID of the NFT for which fees are being collected
    /// @param recipient The address that should receive the fees
    /// @param amount0Requested The maximum amount of token0 to collect
    /// @param amount1Requested The maximum amount of token1 to collect
    /// @return amount0 The amount of fees collected in token0
    /// @return amount1 The amount of fees collected in token1
    function collectFees(
        uint256 tokenId,
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint256 amount0, uint256 amount1) {
        bytes memory data = Address.functionDelegateCall(
            liquidityHandlerImplementation,
            abi.encodeWithSignature(
                "collectFees(uint256,address,uint128,uint128)",
                tokenId,
                recipient,
                amount0Requested,
                amount1Requested
            ),
            "Liquidity handler delegation failed"
        );
        return abi.decode(data, (uint256, uint256));
    }

    /// @inheritdoc IUniswapV3Staker
    /// @dev Calculates the current reward for a staked token
    function getRewardInfo(IncentiveKey memory key, uint256 tokenId)
    external
    view
    override
    returns (uint256 reward, uint256 maxReward, uint160 secondsInsideX128)
    {
        bytes32 incentiveId = IncentiveId.compute(key);

        if (key.accrualMechanism == RewardAccrualMechanism.ShareWeighted) {
            // For share-weighted incentives, check if token is staked
            ShareWeightedStake storage stake = shareWeightedStakes[tokenId][incentiveId];
            require(stake.amount > 0, 'E027');
            
            maxReward = 0; // Not relevant to share based rewards
            secondsInsideX128 = 0; // Not relevant to share based rewards

            // Calculate current earned rewards for share-weighted incentive
            reward = _earned(tokenId, incentiveId);
        } else {
            // For liquidity-weighted incentives, use the regular stakes mapping
            (uint160 secondsPerLiquidityInsideInitialX128, uint32 secondsInsideInitial, uint128 liquidity) =
                            stakes(tokenId, incentiveId);

            require(liquidity > 0, 'E027');

            Deposit memory deposit = deposits[tokenId];
            Incentive memory incentive = incentives[incentiveId];

            (, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) =
                            key.pool.snapshotCumulativesInside(deposit.tickLower, deposit.tickUpper);

            (reward, maxReward, secondsInsideX128) = RewardMath.computeRewardAmount(
                RewardMath.ComputeRewardAmountParams(
                    incentive.totalRewardUnclaimed,
                    incentive.totalSecondsClaimedX128,
                    key.startTime,
                    key.endTime,
                    key.vestingPeriod,
                    liquidity,
                    secondsPerLiquidityInsideInitialX128,
                    secondsPerLiquidityInsideX128,
                    secondsInsideInitial,
                    secondsInside,
                    block.timestamp
                )
            );
        }
    }


    /// @notice Emits the IncentiveCreated event with all relevant incentive parameters
    /// @param reward The amount of reward tokens to be distributed
    /// @param key The incentive key containing all parameters
    /// @dev Helper function to emit a properly formatted incentive created event
    function _emitCreationEvent(uint256 reward, IncentiveKey memory key) private {
        emit IncentiveCreated(
            key.rewardToken,
            key.pool,
            key.startTime,
            key.endTime,
            key.vestingPeriod,
            key.refundee,
            reward,
            key.rangeSettings.hasTickRange,
            key.rangeSettings.rangeType,
            key.rangeSettings.requiredTickLower,
            key.rangeSettings.requiredTickUpper,
            key.rangeSettings.hasMinWidth,
            key.rangeSettings.minTickWidth,
            key.rangeSettings.buildsPOL
        );
    }

    // ========== LIQUIDITY MANAGEMENT ===========

    /// @notice Increases liquidity for a deposited position
    /// @dev Automatically unstakes from all incentives, increases liquidity, then restakes
    /// @param tokenId The ID of the NFT position
    /// @param amountAdd0 The amount of token0 to add
    /// @param amountAdd1 The amount of token1 to add
    /// @param amount0Min Minimum amount of token0 to add (slippage protection)
    /// @param amount1Min Minimum amount of token1 to add (slippage protection)
    /// @param deadline Timestamp after which the transaction will revert
    /// @return liquidity The new liquidity amount
    /// @return amount0 The amount of token0 added
    /// @return amount1 The amount of token1 added
    function increaseLiquidity(
        uint256 tokenId,
        uint256 amountAdd0,
        uint256 amountAdd1,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 deadline
    ) external override returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        bytes memory data = Address.functionDelegateCall(
            liquidityHandlerImplementation,
            abi.encodeWithSignature(
                "increaseLiquidity(uint256,uint256,uint256,uint256,uint256,uint256)",
                tokenId,
                amountAdd0,
                amountAdd1,
                amount0Min,
                amount1Min,
                deadline
            ),
            "Liquidity handler delegation failed"
        );
        return abi.decode(data, (uint128, uint256, uint256));
    }


    /// @notice Decreases liquidity for a deposited position
    /// @dev Automatically unstakes from all incentives, decreases liquidity, then restakes
    /// @param tokenId The ID of the NFT position
    /// @param liquidity The amount of liquidity to remove
    /// @param amount0Min Minimum amount of token0 to receive (slippage protection)
    /// @param amount1Min Minimum amount of token1 to receive (slippage protection)
    /// @param deadline Timestamp after which the transaction will revert
    /// @return amount0 The amount of token0 received
    /// @return amount1 The amount of token1 received
    function decreaseLiquidity(
        uint256 tokenId,
        uint128 liquidity,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 deadline
    ) external override returns (uint256 amount0, uint256 amount1) {
        bytes memory data = Address.functionDelegateCall(
            liquidityHandlerImplementation,
            abi.encodeWithSignature(
                "decreaseLiquidity(uint256,uint128,uint256,uint256,uint256)",
                tokenId,
                liquidity,
                amount0Min,
                amount1Min,
                deadline
            ),
            "Liquidity handler delegation failed"
        );
        return abi.decode(data, (uint256, uint256));
    }

    /// @notice Validates that the provided pool is a valid Uniswap V3 pool
    /// @dev Checks that the pool is a contract and was created by the correct factory (within reason...)
    /// @param pool The pool to validate
    function _validatePool(IUniswapV3Pool pool) private view {
        require(Address.isContract(address(pool)), 'E044'); // pool is not a valid Uniswap V3 pool

        try pool.factory() returns (address poolFactory) {
            require(poolFactory == address(factory), 'E044');
        } catch {
            revert('E044');
        }
    }
}
UniswapV3StakerLiquidityHandler.sol 346 lines
pragma solidity =0.7.6;
pragma abicoder v2;

import "./UniswapV3StakerState.sol";
import "./libraries/IncentiveId.sol";
import "./libraries/TransferHelperExtended.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol";

/// @title UniswapV3StakerLiquidityHandler
/// @notice Handles liquidity management operations for the UniswapV3Staker
/// @dev This contract is meant to be used via delegatecall from UniswapV3Staker
contract UniswapV3StakerLiquidityHandler is UniswapV3StakerState {
    using EnumerableSet for EnumerableSet.UintSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;
    
    /// @notice Constructor
    constructor() UniswapV3StakerState(
        IUniswapV3Factory(address(0)),
        INonfungiblePositionManager(address(0)),
        0,
        0
    ) {}

    // Liquidity management functions
    function increaseLiquidity(
        uint256 tokenId,
        uint256 amountAdd0,
        uint256 amountAdd1,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 deadline
    ) external override returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        // Verify ownership
        require(deposits[tokenId].owner == msg.sender, 'E020');

        // Auto-unstake and get incentives if necessary
        IncentiveKey[] memory incentivesToRestake;
        if (deposits[tokenId].numberOfStakes > 0) {
            incentivesToRestake = _unstakeAndGetIncentives(tokenId);
        }

        // Execute liquidity increase
        (liquidity, amount0, amount1) = _executeLiquidityIncrease(
            tokenId,
            amountAdd0,
            amountAdd1,
            amount0Min,
            amount1Min,
            deadline
        );

        // Restake to previous incentives if any
        if (incentivesToRestake.length > 0) {
            _restakeToIncentives(tokenId, incentivesToRestake);
        }
    }

    function decreaseLiquidity(
        uint256 tokenId,
        uint128 liquidity,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 deadline
    ) external override returns (uint256 amount0, uint256 amount1) {
        require(deposits[tokenId].owner == msg.sender, 'E020');

        // POL positions cannot decrease liquidity
        require(!deposits[tokenId].buildsPOL, 'E024');

        // Auto-unstake and get incentives if necessary
        IncentiveKey[] memory incentivesToRestake;
        if (deposits[tokenId].numberOfStakes > 0) {
            incentivesToRestake = _unstakeAndGetIncentives(tokenId);
        }

        (amount0, amount1) = _executeLiquidityDecrease(
            tokenId,
            liquidity,
            amount0Min,
            amount1Min,
            deadline
        );

        // Restake to previous incentives if any
        if (incentivesToRestake.length > 0) {
            _restakeToIncentives(tokenId, incentivesToRestake);
        }
    }

    // Collects fees
    function collectFees(
        uint256 tokenId,
        address recipient,
        uint128 amount0Requested,
        uint128 amount1Requested
    ) external returns (uint256 amount0, uint256 amount1) {
        // Only the deposit owner can collect fees
        require(deposits[tokenId].owner == msg.sender, 'E020');

        // Recipient must be valid
        require(recipient != address(0), 'E018');

        // Collect fees through position manager
        INonfungiblePositionManager.CollectParams memory params =
                            INonfungiblePositionManager.CollectParams({
                tokenId: tokenId,
                recipient: recipient,
                amount0Max: amount0Requested,
                amount1Max: amount1Requested
            });

        (amount0, amount1) = nonfungiblePositionManager.collect(params);
    }

    /// @notice Helper function to execute liquidity increase
    function _executeLiquidityIncrease(
        uint256 tokenId,
        uint256 amountAdd0,
        uint256 amountAdd1,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 deadline
    ) private returns (uint128 liquidity, uint256 amount0, uint256 amount1) {
        (, , address token0, address token1, , , , , , , , ) =
            nonfungiblePositionManager.positions(tokenId);
        
        TransferHelperExtended.safeTransferFrom(token0, msg.sender, address(this), amountAdd0);
        TransferHelperExtended.safeTransferFrom(token1, msg.sender, address(this), amountAdd1);
        TransferHelper.safeApprove(token0, address(nonfungiblePositionManager), amountAdd0);
        TransferHelper.safeApprove(token1, address(nonfungiblePositionManager), amountAdd1);

        INonfungiblePositionManager.IncreaseLiquidityParams memory params =
            INonfungiblePositionManager.IncreaseLiquidityParams({
                tokenId: tokenId,
                amount0Desired: amountAdd0,
                amount1Desired: amountAdd1,
                amount0Min: amount0Min,
                amount1Min: amount1Min,
                deadline: deadline
            });

        (liquidity, amount0, amount1) = nonfungiblePositionManager.increaseLiquidity(params);

        // Refund any unused tokens, and clear unconsumed approval for compatibility with USDT like approval flows
        if (amountAdd0 > amount0) {
            TransferHelperExtended.safeTransfer(token0, msg.sender, amountAdd0 - amount0);
            TransferHelper.safeApprove(token0, address(nonfungiblePositionManager), 0);
        }
        if (amountAdd1 > amount1) {
            TransferHelperExtended.safeTransfer(token1, msg.sender, amountAdd1 - amount1);
            TransferHelper.safeApprove(token1, address(nonfungiblePositionManager), 0);
        }

        emit LiquidityIncreased(tokenId, liquidity, amount0, amount1);
    }

    /// @notice Helper function to execute liquidity decrease
    function _executeLiquidityDecrease(
        uint256 tokenId,
        uint128 liquidity,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 deadline
    ) private returns (uint256 amount0, uint256 amount1) {
        INonfungiblePositionManager.DecreaseLiquidityParams memory params =
            INonfungiblePositionManager.DecreaseLiquidityParams({
                tokenId: tokenId,
                liquidity: liquidity,
                amount0Min: amount0Min,
                amount1Min: amount1Min,
                deadline: deadline
            });
        
        (amount0, amount1) = nonfungiblePositionManager.decreaseLiquidity(params);
        
        // Collect only the tokens from decreased liquidity (not fees)
        // Note: This will also collect any accumulated fees as a side effect
        INonfungiblePositionManager.CollectParams memory collectParams =
            INonfungiblePositionManager.CollectParams({
                tokenId: tokenId,
                recipient: msg.sender,
                amount0Max: uint128(amount0),
                amount1Max: uint128(amount1)
            });
        
        nonfungiblePositionManager.collect(collectParams);
        
        emit LiquidityDecreased(tokenId, liquidity, amount0, amount1);
    }

    /// @notice Unstakes a token from all active incentives and returns the incentive keys
    /// @param tokenId The ID of the token to unstake
    /// @return incentiveKeysToRestake Array of incentive keys that were unstaked
    function _unstakeAndGetIncentives(uint256 tokenId)
    private returns (IncentiveKey[] memory incentiveKeysToRestake)
    {
        Deposit storage deposit = deposits[tokenId];
        address owner = deposit.owner;

        // Get all active stake incentive IDs for this token from userERC721Stakes
        uint256 numStakes = userERC721Stakes[owner][tokenId].length();
        bytes32[] memory activeIncentiveIds = new bytes32[](numStakes);
        for (uint256 i = 0; i < numStakes; i++) {
            activeIncentiveIds[i] = userERC721Stakes[owner][tokenId].at(i);
        }

        // Initialize array to store incentive keys
        incentiveKeysToRestake = new IncentiveKey[](activeIncentiveIds.length);

        // Unstake from each incentive
        for (uint256 i = 0; i < activeIncentiveIds.length; i++) {
            bytes32 incentiveId = activeIncentiveIds[i];

            // Get the IncentiveKey from the existing incentive storage
            IncentiveKey memory key = incentives[incentiveId].key;

            // Store incentive key for restaking later
            incentiveKeysToRestake[i] = key;

            // Perform internal unstake and get reward
            uint256 reward = _unstakeToken(key, tokenId, deposit);

            emit AutoUnstaked(tokenId, incentiveId, reward);
        }
    }

    /// @notice Restakes a token to previously active incentives
    /// @param tokenId The ID of the token to restake
    /// @param incentiveKeys Array of incentive keys to restake to
    function _restakeToIncentives(uint256 tokenId, IncentiveKey[] memory incentiveKeys) private {
        for (uint256 i = 0; i < incentiveKeys.length; i++) {
            IncentiveKey memory key = incentiveKeys[i];
            bytes32 incentiveId = IncentiveId.compute(key);

            // Check if incentive is still valid for staking
            if (_canRestakeToIncentive(key)) {
                try this._stakeTokenExternal(key, tokenId) {
                    emit AutoRestaked(tokenId, incentiveId);
                } catch {
                    emit IncentiveSkippedOnRestake(tokenId, incentiveId, "Staking failed");
                }
            } else {
                emit IncentiveSkippedOnRestake(tokenId, incentiveId, "Incentive no longer valid");
            }
        }
    }

    /// @notice Checks if an incentive is still valid for restaking
    /// @param key The incentive key to check
    /// @return Whether the incentive can be restaked to
    function _canRestakeToIncentive(IncentiveKey memory key) private view returns (bool) {
        // Check if incentive is still active
        if (block.timestamp >= key.endTime) return false;

        // Check if incentive exists and has rewards
        bytes32 incentiveId = IncentiveId.compute(key);
        if (incentives[incentiveId].totalRewardUnclaimed == 0) return false;

        return true;
    }

    // IERC721Receiver
    function onERC721Received(address, address, uint256, bytes calldata) external pure override returns (bytes4) {
        revert("Not implemented");
    }

    // IMulticall
    function multicall(bytes[] calldata) external payable override returns (bytes[] memory) {
        revert("Not implemented");
    }

    // IUniswapV3Staker functions (not related to liquidity)
    function createIncentive(IncentiveKey memory) external pure override {
        revert("Not implemented");
    }

    // IUniswapV3Staker functions (not related to liquidity)
    function endIncentive(IncentiveKey memory) external pure override returns (uint256) {
        revert("Not implemented");
    }

    // IUniswapV3Staker functions (not related to liquidity)
    function transferDeposit(uint256, address) external pure override {
        revert("Not implemented");
    }

    // IUniswapV3Staker functions (not related to liquidity)
    function withdrawToken(uint256, address, bytes memory) external pure override {
        revert("Not implemented");
    }

    // IUniswapV3Staker functions (not related to liquidity)
    function getRewardInfo(IncentiveKey memory, uint256) external pure override returns (uint256, uint256, uint160) {
        revert("Not implemented");
    }

    // Storage access functions
    function getActiveIncentiveAt(uint256) external pure override returns (bytes32) {
        revert("Not implemented");
    }

    function getActiveIncentivesLength() external pure override returns (uint256) {
        revert("Not implemented");
    }

    function getUserERC721DepositAt(address, uint256) external pure override returns (uint256) {
        revert("Not implemented");
    }

    function getUserERC721DepositsLength(address) external pure override returns (uint256) {
        revert("Not implemented");
    }

    function getUserERC721StakeAt(address, uint256, uint256) external pure override returns (bytes32) {
        revert("Not implemented");
    }

    function getUserERC721StakesLength(address, uint256) external pure override returns (uint256) {
        revert("Not implemented");
    }

    function getPOLTokenIdAt(uint256) external pure override returns (uint256) {
        revert("Not implemented");
    }

    function getPOLTokenIdsLength() external pure override returns (uint256) {
        revert("Not implemented");
    }

    function getIncentiveTokenAt(bytes32, uint256) external pure override returns (uint256) {
        revert("Not implemented");
    }

    function getIncentiveTokensLength(bytes32) external pure override returns (uint256) {
        revert("Not implemented");
    }

    function stakeToken(IncentiveKey memory, uint256) external pure override {
        revert("Not implemented");
    }

    function unstakeToken(IncentiveKey memory, uint256) external pure override {
        revert("Not implemented");
    }
}
UniswapV3StakerState.sol 525 lines
pragma solidity =0.7.6;
pragma abicoder v2;
import "./EmissionController.sol";
import "./interfaces/IEmissionController.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol";
import "@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol";
import "./interfaces/IUniswapV3Staker.sol";
import './libraries/IncentiveId.sol';
import './libraries/NFTPositionInfo.sol';
import './libraries/RewardMath.sol';
import './libraries/TransferHelperExtended.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol';

abstract contract UniswapV3StakerState is IUniswapV3Staker {
    using EnumerableSet for EnumerableSet.UintSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;
    
    /// @inheritdoc IUniswapV3Staker
    IUniswapV3Factory public override factory;
    /// @inheritdoc IUniswapV3Staker
    INonfungiblePositionManager public override nonfungiblePositionManager;
    /// @dev Currently active incentives
    EnumerableSet.Bytes32Set internal activeIncentives;

    /// @inheritdoc IUniswapV3Staker
    uint256 public override maxIncentiveStartLeadTime;
    /// @inheritdoc IUniswapV3Staker
    uint256 public override maxIncentiveDuration;

    /// @notice Handles time-locked rewards
    /// @dev Contract responsible for managing different emission styles (Dripped, Vested)
    IEmissionController public emissionController;

    /// @dev bytes32 refers to the return value of IncentiveId.compute
    mapping(bytes32 => Incentive) public override incentives;

    /// @dev deposits[tokenId] => Deposit
    mapping(uint256 => Deposit) public override deposits;

    /// @dev stakes[tokenId][incentiveHash] => Stake
    mapping(uint256 => mapping(bytes32 => Stake)) internal _stakes;

    /// @dev userERC721Deposits[user] => EnumerableSet.UintSet
    mapping(address => EnumerableSet.UintSet) internal userERC721Deposits;

    /// @dev userERC721Stakes[user][tokenId] => EnumerableSet.Bytes32Set
    mapping(address => mapping(uint256 => EnumerableSet.Bytes32Set)) internal userERC721Stakes;

    /// @dev incentiveTokens[incentiveId] => EnumerableSet.UintSet of tokenIds
    mapping(bytes32 => EnumerableSet.UintSet) internal incentiveTokens;

    // Tracks all token IDs that are currently locked as POL
    EnumerableSet.UintSet internal polTokenIds;

    /// @dev Maximum allowed staging duration
    uint256 public constant MAX_STAGING_DURATION = 30 days;
    
    /// @dev Precision factor for share-weighted reward calculations
    uint256 internal constant PRECISION = 1e27;

    /// @notice Maximum number of incentives a single position can be staked in
    uint256 public maxIncentivesPerPosition = 10;

    /// @notice State for share-weighted reward distribution
    /// @dev Tracks the state needed for proportional reward distribution based on fixed liquidity share
    struct ShareWeightedState {
        uint256 totalStaked;           // Total liquidity staked in the incentive
        uint256 rewardRate;            // Rewards per second (scaled by PRECISION)
        uint256 rewardPerTokenStored;  // Accumulated rewards per token
        uint256 lastUpdateTime;        // Last time rewards were updated/paid
    }
    
    /// @notice Individual stake tracking for share-weighted rewards
    /// @dev Tracks user's stake state for share-weighted reward calculations
    struct ShareWeightedStake {
        uint128 amount;                // Amount of liquidity staked
        uint256 rewardPerTokenPaid;    // Reward per token already paid to the user
        uint256 rewards;               // Accumulated rewards for the user
    }

    /// @dev Mapping from incentive ID to share-weighted state
    mapping(bytes32 => ShareWeightedState) internal shareWeightedStates;
    
    /// @dev Mapping from tokenId to incentiveId to share-weighted stake
    mapping(uint256 => mapping(bytes32 => ShareWeightedStake)) internal shareWeightedStakes;

    constructor(
        IUniswapV3Factory _factory,
        INonfungiblePositionManager _nonfungiblePositionManager,
        uint256 _maxIncentiveStartLeadTime,
        uint256 _maxIncentiveDuration
    ) {
        factory = _factory;
        nonfungiblePositionManager = _nonfungiblePositionManager;
        maxIncentiveStartLeadTime = _maxIncentiveStartLeadTime;
        maxIncentiveDuration = _maxIncentiveDuration;
        emissionController = new EmissionController();
    }

    /// @inheritdoc IUniswapV3Staker
    function stakes(uint256 tokenId, bytes32 incentiveId)
    public
    view
    override
    returns (uint160 secondsPerLiquidityInsideInitialX128, uint32 secondsInsideInitial, uint128 liquidity)
    {
        Stake storage stake = _stakes[tokenId][incentiveId];
        secondsPerLiquidityInsideInitialX128 = stake.secondsPerLiquidityInsideInitialX128;
        secondsInsideInitial = stake.secondsInsideInitial;
        liquidity = stake.liquidityNoOverflow;
        if (liquidity == type(uint64).max) {
            liquidity = stake.liquidityIfOverflow;
        }
    }

    /// @notice Stakes a deposited token without doing an ownership check
    /// @param key The incentive key to stake in
    /// @param tokenId The ID of the token to stake
    /// @dev Internal function used for staking tokens, validates all requirements
    function _stakeToken(IncentiveKey memory key, uint256 tokenId) internal {
        require(block.timestamp >= key.startTime, 'E028');
        require(block.timestamp < key.endTime, 'E029');

        bytes32 incentiveId = IncentiveId.compute(key);
        Incentive storage incentive = incentives[incentiveId];

        require(
            incentive.totalRewardUnclaimed > 0,
            'E030'
        );

        // Add this incentive to the user's stakes for this token using EnumerableSet if not already present
        address owner = deposits[tokenId].owner;
        require(userERC721Stakes[owner][tokenId].length() < maxIncentivesPerPosition, 'E041');
        userERC721Stakes[owner][tokenId].add(incentiveId);
        incentiveTokens[incentiveId].add(tokenId);

        (IUniswapV3Pool pool, int24 tickLower, int24 tickUpper, uint128 liquidity) =
                            NFTPositionInfo.getPositionInfo(factory, nonfungiblePositionManager, tokenId);

        require(pool == key.pool, 'E032');
        require(liquidity > 0, 'E033');

        require(
            _matchesRequiredCharacteristics(incentiveId, tickLower, tickUpper),
            'E034'
        );

        if (incentive.rangeSettings.buildsPOL && !deposits[tokenId].buildsPOL) {
            deposits[tokenId].buildsPOL = true;
            polTokenIds.add(tokenId);
            emit POLStatusChanged(tokenId, true);
        }

        deposits[tokenId].numberOfStakes++;
        incentive.numberOfStakes++;

        if (key.accrualMechanism == RewardAccrualMechanism.ShareWeighted) {
            ShareWeightedState storage state = shareWeightedStates[incentiveId];
            ShareWeightedStake storage stake = shareWeightedStakes[tokenId][incentiveId];

            // Prevent double stake
            require(stake.amount == 0, 'E031');

            // Update rewards before changing stake
            _updateReward(tokenId, incentiveId);
            
            // Add liquidity to total staked
            state.totalStaked = state.totalStaked + uint256(liquidity);
            
            // Update stake amount
            stake.amount = liquidity;
        } else {
            // LiquidityWeighted path

            // Prevent double stake
            require(_stakes[tokenId][incentiveId].liquidityNoOverflow == 0, 'E031');

            (, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) =
                                pool.snapshotCumulativesInside(tickLower, tickUpper);

            if (liquidity >= type(uint64).max) {
                _stakes[tokenId][incentiveId] = Stake({
                    secondsPerLiquidityInsideInitialX128: secondsPerLiquidityInsideX128,
                    secondsInsideInitial: secondsInside,
                    liquidityNoOverflow: type(uint64).max,
                    liquidityIfOverflow: liquidity
                });
            } else {
                Stake storage stake = _stakes[tokenId][incentiveId];
                stake.secondsPerLiquidityInsideInitialX128 = secondsPerLiquidityInsideX128;
                stake.secondsInsideInitial = secondsInside;
                stake.liquidityNoOverflow = uint64(liquidity);
            }
        }

        emit TokenStaked(tokenId, incentiveId, liquidity);
    }

    /// @notice Internal function to unstake a token
    /// @param key The incentive key
    /// @param tokenId The token ID to unstake
    /// @param deposit The deposit data for the token
    /// @return reward The reward amount earned
    function _unstakeToken(IncentiveKey memory key, uint256 tokenId, Deposit memory deposit) internal virtual returns (uint256 reward) {
        bytes32 incentiveId = IncentiveId.compute(key);

        // Get stake and validate it exists
        (uint160 secondsPerLiquidityInsideInitialX128, uint32 secondsInsideInitial, uint128 liquidity) =
                        _getAndValidateStake(tokenId, incentiveId, key);

        _updateStakeCounts(tokenId, incentiveId);
        userERC721Stakes[deposit.owner][tokenId].remove(incentiveId);
        incentiveTokens[incentiveId].remove(tokenId);
        _cleanupStakeStorage(tokenId, incentiveId, liquidity);

        if (key.accrualMechanism == RewardAccrualMechanism.ShareWeighted) {
            ShareWeightedState storage state = shareWeightedStates[incentiveId];
            ShareWeightedStake storage stake = shareWeightedStakes[tokenId][incentiveId];
            
            // Update rewards before changing stake
            _updateReward(tokenId, incentiveId);
            
            // Calculate final reward
            reward = stake.rewards;
            
            // Subtract liquidity from total staked
            state.totalStaked = state.totalStaked - uint256(liquidity);

            // Cap reward at available unclaimed amount
            if (reward > incentives[incentiveId].totalRewardUnclaimed) {
                reward = incentives[incentiveId].totalRewardUnclaimed;
            }

            incentives[incentiveId].totalRewardUnclaimed -= reward;
            stake.amount = 0;
            stake.rewards = 0;
            
            // Distribute the reward
            if (reward > 0) {
                _distributeReward(key, incentiveId, incentives[incentiveId], deposit.owner, reward);
            }
        } else {
            // LiquidityWeighted path
            reward = _calculateAndDistributeRewards(
                key,
                deposit,
                incentiveId,
                secondsPerLiquidityInsideInitialX128,
                secondsInsideInitial,
                liquidity
            );
        }

        emit TokenUnstaked(tokenId, incentiveId);
    }

    /// @notice Check if a token's tick range matches the required tick range for an incentive
    /// @param incentiveId The ID of the incentive to check
    /// @param tokenTickLower The lower tick of the token position
    /// @param tokenTickUpper The upper tick of the token position
    /// @return True if the token's tick range matches the required tick range or if there's no requirement
    /// @dev Validates tick range requirements based on incentive settings
    function _matchesRequiredCharacteristics(bytes32 incentiveId, int24 tokenTickLower, int24 tokenTickUpper) internal view returns (bool) {
        Incentive storage incentive = incentives[incentiveId];

        // Check min width if required
        if (incentive.rangeSettings.hasMinWidth) {
            // assuming safe from overflow here, as Uniswap has min/max ticks of -887272/887272
            // (887,272) - (-887,272) == 1,774,544
            // 1,774,544 < 8,388,607, with 8,388,607 being max positive value of int24
            int24 width = tokenTickUpper - tokenTickLower;
            if (width < int24(incentive.rangeSettings.minTickWidth)) { // overflow prevention checked as part of createIncentive
                return false;
            }
        }

        // If incentive doesn't have a tick range requirement, all positions are valid
        if (!incentive.rangeSettings.hasTickRange) {
            return true;
        } else {
            if (incentive.rangeSettings.rangeType == RangeType.Fixed) {
                // If incentive has a Fixed tick range requirement, the token's tick range must match exactly
                return tokenTickLower == incentive.rangeSettings.requiredTickLower && tokenTickUpper == incentive.rangeSettings.requiredTickUpper;
            } else {
                // If incentive has a Bounded tick range requirement, the token's tick range must fall fuzzily within the range
                return tokenTickLower >= incentive.rangeSettings.requiredTickLower && tokenTickUpper <= incentive.rangeSettings.requiredTickUpper;
            }
        }
    }

    /// @notice Retrieves and validates a stake exists
    /// @param tokenId The ID of the token to get the stake for
    /// @param incentiveId The ID of the incentive the token is staked in
    /// @param key The incentive key to determine stake type
    function _getAndValidateStake(uint256 tokenId, bytes32 incentiveId, IncentiveKey memory key)
    internal
    view
    returns (uint160, uint32, uint128)
    {
        if (key.accrualMechanism == RewardAccrualMechanism.ShareWeighted) {
            ShareWeightedStake storage stake = shareWeightedStakes[tokenId][incentiveId];
            require(stake.amount != 0, 'E027.1');
            // Return dummy values for secondsPerLiquidityInsideInitialX128 and secondsInsideInitial
            // as they're not used in share-weighted calculations
            return (0, 0, stake.amount);
        } else {
            // For liquidity-weighted incentives, use the regular stakes mapping
            (uint160 secondsPerLiquidityInsideInitialX128, uint32 secondsInsideInitial, uint128 liquidity) =
                            stakes(tokenId, incentiveId);

            require(liquidity != 0, 'E027.1');

            return (secondsPerLiquidityInsideInitialX128, secondsInsideInitial, liquidity);
        }
    }

    /// @notice Updates stake counts in storage
    /// @param tokenId The ID of the token being unstaked
    /// @param incentiveId The ID of the incentive being unstaked from
    /// @dev Decrements stake counts in both deposit and incentive storage
    function _updateStakeCounts(uint256 tokenId, bytes32 incentiveId) internal {
        deposits[tokenId].numberOfStakes--;
        incentives[incentiveId].numberOfStakes--;
    }

    /// @notice Cleans up stake storage after unstaking
    /// @param tokenId The ID of the token being unstaked
    /// @param incentiveId The ID of the incentive being unstaked from
    /// @param liquidity The liquidity amount of the stake
    /// @dev Deletes stake data to free up storage and gas refunds
    function _cleanupStakeStorage(uint256 tokenId, bytes32 incentiveId, uint128 liquidity) internal {
        Stake storage stake = _stakes[tokenId][incentiveId];
        delete stake.secondsPerLiquidityInsideInitialX128;
        delete stake.secondsInsideInitial;
        delete stake.liquidityNoOverflow;
        if (liquidity >= type(uint64).max) delete stake.liquidityIfOverflow;
    }

    /// @notice Calculates and distributes rewards for unstaking
    /// @param key The incentive key
    /// @param deposit The deposit information
    /// @param incentiveId The ID of the incentive
    /// @param secondsPerLiquidityInsideInitialX128 The initial seconds per liquidity inside the position
    /// @param secondsInsideInitial The initial seconds inside the position
    /// @param liquidity The liquidity of the position
    /// @return reward The calculated reward amount
    /// @dev Calculates rewards and distributes them according to the emission style
    function _calculateAndDistributeRewards(
        IncentiveKey memory key,
        Deposit memory deposit,
        bytes32 incentiveId,
        uint160 secondsPerLiquidityInsideInitialX128,
        uint32 secondsInsideInitial,
        uint128 liquidity
    ) internal returns (uint256) {
        Incentive storage incentive = incentives[incentiveId];

        (uint256 reward, uint256 maxReward, uint160 secondsInsideX128) = _computeRewardAmount(
            key,
            incentive,
            deposit,
            secondsPerLiquidityInsideInitialX128,
            liquidity,
            secondsInsideInitial
        );

        _updateIncentiveAccounting(incentive, secondsInsideX128, maxReward, reward);

        // Distribute rewards based on emission style
        _distributeReward(key, incentiveId, incentive, deposit.owner, reward);

        return reward;
    }

    /// @notice Computes the reward amount for a position
    /// @dev Virtual function that can be overridden for testing
    function _computeRewardAmount(
        IncentiveKey memory key,
        Incentive storage incentive,
        Deposit memory deposit,
        uint160 secondsPerLiquidityInsideInitialX128,
        uint128 liquidity,
        uint32 secondsInsideInitial
    ) internal virtual view returns (uint256 reward, uint256 maxReward, uint160 secondsInsideX128) {
        (, uint160 secondsPerLiquidityInsideX128, uint32 secondsInside) =
                                key.pool.snapshotCumulativesInside(deposit.tickLower, deposit.tickUpper);

        return RewardMath.computeRewardAmount(
            RewardMath.ComputeRewardAmountParams(
                incentive.totalRewardUnclaimed,
                incentive.totalSecondsClaimedX128,
                key.startTime,
                key.endTime,
                key.vestingPeriod,
                liquidity,
                secondsPerLiquidityInsideInitialX128,
                secondsPerLiquidityInsideX128,
                secondsInsideInitial,
                secondsInside,
                block.timestamp
            )
        );
    }

    /// @notice Updates incentive accounting based on reward calculation
    function _updateIncentiveAccounting(
        Incentive storage incentive,
        uint160 secondsInsideX128,
        uint256 maxReward,
        uint256 reward
    ) internal {
        // if this overflows, e.g. after 2^32-1 full liquidity seconds have been claimed,
        // reward rate will fall drastically so it's safe
        incentive.totalSecondsClaimedX128 += secondsInsideX128;

        // reward is never greater than total reward unclaimed
        incentive.totalRewardUnclaimed -= maxReward;

        // if not all reward is paid to owner, add difference to locked amount to be withdrawable at end of incentive
        if (maxReward > reward) {
            incentive.totalRewardLocked += maxReward - reward;
        }
    }

    /// @notice Distributes rewards according to the emission style
    /// @dev Either sends immediate rewards or creates a time-locked emission
    function _distributeReward(
        IncentiveKey memory key,
        bytes32 incentiveId,
        Incentive storage incentive,
        address owner,
        uint256 reward
    ) internal {
        if(reward == 0) {
            return;
        }

        if (incentive.emissionSettings.emissionStyle == IEmissionController.EmissionStyle.Regular) {
            TransferHelperExtended.safeTransfer(address(key.rewardToken), owner, reward);
            emit RewardClaimed(key.rewardToken, owner, reward);
        } else {
            TransferHelper.safeApprove(address(key.rewardToken), address(emissionController), reward);

            emissionController.createEmission(
                incentiveId,
                key.rewardToken,
                owner,
                reward,
                incentive.emissionSettings,
                key.refundee
            );
        }
    }

    /// @notice External wrapper for _stakeToken to enable try/catch
    /// @dev This is needed because try/catch only works with external calls, this is actually called from within UniswapV3LiquidityHandler...
    function _stakeTokenExternal(IncentiveKey memory key, uint256 tokenId) external {
        require(msg.sender == address(this), "E040");
        _stakeToken(key, tokenId);
    }
    
    /// @notice Returns the current reward per token value for a share-weighted incentive
    /// @param incentiveId The ID of the incentive
    /// @return The current reward per token value
    function _rewardPerToken(bytes32 incentiveId) internal view returns (uint256) {
        ShareWeightedState storage state = shareWeightedStates[incentiveId];
        
        if (state.totalStaked == 0) {
            return state.rewardPerTokenStored;
        }
        
        // Get the appropriate time based on incentive boundaries
        Incentive storage incentive = incentives[incentiveId];
        uint256 lastTimeRewardApplicable = block.timestamp < incentive.key.endTime
            ? block.timestamp
            : incentive.key.endTime;
            
        if (lastTimeRewardApplicable <= state.lastUpdateTime) {
            return state.rewardPerTokenStored;
        }
        
        // Calculate additional reward per token since last update
        return state.rewardPerTokenStored + 
            ((lastTimeRewardApplicable - state.lastUpdateTime) * state.rewardRate / state.totalStaked);
    }
    
    /// @notice Returns the amount of cumulative reward tokens earned for a position
    /// @param tokenId The ID of the NFT position
    /// @param incentiveId The ID of the incentive
    /// @return The amount of rewards earned
    function _earned(uint256 tokenId, bytes32 incentiveId) internal view returns (uint256) {
        ShareWeightedStake storage stake = shareWeightedStakes[tokenId][incentiveId];
        if (stake.amount == 0) {
            return 0;
        }
        
        uint256 currentRewardPerToken = _rewardPerToken(incentiveId);
        uint256 rewardsSinceLastCalculation = uint256(stake.amount) * 
            (currentRewardPerToken - stake.rewardPerTokenPaid) / PRECISION;
            
        return stake.rewards + rewardsSinceLastCalculation;
    }
    
    /// @notice Updates the reward accounting for a specific position
    /// @param tokenId The ID of the NFT position
    /// @param incentiveId The ID of the incentive
    function _updateReward(uint256 tokenId, bytes32 incentiveId) internal {
        ShareWeightedState storage state = shareWeightedStates[incentiveId];
        Incentive storage incentive = incentives[incentiveId];
        
        // Update incentive-level reward tracking
        state.rewardPerTokenStored = _rewardPerToken(incentiveId);
        state.lastUpdateTime = block.timestamp < incentive.key.endTime
            ? block.timestamp
            : incentive.key.endTime;
            
        // Update position-level reward tracking
        ShareWeightedStake storage stake = shareWeightedStakes[tokenId][incentiveId];
        stake.rewards = _earned(tokenId, incentiveId);
        stake.rewardPerTokenPaid = state.rewardPerTokenStored;
    }
}
UniswapV3StakerViews.sol 262 lines
pragma solidity =0.7.6;
pragma abicoder v2;

import './interfaces/IUniswapV3Staker.sol';
import '@openzeppelin/contracts/utils/EnumerableSet.sol';

/// @title UniswapV3StakerViews
/// @notice A view-only contract that provides paginated access to UniswapV3Staker data
/// @dev This contract is designed to reduce the main staker contract size by extracting view functions
contract UniswapV3StakerViews {
    using EnumerableSet for EnumerableSet.UintSet;
    using EnumerableSet for EnumerableSet.Bytes32Set;

    /// @notice The UniswapV3Staker contract
    IUniswapV3Staker public immutable staker;

    constructor(IUniswapV3Staker _staker) {
        staker = _staker;
    }

    /// @notice Get the total number of active incentives
    /// @return The total count of active incentives
    function getActiveIncentivesCount() external view returns (uint256) {
        return staker.getActiveIncentivesLength();
    }

    /// @notice Get paginated active incentive IDs
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return incentiveIds Array of active incentive IDs
    /// @return total Total number of active incentives
    function getActiveIncentivesPaginated(uint256 offset, uint256 limit) external view returns (bytes32[] memory incentiveIds, uint256 total) {
        total = staker.getActiveIncentivesLength();
        
        if (offset >= total || limit == 0) {
            return (new bytes32[](0), total);
        }
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        incentiveIds = new bytes32[](count);
        
        for (uint256 i = 0; i < count; i++) {
            incentiveIds[i] = staker.getActiveIncentiveAt(offset + i);
        }
        
        return (incentiveIds, total);
    }

    /// @notice Get the total number of ERC721 deposits for a user
    /// @param user The user address
    /// @return The total count of deposits
    function getUserERC721DepositsCount(address user) external view returns (uint256) {
        return staker.getUserERC721DepositsLength(user);
    }

    /// @notice Get paginated user ERC721 deposits
    /// @param user The user address
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return tokenIds Array of token IDs
    /// @return total Total number of deposits
    function getUserERC721DepositsPaginated(address user, uint256 offset, uint256 limit) external view returns (uint256[] memory tokenIds, uint256 total) {
        total = staker.getUserERC721DepositsLength(user);
        
        if (offset >= total || limit == 0) {
            return (new uint256[](0), total);
        }
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        tokenIds = new uint256[](count);
        
        for (uint256 i = 0; i < count; i++) {
            tokenIds[i] = staker.getUserERC721DepositAt(user, offset + i);
        }
        
        return (tokenIds, total);
    }

    /// @notice Get the total number of incentives a user has staked a specific token ID in
    /// @param user The user address
    /// @param tokenId The token ID
    /// @return The total count of stakes
    function getUserERC721StakesCount(address user, uint256 tokenId) external view returns (uint256) {
        return staker.getUserERC721StakesLength(user, tokenId);
    }

    /// @notice Get paginated user ERC721 stakes for a specific token
    /// @param user The user address
    /// @param tokenId The token ID
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return incentiveIds Array of incentive IDs
    /// @return total Total number of stakes
    function getUserERC721StakesPaginated(address user, uint256 tokenId, uint256 offset, uint256 limit) external view returns (bytes32[] memory incentiveIds, uint256 total) {
        total = staker.getUserERC721StakesLength(user, tokenId);
        
        if (offset >= total || limit == 0) {
            return (new bytes32[](0), total);
        }
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        incentiveIds = new bytes32[](count);
        
        for (uint256 i = 0; i < count; i++) {
            incentiveIds[i] = staker.getUserERC721StakeAt(user, tokenId, offset + i);
        }
        
        return (incentiveIds, total);
    }

    /// @notice Get the total number of POL token IDs
    /// @return The total count of POL tokens
    function getAllPOLTokenIdsCount() external view returns (uint256) {
        return staker.getPOLTokenIdsLength();
    }

    /// @notice Get paginated POL token IDs
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return tokenIds Array of token IDs
    /// @return total Total number of POL tokens
    function getAllPOLTokenIdsPaginated(uint256 offset, uint256 limit) external view returns (uint256[] memory tokenIds, uint256 total) {
        total = staker.getPOLTokenIdsLength();
        
        if (offset >= total || limit == 0) {
            return (new uint256[](0), total);
        }
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        tokenIds = new uint256[](count);
        
        for (uint256 i = 0; i < count; i++) {
            tokenIds[i] = staker.getPOLTokenIdAt(offset + i);
        }
        
        return (tokenIds, total);
    }

    /// @notice Get all active incentive details
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return incentiveKeys Array of incentive keys
    /// @return total Total number of active incentives
    function getActiveIncentiveDetails(uint256 offset, uint256 limit) 
        external 
        view 
        returns (IUniswapV3Staker.IncentiveKey[] memory incentiveKeys, uint256 total) 
    {
        total = staker.getActiveIncentivesLength();
        
        if (offset >= total || limit == 0) {
            return (new IUniswapV3Staker.IncentiveKey[](0), total);
        }
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        incentiveKeys = new IUniswapV3Staker.IncentiveKey[](count);
        
        for (uint256 i = 0; i < count; i++) {
            bytes32 incentiveId = staker.getActiveIncentiveAt(offset + i);
            (IUniswapV3Staker.IncentiveKey memory key, , , , , ,) = staker.incentives(incentiveId);
            incentiveKeys[i] = key;
        }
        
        return (incentiveKeys, total);
    }

    /// @notice Get user's deposit details
    /// @param user The user address
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return depositInfo Array of deposit information
    /// @return total Total number of deposits
    function getUserDepositDetails(address user, uint256 offset, uint256 limit)
        external
        view
        returns (IUniswapV3Staker.DepositInfo[] memory depositInfo, uint256 total)
    {
        total = staker.getUserERC721DepositsLength(user);
        
        if (offset >= total || limit == 0) {
            return (new IUniswapV3Staker.DepositInfo[](0), total);
        }
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        depositInfo = new IUniswapV3Staker.DepositInfo[](count);
        
        for (uint256 i = 0; i < count; i++) {
            uint256 tokenId = staker.getUserERC721DepositAt(user, offset + i);
            (address owner, uint48 numberOfStakes, int24 tickLower, int24 tickUpper, bool buildsPOL) = staker.deposits(tokenId);
            
            depositInfo[i] = IUniswapV3Staker.DepositInfo({
                tokenId: tokenId,
                owner: owner,
                numberOfStakes: numberOfStakes,
                tickLower: tickLower,
                tickUpper: tickUpper,
                buildsPOL: buildsPOL
            });
        }
        
        return (depositInfo, total);
    }

    /// @notice Information about a staked token including its rewards
    struct StakedTokenInfo {
        uint256 tokenId;
        address owner;
        uint48 numberOfStakes;
        int24 tickLower;
        int24 tickUpper;
        bool buildsPOL;
        uint256 reward;
        uint256 maxReward;
        uint160 secondsInsideX128;
    }

    /// @notice Get detailed information about tokens staked in a specific incentive including rewards
    /// @param incentiveId The incentive ID
    /// @param offset Starting index
    /// @param limit Maximum number of items to return
    /// @return stakedTokens Array of staked token information including rewards
    /// @return total Total number of tokens staked in the incentive
    function getIncentiveTokenDetailsPaginated(bytes32 incentiveId, uint256 offset, uint256 limit)
        external
        view
        returns (StakedTokenInfo[] memory stakedTokens, uint256 total)
    {
        total = staker.getIncentiveTokensLength(incentiveId);
        
        if (offset >= total || limit == 0) {
            return (new StakedTokenInfo[](0), total);
        }
        
        // Get the incentive key for reward calculation
        (IUniswapV3Staker.IncentiveKey memory key, , , , , ,) = staker.incentives(incentiveId);
        
        uint256 count = (offset + limit > total) ? (total - offset) : limit;
        stakedTokens = new StakedTokenInfo[](count);
        
        for (uint256 i = 0; i < count; i++) {
            uint256 tokenId = staker.getIncentiveTokenAt(incentiveId, offset + i);
            (address owner, uint48 numberOfStakes, int24 tickLower, int24 tickUpper, bool buildsPOL) = staker.deposits(tokenId);
            
            // Get reward info for this token
            (uint256 reward, uint256 maxReward, uint160 secondsInsideX128) = staker.getRewardInfo(key, tokenId);
            
            stakedTokens[i] = StakedTokenInfo({
                tokenId: tokenId,
                owner: owner,
                numberOfStakes: numberOfStakes,
                tickLower: tickLower,
                tickUpper: tickUpper,
                buildsPOL: buildsPOL,
                reward: reward,
                maxReward: maxReward,
                secondsInsideX128: secondsInsideX128
            });
        }
        
        return (stakedTokens, total);
    }
}
IERC20Detailed.sol 95 lines
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20Detailed {
    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

    /**
     * @dev Moves `amount` tokens from the caller's account to `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, uint256 amount) external returns (bool);

    /**
     * @dev Returns the remaining number of tokens that `spender` will be
     * allowed to spend on behalf of `owner` through {transferFrom}. This is
     * zero by default.
     *
     * This value changes when {approve} or {transferFrom} are called.
     */
    function allowance(address owner, address spender) external view returns (uint256);

    /**
     * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * IMPORTANT: Beware that changing an allowance with this method brings the risk
     * that someone may use both the old and the new allowance by unfortunate
     * transaction ordering. One possible solution to mitigate this race
     * condition is to first reduce the spender's allowance to 0 and set the
     * desired value afterwards:
     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
     *
     * Emits an {Approval} event.
     */
    function approve(address spender, uint256 amount) external returns (bool);

    /**
     * @dev Moves `amount` tokens from `sender` to `recipient` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

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

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);

    /**
     * @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);
}
IEmissionController.sol 71 lines
pragma solidity =0.7.6;
pragma abicoder v2;

import "@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol";

/**
 * @title IEmissionController
 * @notice Interface for the EmissionController contract that manages token emission schedules
 * @dev Provides functionality for creating and claiming rewards with different vesting schedules
 */
interface IEmissionController {
    /**
     * @notice Defines the emission style for reward vesting
     * @dev Each style corresponds to a specific vesting algorithm
     * @param Regular Standard rewards that are immediately claimable (not handled in EmissionController)
     * @param Dripped Linear vesting schedule with optional cliff
     * @param Vested Non-linear vesting with slow start and exponential growth
     */
    enum EmissionStyle { Regular, Dripped, Vested }

    /**
     * @notice Settings that define how rewards vest over time
     * @dev Used when creating new emissions
     * @param emissionStyle The vesting algorithm to use (Regular, Dripped, or Vested)
     * @param period Total duration of the vesting period in seconds
     * @param cliff Duration of the cliff period in seconds before vesting begins
     * @param stagingDuration Additional hold period after claiming but before tokens are transferable
     * @param isForfeitable If true, unclaimed rewards are forfeit after first claim (one-shot)
     */
    struct EmissionSettings {
        EmissionStyle emissionStyle;
        uint64 period;
        uint64 cliff;
        uint64 stagingDuration;
        bool isForfeitable;
    }

    /**
     * @notice Creates a new emission for a specific incentive
     * @dev Called by the staker contract when rewards are distributed
     * @param incentiveId ID of the incentive this emission belongs to
     * @param rewardToken Token to be distributed as rewards
     * @param onBehalfOf Address that will own this emission and can claim rewards
     * @param amount Amount of tokens to be distributed
     * @param emissionSettings Vesting and emission parameters
     * @param refundee Address to receive forfeited or unclaimed rewards
     */
    function createEmission(
        bytes32 incentiveId,
        IERC20Minimal rewardToken,
        address onBehalfOf,
        uint256 amount,
        EmissionSettings memory emissionSettings,
        address refundee
    ) external;

    /**
     * @notice Claims rewards from an emission based on its vesting schedule
     * @dev Transfers tokens immediately if no staging period, otherwise creates a staged reward
     * @param emissionId ID of the emission to claim rewards from
     * @return reward Amount of tokens claimed
     */
    function claimReward(uint256 emissionId) external returns (uint256 reward);

    /**
     * @notice Claims rewards that have passed their staging period
     * @dev Transfers tokens to the owner after the staging period has passed
     * @param emissionId ID of the staged reward to claim
     */
    function claimStagedReward(uint256 emissionId) external;
}
IUniswapV3Staker.sol 356 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import "./IEmissionController.sol";
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';

import '@openzeppelin/contracts/utils/EnumerableSet.sol';
import '@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';

import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-periphery/contracts/interfaces/IMulticall.sol';
import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol';

/// @title Uniswap V3 Staker Interface
/// @notice Allows staking nonfungible liquidity tokens in exchange for reward tokens
interface IUniswapV3Staker is IERC721Receiver, IMulticall {
    enum RangeType {
        Fixed,  // if fixed, then range must match requiredTickLower & requiredTickUpper exactly
        Bounded // if bounded, then range must fall within requiredTickLower, requiredTickUpper
    }

    enum RewardAccrualMechanism {
        LiquidityWeighted, // Rewards earned as a share of overall pool liquidity (both staked and non-staked)
        ShareWeighted      // Rewards earned as a share of ONLY staked liquidity
    }

    struct RangeSettings {
        bool hasTickRange;
        RangeType rangeType;
        int24 requiredTickLower;
        int24 requiredTickUpper;
        bool hasMinWidth;
        uint256 minTickWidth;
        bool buildsPOL;
    }

    /// @notice Position deposit information
    struct DepositInfo {
        uint256 tokenId;
        address owner;
        uint48 numberOfStakes;
        int24 tickLower;
        int24 tickUpper;
        bool buildsPOL;
    }

    /// @notice Key for identifying an incentive
    /// @param rewardToken The token being distributed as a reward
    /// @param pool The Uniswap V3 pool
    /// @param reward The total amount of reward tokens to be distributed
    /// @param startTime The time when the incentive program begins
    /// @param endTime The time when rewards stop accruing
    /// @param vestingPeriod The minimal in range period (in seconds) after which full rewards are payed out
    /// @param refundee The address which receives any remaining reward tokens when the incentive is ended
    /// @param rangeSettings Configuration for tick range requirements (fixed/bounded ranges, min width, POL)
    /// @param emissionSettings Configuration for reward emission style (regular/dripped/vested)
    /// @param accrualMechanism Mechanism for reward accrual (0=LiquidityWeighted, 1=ShareWeighted)
    struct IncentiveKey {
        IERC20Minimal rewardToken;
        IUniswapV3Pool pool;
        uint256 reward;
        uint256 startTime;
        uint256 endTime;
        uint256 vestingPeriod;
        address refundee;
        RangeSettings rangeSettings;
        IEmissionController.EmissionSettings emissionSettings;
        RewardAccrualMechanism accrualMechanism;
    }

    /// @notice Represents the deposit of a liquidity NFT
    /// @dev Contains owner information and position details for a deposited NFT, including whether it can become locked via POL
    struct Deposit {
        address owner;
        uint48 numberOfStakes;
        int24 tickLower;
        int24 tickUpper;
        bool buildsPOL;
    }

    /// @notice Represents a staked liquidity NFT
    /// @dev Stores initial state and liquidity amount for a staked position
    struct Stake {
        uint160 secondsPerLiquidityInsideInitialX128;
        uint32 secondsInsideInitial;
        uint64 liquidityNoOverflow;
        uint128 liquidityIfOverflow;
    }

    /// @notice Event emitted when a liquidity mining incentive has been created
    /// @param rewardToken The token being distributed as a reward
    /// @param pool The Uniswap V3 pool
    /// @param startTime The time when the incentive program begins
    /// @param endTime The time when rewards stop accruing
    /// @param vestingPeriod The minimal in range period (in seconds) after which full rewards are payed out
    /// @param refundee The address which receives any remaining reward tokens after the end time
    /// @param reward The amount of reward tokens to be distributed
    /// @param hasTickRange Whether or not the incentives require fixed range NFTs to be provided
    /// @param requiredTickLower If hasTickRange is true, the required lower tick
    /// @param requiredTickUpper If hasTickRange is true, the required upper tick
    /// @param buildsPOL If deposits into the incentive soft-lock the liquidity as POL
    event IncentiveCreated(
        IERC20Minimal indexed rewardToken,
        IUniswapV3Pool indexed pool,
        uint256 startTime,
        uint256 endTime,
        uint256 vestingPeriod,
        address refundee,
        uint256 reward,
        bool hasTickRange,
        RangeType rangeType,
        int24 requiredTickLower,
        int24 requiredTickUpper,
        bool hasMinWidth,
        uint256 minTickWidth,
        bool buildsPOL
    );

    /// @notice Event that can be emitted when a liquidity mining incentive has ended
    /// @param incentiveId The incentive which is ending
    /// @param refund The amount of reward tokens refunded
    event IncentiveEnded(bytes32 indexed incentiveId, uint256 refund);

    /// @notice Emitted when ownership of a deposit changes
    /// @param tokenId The ID of the deposit (and token) that is being transferred
    /// @param oldOwner The owner before the deposit was transferred
    /// @param newOwner The owner after the deposit was transferred
    event DepositTransferred(uint256 indexed tokenId, address indexed oldOwner, address indexed newOwner);

    /// @notice Event emitted when a Uniswap V3 LP token has been staked
    /// @param tokenId The unique identifier of an Uniswap V3 LP token
    /// @param liquidity The amount of liquidity staked
    /// @param incentiveId The incentive in which the token is staking
    event TokenStaked(uint256 indexed tokenId, bytes32 indexed incentiveId, uint128 liquidity);

    /// @notice Event emitted when a Uniswap V3 LP token has been unstaked
    /// @param tokenId The unique identifier of an Uniswap V3 LP token
    /// @param incentiveId The incentive in which the token is staking
    event TokenUnstaked(uint256 indexed tokenId, bytes32 indexed incentiveId);

    /// @notice Event emitted when a reward token has been claimed
    /// @param rewardToken Reward token which was claimed
    /// @param to The address where claimed rewards were sent to
    /// @param reward The amount of reward tokens claimed
    event RewardClaimed(IERC20Minimal indexed rewardToken, address indexed to, uint256 reward);

    /// @notice Event emitted when a token's POL status changes, either locked or unlocked
    event POLStatusChanged(uint256 indexed tokenId, bool buildsPOL);

    /// @notice Represents a staking incentive
    /// @dev Holds all data related to a staking incentive, including rewards and range requirements
    struct Incentive {
        IncentiveKey key;
        uint256 totalRewardUnclaimed;
        uint256 totalRewardLocked;
        uint160 totalSecondsClaimedX128;
        uint96 numberOfStakes;
        RangeSettings rangeSettings;
        IEmissionController.EmissionSettings emissionSettings;
    }

    /// @notice Event emitted when the max incentives per position is updated
    event MaxIncentivesPerPositionUpdated(uint256 newMax);

    /// @notice Event emitted when liquidity is increased for a position
    event LiquidityIncreased(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    /// @notice Event emitted when liquidity is decreased for a position
    event LiquidityDecreased(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);

    /// @notice Event emitted when a position is automatically unstaked during liquidity operations
    event AutoUnstaked(uint256 indexed tokenId, bytes32 indexed incentiveId, uint256 reward);

    /// @notice Event emitted when a position is automatically restaked after liquidity operations
    event AutoRestaked(uint256 indexed tokenId, bytes32 indexed incentiveId);

    /// @notice Event emitted when an incentive cannot be restaked to
    event IncentiveSkippedOnRestake(uint256 indexed tokenId, bytes32 indexed incentiveId, string reason);

    /// @notice The Uniswap V3 Factory
    function factory() external view returns (IUniswapV3Factory);

    /// @notice The nonfungible position manager with which this staking contract is compatible
    function nonfungiblePositionManager() external view returns (INonfungiblePositionManager);

    /// @notice The max duration of an incentive in seconds
    function maxIncentiveDuration() external view returns (uint256);

    /// @notice The max amount of seconds into the future the incentive startTime can be set
    function maxIncentiveStartLeadTime() external view returns (uint256);

    /// @notice Represents a staking incentive
    /// @param incentiveId The ID of the incentive computed from its parameters
    /// @return key The Incentive identifier
    /// @return totalRewardUnclaimed The amount of reward token not yet claimed by users
    /// @return totalRewardLocked The amount of reward token locked because of incomplete vesting
    /// @return totalSecondsClaimedX128 Total liquidity-seconds claimed, represented as a UQ32.128
    /// @return numberOfStakes The count of deposits that are currently staked for the incentive
    function incentives(bytes32 incentiveId)
        external
        view
        returns (
            IncentiveKey memory key,
            uint256 totalRewardUnclaimed,
            uint256 totalRewardLocked,
            uint160 totalSecondsClaimedX128,
            uint96 numberOfStakes,
            RangeSettings memory rangeSettings,
            IEmissionController.EmissionSettings memory emissionSettings
        );

    /// @notice Returns information about a deposited NFT
    /// @return owner The owner of the deposited NFT
    /// @return numberOfStakes Counter of how many incentives for which the liquidity is staked
    /// @return tickLower The lower tick of the range
    /// @return tickUpper The upper tick of the range
    /// @return buildsPOL If the deposit is currently considered locked within the platform
    function deposits(uint256 tokenId)
        external
        view
        returns (
            address owner,
            uint48 numberOfStakes,
            int24 tickLower,
            int24 tickUpper,
            bool buildsPOL
        );

    /// @notice Returns information about a staked liquidity NFT
    /// @param tokenId The ID of the staked token
    /// @param incentiveId The ID of the incentive for which the token is staked
    /// @return secondsPerLiquidityInsideInitialX128 secondsPerLiquidity represented as a UQ32.128
    /// @return secondsInsideInitial secondsInside value when staked
    /// @return liquidity The amount of liquidity in the NFT as of the last time the rewards were computed
    function stakes(uint256 tokenId, bytes32 incentiveId)
        external
        view
        returns (uint160 secondsPerLiquidityInsideInitialX128, uint32 secondsInsideInitial, uint128 liquidity);

    /// @notice Creates a new incentive with optional parameters for POL, tick range, and minimum width
    /// @param key The incentive key (pool, reward token, timestamps, etc)
    function createIncentive(IncentiveKey memory key) external;

    /// @notice Ends an incentive after the incentive end time has passed and all stakes have been withdrawn
    /// @param key Details of the incentive to end
    /// @return refund The remaining reward tokens when the incentive is ended
    function endIncentive(IncentiveKey memory key) external returns (uint256 refund);

    /// @notice Transfers ownership of a deposit from the sender to the given recipient
    /// @param tokenId The ID of the token (and the deposit) to transfer
    /// @param to The new owner of the deposit
    function transferDeposit(uint256 tokenId, address to) external;

    /// @notice Withdraws a Uniswap V3 LP token `tokenId` from this contract to the recipient `to`
    /// @param tokenId The unique identifier of an Uniswap V3 LP token
    /// @param to The address where the LP token will be sent
    /// @param data An optional data array that will be passed along to the `to` address via the NFT safeTransferFrom
    function withdrawToken(
        uint256 tokenId,
        address to,
        bytes memory data
    ) external;

    /// @notice Stakes a Uniswap V3 LP token
    /// @param key The key of the incentive for which to stake the NFT
    /// @param tokenId The ID of the token to stake
    function stakeToken(IncentiveKey memory key, uint256 tokenId) external;

    /// @notice Unstakes a Uniswap V3 LP token
    /// @param key The key of the incentive for which to unstake the NFT
    /// @param tokenId The ID of the token to unstake
    function unstakeToken(IncentiveKey memory key, uint256 tokenId) external;

    /// @notice Calculates the reward amount that will be received for the given stake
    /// @param key The key of the incentive
    /// @param tokenId The ID of the token
    /// @return reward The reward accrued to the NFT for the given incentive thus far (including vesting modifier)
    /// @return maxReward The reward accrued to the NFT for the given incentive thus far
    function getRewardInfo(IncentiveKey memory key, uint256 tokenId)
        external
        view
        returns (uint256 reward, uint256 maxReward, uint160 secondsInsideX128);

    // ========== LIQUIDITY MANAGEMENT ==========

    /// @notice Increases liquidity for a deposited position
    /// @dev Automatically unstakes from all incentives, increases liquidity, then restakes
    /// @param tokenId The ID of the NFT position
    /// @param amountAdd0 The amount of token0 to add
    /// @param amountAdd1 The amount of token1 to add
    /// @param amount0Min Minimum amount of token0 to add (slippage protection)
    /// @param amount1Min Minimum amount of token1 to add (slippage protection)
    /// @param deadline Timestamp after which the transaction will revert
    /// @return liquidity The new liquidity amount
    /// @return amount0 The amount of token0 added
    /// @return amount1 The amount of token1 added
    function increaseLiquidity(
        uint256 tokenId,
        uint256 amountAdd0,
        uint256 amountAdd1,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 deadline
    ) external returns (uint128 liquidity, uint256 amount0, uint256 amount1);

    /// @notice Decreases liquidity for a deposited position
    /// @dev Automatically unstakes from all incentives, decreases liquidity, then restakes
    /// @param tokenId The ID of the NFT position
    /// @param liquidity The amount of liquidity to remove
    /// @param amount0Min Minimum amount of token0 to receive (slippage protection)
    /// @param amount1Min Minimum amount of token1 to receive (slippage protection)
    /// @param deadline Timestamp after which the transaction will revert
    /// @return amount0 The amount of token0 received
    /// @return amount1 The amount of token1 received
    function decreaseLiquidity(
        uint256 tokenId,
        uint128 liquidity,
        uint256 amount0Min,
        uint256 amount1Min,
        uint256 deadline
    ) external returns (uint256 amount0, uint256 amount1);

    // ========== STORAGE ACCESS FOR VIEWS ==========

    /// @notice Get an active incentive by index
    function getActiveIncentiveAt(uint256 index) external view returns (bytes32);

    /// @notice Get the count of active incentives
    function getActiveIncentivesLength() external view returns (uint256);

    /// @notice Get a user's ERC721 deposit by index
    function getUserERC721DepositAt(address user, uint256 index) external view returns (uint256);

    /// @notice Get the count of a user's ERC721 deposits
    function getUserERC721DepositsLength(address user) external view returns (uint256);

    /// @notice Get a user's ERC721 stake by index
    function getUserERC721StakeAt(address user, uint256 tokenId, uint256 index) external view returns (bytes32);

    /// @notice Get the count of a user's ERC721 stakes for a token
    function getUserERC721StakesLength(address user, uint256 tokenId) external view returns (uint256);

    /// @notice Get a POL token ID by index
    function getPOLTokenIdAt(uint256 index) external view returns (uint256);

    /// @notice Get the count of POL token IDs
    function getPOLTokenIdsLength() external view returns (uint256);

    /// @notice Get a token ID staked in an incentive by index
    function getIncentiveTokenAt(bytes32 incentiveId, uint256 index) external view returns (uint256);

    /// @notice Get the count of tokens staked in an incentive
    function getIncentiveTokensLength(bytes32 incentiveId) external view returns (uint256);
}
IWETH9.sol 23 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.7.5;

/// @title Interface for WETH9
interface IWETH9 {
    /// @notice Deposit ether to get wrapped ether
    function deposit() external payable;

    /// @notice Withdraw wrapped ether to get ether
    function withdraw(uint256) external;

    /// @notice Get the balance of an account
    function balanceOf(address) external view returns (uint256);

    /// @notice Transfer wrapped ether to another account
    function transfer(address, uint256) external returns (bool);

    /// @notice Approve spending of wrapped ether
    function approve(address, uint256) external returns (bool);

    /// @notice Transfer wrapped ether from one account to another
    function transferFrom(address, address, uint256) external returns (bool);
}
IncentiveId.sol 14 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '../interfaces/IUniswapV3Staker.sol';

library IncentiveId {
    /// @notice Calculate the key for a staking incentive
    /// @param key The components used to compute the incentive identifier
    /// @return incentiveId The identifier for the incentive
    function compute(IUniswapV3Staker.IncentiveKey memory key) internal pure returns (bytes32 incentiveId) {
        return keccak256(abi.encode(key));
    }
}
NFTPositionInfo.sol 47 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;

import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';

import '@uniswap/v3-periphery/contracts/libraries/PoolAddress.sol';

/// @notice Encapsulates the logic for getting info about a NFT token ID
library NFTPositionInfo {
    /// @param factory The address of the Uniswap V3 Factory used in computing the pool address
    /// @param nonfungiblePositionManager The address of the nonfungible position manager to query
    /// @param tokenId The unique identifier of an Uniswap V3 LP token
    /// @return pool The address of the Uniswap V3 pool
    /// @return tickLower The lower tick of the Uniswap V3 position
    /// @return tickUpper The upper tick of the Uniswap V3 position
    /// @return liquidity The amount of liquidity staked
    function getPositionInfo(
        IUniswapV3Factory factory,
        INonfungiblePositionManager nonfungiblePositionManager,
        uint256 tokenId
    )
        internal
        view
        returns (
            IUniswapV3Pool pool,
            int24 tickLower,
            int24 tickUpper,
            uint128 liquidity
        )
    {
        address token0;
        address token1;
        uint24 fee;
        (, , token0, token1, fee, tickLower, tickUpper, liquidity, , , , ) = nonfungiblePositionManager.positions(
            tokenId
        );

        pool = IUniswapV3Pool(
            PoolAddress.computeAddress(
                address(factory),
                PoolAddress.PoolKey({token0: token0, token1: token1, fee: fee})
            )
        );
    }
}
RewardMath.sol 57 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;

import '@uniswap/v3-core/contracts/libraries/FullMath.sol';
import '@openzeppelin/contracts/math/Math.sol';

/// @title Math for computing rewards
/// @notice Allows computing rewards given some parameters of stakes and incentives
library RewardMath {

    /// @param totalRewardUnclaimed The total amount of unclaimed rewards left for an incentive
    /// @param totalSecondsClaimedX128 How many full liquidity-seconds have been already claimed for the incentive
    /// @param startTime When the incentive rewards began in epoch seconds
    /// @param endTime When rewards are no longer being dripped out in epoch seconds
    /// @param vestingPeriod The minimal in range time after which full rewards are payed out
    /// @param liquidity The amount of liquidity, assumed to be constant over the period over which the snapshots are measured
    /// @param secondsPerLiquidityInsideInitialX128 The seconds per liquidity of the liquidity tick range as of the beginning of the period
    /// @param secondsPerLiquidityInsideX128 The seconds per liquidity of the liquidity tick range as of the current block timestamp
    /// @param currentTime The current block timestamp, which must be greater than or equal to the start time
    struct ComputeRewardAmountParams {
        uint256 totalRewardUnclaimed;
        uint160 totalSecondsClaimedX128;
        uint256 startTime;
        uint256 endTime;
        uint256 vestingPeriod;
        uint128 liquidity;
        uint160 secondsPerLiquidityInsideInitialX128;
        uint160 secondsPerLiquidityInsideX128;
        uint32 secondsInsideInitial;
        uint32 secondsInside;
        uint256 currentTime;
    }

    /// @notice Compute the amount of rewards owed given parameters of the incentive and stake
    /// @param params Params see struct
    /// @return reward The amount of rewards owed (considering vesting)
    /// @return maxReward The max amount of rewards owed 
    /// @return secondsInsideX128 The total liquidity seconds inside the position's range for the duration of the stake
    function computeRewardAmount(ComputeRewardAmountParams memory params) internal pure returns (uint256 reward, uint256 maxReward, uint160 secondsInsideX128) {
        // this should never be called before the start time
        assert(params.currentTime >= params.startTime);

        // this operation is safe, as the difference cannot be greater than 1/stake.liquidity
        secondsInsideX128 = (params.secondsPerLiquidityInsideX128 - params.secondsPerLiquidityInsideInitialX128) * params.liquidity;

        uint256 totalSecondsUnclaimedX128 =
            ((Math.max(params.endTime, params.currentTime) - params.startTime) << 128) - params.totalSecondsClaimedX128;

        maxReward = FullMath.mulDiv(params.totalRewardUnclaimed, secondsInsideX128, totalSecondsUnclaimedX128);

        if (params.vestingPeriod <= params.secondsInside - params.secondsInsideInitial) {
            reward = maxReward;
        } else {
            reward = maxReward * (params.secondsInside - params.secondsInsideInitial) / params.vestingPeriod;
        }
    }
}
TransferHelperExtended.sol 39 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.6.0;

import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@openzeppelin/contracts/utils/Address.sol';

library TransferHelperExtended {
    using Address for address;

    /// @notice Transfers tokens from the targeted address to the given destination
    /// @notice Errors with 'STF' if transfer fails
    /// @param token The contract address of the token to be transferred
    /// @param from The originating address from which the tokens will be transferred
    /// @param to The destination address of the transfer
    /// @param value The amount to be transferred
    function safeTransferFrom(
        address token,
        address from,
        address to,
        uint256 value
    ) internal {
        require(token.isContract(), 'TransferHelperExtended::safeTransferFrom: call to non-contract');
        TransferHelper.safeTransferFrom(token, from, to, value);
    }

    /// @notice Transfers tokens from msg.sender to a recipient
    /// @dev Errors with ST if transfer fails
    /// @param token The contract address of the token which will be transferred
    /// @param to The recipient of the transfer
    /// @param value The value of the transfer
    function safeTransfer(
        address token,
        address to,
        uint256 value
    ) internal {
        require(token.isContract(), 'TransferHelperExtended::safeTransfer: call to non-contract');
        TransferHelper.safeTransfer(token, to, value);
    }
}
TestERC20.sol 15 lines
// SPDX-License-Identifier: UNLICENSED
// uniswap-v3-core/contracts/test/TestERC20.sol
pragma solidity =0.7.6;

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

contract TestERC20 is ERC20 {
    constructor(uint256 amountToMint, string memory name) ERC20(name, name) {
        _mint(msg.sender, amountToMint);
    }

    function mint(address to, uint256 amount) public {
        _mint(to, amount);
    }
}
TestERC20Decimals.sol 26 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.7.6;

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

contract TestERC20Decimals is ERC20 {
    uint8 private _decimals;

    constructor(
        uint256 amountToMint,
        string memory name,
        string memory symbol,
        uint8 decimals_
    ) ERC20(name, symbol) {
        _decimals = decimals_;
        _mint(msg.sender, amountToMint);
    }

    function decimals() public view virtual override returns (uint8) {
        return _decimals;
    }

    function mint(address to, uint256 amount) public {
        _mint(to, amount);
    }
}
TestIncentiveId.sol 14 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '../interfaces/IUniswapV3Staker.sol';

import '../libraries/IncentiveId.sol';

/// @dev Test contract for IncentiveId
contract TestIncentiveId {
    function compute(IUniswapV3Staker.IncentiveKey memory key) public pure returns (bytes32) {
        return IncentiveId.compute(key);
    }
}
TestRewardMath.sol 14 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import '../interfaces/IUniswapV3Staker.sol';

import '../libraries/RewardMath.sol';

/// @dev Test contract for RewardMatrh
contract TestRewardMath {
    function computeRewardAmount(RewardMath.ComputeRewardAmountParams memory params) public pure returns (uint256 reward, uint256 maxReward, uint160 secondsInsideX128) {
        (reward, maxReward, secondsInsideX128) = RewardMath.computeRewardAmount(params);
    }
}
TestUniswapV3Staker.sol 71 lines
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma abicoder v2;

import "../UniswapV3Staker.sol";

/// @title Test version of UniswapV3Staker
/// @notice Allows overriding reward calculations for testing edge cases
contract TestUniswapV3Staker is UniswapV3Staker {
    bool public forceFullReward;
    bool public forceZeroReward;
    
    constructor(
        IUniswapV3Factory _factory,
        INonfungiblePositionManager _nonfungiblePositionManager,
        uint256 _maxIncentiveStartLeadTime,
        uint256 _maxIncentiveDuration,
        address _liquidityHandlerImplementation
    ) UniswapV3Staker(
        _factory,
        _nonfungiblePositionManager,
        _maxIncentiveStartLeadTime,
        _maxIncentiveDuration,
        _liquidityHandlerImplementation
    ) {}
    
    /// @notice Set whether to force full reward distribution
    /// @param _forceFullReward If true, always return full unclaimed amount as reward
    function setForceFullReward(bool _forceFullReward) external {
        forceFullReward = _forceFullReward;
    }
    
    /// @notice Set whether to force zero reward distribution
    /// @param _forceZeroReward If true, always return 0 as reward
    function setForceZeroReward(bool _forceZeroReward) external {
        forceZeroReward = _forceZeroReward;
    }
    
    /// @notice Override reward computation for testing
    /// @dev When forceFullReward is true, returns the full unclaimed amount
    /// @dev When forceZeroReward is true, returns 0 for all values
    function _computeRewardAmount(
        IncentiveKey memory key,
        Incentive storage incentive,
        Deposit memory deposit,
        uint160 secondsPerLiquidityInsideInitialX128,
        uint128 liquidity,
        uint32 secondsInsideInitial
    ) internal virtual view override returns (uint256 reward, uint256 maxReward, uint160 secondsInsideX128) {
        if (forceZeroReward) {
            // Return 0 for all values to simulate no rewards earned
            return (0, 0, 0);
        }
        
        if (forceFullReward) {
            // Return the full unclaimed amount as both reward and maxReward
            // Use a large value for secondsInsideX128 to simulate full time accumulation
            return (incentive.totalRewardUnclaimed, incentive.totalRewardUnclaimed, type(uint160).max);
        }
        
        // Otherwise use the normal calculation
        return super._computeRewardAmount(
            key,
            incentive,
            deposit,
            secondsPerLiquidityInsideInitialX128,
            liquidity,
            secondsInsideInitial
        );
    }
}
FullRangeZap.sol 393 lines
pragma solidity =0.7.6;
pragma abicoder v2;

import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol';
import '@uniswap/v3-core/contracts/interfaces/IUniswapV3Factory.sol';
import '@uniswap/v3-core/contracts/interfaces/IERC20Minimal.sol';
import '@uniswap/v3-periphery/contracts/interfaces/INonfungiblePositionManager.sol';
import '@uniswap/v3-periphery/contracts/interfaces/ISwapRouter.sol';
import '@uniswap/v3-periphery/contracts/interfaces/IQuoter.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '../libraries/IncentiveId.sol';
import "../interfaces/IUniswapV3Staker.sol";

/// @title ZapExtension for UniswapV3Staker
/// @notice Extension for the UniswapV3Staker that allows users to zap into full range staked positions
/// @dev Provides a single-transaction entry point for creating a position with a single token
contract FullRangeZap {
    /// @notice The Uniswap V3 staker contract
    IUniswapV3Staker public immutable staker;

    /// @notice The Uniswap V3 factory
    IUniswapV3Factory public immutable factory;

    /// @notice The nonfungible position manager
    INonfungiblePositionManager public immutable nonfungiblePositionManager;

    /// @notice The swap router
    ISwapRouter public immutable swapRouter;

    /// @notice Quoter contract for estimating swap outputs
    IQuoter public immutable quoter;

    /// @notice Event emitted when a zap operation is completed
    /// @param tokenId The ID of the created NFT position
    /// @param incentiveId The ID of the incentive the position was staked in
    /// @param user The address of the user who created the position
    /// @param inputToken The token that was supplied by the user
    /// @param inputAmount The amount of input token supplied
    /// @param outputToken0 The amount of token0 used in the position
    /// @param outputToken1 The amount of token1 used in the position
    /// @param minSwapToken0 The minimum amount of token0 expected from swap
    /// @param minSwapToken1 The minimum amount of token1 expected from swap
    /// @param minLiquidityToken0 The minimum amount of token0 accepted for adding liquidity
    /// @param minLiquidityToken1 The minimum amount of token1 accepted for adding liquidity
    event ZapCompleted(
        uint256 tokenId,
        bytes32 indexed incentiveId,
        address indexed user,
        address indexed inputToken,
        uint256 inputAmount,
        uint256 outputToken0,
        uint256 outputToken1,
        uint256 minSwapToken0,
        uint256 minSwapToken1,
        uint256 minLiquidityToken0,
        uint256 minLiquidityToken1
    );

    // Input struct for the zap function to reduce stack usage
    struct ZapInput {
        IUniswapV3Staker.IncentiveKey incentiveKey;
        IERC20Minimal inputToken;
        uint256 inputAmount;
        IUniswapV3Pool pool;
        uint256 minSwapToken0;
        uint256 minSwapToken1;
        uint256 minLiquidityToken0;
        uint256 minLiquidityToken1;
        uint256 deadline;
    }

    struct ZapParams {
        address inputTokenAddress;
        uint256 inputAmount;
        address token0;
        address token1;
        uint24 fee;
        uint256 minSwapToken0;
        uint256 minSwapToken1;
        uint256 minLiquidityToken0;
        uint256 minLiquidityToken1;
        bytes32 incentiveId;
    }

    struct PositionAmounts {
        uint256 token0Amount;
        uint256 token1Amount;
    }

    /// @notice Constructor initializes the contract with required dependencies
    /// @param _staker The Uniswap V3 staker contract
    /// @param _factory The Uniswap V3 factory
    /// @param _nonfungiblePositionManager The nonfungible position manager
    /// @param _swapRouter The swap router
    /// @param _quoter The quoter contract
    constructor(
        IUniswapV3Staker _staker,
        IUniswapV3Factory _factory,
        INonfungiblePositionManager _nonfungiblePositionManager,
        ISwapRouter _swapRouter,
        IQuoter _quoter
    ) {
        staker = _staker;
        factory = _factory;
        nonfungiblePositionManager = _nonfungiblePositionManager;
        swapRouter = _swapRouter;
        quoter = _quoter;
    }

    /// @notice Creates a staked position from a single token with explicit minimum output amounts for swaps and liquidity
    /// @param input Struct containing all input parameters
    /// @return tokenId The ID of the created NFT position
    function zap(ZapInput memory input) external returns (uint256) {
        _validateZapParams(input.incentiveKey, input.pool, input.minLiquidityToken0, input.minLiquidityToken1);

        ZapParams memory params = _initZapParams(
            address(input.inputToken),
            input.inputAmount,
            input.pool,
            input.minSwapToken0,
            input.minSwapToken1,
            input.minLiquidityToken0,
            input.minLiquidityToken1,
            input.incentiveKey
        );

        TransferHelper.safeTransferFrom(params.inputTokenAddress, msg.sender, address(this), params.inputAmount);
        PositionAmounts memory amounts = _calculateAndSwapTokens(params, input.deadline);
        (uint256 tokenId, uint256 amount0, uint256 amount1) = _createAndStakePosition(params, amounts, input.incentiveKey, input.deadline);
        _refundLeftoverTokens(params);

        emit ZapCompleted(
            tokenId,
            params.incentiveId,
            msg.sender,
            params.inputTokenAddress,
            params.inputAmount,
            amount0,
            amount1,
            params.minSwapToken0,
            params.minSwapToken1,
            params.minLiquidityToken0,
            params.minLiquidityToken1
        );

        return tokenId;
    }

    /// @dev Validates the input parameters for the zap function
    function _validateZapParams(
        IUniswapV3Staker.IncentiveKey memory incentiveKey,
        IUniswapV3Pool pool,
        uint256 minLiquidityToken0,
        uint256 minLiquidityToken1
    ) private view {
        require(pool == incentiveKey.pool, "Pool does not match incentive");
        require(minLiquidityToken0 > 0 || minLiquidityToken1 > 0, "Min liquidity amounts cannot both be zero");

        bytes32 incentiveId = IncentiveId.compute(incentiveKey);
        (,uint256 totalRewardUnclaimed,,,,,) = staker.incentives(incentiveId);
        require(totalRewardUnclaimed > 0, "Invalid or expired incentive");
    }

    /// @dev Initializes the zap parameters
    function _initZapParams(
        address inputTokenAddress,
        uint256 inputAmount,
        IUniswapV3Pool pool,
        uint256 minSwapToken0,
        uint256 minSwapToken1,
        uint256 minLiquidityToken0,
        uint256 minLiquidityToken1,
        IUniswapV3Staker.IncentiveKey memory incentiveKey
    ) private view returns (ZapParams memory params) {
        params.inputTokenAddress = inputTokenAddress;
        params.inputAmount = inputAmount;
        params.token0 = pool.token0();
        params.token1 = pool.token1();
        params.fee = pool.fee();
        params.minSwapToken0 = minSwapToken0;
        params.minSwapToken1 = minSwapToken1;
        params.minLiquidityToken0 = minLiquidityToken0;
        params.minLiquidityToken1 = minLiquidityToken1;
        params.incentiveId = IncentiveId.compute(incentiveKey);
        return params;
    }

    /// @dev Calculates token amounts and performs necessary swaps
    function _calculateAndSwapTokens(ZapParams memory params, uint256 deadline) private returns (PositionAmounts memory amounts) {
        if (params.inputTokenAddress == params.token0) {
            amounts.token0Amount = params.inputAmount / 2;
            amounts.token1Amount = _swapExactInputSingle(
                params.inputTokenAddress,
                params.token1,
                params.fee,
                amounts.token0Amount,
                params.minSwapToken1,
                deadline
            );
        } else if (params.inputTokenAddress == params.token1) {
            amounts.token1Amount = params.inputAmount / 2;
            amounts.token0Amount = _swapExactInputSingle(
                params.inputTokenAddress,
                params.token0,
                params.fee,
                amounts.token1Amount,
                params.minSwapToken0,
                deadline
            );
        } else {
            revert("Unexpected source token for swap");
        }
        return amounts;
    }

    /// @dev Creates and stakes the position
    function _createAndStakePosition(
        ZapParams memory params,
        PositionAmounts memory amounts,
        IUniswapV3Staker.IncentiveKey memory incentiveKey,
        uint256 deadline
    ) private returns (uint256 tokenId, uint256 amount0, uint256 amount1) {
        // Approve tokens to the position manager for liquidity provision
        TransferHelper.safeApprove(params.token0, address(nonfungiblePositionManager), amounts.token0Amount);
        TransferHelper.safeApprove(params.token1, address(nonfungiblePositionManager), amounts.token1Amount);

        // Get min/max ticks for full range position
        int24 tickSpacing = IUniswapV3Pool(incentiveKey.pool).tickSpacing();
        int24 minTick = -887272; // Minimum tick for full range
        int24 maxTick = 887272;  // Maximum tick for full range

        // Ensure ticks are divisible by tickSpacing
        minTick = (minTick / tickSpacing) * tickSpacing;
        maxTick = (maxTick / tickSpacing) * tickSpacing;

        // Create the position using explicit min liquidity amounts for slippage protection
        (tokenId, , amount0, amount1) = nonfungiblePositionManager.mint(
            INonfungiblePositionManager.MintParams({
                token0: params.token0,
                token1: params.token1,
                fee: params.fee,
                tickLower: minTick,
                tickUpper: maxTick,
                amount0Desired: amounts.token0Amount,
                amount1Desired: amounts.token1Amount,
                amount0Min: params.minLiquidityToken0,
                amount1Min: params.minLiquidityToken1,
                recipient: address(this),
                deadline: deadline
            })
        );

        // Encode the incentive key for staking
        bytes memory incentiveData = abi.encode(incentiveKey);

        // Approve position to staker
        nonfungiblePositionManager.approve(address(staker), tokenId);
        nonfungiblePositionManager.safeTransferFrom(address(this), address(staker), tokenId, incentiveData);

        // Transfer created deposit to initiating user
        staker.transferDeposit(tokenId, msg.sender);

        // Clear allowances for USDT like token approval flows
        if (amount0 < amounts.token0Amount) {
            TransferHelper.safeApprove(params.token0, address(nonfungiblePositionManager), 0);
        }

        if (amount1 < amounts.token1Amount) {
            TransferHelper.safeApprove(params.token1, address(nonfungiblePositionManager), 0);
        }

        return (tokenId, amount0, amount1);
    }

    /// @dev Refunds any leftover tokens to the user
    function _refundLeftoverTokens(ZapParams memory params) private {
        uint256 refundToken0 = IERC20Minimal(params.token0).balanceOf(address(this));
        uint256 refundToken1 = IERC20Minimal(params.token1).balanceOf(address(this));

        if (refundToken0 > 0) {
            TransferHelper.safeTransfer(params.token0, msg.sender, refundToken0);
        }

        if (refundToken1 > 0) {
            TransferHelper.safeTransfer(params.token1, msg.sender, refundToken1);
        }
    }

    /// @notice Helper function to perform a swap with an exact input amount and minimum output
    /// @param tokenIn The input token address
    /// @param tokenOut The output token address
    /// @param fee The pool fee tier to use for the swap
    /// @param amountIn The amount of input tokens to swap
    /// @param amountOutMinimum The minimum amount of output tokens to receive
    /// @param deadline The deadline for the swap transaction
    /// @return amountOut The amount of output tokens received
    function _swapExactInputSingle(
        address tokenIn, address tokenOut, uint24 fee, uint256 amountIn, uint256 amountOutMinimum, uint256 deadline
    ) private returns (uint256 amountOut) {
        TransferHelper.safeApprove(tokenIn, address(swapRouter), amountIn);

        ISwapRouter.ExactInputSingleParams memory params =
            ISwapRouter.ExactInputSingleParams({
                tokenIn: tokenIn,
                tokenOut: tokenOut,
                fee: fee,
                recipient: address(this),
                deadline: deadline,
                amountIn: amountIn,
                amountOutMinimum: amountOutMinimum,
                sqrtPriceLimitX96: 0
            });

        amountOut = swapRouter.exactInputSingle(params);

        // Just in case, clear allowance to account of USDT like token approval patterns
        if (IERC20(tokenIn).allowance(address(this), address(swapRouter)) != 0) {
            TransferHelper.safeApprove(tokenIn, address(swapRouter), 0);
        }
    }

    // Local struct to reduce stack variables for estimation functions
    struct EstimateParams {
        address token0;
        address token1;
        uint24 fee;
        uint256 amountToSwap;
        uint256 remainingAmount;
    }

    // Input struct for estimate function to further reduce stack usage
    struct EstimateInput {
        address inputToken;
        uint256 inputAmount;
        IUniswapV3Pool pool;
    }

    /// @notice Helper function to estimate expected amounts using Uniswap's Quoter
    /// @param input Struct containing input parameters for estimation
    /// @return expectedSwapToken0 Estimated amount of token0 from swapping (if needed)
    /// @return expectedSwapToken1 Estimated amount of token1 from swapping (if needed)
    /// @return expectedLiquidityToken0 Estimated amount of token0 for liquidity
    /// @return expectedLiquidityToken1 Estimated amount of token1 for liquidity
    function estimateOutputAmounts(EstimateInput calldata input) external returns (
        uint256 expectedSwapToken0,
        uint256 expectedSwapToken1,
        uint256 expectedLiquidityToken0,
        uint256 expectedLiquidityToken1
    ) {
        if (input.inputAmount == 0) {
            return (0, 0, 0, 0);
        }

        uint24 fee = input.pool.fee();
        address token0 = input.pool.token0();
        address token1 = input.pool.token1();
        require(input.inputToken == token0 || input.inputToken == token1, "Input token must be either token0 or token1");

        // Calculate half the input amount for swapping
        uint256 amountToSwap = input.inputAmount / 2;

        if (input.inputToken == token0) {
            expectedLiquidityToken0 = amountToSwap;

            // Quote swap from token0 to token1
            try quoter.quoteExactInputSingle(token0, token1, fee, amountToSwap, 0) returns (uint256 amountOut) {
                expectedLiquidityToken1 = amountOut;
                expectedSwapToken1 = amountOut;
            } catch {
                expectedLiquidityToken1 = 0;
                expectedSwapToken1 = 0;
            }
        } else if (input.inputToken == token1) {
            expectedLiquidityToken1 = amountToSwap;

            // Quote swap from token1 to token0
            try quoter.quoteExactInputSingle(token1, token0, fee, amountToSwap, 0) returns (uint256 amountOut) {
                expectedLiquidityToken0 = amountOut;
                expectedSwapToken0 = amountOut;
            } catch {
                expectedLiquidityToken0 = 0;
                expectedSwapToken0 = 0;
            }
        }

        return (
            expectedSwapToken0,
            expectedSwapToken1,
            expectedLiquidityToken0,
            expectedLiquidityToken1
        );
    }
}
FullRangeZapETH.sol 129 lines
pragma solidity =0.7.6;
pragma abicoder v2;

import './FullRangeZap.sol';
import '../interfaces/IWETH9.sol';
import '@uniswap/v3-periphery/contracts/libraries/TransferHelper.sol';
import '@openzeppelin/contracts/access/Ownable.sol';

/// @title FullRangeZapETH - ETH-specific wrapper for FullRangeZap
/// @notice Handles ETH zapping functionality by wrapping ETH to WETH before using FullRangeZap
/// @dev This contract accepts ETH, wraps it to WETH, and delegates to FullRangeZap
contract FullRangeZapETH is Ownable {
    /// @notice The FullRangeZap contract to delegate to
    FullRangeZap public immutable fullRangeZap;
    
    /// @notice The WETH9 contract address
    address public immutable weth;

    /// @notice Input struct for zapWithEth function
    struct ZapWithEthInput {
        IUniswapV3Staker.IncentiveKey incentiveKey;
        IUniswapV3Pool pool;
        uint256 minSwapToken0;
        uint256 minSwapToken1;
        uint256 minLiquidityToken0;
        uint256 minLiquidityToken1;
        uint256 deadline;
    }

    /// @notice Constructor initializes the contract with required dependencies
    /// @param _fullRangeZap The FullRangeZap contract address
    /// @param _weth The WETH9 contract address
    constructor(FullRangeZap _fullRangeZap, address _weth) {
        require(address(_fullRangeZap) != address(0), "Invalid FullRangeZap address");
        require(_weth != address(0), "Invalid WETH address");
        fullRangeZap = _fullRangeZap;
        weth = _weth;
    }

    /// @notice Creates a staked position from ETH
    /// @dev Accepts ETH, wraps it to WETH, calls the main zap function, then transfers ownership to msg.sender
    /// @param input Struct containing all input parameters except inputToken and inputAmount
    /// @return tokenId The ID of the created NFT position
    function zapWithEth(ZapWithEthInput calldata input) external payable returns (uint256 tokenId) {
        require(msg.value > 0, "No ETH sent");

        // Unwrap WETH to ETH if some was sent to contract, to prep it for extraction
        IWETH9 _weth = IWETH9(weth);
        uint256 wethBalance = _weth.balanceOf(address(this));
        if (wethBalance > 0) {
            _weth.withdraw(wethBalance); // Mistakenly send WETH can be collected later by owner
        }

        // Wrap ETH to WETH
        _weth.deposit{value: msg.value}();
        
        // Approve WETH to FullRangeZap
        TransferHelper.safeApprove(weth, address(fullRangeZap), msg.value);

        // Create ZapInput struct with WETH as input token
        FullRangeZap.ZapInput memory zapInput = FullRangeZap.ZapInput({
            incentiveKey: input.incentiveKey,
            inputToken: IERC20Minimal(weth),
            inputAmount: msg.value,
            pool: input.pool,
            minSwapToken0: input.minSwapToken0,
            minSwapToken1: input.minSwapToken1,
            minLiquidityToken0: input.minLiquidityToken0,
            minLiquidityToken1: input.minLiquidityToken1,
            deadline: input.deadline
        });

        // Call the main zap function
        tokenId = fullRangeZap.zap(zapInput);
        
        // The position is now owned by this contract, we need to transfer it to the user
        fullRangeZap.staker().transferDeposit(tokenId, msg.sender);

        // Now, check for unused WETH and refund user
        uint256 unusedWeth = _weth.balanceOf(address(this));
        if (unusedWeth > 0) {
            _weth.withdraw(unusedWeth);
            TransferHelper.safeTransferETH(msg.sender, unusedWeth);
        }

        return tokenId;
    }

    /// @notice Estimates expected output amounts when zapping with ETH
    /// @param ethAmount The amount of ETH to zap
    /// @param pool The Uniswap V3 pool to zap into
    /// @return expectedSwapToken0 Estimated amount of token0 from swapping (if needed)
    /// @return expectedSwapToken1 Estimated amount of token1 from swapping (if needed)
    /// @return expectedLiquidityToken0 Estimated amount of token0 for liquidity
    /// @return expectedLiquidityToken1 Estimated amount of token1 for liquidity
    function estimateETHOutputAmounts(
        uint256 ethAmount,
        IUniswapV3Pool pool
    ) external returns (
        uint256 expectedSwapToken0,
        uint256 expectedSwapToken1,
        uint256 expectedLiquidityToken0,
        uint256 expectedLiquidityToken1
    ) {
        // Create EstimateInput with WETH as input token
        FullRangeZap.EstimateInput memory input = FullRangeZap.EstimateInput({
            inputToken: weth,
            inputAmount: ethAmount,
            pool: pool
        });

        // Use the existing estimation function
        return fullRangeZap.estimateOutputAmounts(input);
    }

    /// @notice Allows owner to sweep orphaned ETH from the contract
    function sweepETH() external onlyOwner {
        uint256 balance = address(this).balance;
        if (balance > 0) {
            TransferHelper.safeTransferETH(owner(), balance);
        }
    }

    /// @notice Fallback function to receive ETH from WETH withdraw
    receive() external payable {
        // Only accept ETH from WETH contract
        require(msg.sender == weth, "Direct ETH transfers not accepted");
    }
}

Read Contract

MAX_STAGING_DURATION 0xcbcb9746 → uint256
deposits 0xb02c43d0 → address, uint48, int24, int24, bool
emissionController 0x6dee2012 → address
factory 0xc45a0155 → address
getActiveIncentiveAt 0x59851e0d → bytes32
getActiveIncentivesLength 0xccafa5b4 → uint256
getIncentiveTokenAt 0x8e106865 → uint256
getIncentiveTokensLength 0xfa25cc2d → uint256
getPOLTokenIdAt 0x9261a0bf → uint256
getPOLTokenIdsLength 0x9be8fc99 → uint256
getRewardInfo 0x085fee76 → uint256, uint256, uint160
getUserERC721DepositAt 0x1a4774c7 → uint256
getUserERC721DepositsLength 0x7d86e66d → uint256
getUserERC721StakeAt 0x247884a0 → bytes32
getUserERC721StakesLength 0x883ce8b2 → uint256
incentives 0x60777795 → tuple, uint256, uint256, uint160, uint96, tuple, tuple
liquidityHandlerImplementation 0xba3296ff → address
maxIncentiveDuration 0x3dc0714b → uint256
maxIncentiveStartLeadTime 0x01b75440 → uint256
maxIncentivesPerPosition 0xe07974b7 → uint256
nonfungiblePositionManager 0xb44a2722 → address
owner 0x8da5cb5b → address
stakes 0xc36c1ea5 → uint160, uint32, uint128

Write Contract 16 functions

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

_stakeTokenExternal 0xf301a8d3
tuple key
uint256 tokenId
collectFees 0x59f3f952
uint256 tokenId
address recipient
uint128 amount0Requested
uint128 amount1Requested
returns: uint256, uint256
createIncentive 0x6aaa12c1
tuple key
decreaseLiquidity 0x03a3f2ab
uint256 tokenId
uint128 liquidity
uint256 amount0Min
uint256 amount1Min
uint256 deadline
returns: uint256, uint256
endIncentive 0x68372050
tuple key
returns: uint256
increaseLiquidity 0x12d7b2c4
uint256 tokenId
uint256 amountAdd0
uint256 amountAdd1
uint256 amount0Min
uint256 amount1Min
uint256 deadline
returns: uint128, uint256, uint256
multicall 0xac9650d8
bytes[] data
returns: bytes[]
onERC721Received 0x150b7a02
address
address from
uint256 tokenId
bytes data
returns: bytes4
releasePOL 0x68b6e033
uint256 tokenId
renounceOwnership 0x715018a6
No parameters
setMaxIncentivesPerPosition 0xd5053e11
uint256 _maxIncentivesPerPosition
stakeToken 0xb0e414d6
tuple key
uint256 tokenId
transferDeposit 0x26bfee04
uint256 tokenId
address to
transferOwnership 0xf2fde38b
address newOwner
unstakeToken 0x8c3a7001
tuple key
uint256 tokenId
withdrawToken 0x3c423f0b
uint256 tokenId
address to
bytes data

Recent Transactions

No transactions found for this address