Address Contract Verified
Address
0x2Bcdded6B4932F36C0E78E576771F43dE0D19147
Balance
0 ETH
Nonce
1
Code Size
12249 bytes
Creator
0xd1EafE84...a538 at tx 0xc2f91040...d1ecc4
Indexed Transactions
0
Contract Bytecode
12249 bytes
0x6080604052600436101561001a575b3615610018575f80fd5b005b5f3560e01c806314e9c86b146101755780631a7a73c21461017057806323a69e75146101115780632622082e1461016b5780632b6023b2146101665780633006219214610161578063601963391461015c57806389a30271146101575780638da5cb5b1461015257806391dd73461461014d578063ad5c464814610148578063adc326ba14610143578063ade540241461013e578063b8f5965914610139578063c54e44eb14610134578063dc4c90d31461012f578063dcf844a71461012a578063e0bab4c414610125578063e5f8d07414610120578063f018a8c11461011b578063f3fef3a3146101165763fa461e330361000e575b6103a1565b6115c9565b611520565b6114e0565b6114b2565b611477565b611433565b611405565b611365565b61121c565b610da2565b610d17565b610bbd565b610b3c565b610b0e565b6109df565b610990565b610873565b610750565b6102a1565b61018f565b6001600160a01b0381160361018b57565b5f80fd5b3461018b57604036600319011261018b576004356101ac8161017a565b5f54602435916001600160a01b03918216330361028f57821561027d576001600160a01b0381165f9081526005602052604090208390541061026b576001600160a01b0381165f9081526005602052604090207f74b3d863e79caa554c32d16975d57c7a092d3af7f08c48f20846cb549d9941f0926102569290915b61023386825461162e565b905516928361025b576102468133611bea565b6040519081529081906020820190565b0390a2005b610266813386611b6d565b610246565b604051638d53e55360e01b8152600490fd5b60405163291b459d60e01b8152600490fd5b6040516330cd747160e01b8152600490fd5b3461018b57604036600319011261018b576004356102be8161017a565b5f54602435916001600160a01b03918216330361028f57821561027d576001600160a01b0381165f9081526004602052604090208390541061026b576001600160a01b0381165f9081526004602052604090207f50162071084f8224308c7b81a2a261c209c326b5d853d294630e694d291c3f4692610256929091610228565b9181601f8401121561018b578235916001600160401b03831161018b576020838186019501011161018b57565b606060031982011261018b576004359160243591604435906001600160401b03821161018b5761039d9160040161033e565b9091565b3461018b576103be6103b23661036b565b81949293940190611c34565b6001600160a01b039390841691503382900361073e575f81131561073657915b5f81131561072e57915b806105bb575b50816103f657005b60409182519384809363d21220a760e01b8252602094859160049889915afa9081156104e7575f9161058e575b508451636eb1769f60e11b8152308782019081523360208201529092909116908490839081906040010381845afa9182156104e757849284915f91610561575b50106104ec575b845163a9059cbb60e01b81523387820190815260208101949094529283919082905f90829060400103925af19182156104e7575f926104ba575b5050156104ad57005b516312171d8360e31b8152fd5b6104d99250803d106104e0575b6104d181836116c3565b810190611c59565b5f806104a4565b503d6104c7565b611893565b845163095ea7b360e01b815233878201908152602081018590529192509084908290819060400103815f865af19081156104e7575f91610544575b501561053457829061046a565b505050516340b27c2160e11b8152fd5b61055b9150843d86116104e0576104d181836116c3565b5f610527565b6105819150843d8611610587575b61057981836116c3565b8101906117ff565b5f610463565b503d61056f565b6105ae9150843d86116105b4575b6105a681836116c3565b810190611a38565b5f610423565b503d61059c565b60408051630dfe168160e01b815260049260209182818681895afa80156104e75788915f91610711575b508451636eb1769f60e11b8152308782019081523360208201529190921692908490839081906040010381865afa9182156104e757849282915f916106f4575b501061068f575b845163a9059cbb60e01b815233878201908152602081019290925292839182905f90829060400103925af19182156104e7575f92610672575b5050156104ad57506103ee565b6106889250803d106104e0576104d181836116c3565b5f80610665565b845163095ea7b360e01b815233878201908152602081018390529192509084908290819060400103815f875af19081156104e7575f916106d7575b501561053457829061062c565b6106ee9150843d86116104e0576104d181836116c3565b5f6106ca565b61070b9150843d86116105875761057981836116c3565b5f610625565b6107289150843d86116105b4576105a681836116c3565b5f6105e5565b505f916103e8565b505f916103de565b604051636edaef2f60e11b8152600490fd5b3461018b57602036600319011261018b5760043561076d8161017a565b60018060a01b03165f526003602052602060ff60405f2054166040519015158152f35b9181601f8401121561018b578235916001600160401b03831161018b576020808501948460051b01011161018b57565b9181601f8401121561018b578235916001600160401b03831161018b5760208085019460a0850201011161018b57565b60e060031982011261018b576001600160401b039160043583811161018b578261081c91600401610790565b9390939260243582811161018b578161083791600401610790565b939093926044359260643561084b8161017a565b926084359260a43561085c8161017a565b9260c43591821161018b5761039d916004016107c0565b3461018b57610881366107f0565b939198909295889795971561097e5780890361096c57871561027d576108cb956108c38b60018060a01b039a6108bd818d309033908b16611c6e565b86611cf3565b9a9093611dee565b9490809415610958575b5050821061094657604080518381526001600160a01b038516602082015261092892849290917f5e151cf22271fbddd8ba632d1dfc6790556a3990827574210cf70d2ed216a5059190a133908516611b6d565b604080519182526001600160a01b03929092166020820152f35b0390f35b604051638199f5f360e01b8152600490fd5b61096492945085611fbf565b915f806108d5565b60405163512509d360e11b8152600490fd5b60405163b4fa3fb360e01b8152600490fd5b3461018b57602036600319011261018b576004356109ad8161017a565b60018060a01b03165f526005602052602060405f2054604051908152f35b6003111561018b57565b8015150361018b57565b3461018b57606036600319011261018b576004356109fc816109cb565b602435610a088161017a565b604435610a14816109d5565b5f546001600160a01b03908116330361028f57821692831561097e57610a3981611640565b80610a9d57610a8e82610a7d7f35f4607091cf1dd7cd09a3ad12b18362500b8dcd4efbdc68d5dd813fd7ea78889560018060a01b03165f52600260205260405f2090565b9060ff801983541691151516179055565b6102566040519283928361165e565b610aa681611640565b60018103610af257610aed82610a7d7f35f4607091cf1dd7cd09a3ad12b18362500b8dcd4efbdc68d5dd813fd7ea78889560018060a01b03165f52600360205260405f2090565b610a8e565b60405163b01318a560e01b8152600490fd5b5f91031261018b57565b3461018b575f36600319011261018b57602060405173a0b86991c6218b36c1d19d4a2e9eb0ce3606eb488152f35b3461018b575f36600319011261018b575f546040516001600160a01b039091168152602090f35b5f5b838110610b745750505f910152565b8181015183820152602001610b65565b90602091610b9d81518092818552858086019101610b63565b601f01601f1916010190565b906020610bba928181520190610b84565b90565b3461018b5760208060031936011261018b576004356001600160401b03811161018b57610bee90369060040161033e565b917f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b0316913383900361073e57610c3381610ca29584930190611795565b92835190610c4383860151151590565b60408601516060870151919391610c8591906001600160a01b031690610c71610c6a6116e4565b9615158752565b858701526001600160a01b03166040850152565b5f604051809881958294633cf3645360e21b84526004840161180e565b03925af19081156104e757610942935f92610cf2575b50610cc882610ce693945161211b565b6040519081019283529182906020015b03601f1981018352826116c3565b60405191829182610ba9565b610ce69250610d10610cc891833d85116105875761057981836116c3565b9250610cb8565b3461018b575f36600319011261018b576001546040516001600160a01b039091168152602090f35b6020808201906020835283518092526040830192602060408460051b8301019501935f915b848310610d745750505050505090565b9091929394958480610d92600193603f198682030187528a51610b84565b9801930193019194939290610d64565b3461018b5760408060031936011261018b576004906001600160401b0390823582811161018b57610dd69036908501610790565b9260243590811161018b57610dee9036908601610790565b939091610dfc85831461189e565b610e0582611910565b945f5b838110610e1c578551806109428982610d3f565b610e2f610e2a82848861197b565b61198b565b610e3881611640565b610faa57610e61610e55610e55610e5084888861197b565b611995565b6001600160a01b031690565b908651630240bc6b60e21b815260609081818c81875afa9081156104e7575f925f92610f78575b50508851630dfe168160e01b815260209081818e81895afa9586156104e7578d915f97610f57575b5082908c519283809263d21220a760e01b82525afa80156104e757600196610f1c94610cd8935f93610f38575b508d516001600160701b03978816958101958652961660208501525f60408501526001600160a01b039081166060850152166080830152839160a00190565b610f26828a611a97565b52610f318189611a97565b5001610e08565b610f50919350853d87116105b4576105a681836116c3565b915f610edd565b83919750610f7190823d84116105b4576105a681836116c3565b9690610eb0565b610f9b935080919250903d10610fa3575b610f9381836116c3565b810190611a61565b505f80610e88565b503d610f89565b6001610fba610e2a83858961197b565b610fc381611640565b0361116c57610fdc610e55610e55610e5084888861197b565b908651633850c7bd60e01b815260e080828c81875afa9182156104e7575f915f93611135575b50508851630d34328160e11b815260209485828e81845afa9182156104e7575f92611106575b508a51630dfe168160e01b815286818f81855afa9081156104e7578e9288915f936110e7575b508d5163d21220a760e01b815293849182905afa9081156104e7576001976001600160801b03966110c3968f610cd8965f966110c8575b50516001600160a01b0391821693810193845260029290920b6020840152959097166040820152908416606082015292166080830152839160a00190565b610f1c565b6110e0919650843d86116105b4576105a681836116c3565b945f611085565b6110ff919350823d84116105b4576105a681836116c3565b915f61104e565b611127919250863d881161112e575b61111f81836116c3565b810190611a19565b905f611028565b503d611115565b611158935080919250903d10611165575b61115081836116c3565b8101906119ae565b5050505050905f80611002565b503d611146565b600261117e610e2a8a9389958961197b565b61118781611640565b036111db576111d7915191829162461bcd60e51b8352820160609060208152601e60208201527f5573652053746174655669657720666f7220563420706f6f6c2064617461000060408201520190565b0390fd5b6111d7915191829162461bcd60e51b835282016060906020815260136020820152722ab739bab83837b93a32b2103b32b939b4b7b760691b60408201520190565b3461018b5761122a366107f0565b9391955f999193999897959850871561097e5780880361096c57881561027d576112729561126a888b6108bd60018060a01b039d8e309033908b16611c6e565b999093611dee565b600154909491939061128c906001600160a01b0316610e55565b918083169086160361097e5715611355575050915b821061094657604080518381526001600160a01b039290921660208301527f5e151cf22271fbddd8ba632d1dfc6790556a3990827574210cf70d2ed216a50591a16001546112f7906001600160a01b0316610e55565b90813b1561018b57604051632e1a7d4d60e01b815260048101829052915f908390602490829084905af19182156104e7576109429261133c575b506102468133611bea565b8061134961134f92611690565b80610b04565b5f611331565b9161135f92611fbf565b916112a1565b60c036600319011261018b576001600160401b0360043581811161018b57611391903690600401610790565b60243583811161018b576113a9903690600401610790565b90926113b660443561017a565b608435916113c38361017a565b60a43595861161018b576113de6113ea9636906004016107c0565b95909460643593611aab565b604080519283526001600160a01b0391909116602083015290f35b3461018b575f36600319011261018b57602060405173dac17f958d2ee523a2206206994597c13d831ec78152f35b3461018b575f36600319011261018b576040517f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b03168152602090f35b3461018b57602036600319011261018b576004356114948161017a565b60018060a01b03165f526004602052602060405f2054604051908152f35b3461018b575f36600319011261018b576020604051736b175474e89094c44da98b954eedeac495271d0f8152f35b3461018b57602036600319011261018b576004356114fd8161017a565b60018060a01b03165f526002602052602060ff60405f2054166040519015158152f35b3461018b57602036600319011261018b57600435801561027d5760015461156090829061155790610e55906001600160a01b031681565b30903390611c6e565b600154611575906001600160a01b0316610e55565b90813b1561018b57604051632e1a7d4d60e01b815260048101829052915f908390602490829084905af19182156104e757610018926115b6575b5033611bea565b806113496115c392611690565b5f6115af565b3461018b57604036600319011261018b576004356115e68161017a565b5f54602435916001600160a01b03918216330361028f5716908161160f57610018915033611bea565b610018913390611b6d565b634e487b7160e01b5f52601160045260245ffd5b9190820391821161163b57565b61161a565b6003111561164a57565b634e487b7160e01b5f52602160045260245ffd5b909291926040820193600382101561164a5760209183521515910152565b634e487b7160e01b5f52604160045260245ffd5b6001600160401b0381116116a357604052565b61167c565b60a081019081106001600160401b038211176116a357604052565b90601f801991011681019081106001600160401b038211176116a357604052565b60405190606082018281106001600160401b038211176116a357604052565b60405190611710826116a8565b565b8060020b0361018b57565b91908260a091031261018b57604051611735816116a8565b809280356117428161017a565b825260208101356117528161017a565b6020830152604081013562ffffff8116810361018b5760809182916040850152606081013561178081611712565b60608501520135916117918361017a565b0152565b6101208183031261018b57610100906117ba604051936117b4856116a8565b8261171d565b835260a08101356117ca816109d5565b602084015260c0810135604084015260e08101356117e78161017a565b606084015201356117f78161017a565b608082015290565b9081602091031261018b575190565b905f906101409361185f84610120936080908160018060a01b039182815116855282602082015116602086015262ffffff6040820151166040860152606081015160020b6060860152015116910152565b8051151560a0850152602081015160c0850152604001516001600160a01b031660e084015261010083018190528201520190565b6040513d5f823e3d90fd5b156118a557565b60405162461bcd60e51b815260206004820152602660248201527f496e70757420617272617973206d7573742068617665207468652073616d65206044820152650d8cadccee8d60d31b6064820152608490fd5b6001600160401b0381116116a35760051b60200190565b9061191a826118f9565b61192760405191826116c3565b8281528092611938601f19916118f9565b01905f5b82811061194857505050565b80606060208093850101520161193c565b634e487b7160e01b5f52603260045260245ffd5b90156119765790565b611959565b91908110156119765760051b0190565b35610bba816109cb565b35610bba8161017a565b519061ffff8216820361018b57565b908160e091031261018b5780516119c48161017a565b9160208201516119d381611712565b916119e06040820161199f565b916119ed6060830161199f565b916119fa6080820161199f565b9160a082015160ff8116810361018b5760c090920151610bba816109d5565b9081602091031261018b57516001600160801b038116810361018b5790565b9081602091031261018b5751610bba8161017a565b51906001600160701b038216820361018b57565b9081606091031261018b57611a7581611a4d565b916040611a8460208401611a4d565b92015163ffffffff8116810361018b5790565b80518210156119765760209160051b010190565b97969293949795919095861561097e5784870361096c57341561027d57611af594611ad46122e5565b600154611ae9906001600160a01b0316610e55565b9261126a8b3486611cf3565b9490809315611b59575b5050811061094657604080518281526001600160a01b03851660208201527f5e151cf22271fbddd8ba632d1dfc6790556a3990827574210cf70d2ed216a5059190a1611b5581336001600160a01b038616611b6d565b9190565b611b6592935085611fbf565b905f80611aff565b60405163a9059cbb60e01b81526001600160a01b03909216600483015260248201929092526020915f9160449183905af13d15601f3d1160015f511416171615611bb357565b60405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606490fd5b5f80809381935af115611bf957565b60405162461bcd60e51b815260206004820152601360248201527211551217d514905394d1915497d19052531151606a1b6044820152606490fd5b919082604091031261018b5760208235611c4d8161017a565b920135610bba8161017a565b9081602091031261018b5751610bba816109d5565b915f8093602095606494604051946323b872dd60e01b865260018060a01b03809216600487015216602485015260448401525af13d15601f3d1160015f511416171615611cb757565b60405162461bcd60e51b81526020600482015260146024820152731514905394d1915497d19493d357d1905253115160621b6044820152606490fd5b6001546001600160a01b0391908183169083168114908115611db5575b8115611d97575b8115611d79575b5015611d705761271061270f606485020104938415611d665783851015611d545784611d4d938216159261234c565b0390600190565b6040516313b7709160e11b8152600490fd5b5050509050905f90565b50509050905f90565b736b175474e89094c44da98b954eedeac495271d0f9150145f611d1e565b73dac17f958d2ee523a2206206994597c13d831ec781149150611d17565b73a0b86991c6218b36c1d19d4a2e9eb0ce3606eb4881149150611d10565b91908110156119765760a0020190565b610bba90369061171d565b9197969590929395611e1989611e07610e50878761196d565b878015159283611f9b575b50506124f7565b906001600160a01b0388811690821603611f8b57509895939198949290945b985f80955b848710611e51575050505050505050509190565b919395979a88868d611e6c610e2a84849d9f97999b8461197b565b611e7581611640565b611ec2575050611eab93929150611e93610e50611e98928a8a61197b565b612b34565b611ea6610e508a898961197b565b612c27565b9990975b60018b9801969492909695939197611e3d565b91610e2a91611ed09361197b565b611ed981611640565b6001908103611f1a57505090611f1291611eff611efa610e508b8a8a61197b565b612841565b611f0d610e508a898961197b565b61294c565b999097611eaf565b909b926002611f30610e2a8c8c969e968861197b565b611f3981611640565b14611f46575b5050611eaf565b909b5081939991158015611f81575b61097e57611f7591611f70611f6b8c8789611dd3565b611de3565b6125c4565b9a909801915f80611f3f565b50838a1015611f55565b9050989593919894929094611e38565b6001929350611fad91610e2a9161196d565b611fb681611640565b1490878c611e12565b612710928361270f6064850201049384156120f35783851015611d545761177085020490818503926120018160018060a01b03165f52600460205260405f2090565b61200c84825461233f565b90556001600160a01b0382811691821515806120e9575b1561209057917f0a721ab4682ceb61c7e4d264ef879fc419a6d764b136e7d96ef54b2053c756736120708761024661208997955f80516020612f84833981519152999716998a9687611b6d565b0390a3604080519182525f602083015290918291820190565b0390a20390565b915091506120895f80516020612f8483398151915293946120c18360018060a01b03165f52600560205260405f2090565b6120cc82825461233f565b905560405193849316958360209093929193604081019481520152565b5084881415612023565b505050905090565b600f0b6f7fffffffffffffffffffffffffffffff19811461163b575f0390565b908060801d80600f0b5f81135f146122365750825161214f91906001600160a01b03165b906001600160801b031690612ed5565b80600f0b5f81135f1461217757506020919091015161171091906001600160a01b031661213f565b90505f8112612184575050565b602091909101516001600160a01b037f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a90811692916121d4916121c891165b926120fb565b6001600160801b031690565b823b1561018b57604051630b0d9c0960e01b81526001600160a01b039290921660048301523060248301526001600160801b03166044820152905f908290606490829084905af180156104e757612229575b50565b8061134961171092611690565b5f13612243575b5061214f565b82516001600160a01b037f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a9081169291612280916121c891166121c2565b823b1561018b57604051630b0d9c0960e01b81526001600160a01b039290921660048301523060248301526001600160801b03166044820152905f908290606490829084905af180156104e7571561223d57806113496122df92611690565b5f61223d565b341561232d576001546001600160a01b0316803b1561018b575f60049160405192838092630d0e30db60e41b825234905af180156104e7576123245750565b61171090611690565b60405163d73ab2e160e01b8152600490fd5b9190820180921161163b57565b6001600160a01b0381165f9081526004602052604090206127106117708402048084039590949392909161238186825461233f565b90556001600160a01b038481169390929084151590879082612459575b505015612427576123f657917f0a721ab4682ceb61c7e4d264ef879fc419a6d764b136e7d96ef54b2053c75673612070876102466123f197955f80516020612f84833981519152999716998a9687611b6d565b0390a2565b915091506123f15f80516020612f8483398151915293946120c18360018060a01b03165f52600560205260405f2090565b50915091506123f15f80516020612f8483398151915293946120c18360018060a01b03165f52600560205260405f2090565b14159050865f61239e565b604051630dfe168160e01b81526001600160a01b039190911691906020908181600481875afa9081156104e75760049183915f916124da575b50946040519283809263d21220a760e01b82525afa9182156104e7575f926124c457505090565b610bba9250803d106105b4576105a681836116c3565b6124f19150823d84116105b4576105a681836116c3565b5f61249d565b901561246457604051630dfe168160e01b81526001600160a01b039190911691906020908181600481875afa9081156104e75760049183915f916124da5750946040519283809263d21220a760e01b82525afa9182156104e7575f926124c457505090565b60208183031261018b5780516001600160401b039182821161018b57019082601f8301121561018b5781519081116116a357604051926125a6601f8301601f1916602001856116c3565b8184526020828401011161018b57610bba9160208085019101610b63565b929192811561027d5780516125e1906001600160a01b0316610e55565b6001600160a01b039485168186161490811561283b5750602082015161260f906001600160a01b0316610e55565b945b6040516370a0823160e01b808252306004830152602095838916939192908782602481885afa9586156104e75788925f976127fa575b5061271c5f96979861269861273895899795612683610cd896808b146127df576401000276a4935b612677611703565b96875286019015159052565b60408401526001600160a01b03166060830152565b3060808201526040519283918c8301815180516001600160a01b03908116835260208083015182168185015260408084015162ffffff168186015260608085015160020b8187015260809485015184168587015291860151151560a086015285015160c0850152840151811660e08401529201519091166101008201526101200190565b6040519586809481936348c8949160e01b835260048301610ba9565b03927f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a90165af19182156104e75785926127bd575b506040519081523060048201529182908180602481015b03915afa9081156104e757611b55935f926127a0575b505061162e565b6127b69250803d106105875761057981836116c3565b5f80612799565b6127d8903d805f833e6127d081836116c3565b81019061255c565b505f61276c565b73fffd8963efd1fc6a506488495d951d5263988d259361266f565b5f969750610cd891986126988589979561268361282961271c966127389a3d86116105875761057981836116c3565b9c9b5050959750955050989150612647565b94612611565b6001600160a01b0316801561097e5760206004916040519283809263c45a015560e01b82525afa5f91816128dc575b506128875760405163b4fa3fb360e01b8152600490fd5b6001600160a01b0381165f9081526003602052604090206128b2906128ae905b5460ff1690565b1590565b6128b95750565b60405163ad7dd91360e01b81526001600160a01b03919091166004820152602490fd5b6128f691925060203d6020116105b4576105a681836116c3565b905f612870565b919082604091031261018b576020825192015190565b6001600160a01b039182168152911515602083015260408201929092529116606082015260a060808201819052610bba92910190610b84565b929192811561027d5761295e81612464565b6001600160a01b03958616928287168414929091908315612b2c5750955b604080516370a0823160e01b808252306004830152602097848b16969194919290919089816024818b5afa9889156104e7578a915f9a612b05575b50855163095ea7b360e01b81526001600160a01b03891660048201526024810185905291908290815f81604481015b03925af19081156104e7575f91612ae8575b5015612ad7578392915f8792848214612abc576401000276a4945b865133818f019081526001600160a01b03909b1660208c015299612a44908b9060400103601f1981018c528b6116c3565b612a6487519a8b9788968794630251596160e31b86523060048701612913565b0393165af19283156104e7578693612a90575b5051908152306004820152918290818060248101612783565b612aaf90823d8411612ab5575b612aa781836116c3565b8101906128fd565b50612a77565b503d612a9d565b73fffd8963efd1fc6a506488495d951d5263988d2594612a13565b83516340b27c2160e11b8152600490fd5b612aff91508a3d8c116104e0576104d181836116c3565b5f6129f8565b82919a50612b2385916129e6943d85116105875761057981836116c3565b9a9192506129b7565b90509561297c565b6001600160a01b0316801561097e5760206004916040519283809263c45a015560e01b82525afa5f9181612b9e575b50612b7a5760405163b4fa3fb360e01b8152600490fd5b6001600160a01b0381165f9081526002602052604090206128b2906128ae906128a7565b612bb891925060203d6020116105b4576105a681836116c3565b905f612b63565b906103e79182810292818404149015171561163b57565b604051602081018181106001600160401b038211176116a3576040525f8152905f368137565b9092608092610bba95948352602083015260018060a01b031660408201528160608201520190610b84565b909291831561027d57612c3982612464565b6001600160a01b03928316938284168514929091612c61918415612ecd5750965b8286611b6d565b828116936040918251630240bc6b60e21b815260049260608285818b5afa9081156104e7575f925f92612ea8575b508615612e2e5785516370a0823160e01b81526001600160a01b03909416858501908152602091859182908190850103915afa9182156104e757612cec612d0e93612d16955f91612e0f575b506001600160701b0383169061162e565b8715612df857612d09926001600160701b03809116921690612f54565b612bbf565b6103e8900490565b9215612df1575f92935b82516370a0823160e01b808252308483019081526020989297938b169391929089908990819083010381875afa9788156104e7575f98612dd2575b50612d64612bd6565b90803b1561018b57612d90975f809489519a8b958694859363022c0d9f60e01b855230918d8601612bfc565b03925af19384156104e757612783958895612dbf575b5051908152309281019283529384928391829160200190565b80611349612dcc92611690565b5f612da6565b612dea919850893d8b116105875761057981836116c3565b965f612d5b565b5f93612d20565b612d09926001600160701b03928316921690612f54565b612e28915060203d6020116105875761057981836116c3565b5f612cdb565b85516370a0823160e01b81526001600160a01b03909416858501908152602091859182908190850103915afa9182156104e757612e84612d0e93612d16955f91612e89575b506001600160701b0384169061162e565b612cec565b612ea2915060203d6020116105875761057981836116c3565b5f612e73565b909250612ec4915060603d606011610fa357610f9381836116c3565b5090915f612c8f565b905096612c5a565b6001600160801b03612f1a6020925f9460018060a01b03807f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a9016948592169216611b6d565b600460405180948193630476982d60e21b83525af180156104e757612f3c5750565b6122269060203d6020116105875761057981836116c3565b916103e5916103e8838502910201928315612f6f5702020490565b634e487b7160e01b5f52601260045260245ffdfed2f36b7fd206a8b1cc41c911e5097cad7b212c0fdb230311dd2568194e7d9a5da264697066735822122048a36ee2e1e8b35fc9a6b02faa2278675c47b6d3f7c5aacf5d1cbf851741470964736f6c63430008180033
Verified Source Code Full Match
Compiler: v0.8.24+commit.e11b9ed9
EVM: shanghai
Optimization: Yes (200 runs)
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);
}
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);
}
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
);
}
IExtsload.sol 21 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for functions to access any storage slot in a contract
interface IExtsload {
/// @notice Called by external contracts to access granular pool state
/// @param slot Key of slot to sload
/// @return value The value of the slot as bytes32
function extsload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access granular pool state
/// @param startSlot Key of slot to start sloading from
/// @param nSlots Number of slots to load into return value
/// @return values List of loaded values.
function extsload(bytes32 startSlot, uint256 nSlots) external view returns (bytes32[] memory values);
/// @notice Called by external contracts to access sparse pool state
/// @param slots List of slots to SLOAD from.
/// @return values List of loaded values.
function extsload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
IExttload.sol 15 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
/// @notice Interface for functions to access any transient storage slot in a contract
interface IExttload {
/// @notice Called by external contracts to access transient storage of the contract
/// @param slot Key of slot to tload
/// @return value The value of the slot as bytes32
function exttload(bytes32 slot) external view returns (bytes32 value);
/// @notice Called by external contracts to access sparse transient pool state
/// @param slots List of slots to tload
/// @return values List of loaded values
function exttload(bytes32[] calldata slots) external view returns (bytes32[] memory values);
}
IHooks.sol 152 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {BeforeSwapDelta} from "../types/BeforeSwapDelta.sol";
/// @notice V4 decides whether to invoke specific hooks by inspecting the least significant bits
/// of the address that the hooks contract is deployed to.
/// For example, a hooks contract deployed to address: 0x0000000000000000000000000000000000002400
/// has the lowest bits '10 0100 0000 0000' which would cause the 'before initialize' and 'after add liquidity' hooks to be used.
/// See the Hooks library for the full spec.
/// @dev Should only be callable by the v4 PoolManager.
interface IHooks {
/// @notice The hook called before the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @return bytes4 The function selector for the hook
function beforeInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96) external returns (bytes4);
/// @notice The hook called after the state of a pool is initialized
/// @param sender The initial msg.sender for the initialize call
/// @param key The key for the pool being initialized
/// @param sqrtPriceX96 The sqrt(price) of the pool as a Q64.96
/// @param tick The current tick after the state of a pool is initialized
/// @return bytes4 The function selector for the hook
function afterInitialize(address sender, PoolKey calldata key, uint160 sqrtPriceX96, int24 tick)
external
returns (bytes4);
/// @notice The hook called before liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is added
/// @param sender The initial msg.sender for the add liquidity call
/// @param key The key for the pool
/// @param params The parameters for adding liquidity
/// @param delta The caller's balance delta after adding liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterAddLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after liquidity is removed
/// @param sender The initial msg.sender for the remove liquidity call
/// @param key The key for the pool
/// @param params The parameters for removing liquidity
/// @param delta The caller's balance delta after removing liquidity; the sum of principal delta, fees accrued, and hook delta
/// @param feesAccrued The fees accrued since the last time fees were collected from this position
/// @param hookData Arbitrary data handed into the PoolManager by the liquidity provider to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BalanceDelta The hook's delta in token0 and token1. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterRemoveLiquidity(
address sender,
PoolKey calldata key,
ModifyLiquidityParams calldata params,
BalanceDelta delta,
BalanceDelta feesAccrued,
bytes calldata hookData
) external returns (bytes4, BalanceDelta);
/// @notice The hook called before a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return BeforeSwapDelta The hook's delta in specified and unspecified currencies. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
/// @return uint24 Optionally override the lp fee, only used if three conditions are met: 1. the Pool has a dynamic fee, 2. the value's 2nd highest bit is set (23rd bit, 0x400000), and 3. the value is less than or equal to the maximum fee (1 million)
function beforeSwap(address sender, PoolKey calldata key, SwapParams calldata params, bytes calldata hookData)
external
returns (bytes4, BeforeSwapDelta, uint24);
/// @notice The hook called after a swap
/// @param sender The initial msg.sender for the swap call
/// @param key The key for the pool
/// @param params The parameters for the swap
/// @param delta The amount owed to the caller (positive) or owed to the pool (negative)
/// @param hookData Arbitrary data handed into the PoolManager by the swapper to be be passed on to the hook
/// @return bytes4 The function selector for the hook
/// @return int128 The hook's delta in unspecified currency. Positive: the hook is owed/took currency, negative: the hook owes/sent currency
function afterSwap(
address sender,
PoolKey calldata key,
SwapParams calldata params,
BalanceDelta delta,
bytes calldata hookData
) external returns (bytes4, int128);
/// @notice The hook called before donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function beforeDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
/// @notice The hook called after donate
/// @param sender The initial msg.sender for the donate call
/// @param key The key for the pool
/// @param amount0 The amount of token0 being donated
/// @param amount1 The amount of token1 being donated
/// @param hookData Arbitrary data handed into the PoolManager by the donor to be be passed on to the hook
/// @return bytes4 The function selector for the hook
function afterDonate(
address sender,
PoolKey calldata key,
uint256 amount0,
uint256 amount1,
bytes calldata hookData
) external returns (bytes4);
}
IPoolManager.sol 217 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {Currency} from "../types/Currency.sol";
import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "./IHooks.sol";
import {IERC6909Claims} from "./external/IERC6909Claims.sol";
import {IProtocolFees} from "./IProtocolFees.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
import {PoolId} from "../types/PoolId.sol";
import {IExtsload} from "./IExtsload.sol";
import {IExttload} from "./IExttload.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
/// @notice Interface for the PoolManager
interface IPoolManager is IProtocolFees, IERC6909Claims, IExtsload, IExttload {
/// @notice Thrown when a currency is not netted out after the contract is unlocked
error CurrencyNotSettled();
/// @notice Thrown when trying to interact with a non-initialized pool
error PoolNotInitialized();
/// @notice Thrown when unlock is called, but the contract is already unlocked
error AlreadyUnlocked();
/// @notice Thrown when a function is called that requires the contract to be unlocked, but it is not
error ManagerLocked();
/// @notice Pools are limited to type(int16).max tickSpacing in #initialize, to prevent overflow
error TickSpacingTooLarge(int24 tickSpacing);
/// @notice Pools must have a positive non-zero tickSpacing passed to #initialize
error TickSpacingTooSmall(int24 tickSpacing);
/// @notice PoolKey must have currencies where address(currency0) < address(currency1)
error CurrenciesOutOfOrderOrEqual(address currency0, address currency1);
/// @notice Thrown when a call to updateDynamicLPFee is made by an address that is not the hook,
/// or on a pool that does not have a dynamic swap fee.
error UnauthorizedDynamicLPFeeUpdate();
/// @notice Thrown when trying to swap amount of 0
error SwapAmountCannotBeZero();
///@notice Thrown when native currency is passed to a non native settlement
error NonzeroNativeValue();
/// @notice Thrown when `clear` is called with an amount that is not exactly equal to the open currency delta.
error MustClearExactPositiveDelta();
/// @notice Emitted when a new pool is initialized
/// @param id The abi encoded hash of the pool key struct for the new pool
/// @param currency0 The first currency of the pool by address sort order
/// @param currency1 The second currency 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 hooks The hooks contract address for the pool, or address(0) if none
/// @param sqrtPriceX96 The price of the pool on initialization
/// @param tick The initial tick of the pool corresponding to the initialized price
event Initialize(
PoolId indexed id,
Currency indexed currency0,
Currency indexed currency1,
uint24 fee,
int24 tickSpacing,
IHooks hooks,
uint160 sqrtPriceX96,
int24 tick
);
/// @notice Emitted when a liquidity position is modified
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that modified the pool
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param liquidityDelta The amount of liquidity that was added or removed
/// @param salt The extra data to make positions unique
event ModifyLiquidity(
PoolId indexed id, address indexed sender, int24 tickLower, int24 tickUpper, int256 liquidityDelta, bytes32 salt
);
/// @notice Emitted for swaps between currency0 and currency1
/// @param id The abi encoded hash of the pool key struct for the pool that was modified
/// @param sender The address that initiated the swap call, and that received the callback
/// @param amount0 The delta of the currency0 balance of the pool
/// @param amount1 The delta of the currency1 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 the price of the pool after the swap
/// @param fee The swap fee in hundredths of a bip
event Swap(
PoolId indexed id,
address indexed sender,
int128 amount0,
int128 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick,
uint24 fee
);
/// @notice Emitted for donations
/// @param id The abi encoded hash of the pool key struct for the pool that was donated to
/// @param sender The address that initiated the donate call
/// @param amount0 The amount donated in currency0
/// @param amount1 The amount donated in currency1
event Donate(PoolId indexed id, address indexed sender, uint256 amount0, uint256 amount1);
/// @notice All interactions on the contract that account deltas require unlocking. A caller that calls `unlock` must implement
/// `IUnlockCallback(msg.sender).unlockCallback(data)`, where they interact with the remaining functions on this contract.
/// @dev The only functions callable without an unlocking are `initialize` and `updateDynamicLPFee`
/// @param data Any data to pass to the callback, via `IUnlockCallback(msg.sender).unlockCallback(data)`
/// @return The data returned by the call to `IUnlockCallback(msg.sender).unlockCallback(data)`
function unlock(bytes calldata data) external returns (bytes memory);
/// @notice Initialize the state for a given pool ID
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The pool key for the pool to initialize
/// @param sqrtPriceX96 The initial square root price
/// @return tick The initial tick of the pool
function initialize(PoolKey memory key, uint160 sqrtPriceX96) external returns (int24 tick);
/// @notice Modify the liquidity for the given pool
/// @dev Poke by calling with a zero liquidityDelta
/// @param key The pool to modify liquidity in
/// @param params The parameters for modifying the liquidity
/// @param hookData The data to pass through to the add/removeLiquidity hooks
/// @return callerDelta The balance delta of the caller of modifyLiquidity. This is the total of both principal, fee deltas, and hook deltas if applicable
/// @return feesAccrued The balance delta of the fees generated in the liquidity range. Returned for informational purposes
/// @dev Note that feesAccrued can be artificially inflated by a malicious actor and integrators should be careful using the value
/// For pools with a single liquidity position, actors can donate to themselves to inflate feeGrowthGlobal (and consequently feesAccrued)
/// atomically donating and collecting fees in the same unlockCallback may make the inflated value more extreme
function modifyLiquidity(PoolKey memory key, ModifyLiquidityParams memory params, bytes calldata hookData)
external
returns (BalanceDelta callerDelta, BalanceDelta feesAccrued);
/// @notice Swap against the given pool
/// @param key The pool to swap in
/// @param params The parameters for swapping
/// @param hookData The data to pass through to the swap hooks
/// @return swapDelta The balance delta of the address swapping
/// @dev Swapping on low liquidity pools may cause unexpected swap amounts when liquidity available is less than amountSpecified.
/// Additionally note that if interacting with hooks that have the BEFORE_SWAP_RETURNS_DELTA_FLAG or AFTER_SWAP_RETURNS_DELTA_FLAG
/// the hook may alter the swap input/output. Integrators should perform checks on the returned swapDelta.
function swap(PoolKey memory key, SwapParams memory params, bytes calldata hookData)
external
returns (BalanceDelta swapDelta);
/// @notice Donate the given currency amounts to the in-range liquidity providers of a pool
/// @dev Calls to donate can be frontrun adding just-in-time liquidity, with the aim of receiving a portion donated funds.
/// Donors should keep this in mind when designing donation mechanisms.
/// @dev This function donates to in-range LPs at slot0.tick. In certain edge-cases of the swap algorithm, the `sqrtPrice` of
/// a pool can be at the lower boundary of tick `n`, but the `slot0.tick` of the pool is already `n - 1`. In this case a call to
/// `donate` would donate to tick `n - 1` (slot0.tick) not tick `n` (getTickAtSqrtPrice(slot0.sqrtPriceX96)).
/// Read the comments in `Pool.swap()` for more information about this.
/// @param key The key of the pool to donate to
/// @param amount0 The amount of currency0 to donate
/// @param amount1 The amount of currency1 to donate
/// @param hookData The data to pass through to the donate hooks
/// @return BalanceDelta The delta of the caller after the donate
function donate(PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
external
returns (BalanceDelta);
/// @notice Writes the current ERC20 balance of the specified currency to transient storage
/// This is used to checkpoint balances for the manager and derive deltas for the caller.
/// @dev This MUST be called before any ERC20 tokens are sent into the contract, but can be skipped
/// for native tokens because the amount to settle is determined by the sent value.
/// However, if an ERC20 token has been synced and not settled, and the caller instead wants to settle
/// native funds, this function can be called with the native currency to then be able to settle the native currency
function sync(Currency currency) external;
/// @notice Called by the user to net out some value owed to the user
/// @dev Will revert if the requested amount is not available, consider using `mint` instead
/// @dev Can also be used as a mechanism for free flash loans
/// @param currency The currency to withdraw from the pool manager
/// @param to The address to withdraw to
/// @param amount The amount of currency to withdraw
function take(Currency currency, address to, uint256 amount) external;
/// @notice Called by the user to pay what is owed
/// @return paid The amount of currency settled
function settle() external payable returns (uint256 paid);
/// @notice Called by the user to pay on behalf of another address
/// @param recipient The address to credit for the payment
/// @return paid The amount of currency settled
function settleFor(address recipient) external payable returns (uint256 paid);
/// @notice WARNING - Any currency that is cleared, will be non-retrievable, and locked in the contract permanently.
/// A call to clear will zero out a positive balance WITHOUT a corresponding transfer.
/// @dev This could be used to clear a balance that is considered dust.
/// Additionally, the amount must be the exact positive balance. This is to enforce that the caller is aware of the amount being cleared.
function clear(Currency currency, uint256 amount) external;
/// @notice Called by the user to move value into ERC6909 balance
/// @param to The address to mint the tokens to
/// @param id The currency address to mint to ERC6909s, as a uint256
/// @param amount The amount of currency to mint
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function mint(address to, uint256 id, uint256 amount) external;
/// @notice Called by the user to move value from ERC6909 balance
/// @param from The address to burn the tokens from
/// @param id The currency address to burn from ERC6909s, as a uint256
/// @param amount The amount of currency to burn
/// @dev The id is converted to a uint160 to correspond to a currency address
/// If the upper 12 bytes are not 0, they will be 0-ed out
function burn(address from, uint256 id, uint256 amount) external;
/// @notice Updates the pools lp fees for the a pool that has enabled dynamic lp fees.
/// @dev A swap fee totaling MAX_SWAP_FEE (100%) makes exact output swaps impossible since the input is entirely consumed by the fee
/// @param key The key of the pool to update dynamic LP fees for
/// @param newDynamicLPFee The new dynamic pool LP fee
function updateDynamicLPFee(PoolKey memory key, uint24 newDynamicLPFee) external;
}
IProtocolFees.sol 52 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "../types/Currency.sol";
import {PoolId} from "../types/PoolId.sol";
import {PoolKey} from "../types/PoolKey.sol";
/// @notice Interface for all protocol-fee related functions in the pool manager
interface IProtocolFees {
/// @notice Thrown when protocol fee is set too high
error ProtocolFeeTooLarge(uint24 fee);
/// @notice Thrown when collectProtocolFees or setProtocolFee is not called by the controller.
error InvalidCaller();
/// @notice Thrown when collectProtocolFees is attempted on a token that is synced.
error ProtocolFeeCurrencySynced();
/// @notice Emitted when the protocol fee controller address is updated in setProtocolFeeController.
event ProtocolFeeControllerUpdated(address indexed protocolFeeController);
/// @notice Emitted when the protocol fee is updated for a pool.
event ProtocolFeeUpdated(PoolId indexed id, uint24 protocolFee);
/// @notice Given a currency address, returns the protocol fees accrued in that currency
/// @param currency The currency to check
/// @return amount The amount of protocol fees accrued in the currency
function protocolFeesAccrued(Currency currency) external view returns (uint256 amount);
/// @notice Sets the protocol fee for the given pool
/// @param key The key of the pool to set a protocol fee for
/// @param newProtocolFee The fee to set
function setProtocolFee(PoolKey memory key, uint24 newProtocolFee) external;
/// @notice Sets the protocol fee controller
/// @param controller The new protocol fee controller
function setProtocolFeeController(address controller) external;
/// @notice Collects the protocol fees for a given recipient and currency, returning the amount collected
/// @dev This will revert if the contract is unlocked
/// @param recipient The address to receive the protocol fees
/// @param currency The currency to withdraw
/// @param amount The amount of currency to withdraw
/// @return amountCollected The amount of currency successfully withdrawn
function collectProtocolFees(address recipient, Currency currency, uint256 amount)
external
returns (uint256 amountCollected);
/// @notice Returns the current protocol fee controller address
/// @return address The current protocol fee controller address
function protocolFeeController() external view returns (address);
}
IERC20Minimal.sol 48 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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 an account's balance in the 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);
}
IERC6909Claims.sol 66 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @notice Interface for claims over a contract balance, wrapped as a ERC6909
interface IERC6909Claims {
/*//////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event OperatorSet(address indexed owner, address indexed operator, bool approved);
event Approval(address indexed owner, address indexed spender, uint256 indexed id, uint256 amount);
event Transfer(address caller, address indexed from, address indexed to, uint256 indexed id, uint256 amount);
/*//////////////////////////////////////////////////////////////
FUNCTIONS
//////////////////////////////////////////////////////////////*/
/// @notice Owner balance of an id.
/// @param owner The address of the owner.
/// @param id The id of the token.
/// @return amount The balance of the token.
function balanceOf(address owner, uint256 id) external view returns (uint256 amount);
/// @notice Spender allowance of an id.
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @return amount The allowance of the token.
function allowance(address owner, address spender, uint256 id) external view returns (uint256 amount);
/// @notice Checks if a spender is approved by an owner as an operator
/// @param owner The address of the owner.
/// @param spender The address of the spender.
/// @return approved The approval status.
function isOperator(address owner, address spender) external view returns (bool approved);
/// @notice Transfers an amount of an id from the caller to a receiver.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transfer(address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Transfers an amount of an id from a sender to a receiver.
/// @param sender The address of the sender.
/// @param receiver The address of the receiver.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always, unless the function reverts
function transferFrom(address sender, address receiver, uint256 id, uint256 amount) external returns (bool);
/// @notice Approves an amount of an id to a spender.
/// @param spender The address of the spender.
/// @param id The id of the token.
/// @param amount The amount of the token.
/// @return bool True, always
function approve(address spender, uint256 id, uint256 amount) external returns (bool);
/// @notice Sets or removes an operator for the caller.
/// @param operator The address of the operator.
/// @param approved The approval status.
/// @return bool True, always
function setOperator(address operator, bool approved) external returns (bool);
}
CustomRevert.sol 120 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @title Library for reverting with custom errors efficiently
/// @notice Contains functions for reverting with custom errors with different argument types efficiently
/// @dev To use this library, declare `using CustomRevert for bytes4;` and replace `revert CustomError()` with
/// `CustomError.selector.revertWith()`
/// @dev The functions may tamper with the free memory pointer but it is fine since the call context is exited immediately
library CustomRevert {
/// @dev ERC-7751 error for wrapping bubbled up reverts
error WrappedError(address target, bytes4 selector, bytes reason, bytes details);
/// @dev Reverts with the selector of a custom error in the scratch space
function revertWith(bytes4 selector) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
revert(0, 0x04)
}
}
/// @dev Reverts with a custom error with an address argument in the scratch space
function revertWith(bytes4 selector, address addr) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(addr, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with an int24 argument in the scratch space
function revertWith(bytes4 selector, int24 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, signextend(2, value))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with a uint160 argument in the scratch space
function revertWith(bytes4 selector, uint160 value) internal pure {
assembly ("memory-safe") {
mstore(0, selector)
mstore(0x04, and(value, 0xffffffffffffffffffffffffffffffffffffffff))
revert(0, 0x24)
}
}
/// @dev Reverts with a custom error with two int24 arguments
function revertWith(bytes4 selector, int24 value1, int24 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), signextend(2, value1))
mstore(add(fmp, 0x24), signextend(2, value2))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two uint160 arguments
function revertWith(bytes4 selector, uint160 value1, uint160 value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @dev Reverts with a custom error with two address arguments
function revertWith(bytes4 selector, address value1, address value2) internal pure {
assembly ("memory-safe") {
let fmp := mload(0x40)
mstore(fmp, selector)
mstore(add(fmp, 0x04), and(value1, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(fmp, 0x24), and(value2, 0xffffffffffffffffffffffffffffffffffffffff))
revert(fmp, 0x44)
}
}
/// @notice bubble up the revert message returned by a call and revert with a wrapped ERC-7751 error
/// @dev this method can be vulnerable to revert data bombs
function bubbleUpAndRevertWith(
address revertingContract,
bytes4 revertingFunctionSelector,
bytes4 additionalContext
) internal pure {
bytes4 wrappedErrorSelector = WrappedError.selector;
assembly ("memory-safe") {
// Ensure the size of the revert data is a multiple of 32 bytes
let encodedDataSize := mul(div(add(returndatasize(), 31), 32), 32)
let fmp := mload(0x40)
// Encode wrapped error selector, address, function selector, offset, additional context, size, revert reason
mstore(fmp, wrappedErrorSelector)
mstore(add(fmp, 0x04), and(revertingContract, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(
add(fmp, 0x24),
and(revertingFunctionSelector, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
// offset revert reason
mstore(add(fmp, 0x44), 0x80)
// offset additional context
mstore(add(fmp, 0x64), add(0xa0, encodedDataSize))
// size revert reason
mstore(add(fmp, 0x84), returndatasize())
// revert reason
returndatacopy(add(fmp, 0xa4), 0, returndatasize())
// size additional context
mstore(add(fmp, add(0xa4, encodedDataSize)), 0x04)
// additional context
mstore(
add(fmp, add(0xc4, encodedDataSize)),
and(additionalContext, 0xffffffff00000000000000000000000000000000000000000000000000000000)
)
revert(fmp, add(0xe4, encodedDataSize))
}
}
}
SafeCast.sol 60 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {CustomRevert} from "./CustomRevert.sol";
/// @title Safe casting methods
/// @notice Contains methods for safely casting between types
library SafeCast {
using CustomRevert for bytes4;
error SafeCastOverflow();
/// @notice Cast a uint256 to a uint160, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint160
function toUint160(uint256 x) internal pure returns (uint160 y) {
y = uint160(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a uint128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return y The downcasted integer, now type uint128
function toUint128(uint256 x) internal pure returns (uint128 y) {
y = uint128(x);
if (x != y) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a int128 to a uint128, revert on overflow or underflow
/// @param x The int128 to be casted
/// @return y The casted integer, now type uint128
function toUint128(int128 x) internal pure returns (uint128 y) {
if (x < 0) SafeCastOverflow.selector.revertWith();
y = uint128(x);
}
/// @notice Cast a int256 to a int128, revert on overflow or underflow
/// @param x The int256 to be downcasted
/// @return y The downcasted integer, now type int128
function toInt128(int256 x) internal pure returns (int128 y) {
y = int128(x);
if (y != x) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int256, revert on overflow
/// @param x The uint256 to be casted
/// @return y The casted integer, now type int256
function toInt256(uint256 x) internal pure returns (int256 y) {
y = int256(x);
if (y < 0) SafeCastOverflow.selector.revertWith();
}
/// @notice Cast a uint256 to a int128, revert on overflow
/// @param x The uint256 to be downcasted
/// @return The downcasted integer, now type int128
function toInt128(uint256 x) internal pure returns (int128) {
if (x >= 1 << 127) SafeCastOverflow.selector.revertWith();
return int128(int256(x));
}
}
BalanceDelta.sol 72 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeCast} from "../libraries/SafeCast.sol";
/// @dev Two `int128` values packed into a single `int256` where the upper 128 bits represent the amount0
/// and the lower 128 bits represent the amount1.
type BalanceDelta is int256;
using {add as +, sub as -, eq as ==, neq as !=} for BalanceDelta global;
using BalanceDeltaLibrary for BalanceDelta global;
using SafeCast for int256;
function toBalanceDelta(int128 _amount0, int128 _amount1) pure returns (BalanceDelta balanceDelta) {
assembly ("memory-safe") {
balanceDelta := or(shl(128, _amount0), and(sub(shl(128, 1), 1), _amount1))
}
}
function add(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := add(a0, b0)
res1 := add(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function sub(BalanceDelta a, BalanceDelta b) pure returns (BalanceDelta) {
int256 res0;
int256 res1;
assembly ("memory-safe") {
let a0 := sar(128, a)
let a1 := signextend(15, a)
let b0 := sar(128, b)
let b1 := signextend(15, b)
res0 := sub(a0, b0)
res1 := sub(a1, b1)
}
return toBalanceDelta(res0.toInt128(), res1.toInt128());
}
function eq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) == BalanceDelta.unwrap(b);
}
function neq(BalanceDelta a, BalanceDelta b) pure returns (bool) {
return BalanceDelta.unwrap(a) != BalanceDelta.unwrap(b);
}
/// @notice Library for getting the amount0 and amount1 deltas from the BalanceDelta type
library BalanceDeltaLibrary {
/// @notice A BalanceDelta of 0
BalanceDelta public constant ZERO_DELTA = BalanceDelta.wrap(0);
function amount0(BalanceDelta balanceDelta) internal pure returns (int128 _amount0) {
assembly ("memory-safe") {
_amount0 := sar(128, balanceDelta)
}
}
function amount1(BalanceDelta balanceDelta) internal pure returns (int128 _amount1) {
assembly ("memory-safe") {
_amount1 := signextend(15, balanceDelta)
}
}
}
BeforeSwapDelta.sol 38 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// Return type of the beforeSwap hook.
// Upper 128 bits is the delta in specified tokens. Lower 128 bits is delta in unspecified tokens (to match the afterSwap hook)
type BeforeSwapDelta is int256;
// Creates a BeforeSwapDelta from specified and unspecified
function toBeforeSwapDelta(int128 deltaSpecified, int128 deltaUnspecified)
pure
returns (BeforeSwapDelta beforeSwapDelta)
{
assembly ("memory-safe") {
beforeSwapDelta := or(shl(128, deltaSpecified), and(sub(shl(128, 1), 1), deltaUnspecified))
}
}
/// @notice Library for getting the specified and unspecified deltas from the BeforeSwapDelta type
library BeforeSwapDeltaLibrary {
/// @notice A BeforeSwapDelta of 0
BeforeSwapDelta public constant ZERO_DELTA = BeforeSwapDelta.wrap(0);
/// extracts int128 from the upper 128 bits of the BeforeSwapDelta
/// returned by beforeSwap
function getSpecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaSpecified) {
assembly ("memory-safe") {
deltaSpecified := sar(128, delta)
}
}
/// extracts int128 from the lower 128 bits of the BeforeSwapDelta
/// returned by beforeSwap and afterSwap
function getUnspecifiedDelta(BeforeSwapDelta delta) internal pure returns (int128 deltaUnspecified) {
assembly ("memory-safe") {
deltaUnspecified := signextend(15, delta)
}
}
}
Currency.sol 119 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20Minimal} from "../interfaces/external/IERC20Minimal.sol";
import {CustomRevert} from "../libraries/CustomRevert.sol";
type Currency is address;
using {greaterThan as >, lessThan as <, greaterThanOrEqualTo as >=, equals as ==} for Currency global;
using CurrencyLibrary for Currency global;
function equals(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(other);
}
function greaterThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) > Currency.unwrap(other);
}
function lessThan(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) < Currency.unwrap(other);
}
function greaterThanOrEqualTo(Currency currency, Currency other) pure returns (bool) {
return Currency.unwrap(currency) >= Currency.unwrap(other);
}
/// @title CurrencyLibrary
/// @dev This library allows for transferring and holding native tokens and ERC20 tokens
library CurrencyLibrary {
/// @notice Additional context for ERC-7751 wrapped error when a native transfer fails
error NativeTransferFailed();
/// @notice Additional context for ERC-7751 wrapped error when an ERC20 transfer fails
error ERC20TransferFailed();
/// @notice A constant to represent the native currency
Currency public constant ADDRESS_ZERO = Currency.wrap(address(0));
function transfer(Currency currency, address to, uint256 amount) internal {
// altered from https://github.com/transmissions11/solmate/blob/44a9963d4c78111f77caa0e65d677b8b46d6f2e6/src/utils/SafeTransferLib.sol
// modified custom error selectors
bool success;
if (currency.isAddressZero()) {
assembly ("memory-safe") {
// Transfer the ETH and revert if it fails.
success := call(gas(), to, amount, 0, 0, 0, 0)
}
// revert with NativeTransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(to, bytes4(0), NativeTransferFailed.selector);
}
} else {
assembly ("memory-safe") {
// Get a pointer to some free memory.
let fmp := mload(0x40)
// Write the abi-encoded calldata into memory, beginning with the function selector.
mstore(fmp, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(fmp, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff)) // Append and mask the "to" argument.
mstore(add(fmp, 36), amount) // Append the "amount" argument. Masking not required as it's a full 32 byte type.
success :=
and(
// Set success to whether the call reverted, if not we check it either
// returned exactly 1 (can't just be non-zero data), or had no return data.
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
// We use 68 because the length of our calldata totals up like so: 4 + 32 * 2.
// We use 0 and 32 to copy up to 32 bytes of return data into the scratch space.
// Counterintuitively, this call must be positioned second to the or() call in the
// surrounding and() call or else returndatasize() will be zero during the computation.
call(gas(), currency, 0, fmp, 68, 0, 32)
)
// Now clean the memory we used
mstore(fmp, 0) // 4 byte `selector` and 28 bytes of `to` were stored here
mstore(add(fmp, 0x20), 0) // 4 bytes of `to` and 28 bytes of `amount` were stored here
mstore(add(fmp, 0x40), 0) // 4 bytes of `amount` were stored here
}
// revert with ERC20TransferFailed, containing the bubbled up error as an argument
if (!success) {
CustomRevert.bubbleUpAndRevertWith(
Currency.unwrap(currency), IERC20Minimal.transfer.selector, ERC20TransferFailed.selector
);
}
}
}
function balanceOfSelf(Currency currency) internal view returns (uint256) {
if (currency.isAddressZero()) {
return address(this).balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(address(this));
}
}
function balanceOf(Currency currency, address owner) internal view returns (uint256) {
if (currency.isAddressZero()) {
return owner.balance;
} else {
return IERC20Minimal(Currency.unwrap(currency)).balanceOf(owner);
}
}
function isAddressZero(Currency currency) internal pure returns (bool) {
return Currency.unwrap(currency) == Currency.unwrap(ADDRESS_ZERO);
}
function toId(Currency currency) internal pure returns (uint256) {
return uint160(Currency.unwrap(currency));
}
// If the upper 12 bytes are non-zero, they will be zero-ed out
// Therefore, fromId() and toId() are not inverses of each other
function fromId(uint256 id) internal pure returns (Currency) {
return Currency.wrap(address(uint160(id)));
}
}
PoolId.sol 17 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {PoolKey} from "./PoolKey.sol";
type PoolId is bytes32;
/// @notice Library for computing the ID of a pool
library PoolIdLibrary {
/// @notice Returns value equal to keccak256(abi.encode(poolKey))
function toId(PoolKey memory poolKey) internal pure returns (PoolId poolId) {
assembly ("memory-safe") {
// 0xa0 represents the total size of the poolKey struct (5 slots of 32 bytes)
poolId := keccak256(poolKey, 0xa0)
}
}
}
PoolKey.sol 22 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Currency} from "./Currency.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {PoolIdLibrary} from "./PoolId.sol";
using PoolIdLibrary for PoolKey global;
/// @notice Returns the key for identifying a pool
struct PoolKey {
/// @notice The lower currency of the pool, sorted numerically
Currency currency0;
/// @notice The higher currency of the pool, sorted numerically
Currency currency1;
/// @notice The pool LP fee, capped at 1_000_000. If the highest bit is 1, the pool has a dynamic fee and must be exactly equal to 0x800000
uint24 fee;
/// @notice Ticks that involve positions must be a multiple of tick spacing
int24 tickSpacing;
/// @notice The hooks of the pool
IHooks hooks;
}
PoolOperation.sol 26 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {PoolKey} from "../types/PoolKey.sol";
import {BalanceDelta} from "../types/BalanceDelta.sol";
/// @notice Parameter struct for `ModifyLiquidity` pool operations
struct ModifyLiquidityParams {
// the lower and upper tick of the position
int24 tickLower;
int24 tickUpper;
// how to modify the liquidity
int256 liquidityDelta;
// a value to set if you want unique liquidity positions at the same range
bytes32 salt;
}
/// @notice Parameter struct for `Swap` pool operations
struct SwapParams {
/// Whether to swap token0 for token1 or vice versa
bool zeroForOne;
/// The desired input amount if negative (exactIn), or the desired output amount if positive (exactOut)
int256 amountSpecified;
/// The sqrt price at which, if reached, the swap will stop executing
uint160 sqrtPriceLimitX96;
}
MultiHopSwap.sol 762 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {PoolId, PoolIdLibrary} from "@uniswap/v4-core/src/types/PoolId.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function balanceOf(address) external view returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
}
library SafeTransferLib {
function safeTransferETH(address to, uint256 amount) internal {
bool success;
assembly {
success := call(gas(), to, amount, 0, 0, 0, 0)
}
require(success, "ETH_TRANSFER_FAILED");
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0x23b872dd00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(from, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(freeMemoryPointer, 36), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(freeMemoryPointer, 68), amount)
success := and(
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
call(gas(), token, 0, freeMemoryPointer, 100, 0, 32)
)
}
require(success, "TRANSFER_FROM_FAILED");
}
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0xa9059cbb00000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(freeMemoryPointer, 36), amount)
success := and(
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "TRANSFER_FAILED");
}
function safeApprove(
IERC20 token,
address to,
uint256 amount
) internal {
bool success;
assembly {
let freeMemoryPointer := mload(0x40)
mstore(freeMemoryPointer, 0x095ea7b300000000000000000000000000000000000000000000000000000000)
mstore(add(freeMemoryPointer, 4), and(to, 0xffffffffffffffffffffffffffffffffffffffff))
mstore(add(freeMemoryPointer, 36), amount)
success := and(
or(and(eq(mload(0), 1), gt(returndatasize(), 31)), iszero(returndatasize())),
call(gas(), token, 0, freeMemoryPointer, 68, 0, 32)
)
}
require(success, "APPROVE_FAILED");
}
}
interface IUniswapV2Pair {
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function factory() external view returns (address);
}
contract MultiHopSwap {
using SafeTransferLib for address;
using CurrencyLibrary for Currency;
using PoolIdLibrary for PoolKey;
address public owner;
IWETH public WETH;
IPoolManager public immutable poolManager;
mapping(address => bool) public allowedV2Factories;
mapping(address => bool) public allowedV3Factories;
address internal constant UNISWAP_V2_FACTORY = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f;
address internal constant SUSHISWAP_V2_FACTORY = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac;
address internal constant UNISWAP_V3_FACTORY = 0x1F98431c8aD98523631AE4a59f267346ea31F984;
address internal constant PANCAKESWAP_V3_FACTORY = 0x1097053Fd2ea711dad45caCcc45EfF7548fCB362;
address public constant USDC = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48;
address public constant USDT = 0xdAC17F958D2ee523a2206206994597C13D831ec7;
address public constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
mapping(address => uint256) public protocolFees;
mapping(address => uint256) public communityFees;
enum Version { V2, V3, V4 }
struct V4SwapContext {
PoolKey poolKey;
bool zeroForOne;
int256 amountSpecified;
uint160 sqrtPriceLimitX96;
address recipient;
}
event SwapExecuted(uint amountOut, address outputToken);
event FeesAccrued(address indexed token, uint256 protocolAmount, uint256 communityAmount);
event ReferralPaid(address indexed referral, address indexed token, uint256 amount);
event ProtocolWithdraw(address indexed token, uint256 amount);
event CommunityWithdraw(address indexed token, uint256 amount);
event FactoryStatusUpdated(address indexed factory, Version version, bool allowed);
error NotOwner();
error InvalidSender();
error SlippageExceeded();
error MustSendETH();
error MustSpecifyAmount();
error TransferFailed();
error FundsMustBeSent();
error InvalidInput();
error ArrayLengthMismatch();
error ApprovalFailed();
error InsufficientFees();
error PoolDoesNotExist();
error UnsupportedHook();
error InvalidPoolId();
error AmountTooSmallForFee();
error UnauthorizedFactory(address factory);
error UnsupportedVersion();
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
uint256 internal constant BPS_DENOMINATOR = 10_000;
uint256 internal constant FEE_BPS = 100; // 1%
uint256 internal constant PROTOCOL_FEE_BPS = 6_000; // 60%
constructor(address _WETH, address _poolManager) {
owner = msg.sender;
WETH = IWETH(_WETH);
poolManager = IPoolManager(_poolManager);
_initializeFactoryAllowlist();
}
modifier onlyOwner() {
if (msg.sender != owner) revert NotOwner();
_;
}
receive() external payable {}
function _wrapETH() internal {
if (msg.value == 0) revert MustSendETH();
WETH.deposit{value: msg.value}();
}
function unwrapWETH(uint amount) external {
if (amount == 0) revert MustSpecifyAmount();
SafeTransferLib.safeTransferFrom(IERC20(address(WETH)), msg.sender, address(this), amount);
WETH.withdraw(amount);
SafeTransferLib.safeTransferETH(msg.sender, amount);
}
function _isPriorityToken(address token) internal view returns (bool) {
address weth = address(WETH);
return token == weth || token == USDC || token == USDT || token == DAI;
}
function _calculateFee(uint256 amount) internal pure returns (uint256) {
unchecked {
return (amount * FEE_BPS + (BPS_DENOMINATOR - 1)) / BPS_DENOMINATOR;
}
}
function _applyFee(address feeToken, uint256 feeAmount, address referral, bool deferReferralPayment) internal {
uint256 protocolShare;
unchecked {
protocolShare = (feeAmount * PROTOCOL_FEE_BPS) / BPS_DENOMINATOR;
}
uint256 referralShare;
unchecked {
referralShare = feeAmount - protocolShare;
}
protocolFees[feeToken] += protocolShare;
if (referral != address(0) && referralShare > 0) {
if (!deferReferralPayment) {
SafeTransferLib.safeTransfer(IERC20(feeToken), referral, referralShare);
emit ReferralPaid(referral, feeToken, referralShare);
emit FeesAccrued(feeToken, protocolShare, 0);
} else {
// Defer payment, just record it
communityFees[feeToken] += referralShare;
emit FeesAccrued(feeToken, protocolShare, referralShare);
}
} else {
communityFees[feeToken] += referralShare;
emit FeesAccrued(feeToken, protocolShare, referralShare);
}
}
function _payReferral(address feeToken, address referral) internal {
uint256 amount = communityFees[feeToken];
if (amount > 0 && referral != address(0)) {
communityFees[feeToken] = 0;
SafeTransferLib.safeTransfer(IERC20(feeToken), referral, amount);
emit ReferralPaid(referral, feeToken, amount);
}
}
function _takeInputFee(address feeToken, uint256 amount, address referral) internal returns (uint256 amountAfterFee, bool feeTaken) {
if (!_isPriorityToken(feeToken)) {
return (amount, false);
}
uint256 fee = _calculateFee(amount);
if (fee == 0) {
return (amount, false);
}
if (fee >= amount) revert AmountTooSmallForFee();
// Pay referral immediately if provided, otherwise accumulate
bool deferPayment = (referral == address(0));
_applyFee(feeToken, fee, referral, deferPayment);
unchecked {
amountAfterFee = amount - fee;
}
feeTaken = true;
}
function _takeOutputFee(address feeToken, uint256 amount, address referral) internal returns (uint256 amountAfterFee) {
uint256 fee = _calculateFee(amount);
if (fee == 0) {
return amount;
}
if (fee >= amount) revert AmountTooSmallForFee();
// Pay referral immediately (swap already done)
_applyFee(feeToken, fee, referral, false);
unchecked {
amountAfterFee = amount - fee;
}
}
function _performSwap(
address[] calldata pairs,
Version[] calldata versions,
uint amountIn,
address inputToken,
PoolKey[] calldata poolKeys
) internal returns (uint amountOut, address outputToken) {
amountOut = amountIn;
uint256 pairsLength = pairs.length;
(address token0, address token1) = getTokens(pairs[0], versions.length > 0 && versions[0] == Version.V3);
outputToken = inputToken == token0 ? token1 : token0;
uint256 v4Index = 0;
for (uint i; i < pairsLength;) {
if (versions[i] == Version.V2) {
_validateV2Pair(pairs[i]);
(amountOut, outputToken) = _swapV2(pairs[i], amountOut, inputToken);
} else if (versions[i] == Version.V3) {
_validateV3Pool(pairs[i]);
(amountOut, outputToken) = _swapV3(pairs[i], amountOut, inputToken);
} else if (versions[i] == Version.V4) {
if (poolKeys.length == 0 || v4Index >= poolKeys.length) revert InvalidInput();
(amountOut, outputToken) = _swapV4(poolKeys[v4Index], amountOut, inputToken);
unchecked { ++v4Index; }
}
inputToken = outputToken;
unchecked { ++i; }
}
return (amountOut, outputToken);
}
function _swapV2(address pair, uint amountIn, address inputToken) internal returns (uint amountOut, address outputToken) {
if (amountIn == 0) revert MustSpecifyAmount();
(address token0, address token1) = getTokens(pair, false);
outputToken = inputToken == token0 ? token1 : token0;
// Transfer tokens to pair first
SafeTransferLib.safeTransfer(IERC20(inputToken), pair, amountIn);
// Get reserves AFTER transfer to calculate amounts based on balance delta
(uint112 reserve0, uint112 reserve1,) = IUniswapV2Pair(pair).getReserves();
// Calculate expected amount out with reserves
uint amountInActual = inputToken == token0
? IERC20(inputToken).balanceOf(pair) - reserve0
: IERC20(inputToken).balanceOf(pair) - reserve1;
uint estimatedAmountOut = inputToken == token0
? getAmountOut(amountInActual, reserve0, reserve1)
: getAmountOut(amountInActual, reserve1, reserve0);
// Apply 0.1% buffer to avoid rounding issues
estimatedAmountOut = (estimatedAmountOut * 999) / 1000;
(uint amount0Out, uint amount1Out) = inputToken == token0
? (uint(0), estimatedAmountOut)
: (estimatedAmountOut, uint(0));
uint balanceBefore = IERC20(outputToken).balanceOf(address(this));
IUniswapV2Pair(pair).swap(amount0Out, amount1Out, address(this), new bytes(0));
uint balanceAfter = IERC20(outputToken).balanceOf(address(this));
amountOut = balanceAfter - balanceBefore;
return (amountOut, outputToken);
}
function _swapV3(address pair, uint amountIn, address inputToken) internal returns (uint amountOut, address outputToken) {
if (amountIn == 0) revert MustSpecifyAmount();
(address token0, address token1) = getTokens(pair, true);
outputToken = inputToken == token0 ? token1 : token0;
uint balanceBefore = IERC20(outputToken).balanceOf(address(this));
if (!IERC20(inputToken).approve(pair, amountIn)) revert ApprovalFailed();
IUniswapV3Pool(pair).swap(
address(this),
inputToken == token0,
int256(amountIn),
inputToken == token0 ? uint160(MIN_SQRT_RATIO + 1) : uint160(MAX_SQRT_RATIO - 1),
abi.encode(msg.sender, pair)
);
uint balanceAfter = IERC20(outputToken).balanceOf(address(this));
amountOut = balanceAfter - balanceBefore;
return (amountOut, outputToken);
}
function _swapV4(PoolKey memory poolKey, uint amountIn, address inputToken) internal returns (uint amountOut, address outputToken) {
if (amountIn == 0) revert MustSpecifyAmount();
bool zeroForOne = inputToken == Currency.unwrap(poolKey.currency0);
outputToken = zeroForOne ? Currency.unwrap(poolKey.currency1) : Currency.unwrap(poolKey.currency0);
uint balanceBefore = IERC20(outputToken).balanceOf(address(this));
uint160 sqrtPriceLimitX96 = zeroForOne
? MIN_SQRT_RATIO + 1
: MAX_SQRT_RATIO - 1;
V4SwapContext memory ctx = V4SwapContext({
poolKey: poolKey,
zeroForOne: zeroForOne,
amountSpecified: int256(amountIn),
sqrtPriceLimitX96: sqrtPriceLimitX96,
recipient: address(this)
});
poolManager.unlock(abi.encode(ctx));
uint balanceAfter = IERC20(outputToken).balanceOf(address(this));
amountOut = balanceAfter - balanceBefore;
return (amountOut, outputToken);
}
function unlockCallback(bytes calldata data) external returns (bytes memory) {
if (msg.sender != address(poolManager)) revert InvalidSender();
V4SwapContext memory ctx = abi.decode(data, (V4SwapContext));
BalanceDelta delta = poolManager.swap(
ctx.poolKey,
SwapParams({
zeroForOne: ctx.zeroForOne,
amountSpecified: ctx.amountSpecified,
sqrtPriceLimitX96: ctx.sqrtPriceLimitX96
}),
""
);
_settleV4Deltas(ctx.poolKey, delta);
return abi.encode(delta);
}
function _settleV4Deltas(PoolKey memory poolKey, BalanceDelta delta) internal {
int128 delta0 = delta.amount0();
if (delta0 > 0) {
_payAndSettle(poolKey.currency0, uint128(delta0));
} else if (delta0 < 0) {
poolManager.take(poolKey.currency0, address(this), uint128(-delta0));
}
int128 delta1 = delta.amount1();
if (delta1 > 0) {
_payAndSettle(poolKey.currency1, uint128(delta1));
} else if (delta1 < 0) {
poolManager.take(poolKey.currency1, address(this), uint128(-delta1));
}
}
function _payAndSettle(Currency currency, uint128 amount) internal {
address currencyAddr = Currency.unwrap(currency);
SafeTransferLib.safeTransfer(IERC20(currencyAddr), address(poolManager), amount);
poolManager.settle();
}
function _handleV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) internal {
(, address pool) = abi.decode(data, (address, address));
if (msg.sender != pool) revert InvalidSender();
uint256 amount0 = amount0Delta > 0 ? uint256(amount0Delta) : 0;
uint256 amount1 = amount1Delta > 0 ? uint256(amount1Delta) : 0;
if (amount0 > 0) {
IERC20 token0 = IERC20(IUniswapV3Pool(pool).token0());
uint256 allowance0 = token0.allowance(address(this), msg.sender);
if (allowance0 < amount0) {
if (!token0.approve(msg.sender, amount0)) revert ApprovalFailed();
}
if (!token0.transfer(msg.sender, amount0)) revert TransferFailed();
}
if (amount1 > 0) {
IERC20 token1 = IERC20(IUniswapV3Pool(pool).token1());
uint256 allowance1 = token1.allowance(address(this), msg.sender);
if (allowance1 < amount1) {
if (!token1.approve(msg.sender, amount1)) revert ApprovalFailed();
}
if (!token1.transfer(msg.sender, amount1)) revert TransferFailed();
}
}
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external {
_handleV3SwapCallback(amount0Delta, amount1Delta, data);
}
function pancakeV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external {
_handleV3SwapCallback(amount0Delta, amount1Delta, data);
}
function swapEthPerTokens(
address[] calldata pairs,
Version[] calldata versions,
address /* inputToken */,
uint amountOutMin,
address referral,
PoolKey[] calldata poolKeys
) external payable returns (uint amountOut, address outputToken) {
if (pairs.length == 0) revert InvalidInput();
if (pairs.length != versions.length) revert ArrayLengthMismatch();
if (msg.value == 0) revert MustSpecifyAmount();
uint amountIn = msg.value;
_wrapETH();
address wethAddress = address(WETH);
// When there's a referral, pay immediately (don't defer)
(uint256 swapAmount, bool feeTakenOnInput) = _takeInputFee(wethAddress, amountIn, referral);
(amountOut, outputToken) = _performSwap(pairs, versions, swapAmount, wethAddress, poolKeys);
uint256 netAmount = amountOut;
if (!feeTakenOnInput) {
netAmount = _takeOutputFee(outputToken, amountOut, referral);
}
if (netAmount < amountOutMin) revert SlippageExceeded();
emit SwapExecuted(netAmount, outputToken);
SafeTransferLib.safeTransfer(IERC20(outputToken), msg.sender, netAmount);
return (netAmount, outputToken);
}
function swapTokenPerToken(
address[] calldata pairs,
Version[] calldata versions,
uint amountIn,
address inputToken,
uint amountOutMin,
address referral,
PoolKey[] calldata poolKeys
) external returns (uint amountOut, address outputToken) {
if (pairs.length == 0) revert InvalidInput();
if (pairs.length != versions.length) revert ArrayLengthMismatch();
if (amountIn == 0) revert MustSpecifyAmount();
SafeTransferLib.safeTransferFrom(IERC20(inputToken), msg.sender, address(this), amountIn);
(uint256 swapAmount, bool feeTakenOnInput) = _takeInputFee(inputToken, amountIn, referral);
(amountOut, outputToken) = _performSwap(pairs, versions, swapAmount, inputToken, poolKeys);
uint256 netAmount = amountOut;
if (!feeTakenOnInput) {
netAmount = _takeOutputFee(outputToken, amountOut, referral);
}
if (netAmount < amountOutMin) revert SlippageExceeded();
emit SwapExecuted(netAmount, outputToken);
SafeTransferLib.safeTransfer(IERC20(outputToken), msg.sender, netAmount);
return (netAmount, outputToken);
}
function swapTokenPerEth(
address[] calldata pairs,
Version[] calldata versions,
uint amountIn,
address inputToken,
uint amountOutMin,
address referral,
PoolKey[] calldata poolKeys
) external returns (uint netAmount) {
if (pairs.length == 0) revert InvalidInput();
if (pairs.length != versions.length) revert ArrayLengthMismatch();
if (amountIn == 0) revert MustSpecifyAmount();
SafeTransferLib.safeTransferFrom(IERC20(inputToken), msg.sender, address(this), amountIn);
(uint256 swapAmount, bool feeTakenOnInput) = _takeInputFee(inputToken, amountIn, referral);
(uint amountOut, address outputToken) = _performSwap(pairs, versions, swapAmount, inputToken, poolKeys);
if (outputToken != address(WETH)) revert InvalidInput();
if (feeTakenOnInput) {
netAmount = amountOut;
} else {
netAmount = _takeOutputFee(address(WETH), amountOut, referral);
}
if (netAmount < amountOutMin) revert SlippageExceeded();
emit SwapExecuted(netAmount, outputToken);
WETH.withdraw(netAmount);
SafeTransferLib.safeTransferETH(msg.sender, netAmount);
return netAmount;
}
function getVarsFromPairsOrPool(
address[] calldata addresses,
Version[] calldata versions
) external view returns (bytes[] memory results) {
uint256 length = addresses.length;
require(length == versions.length, "Input arrays must have the same length");
results = new bytes[](length);
for (uint i; i < length;) {
address token0;
address token1;
bytes memory data;
if (versions[i] == Version.V2) {
IUniswapV2Pair pair = IUniswapV2Pair(addresses[i]);
(uint112 reserve0, uint112 reserve1,) = pair.getReserves();
token0 = pair.token0();
token1 = pair.token1();
data = abi.encode(reserve0, reserve1, 0, token0, token1);
} else if (versions[i] == Version.V3) {
IUniswapV3Pool pool = IUniswapV3Pool(addresses[i]);
(uint160 sqrtPriceX96, int24 tick,,,,,) = pool.slot0();
uint256 liquidity = pool.liquidity();
token0 = pool.token0();
token1 = pool.token1();
data = abi.encode(sqrtPriceX96, tick, liquidity, token0, token1);
} else if (versions[i] == Version.V4) {
revert("Use StateView for V4 pool data");
} else {
revert("Unsupported version");
}
results[i] = data;
unchecked { ++i; }
}
}
function getTokens(address pair, bool isV3) internal view returns (address token0, address token1) {
if (isV3) {
token0 = IUniswapV3Pool(pair).token0();
token1 = IUniswapV3Pool(pair).token1();
} else {
token0 = IUniswapV2Pair(pair).token0();
token1 = IUniswapV2Pair(pair).token1();
}
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
unchecked {
uint amountInWithFee = amountIn * 997;
uint numerator = amountInWithFee * reserveOut;
uint denominator = (reserveIn * 1000) + amountInWithFee;
amountOut = numerator / denominator;
}
}
function withdraw(address _addy, uint256 _amount) onlyOwner public {
if (_addy == address(0)) {
SafeTransferLib.safeTransferETH(msg.sender, _amount);
} else {
SafeTransferLib.safeTransfer(IERC20(_addy), msg.sender, _amount);
}
}
function withdrawProtocolFees(address token, uint256 amount) external onlyOwner {
if (amount == 0) revert MustSpecifyAmount();
if (protocolFees[token] < amount) revert InsufficientFees();
protocolFees[token] -= amount;
if (token == address(0)) {
SafeTransferLib.safeTransferETH(msg.sender, amount);
} else {
SafeTransferLib.safeTransfer(IERC20(token), msg.sender, amount);
}
emit ProtocolWithdraw(token, amount);
}
function withdrawCommunityFees(address token, uint256 amount) external onlyOwner {
if (amount == 0) revert MustSpecifyAmount();
if (communityFees[token] < amount) revert InsufficientFees();
communityFees[token] -= amount;
if (token == address(0)) {
SafeTransferLib.safeTransferETH(msg.sender, amount);
} else {
SafeTransferLib.safeTransfer(IERC20(token), msg.sender, amount);
}
emit CommunityWithdraw(token, amount);
}
function setFactoryStatus(Version version, address factory, bool allowed) external onlyOwner {
_setFactoryStatusInternal(version, factory, allowed);
emit FactoryStatusUpdated(factory, version, allowed);
}
function _initializeFactoryAllowlist() internal {
_setFactoryStatusInternal(Version.V2, UNISWAP_V2_FACTORY, true);
_setFactoryStatusInternal(Version.V2, SUSHISWAP_V2_FACTORY, true);
_setFactoryStatusInternal(Version.V3, UNISWAP_V3_FACTORY, true);
_setFactoryStatusInternal(Version.V3, PANCAKESWAP_V3_FACTORY, true);
}
function _setFactoryStatusInternal(Version version, address factory, bool allowed) internal {
if (factory == address(0)) revert InvalidInput();
if (version == Version.V2) {
allowedV2Factories[factory] = allowed;
} else if (version == Version.V3) {
allowedV3Factories[factory] = allowed;
} else {
revert UnsupportedVersion();
}
}
function _validateV2Pair(address pair) internal view {
if (pair == address(0)) revert InvalidInput();
address factory;
try IUniswapV2Pair(pair).factory() returns (address pairFactory) {
factory = pairFactory;
} catch {
revert InvalidInput();
}
if (!allowedV2Factories[factory]) revert UnauthorizedFactory(factory);
}
function _validateV3Pool(address pool) internal view {
if (pool == address(0)) revert InvalidInput();
address factory;
try IUniswapV3Pool(pool).factory() returns (address poolFactory) {
factory = poolFactory;
} catch {
revert InvalidInput();
}
if (!allowedV3Factories[factory]) revert UnauthorizedFactory(factory);
}
}
Read Contract
DAI 0xe0bab4c4 → address
USDC 0x89a30271 → address
USDT 0xc54e44eb → address
WETH 0xad5c4648 → address
allowedV2Factories 0xe5f8d074 → bool
allowedV3Factories 0x2622082e → bool
communityFees 0x30062192 → uint256
getVarsFromPairsOrPool 0xadc326ba → bytes[]
owner 0x8da5cb5b → address
poolManager 0xdc4c90d3 → address
protocolFees 0xdcf844a7 → uint256
Write Contract 11 functions
These functions modify contract state and require a wallet transaction to execute.
pancakeV3SwapCallback 0x23a69e75
int256 amount0Delta
int256 amount1Delta
bytes data
setFactoryStatus 0x60196339
uint8 version
address factory
bool allowed
swapEthPerTokens 0xa235f92a
address[] pairs
uint8[] versions
address
uint256 amountOutMin
address referral
tuple[] poolKeys
returns: uint256, address
swapTokenPerEth 0xe7ee006a
address[] pairs
uint8[] versions
uint256 amountIn
address inputToken
uint256 amountOutMin
address referral
tuple[] poolKeys
returns: uint256
swapTokenPerToken 0x28d2ab12
address[] pairs
uint8[] versions
uint256 amountIn
address inputToken
uint256 amountOutMin
address referral
tuple[] poolKeys
returns: uint256, address
uniswapV3SwapCallback 0xfa461e33
int256 amount0Delta
int256 amount1Delta
bytes data
unlockCallback 0x91dd7346
bytes data
returns: bytes
unwrapWETH 0xf018a8c1
uint256 amount
withdraw 0xf3fef3a3
address _addy
uint256 _amount
withdrawCommunityFees 0x14e9c86b
address token
uint256 amount
withdrawProtocolFees 0x1a7a73c2
address token
uint256 amount
Token Balances (1)
View Transfers →Recent Transactions
No transactions found for this address