Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x3bA779BAd405D9b68a7A7a86ff6916c806A200CC
Balance 0.013214 ETH
Nonce 1
Code Size 9906 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

9906 bytes
0x60806040526004361015610046575b3615610018575f80fd5b6040513481527f88a5966d370b9919b20f3e2c13ff65706f196a4e32cc2c12bf57088f8852587460203392a2005b5f803560e01c806214ac03146116b75780631004e0c514611504578063117803e3146114db5780631237739b146114b057806313e7c9d814611471578063185025ef1461144a57806319a1ccbb146113f05780631e0d8c3d146113d257806321d0ee70146113cd578063259982e5146113cd5780632d2c5565146113a457806333a100ca14611319578063368f5bd51461127c578063398daa851461123d578063416677a514611220578063465fc5d214611202578063468606981461110057806352f58d87146110e257806354d82ebc146110c5578063575e24b41461100f57806362308e8514610fca578063644f849e14610fad57806369e10ac114610f5b5780636c2bbe7e14610aac5780636fe7e6eb14610f0f578063715018a614610ea7578063751fd17914610e0457806379d3cfb914610cc95780637dc6381214610cac5780637f779adf14610c8f57806392ddc51014610bd45780639407114514610b975780639870d7fe14610af65780639d934e1b14610ab15780639f063efc14610aac578063a15467e014610a14578063a5f408b4146108aa578063a64e4f8a14610884578063a6f8e7221461081d578063ab814d6b146107ff578063ac8a584a14610777578063b47b2fb1146106b4578063b6a8b0fa1461039c578063b7cbae871461068e578063c51c2d0e1461065a578063ce404b23146105d1578063d79e856714610529578063dc98354e146104ea578063de4b5c5b146103e6578063de90055a146103c8578063e0efe95c146103a1578063e1b4af691461039c578063f0f44260146102ff5763f7658820146102a2575061000e565b346102fc57806003193601126102fc576002546001600160a01b0316331415806102e5575b6102d6576102d36124c7565b80f35b63089b7a0760e41b8152600490fd5b50338152600360205260ff604082205416156102c7565b80fd5b50346102fc5760203660031901126102fc57610319611701565b6002546001600160a01b0316330361038d576001600160a01b0316801561037e57600180546001600160a01b0319811683179091556001600160a01b03167f4ab5be82436d353e61ca18726e984e561f5c1cc7c6d38b29d2553c790434705a8380a380f35b6302979eb960e31b8252600482fd5b635fc483c560e01b8252600482fd5b61182c565b50346102fc57806003193601126102fc5760206001600160801b0360075416604051908152f35b50346102fc57806003193601126102fc576020600654604051908152f35b50346102fc5760203660031901126102fc57600435908115918215036102fc576007549060ff8260881c16155f1461043d575050506113885b6123288111610434575b604051908152602090f35b50612328610429565b60265490816104585750506001600160801b0391501661041f565b610464602754426119ae565b60285490929080841061048557505050506001600160801b0391501661041f565b6104b0906104ab6001600160801b036104b695969716966104a688866119ae565b611aa3565b611ab6565b906119ae565b92156104c357505061041f565b612710906104dc6104d7846104e5966119ae565b611a8b565b9050049061239b565b61041f565b50346102fc5760e03660031901126102fc57610504611701565b5060a03660231901126102fc5760049061051c611816565b50630a85dc2960e01b8152fd5b50346102fc5760403660031901126102fc57610543611701565b600254602435906001600160a01b031633036105c2576001600160a01b0382169182156105b357839081808438935af1156105a65760207f20f907b58305c7b76035bc03b26f32b1c4f6560f96be6f3bb54c5c848a2d4ddd91604051908152a280f35b63b12d13eb83526004601cfd5b63e6c4247b60e01b8452600484fd5b635fc483c560e01b8352600483fd5b50346102fc57806003193601126102fc576002546001600160a01b0316330361064b5760075460ff8160801c161561063c5760ff60801b19166007556040514281527f9ab953db0fb51a9200df76a91a545d309792ec2787f1c41d1db4b6018eb5ec4490602090a180f35b635ddf5e8560e01b8252600482fd5b635fc483c560e01b8152600490fd5b50346102fc57806003193601126102fc576005546006546040805192835260208301919091524790820152606090f35b0390f35b50346102fc57806003193601126102fc57602060ff60075460881c166040519015158152f35b50346102fc576101603660031901126102fc576106cf611701565b9060a03660231901126102fc5760603660c31901126102fc576101443567ffffffffffffffff811161077357610709903690600401611717565b50507f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b0316330361076457604061074a6101243584612067565b82516001600160e01b03199092168252600f0b6020820152f35b63f655705d60e01b8152600490fd5b5080fd5b50346102fc5760203660031901126102fc57610791611701565b6002546001600160a01b0316330361038d576001600160a01b03168082526003602052604082205460ff166107c4575080f35b808252600360205260408220805460ff191690557f80c0b871b97b595b16a7741c1b06fed0c6f6f558639f18ccbce50724325dc40d8280a280f35b50346102fc57806003193601126102fc576020602754604051908152f35b50346102fc57806003193601126102fc576060906001600160801b0360075460ff8160881c1690815f1461087c576002935b508115610872578216905b60ff6040519416845215156020840152166040820152f35b506113889061085a565b60019361084f565b50346102fc57806003193601126102fc57602060ff60075460801c166040519015158152f35b50346102fc5760803660031901126102fc576004356024356044356064359160018060a01b0360025416331415806109fd575b6109ee57600a8410156109b4576109a37fbb15785662e808c63efc6a05274ce9a7cb01b854b603db64f663b880234dd2fe9361091a831515611ed1565b610928612328851115611f0e565b61093f6001600160801b0360075416851015611f49565b801515806109a9575b61095190611f86565b60405161095d8161187f565b838152600a60208201868152604083019084825260038a029351846008015551600984015551910155604051938493846040919493926060820195825260208201520152565b0390a280f35b506018811115610948565b60405162461bcd60e51b8152602060048201526012602482015271092dcecc2d8d2c840e8d2cae440d2dcc8caf60731b6044820152606490fd5b63089b7a0760e41b8552600485fd5b50338552600360205260ff604086205416156108dd565b50346102fc5760203660031901126102fc57600254600435906001600160a01b0316330361038d5760075460ff8160881c16610a9d5760ff60881b1916600160881b1760075580610a8e575b507f578782da93d16a17f4ef4b318f8984283041cd09a6609e84ef801f05124aa5e16020604051428152a180f35b610a9790612579565b5f610a60565b63cc17dcc760e01b8352600483fd5b6117b7565b50346102fc57806003193601126102fc576040517f00000000000000000000000000000000000000000000000000000000000000006001600160a01b03168152602090f35b50346102fc5760203660031901126102fc57610b10611701565b6002546001600160a01b0316330361038d576001600160a01b03168015610b8857808252600360205260ff60408320541615610b4a575080f35b808252600360205260408220805460ff191660011790557fac6fa858e9350a46cec16539926e0fde25b7629f84b5a72bffaae4df888ae86d8280a280f35b63ccea9e6f60e01b8252600482fd5b50346102fc57806003193601126102fc5760a0610bb2611fc2565b9260409291925194151585526020850152604084015260608301526080820152f35b50346102fc5760203660031901126102fc578054600435906001600160a01b03163303610c805760075460ff8160881c16610a9d5760ff60881b1916600160881b176007557fcaa1be315561689ebd1ec3b715df7e0cef5b2352b525cf47651704c19b18ef1a90604090610c4781612579565b8151908152426020820152a17f578782da93d16a17f4ef4b318f8984283041cd09a6609e84ef801f05124aa5e16020604051428152a180f35b63ade5da5f60e01b8252600482fd5b50346102fc57806003193601126102fc5760206040516103e88152f35b50346102fc57806003193601126102fc5760206040516127108152f35b50346102fc576103c03660031901126102fc57366103c4116102fc576002546001600160a01b031633141580610ded575b6102d657805b600a811015610dc55780610d20610d18600193611ebf565b351515611ed1565b610d3a6123286020610d3184611ebf565b01351115611f0e565b610d5d6020610d4883611ebf565b01356001600160801b03600754161115611f49565b6040610d6882611ebf565b0135151580610da9575b610d7b90611f86565b610d8481611ebf565b600a604060038402928035846008015560208101356009850155013591015501610d00565b50610d7b60186040610dba84611ebf565b013511159050610d72565b507fd5d2b80d37db00992c4bf987fbd89f3fcd6a981ac5862c4d93433e8ca64f459f8180a180f35b50338152600360205260ff60408220541615610cfa565b50346102fc5760403660031901126102fc57610e1e611701565b60243590811515809203610ea3576002546001600160a01b031633036105c2576001600160a01b0316908115610e945760207f210f2a4a589e25d95b24cbdb060d26ae79bbe123a564d0f973503d48badd00ca91838552600482526040852060ff1981541660ff8316179055604051908152a280f35b63e6c4247b60e01b8352600483fd5b8280fd5b50346102fc57806003193601126102fc576002546001600160a01b03811690338290036105c2576bffffffffffffffffffffffff60a01b166002557f656ba3c6830b11142778bbcfaff90d2ecc89186277667c2ce8700e4697ddccc26020604051428152a280f35b50346102fc576101003660031901126102fc57610f2a611701565b5060a03660231901126102fc57610f3f611816565b5060e4358060020b036102fc57630a85dc2960e01b8152600490fd5b50346102fc5760203660031901126102fc57600435600a811015610773576003915002806008015461068a600a6009840154930154604051938493846040919493926060820195825260208201520152565b50346102fc57806003193601126102fc5760206040516113888152f35b50346102fc57806003193601126102fc576040517f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b03168152602090f35b50346102fc576101403660031901126102fc5761102a611701565b9060a03660231901126102fc5760603660c31901126102fc576101243567ffffffffffffffff811161077357611064903690600401611717565b50507f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a906001600160a01b0316330361076457606062ffffff6110a584611b51565b906040939293519363ffffffff60e01b1684526020840152166040820152f35b50346102fc57806003193601126102fc5760206040516107d08152f35b50346102fc57806003193601126102fc576020602854604051908152f35b50346102fc5760203660031901126102fc57600254600435906001600160a01b0316330361038d57606481106111ca576103e881116111915760407f19ad72acd40a59cad104f97c7897cc5675e52fe1e2679088c4bfffd96a9d58a791600754906001600160801b0381166001600160801b03198316176007556001600160801b038351921682526020820152a180f35b60405162461bcd60e51b8152602060048201526011602482015270084c2e6ca40cccaca40e8dede40d0d2ced607b1b6044820152606490fd5b60405162461bcd60e51b815260206004820152601060248201526f426173652066656520746f6f206c6f7760801b6044820152606490fd5b50346102fc57806003193601126102fc576020600554604051908152f35b50346102fc57806003193601126102fc576020604051611f408152f35b50346102fc5760203660031901126102fc5760209060ff906040906001600160a01b03611268611701565b168152600484522054166040519015158152f35b50346102fc57806003193601126102fc576002546001600160a01b031633141580611302575b6102d65760075460ff8160801c166112f35760ff60801b1916600160801b176007556040514281527f17d299d4c9f46c265604fd04fab53eca75a794a9be07578f555ca4f4f9b20be590602090a180f35b631b6d9e0b60e11b8252600482fd5b50338152600360205260ff604082205416156112a2565b50346102fc5760203660031901126102fc57611333611701565b6002546001600160a01b0316330361038d576001600160a01b031680156113955781546001600160a01b03198116821783556001600160a01b03167fe4cec16b1a7e6b7979e923da619a8b1e5fd0f0fb6e5c1cf647f350430ee61ca98380a380f35b632711b74d60e11b8252600482fd5b50346102fc57806003193601126102fc576001546040516001600160a01b039091168152602090f35b611745565b50346102fc57806003193601126102fc576020602654604051908152f35b50346102fc5760203660031901126102fc5780546001600160a01b0316330361143b5760ff60075460881c161561142c576102d3600435612579565b63031491c960e41b8152600490fd5b63ade5da5f60e01b8152600490fd5b50346102fc57806003193601126102fc57546040516001600160a01b039091168152602090f35b50346102fc5760203660031901126102fc5760209060ff906040906001600160a01b0361149c611701565b168152600384522054166040519015158152f35b50346102fc5760203660031901126102fc5760406114cf6004356119f7565b82519182526020820152f35b50346102fc57806003193601126102fc576002546040516001600160a01b039091168152602090f35b503461168d575f36600319011261168d576002546001600160a01b0316331415806116a0575b61169157600554806115d7575b5060065480611544575080f35b81600655818080808460018060a01b036001541661c350f16115646118d1565b5061159b576020817fc2e3331488a93a769ac9345472d928b920788b32bc6172060e2d094e0fe7d25a92600655604051908152a180f35b6001546040519182526001600160a01b0316907fc7c75176ac954c9e607fa8025a6ba69fc5d71adf8636cb39f87fd720966fe2ac90602090a280f35b5f6005819055546001600160a01b0316803b1561168d575f8291600460405180948193630eddd54f60e11b83525af19081611678575b50611648576020817f66da4aac9810dec720296cca93df3f055eca44772d28d1e96f95cae2362bcebb92600555604051908152a15b5f611537565b60207f9dcedea077be392c934563c584683d9cbb5d47d5e60d90ab1656151d232ae5a791604051908152a1611642565b6116859193505f906118af565b5f915f61160d565b5f80fd5b63089b7a0760e41b5f5260045ffd5b50335f52600360205260ff60405f2054161561152a565b3461168d575f36600319011261168d576002546001600160a01b0316331415806116ea575b611691576116e8611910565b005b50335f52600360205260ff60405f205416156116dc565b600435906001600160a01b038216820361168d57565b9181601f8401121561168d5782359167ffffffffffffffff831161168d576020838186019501011161168d57565b3461168d5761016036600319011261168d576004356001600160a01b038116810361168d575060a036602319011261168d5760803660c319011261168d576101443567ffffffffffffffff811161168d576117a4903690600401611717565b5050630a85dc2960e01b5f908152600490fd5b3461168d576101a036600319011261168d576004356001600160a01b038116810361168d575060a036602319011261168d5760803660c319011261168d576101843567ffffffffffffffff811161168d576117a4903690600401611717565b60c435906001600160a01b038216820361168d57565b3461168d5761012036600319011261168d576004356001600160a01b038116810361168d575060a036602319011261168d576101043567ffffffffffffffff811161168d576117a4903690600401611717565b6060810190811067ffffffffffffffff82111761189b57604052565b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff82111761189b57604052565b3d1561190b573d9067ffffffffffffffff821161189b5760405191611900601f8201601f1916602001846118af565b82523d5f602084013e565b606090565b60065480156119ab575f6006555f8080808460018060a01b036001541661c350f16119396118d1565b501561197a576001546040519182526001600160a01b0316907fc7c75176ac954c9e607fa8025a6ba69fc5d71adf8636cb39f87fd720966fe2ac90602090a2565b6020817fc2e3331488a93a769ac9345472d928b920788b32bc6172060e2d094e0fe7d25a92600655604051908152a1565b50565b919082039182116119bb57565b634e487b7160e01b5f52601160045260245ffd5b906040516119dc8161187f565b60406002829480548452600181015460208501520154910152565b600a805b611a125750506001600160801b0360075416905f90565b5f1981018181116119bb57600a811015611a5f576003611a3591026008016119cf565b8051831015611a4e575080156119bb575f1901806119fb565b929150506040602083015192015190565b634e487b7160e01b5f52603260045260245ffd5b9081602091031261168d5751801515810361168d5790565b906103e88202918083046103e814901517156119bb57565b818102929181159184041417156119bb57565b8115611ac0570490565b634e487b7160e01b5f52601260045260245ffd5b15611adb57565b60405162461bcd60e51b815260206004820152600c60248201526b466565206f766572666c6f7760a01b6044820152606490fd5b6001600160801b03611f40911602906001600160801b0382169182036119bb57565b906001600160801b03809116911603906001600160801b0382116119bb57565b5f8054604051634ada218b60e01b815291926001600160a01b0390911691602081600481865afa5f9181611e8e575b50611e4857506001600160a01b038116828114159081611e30575b50611e21575b60ff60075460801c1615918215611e0e575b508115611ded575b50611ddd5760c435801515810361168d57611bdd576315d7892d60e21b918190565b60e435905f821215611dce57600160ff1b82146119bb576001600160801b03612710611c13611c0a6123a8565b80955f03611aa3565b04611c2082821115611ad4565b166127106001600160801b03611c3583611b0f565b1604611c418183611b31565b602435949091906001600160a01b0386811691907f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a901682880361168d57803b1561168d57604051630b0d9c0960e01b81526001600160a01b03891660048201523060248201526001600160801b0387166044820152905f908290606490829084905af18015611dc357611d68575b506001600160801b0383611d5295937fe5f74c1935f87f5b3c2d5f1529e001ae6fedd21cce61a31cf833e909aff18ae3839689611d43611d4c978d9e611d579e50508960405194859485909493926001600160801b0390816060948160808601991685521660208401521660408201520152565b0390a21661263c565b16612653565b61266a565b60801b916315d7892d60e21b929190565b611d57965083611d5295937fe5f74c1935f87f5b3c2d5f1529e001ae6fedd21cce61a31cf833e909aff18ae36001600160801b039689611d43611d4c97611db05f8c996118af565b5f9d509750505050509395509350611ccf565b6040513d5f823e3d90fd5b6321b865b360e01b5f5260045ffd5b506315d7892d60e21b905f908190565b6001600160a01b03165f9081526004602052604081205460ff169150611bbb565b6001600160a01b0382161491505f611bb3565b6312f1f92360e01b5f5260045ffd5b90505f52600460205260ff60405f205416155f611b9b565b611ba1576001600160a01b038116828114159081611e76575b5015611ba1576312f1f92360e01b5f5260045ffd5b90505f52600460205260ff60405f205416155f611e61565b611eb191925060203d602011611eb8575b611ea981836118af565b810190611a73565b905f611b80565b503d611e9f565b600a811015611a5f5760600260040190565b15611ed857565b60405162461bcd60e51b815260206004820152600e60248201526d16995c9bc81d1a1c995cda1bdb1960921b6044820152606490fd5b15611f1557565b60405162461bcd60e51b815260206004820152600c60248201526b08ccaca40e8dede40d0d2ced60a31b6044820152606490fd5b15611f5057565b60405162461bcd60e51b815260206004820152600e60248201526d4665652062656c6f77206261736560901b6044820152606490fd5b15611f8d57565b60405162461bcd60e51b815260206004820152600d60248201526c496e76616c696420646563617960981b6044820152606490fd5b6007549060ff8260881c1615801561205d575b61204857611fe5602754426119ae565b60285492838210156120315750600192611ffd612452565b926120066123a8565b9261201181846119ae565b926064820291808304606414901517156119bb5761202e91611ab6565b90565b5f93506001600160801b0316918291508390606490565b906001600160801b03165f9181905f90606490565b5060265415611fd5565b5f8054604051634ada218b60e01b81529193926001600160a01b0390911691602081600481865afa5f918161237a575b5061233457506001600160a01b03811682811415908161231c575b50611e21575b60ff60075460801c1615918215612309575b5081156122e8575b506122d95760c4358015908115810361168d57506120f6575063b47b2fb160e01b91565b5f60e4351215611dce5760801d9081600f0b5f811315612294575f13612285576001600160801b03612710612137829461212e612452565b95869116611aa3565b0461214482821115611ad4565b16906127106001600160801b0361215a84611b0f565b16046121668184611b31565b602435946001600160a01b037f000000000000000000000000000000000004444c5dc75cb358380d2e3de08a90811693908716919082880361168d57843b1561168d57604051630b0d9c0960e01b81526001600160a01b03891660048201523060248201526001600160801b0388166044820152945f908690606490829084905af1928315611dc3577fe5f74c1935f87f5b3c2d5f1529e001ae6fedd21cce61a31cf833e909aff18ae38289611d436001600160801b0399966122679d611d529c8c99611d4c9b612272575b5050508960405194859485909493926001600160801b0390816060948160808601991685521660208401521660408201520152565b63b47b2fb160e01b91565b61227e91505f906118af565b5f80612232565b6393dafdf160e01b5f5260045ffd5b60405162461bcd60e51b815260206004820152601960248201527f556e6578706563746564206e656761746976652064656c7461000000000000006044820152606490fd5b5063b47b2fb160e01b915f9150565b6001600160a01b03165f9081526004602052604081205460ff1691506120d2565b6001600160a01b0382161491505f6120ca565b90505f52600460205260ff60405f205416155f6120b2565b6120b8576001600160a01b038116828114159081612362575b50156120b8576312f1f92360e01b5f5260045ffd5b90505f52600460205260ff60405f205416155f61234d565b61239491925060203d602011611eb857611ea981836118af565b905f612097565b919082018092116119bb57565b60075460ff8160881c16155f146123d157506113885b61232881116123ca5790565b5061232890565b602654806123e857506001600160801b03166123be565b6123f4602754426119ae565b602854909190808310612412575050506001600160801b03166123be565b6104d76104ab93612441612710946104b0612446956001600160801b0361244d9a169889956104a687866119ae565b6119ae565b049061239b565b6123be565b60075460ff8160881c16155f1461246a575061138890565b6026548061248157506001600160801b03166123be565b61248d602754426119ae565b602854908181106124a9575050506001600160801b03166123be565b906104ab6104b0926104a66001600160801b0361244d9716866119ae565b60055480156119ab575f6005819055546001600160a01b0316803b1561168d575f8291600460405180948193630eddd54f60e11b83525af19081612569575b5061253c576020817f66da4aac9810dec720296cca93df3f055eca44772d28d1e96f95cae2362bcebb92600555604051908152a1565b60207f9dcedea077be392c934563c584683d9cbb5d47d5e60d90ab1656151d232ae5a791604051908152a1565b5f612573916118af565b5f612506565b600a805b612585575050565b5f1901600a811015611a5f576125a0600382026008016119cf565b80518310156125b057508061257d565b9190506125bb612452565b602083019283519182116125d0575b50505050565b6040916026554260275501908151610e10810290808204610e1014901517156119bb5760285591519051604080519384526020840192909252908201527f8cd5e0f587f7e7c378d090135f890298086959967834a15abce5d1589ad1de8990606090a15f8080806125ca565b80156119ab5761264e9060055461239b565b600555565b80156119ab576126659060065461239b565b600655565b6001607f1b81101561228557600f0b9056fea264697066735822122059fed40427e61a0528a62f932197bdea5c6372c4cfedd2eff5f87d9dd8e42da864736f6c634300081a0033

Verified Source Code Full Match

Compiler: v0.8.26+commit.8a97fa7a EVM: cancun Optimization: Yes (200 runs)
MemeStrategyHook.sol 1041 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

/*
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&-MEMS2025-&&&&&&&&&&&&&&&&BOOM&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&                 &&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&                         &&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&                         &&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&   &&&&&&&&&&&&&&               &&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&  &&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&           &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&       &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&       &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&       &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&                   &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&                   &&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&&&&&    &&&&&&&&&&&&&&&&&&&    &&&&&&&&&&&&&&&&&&&&&&&&&&&&
&&&&1986&&&&&&&&&&&&&#                      &&&&       &&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&#                      &&&&       &&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&&&#   &&&&&&&&&&&&&&&&&&&    &&&&   &&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&                       &&&&&&&       &&&&&&&&&&&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&                       &&&&&&&       &&&&&&&&&&&&&&&&&&&&&&&&&

    ╔═══════════════════════════════════════════════════════════════╗
    ║                 MEMESTRATEGY HOOK v1.1                        ║
    ║              Dynamic Fee System (50% → 10-90%)                ║
    ╚═══════════════════════════════════════════════════════════════╝
*/

import {Hooks} from "@uniswap/v4-core/src/libraries/Hooks.sol";
import {IHooks} from "@uniswap/v4-core/src/interfaces/IHooks.sol";
import {IPoolManager} from "@uniswap/v4-core/src/interfaces/IPoolManager.sol";
import {PoolKey} from "@uniswap/v4-core/src/types/PoolKey.sol";
import {SwapParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {ModifyLiquidityParams} from "@uniswap/v4-core/src/types/PoolOperation.sol";
import {BalanceDelta} from "@uniswap/v4-core/src/types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary, toBeforeSwapDelta} from "@uniswap/v4-core/src/types/BeforeSwapDelta.sol";
import {Currency, CurrencyLibrary} from "@uniswap/v4-core/src/types/Currency.sol";
import {SafeCast} from "@uniswap/v4-core/src/libraries/SafeCast.sol";
import {SafeTransferLib} from "solady/utils/SafeTransferLib.sol";

/// @notice Minimal interface for Strategy contract
interface IStrategy {
    function addFeesETH() external payable;
    function tradingEnabled() external view returns (bool);
}

/// @title MemeStrategyHook
/// @notice Uniswap V4 hook that collects dynamic swap fees (Phase 1: 50%, Phase 2: 10-90%)
/// @dev Implements 3-phase system with asymmetric fees and forwards native ETH to strategy
contract MemeStrategyHook is IHooks {
    using CurrencyLibrary for Currency;
    using SafeCast for uint256;
    using SafeCast for int256;
    using SafeCast for int128;
    using Hooks for IHooks;

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                  CONSTANTS                                   */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    IPoolManager public immutable POOL_MANAGER;
    address public STRATEGY;                    // Mutable: can redirect fees to upgraded strategy
    Currency public immutable ETH_CURRENCY;     // Native ETH
    address public TREASURY;                    // Mutable: can update treasury address
    address public OWNER; // Can enable fees (mutable for renounce)

    // Operator Access
    mapping(address => bool) public operators; // Can enable fees and update tiers

    // Fee Exemption (for modules/extensions that burn tokens)
    mapping(address => bool) public feeExempt; // Whitelisted addresses bypass fees

    // Pending Balances (for deferred settlement - best practice for hooks)
    uint256 public pendingStrategy; // Strategy fees awaiting flush
    uint256 public pendingRake;     // Rake fees awaiting flush

    // Fee Constants
    uint128 public BASE_FEE_BIPS = 1000;                // 10% base fee (mutable)
    uint128 public constant PHASE1_FEE_BIPS = 5000;     // 50% Phase 1 flat fee
    uint128 public constant RAKE_BIPS = 2000;           // 20% of total fee to treasury
    uint128 public constant STRATEGY_BIPS = 8000;       // 80% of total fee to strategy
    uint128 public constant TOTAL_BIPS = 10000;
    uint128 public constant BUY_SPIKE_RATIO = 1000;     // Buys pay 10% of spike increase

    // Phase Control
    bool public feesEnabled;        // Phase 0 control
    bool public phase2Activated;    // Phase 2 activation

    // Dynamic Fee System (Phase 2)
    struct FeeSpike {
        uint256 triggerAmount;    // ETH threshold
        uint256 feePercent;       // Fee % in bips
        uint256 decayHours;       // Decay duration
    }

    FeeSpike[10] public feeSpikeTiers;   // 2 ETH to 50 ETH tiers
    uint256 public currentFeeSpike;      // Current spike fee %
    uint256 public feeSpikeTriggerTime;  // When spike started
    uint256 public feeDecayDuration;     // Decay duration in seconds

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                    EVENTS                                    */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    // Access Control Events
    event OperatorAdded(address indexed operator);
    event OperatorRemoved(address indexed operator);
    event OwnershipRenounced(address indexed previousOwner, uint256 timestamp);
    event FeeExemptionSet(address indexed account, bool exempt);
    event StrategyUpdated(address indexed oldStrategy, address indexed newStrategy);
    event TreasuryUpdated(address indexed oldTreasury, address indexed newTreasury);

    // Phase Events
    event FeesEnabled(uint256 timestamp);
    event FeesDisabled(uint256 timestamp);
    event FirstSaleExecuted(uint256 saleAmount, uint256 timestamp);
    event Phase2Activated(uint256 timestamp);
    event FeeSpikeTriggered(
        uint256 saleAmount,
        uint256 feePercent,
        uint256 decayHours
    );

    // Fee Events
    event FeeCollected(
        Currency indexed currency,
        uint256 totalFee,
        uint256 strategyAmount,
        uint256 rakeAmount,
        uint256 feeBips
    );
    event FeesFlushedToStrategy(uint256 amount);
    event StrategyFlushFailed(uint256 amount);
    event RakeFlushed(address indexed treasury, uint256 amount);
    event RakeFlushFailed(uint256 amount);

    // Fee Tier Management
    event FeeTierUpdated(
        uint256 indexed index,
        uint256 triggerAmount,
        uint256 feePercent,
        uint256 decayHours
    );
    event AllFeeTiersUpdated();
    event FeeTiersBootstrapped();  // Emitted once in constructor
    event BaseFeeUpdated(uint256 oldBaseFee, uint256 newBaseFee);

    // Emergency Events
    event EmergencyWithdrawETH(address indexed to, uint256 amount);
    event Received(address indexed sender, uint256 amount);

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                    ERRORS                                    */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    error InvalidStrategy();
    error InvalidTreasury();
    error InvalidOwner();
    error InvalidOperator();
    error InvalidAddress();
    error OnlyPoolManager();
    error OnlyStrategy();
    error OnlyOwner();
    error OnlyOwnerOrOperator();
    error FeesAlreadyEnabled();
    error FeesAlreadyDisabled();
    error Phase2AlreadyActive();
    error Phase2NotActive();
    error HookNotImplemented();
    error ExactOutputNotSupported();
    error TradingNotEnabled();

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                                 CONSTRUCTOR                                  */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @param _poolManager Uniswap V4 PoolManager
    /// @param _strategy MemeStrategy contract address
    /// @param _treasury Treasury address for 20% rake
    /// @param _owner Owner address (can enable fees)
    constructor(
        IPoolManager _poolManager,
        address _strategy,
        address _treasury,
        address _owner
    ) {
        if (_strategy == address(0)) revert InvalidStrategy();
        if (_treasury == address(0)) revert InvalidTreasury();
        if (_owner == address(0)) revert InvalidOwner();

        POOL_MANAGER = _poolManager;
        STRATEGY = _strategy;
        ETH_CURRENCY = Currency.wrap(address(0));  // Native ETH
        TREASURY = _treasury;
        OWNER = _owner;

        feesEnabled = false;  // Start with fees OFF
        phase2Activated = false;

        // Initialize 10-tier fee spike system
        feeSpikeTiers[0] = FeeSpike({
            triggerAmount: 2 ether,
            feePercent: 1250,
            decayHours: 1
        });
        feeSpikeTiers[1] = FeeSpike({
            triggerAmount: 5 ether,
            feePercent: 1500,
            decayHours: 4
        });
        feeSpikeTiers[2] = FeeSpike({
            triggerAmount: 10 ether,
            feePercent: 2000,
            decayHours: 5
        });
        feeSpikeTiers[3] = FeeSpike({
            triggerAmount: 15 ether,
            feePercent: 2500,
            decayHours: 6
        });
        feeSpikeTiers[4] = FeeSpike({
            triggerAmount: 20 ether,
            feePercent: 4000,
            decayHours: 7
        });
        feeSpikeTiers[5] = FeeSpike({
            triggerAmount: 25 ether,
            feePercent: 5000,
            decayHours: 8
        });
        feeSpikeTiers[6] = FeeSpike({
            triggerAmount: 30 ether,
            feePercent: 6000,
            decayHours: 9
        });
        feeSpikeTiers[7] = FeeSpike({
            triggerAmount: 35 ether,
            feePercent: 7000,
            decayHours: 10
        });
        feeSpikeTiers[8] = FeeSpike({
            triggerAmount: 40 ether,
            feePercent: 8000,
            decayHours: 11
        });
        feeSpikeTiers[9] = FeeSpike({
            triggerAmount: 50 ether,
            feePercent: 9000,
            decayHours: 12
        });

        // Emit bootstrap event for off-chain indexers to cache initial tier configuration
        emit FeeTiersBootstrapped();

        // Validate hook address has correct permissions
        Hooks.validateHookPermissions(
            IHooks(address(this)),
            Hooks.Permissions({
                beforeInitialize: false,
                afterInitialize: false,
                beforeAddLiquidity: false,
                afterAddLiquidity: false,
                beforeRemoveLiquidity: false,
                afterRemoveLiquidity: false,
                beforeSwap: true,                    // ← ENABLED for buy-side fees
                afterSwap: true,
                beforeDonate: false,
                afterDonate: false,
                beforeSwapReturnDelta: true,         // ← ENABLED for fee collection
                afterSwapReturnDelta: true,
                afterAddLiquidityReturnDelta: false,
                afterRemoveLiquidityReturnDelta: false
            })
        );
    }

    modifier onlyPoolManager() {
        if (msg.sender != address(POOL_MANAGER)) revert OnlyPoolManager();
        _;
    }

    modifier onlyOwnerOrOperator() {
        if (msg.sender != OWNER && !operators[msg.sender]) revert OnlyOwnerOrOperator();
        _;
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                          OPERATOR MANAGEMENT                                 */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Add operator (can enable fees and update tiers)
    function addOperator(address operator) external {
        if (msg.sender != OWNER) revert OnlyOwner();
        if (operator == address(0)) revert InvalidOperator();
        if (!operators[operator]) {
            operators[operator] = true;
            emit OperatorAdded(operator);
        }
    }

    /// @notice Remove operator
    function removeOperator(address operator) external {
        if (msg.sender != OWNER) revert OnlyOwner();
        if (operators[operator]) {
            operators[operator] = false;
            emit OperatorRemoved(operator);
        }
    }

    /// @notice Renounce ownership (permanently decentralize hook)
    /// @dev IRREVERSIBLE - Sets OWNER to address(0), disabling all owner-only functions
    ///      Use with extreme caution. Ensure all fee tiers and settings are finalized.
    ///      After renouncing: no fee tier updates, no emergency withdrawals, no operator changes
    function renounceOwnership() external {
        if (msg.sender != OWNER) revert OnlyOwner();
        address previousOwner = OWNER;
        OWNER = address(0);
        emit OwnershipRenounced(previousOwner, block.timestamp);
    }

    /// @notice Set fee exemption for modules/extensions
    /// @dev Allows certain addresses to bypass fees (e.g., ModuleManager, burn modules)
    /// @param account Address to exempt or un-exempt
    /// @param exempt True to exempt from fees, false to remove exemption
    function setFeeExemption(address account, bool exempt) external {
        if (msg.sender != OWNER) revert OnlyOwner();
        if (account == address(0)) revert InvalidAddress();

        feeExempt[account] = exempt;
        emit FeeExemptionSet(account, exempt);
    }

    /// @notice Update strategy address to redirect fee flows
    /// @dev Owner only - allows upgrading to a new strategy contract without redeploying hook
    ///      IMPORTANT: Flush pending fees to old strategy before updating
    /// @param newStrategy Address of the new strategy contract
    function setStrategy(address newStrategy) external {
        if (msg.sender != OWNER) revert OnlyOwner();
        if (newStrategy == address(0)) revert InvalidStrategy();

        address oldStrategy = STRATEGY;
        STRATEGY = newStrategy;
        emit StrategyUpdated(oldStrategy, newStrategy);
    }

    /// @notice Update treasury address to redirect rake fees
    /// @dev Owner only - allows updating treasury without redeploying hook
    ///      IMPORTANT: Flush pending rake to old treasury before updating
    /// @param newTreasury Address of the new treasury
    function setTreasury(address newTreasury) external {
        if (msg.sender != OWNER) revert OnlyOwner();
        if (newTreasury == address(0)) revert InvalidTreasury();

        address oldTreasury = TREASURY;
        TREASURY = newTreasury;
        emit TreasuryUpdated(oldTreasury, newTreasury);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                              PHASE 0 - FEE ACTIVATION                        */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Enable fees (toggleable, can be called multiple times)
    /// @dev Owner or operator can enable. Used for launch and after emergency pauses.
    function enableFees() external onlyOwnerOrOperator {
        if (feesEnabled) revert FeesAlreadyEnabled();

        feesEnabled = true;
        emit FeesEnabled(block.timestamp);
    }

    /// @notice Disable fees (emergency pause, toggleable)
    /// @dev Owner only - pauses all fee collection. Can be re-enabled later.
    ///      Use cases: market crisis, bug discovered, regulatory, promotional periods
    function disableFees() external {
        if (msg.sender != OWNER) revert OnlyOwner();
        if (!feesEnabled) revert FeesAlreadyDisabled();

        feesEnabled = false;
        emit FeesDisabled(block.timestamp);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                          PHASE TRANSITIONS & FEE SPIKES                      */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Manually activate Phase 2 (Owner only)
    /// @dev Allows owner to transition from Phase 1 (50% flat) to Phase 2 (10-90% dynamic)
    ///      without waiting for strategy's first sale. Useful for:
    ///      - Skipping Phase 1 entirely at launch
    ///      - Testing Phase 2 functionality
    ///      - Emergency transition to lower base fees
    /// @param initialSpikeAmount ETH amount to trigger initial spike (0 for no spike, starts at 10% base)
    function activatePhase2(uint256 initialSpikeAmount) external {
        if (msg.sender != OWNER) revert OnlyOwner();
        if (phase2Activated) revert Phase2AlreadyActive();

        // Activate Phase 2 first (before spike trigger for safety)
        phase2Activated = true;

        // Optionally trigger initial spike if amount provided
        if (initialSpikeAmount > 0) {
            _triggerFeeSpike(initialSpikeAmount);
        }

        emit Phase2Activated(block.timestamp);
    }

    /// @notice Strategy calls this after FIRST successful sale (Phase 1 → Phase 2)
    /// @dev Automatic transition - strategy triggers this after first successful sale
    function notifyFirstSale(uint256 saleAmount) external {
        if (msg.sender != address(STRATEGY)) revert OnlyStrategy();
        if (phase2Activated) revert Phase2AlreadyActive();

        // Activate Phase 2 first (before spike trigger for safety)
        phase2Activated = true;

        // Trigger initial fee spike
        _triggerFeeSpike(saleAmount);

        emit FirstSaleExecuted(saleAmount, block.timestamp);
        emit Phase2Activated(block.timestamp);
    }

    /// @notice Trigger fee spike on subsequent sales
    function triggerFeeSpike(uint256 saleAmount) external {
        if (msg.sender != address(STRATEGY)) revert OnlyStrategy();
        if (!phase2Activated) revert Phase2NotActive();

        _triggerFeeSpike(saleAmount);
    }

    /// @notice Internal spike logic - determines tier and sets fee
    function _triggerFeeSpike(uint256 saleAmount) internal {
        // Use storage reference for gas optimization
        FeeSpike[10] storage tiers = feeSpikeTiers;
        uint256 len = tiers.length;

        // Find the appropriate tier (iterate from highest to lowest)
        for (uint256 i = len; i > 0; ) {
            unchecked {
                --i;
            } // Safe: i > 0 checked in loop condition
            FeeSpike memory tier = tiers[i];

            if (saleAmount >= tier.triggerAmount) {
                // Check current sell fee to avoid downgrading during active spike
                uint256 currentSellFee = getCurrentFee(false);

                // Only spike if new fee is higher than current
                if (tier.feePercent > currentSellFee) {
                    currentFeeSpike = tier.feePercent;
                    feeSpikeTriggerTime = block.timestamp;
                    feeDecayDuration = tier.decayHours * 1 hours;

                    emit FeeSpikeTriggered(
                        saleAmount,
                        tier.feePercent,
                        tier.decayHours
                    );
                }
                break;
            }
        }
    }

    /// @notice Calculate current dynamic fee with decay
    /// @dev Includes runtime cap at 90% (9000 BPS) as defense-in-depth safety measure
    function getCurrentFee(bool isBuy) public view returns (uint256) {
        uint256 fee;

        // Phase 1: Flat 50% fee
        if (!phase2Activated) {
            fee = PHASE1_FEE_BIPS;
        }
        // Phase 2: No active spike - return base fee
        else if (currentFeeSpike == 0) {
            fee = BASE_FEE_BIPS;
        }
        // Phase 2: Active spike with decay
        else {
            // Calculate time elapsed since spike
            uint256 elapsed = block.timestamp - feeSpikeTriggerTime;

            // Decay period complete - back to base
            if (elapsed >= feeDecayDuration) {
                fee = BASE_FEE_BIPS;
            } else {
                // Linear decay: currentSpike → baseFee over decay duration
                uint256 spikeIncrease = currentFeeSpike - BASE_FEE_BIPS;
                uint256 decayAmount = (spikeIncrease * elapsed) / feeDecayDuration;
                uint256 currentSellFee = currentFeeSpike - decayAmount;

                // SELLS: Full spike fee
                if (!isBuy) {
                    fee = currentSellFee;
                }
                // BUYS: Asymmetric fee - Base + 10% of spike increase
                // Example: If spike = 9000 bips (90%), buys pay:
                //   Base (1000) + 10% of (9000-1000) = 1000 + 800 = 1800 bips (18%)
                // This creates favorable conditions for buyers during high-fee periods
                else {
                    uint256 activeSpikeIncrease = currentSellFee - BASE_FEE_BIPS;
                    uint256 buyFeeIncrease = (activeSpikeIncrease * BUY_SPIKE_RATIO) /
                        TOTAL_BIPS;
                    fee = BASE_FEE_BIPS + buyFeeIncrease;
                }
            }
        }

        // Defense-in-depth: Runtime cap at 90% (protects against config errors or future bugs)
        if (fee > 9000) {
            fee = 9000;
        }

        return fee;
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                          FEE TIER MANAGEMENT (ADMIN)                         */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Update base fee (Phase 2 base fee when no spike active)
    /// @param newBaseFee New base fee in bips (e.g., 500 = 5%, 1000 = 10%)
    /// @dev Owner only - changes the floor fee that spikes decay back to
    ///      IMPORTANT: All existing tier feePercent values must be >= newBaseFee
    ///      Consider updating tiers first if lowering base fee below current minimums
    function setBaseFee(uint256 newBaseFee) external {
        if (msg.sender != OWNER) revert OnlyOwner();
        require(newBaseFee >= 100, "Base fee too low"); // Min 1%
        require(newBaseFee <= 1000, "Base fee too high"); // Max 10%
        
        uint256 oldBaseFee = BASE_FEE_BIPS;
        BASE_FEE_BIPS = uint128(newBaseFee);
        
        emit BaseFeeUpdated(oldBaseFee, newBaseFee);
    }

    /// @notice Update a single fee tier
    /// @param index Tier index (0-9)
    /// @param triggerAmount New ETH threshold
    /// @param feePercent New fee percentage in bips
    /// @param decayHours New decay duration in hours
    function updateFeeTier(
        uint256 index,
        uint256 triggerAmount,
        uint256 feePercent,
        uint256 decayHours
    ) external onlyOwnerOrOperator {
        require(index < 10, "Invalid tier index");
        require(triggerAmount > 0, "Zero threshold");
        require(feePercent <= 9000, "Fee too high"); // Max 90%
        require(feePercent >= BASE_FEE_BIPS, "Fee below base"); // Must be >= current base
        require(decayHours > 0 && decayHours <= 24, "Invalid decay");

        feeSpikeTiers[index] = FeeSpike({
            triggerAmount: triggerAmount,
            feePercent: feePercent,
            decayHours: decayHours
        });

        emit FeeTierUpdated(index, triggerAmount, feePercent, decayHours);
    }

    /// @notice Update all fee tiers at once
    /// @param newTiers Array of 10 new tier configurations
    function updateAllFeeTiers(
        FeeSpike[10] calldata newTiers
    ) external onlyOwnerOrOperator {
        for (uint256 i = 0; i < 10; i++) {
            require(newTiers[i].triggerAmount > 0, "Zero threshold");
            require(newTiers[i].feePercent <= 9000, "Fee too high");
            require(newTiers[i].feePercent >= BASE_FEE_BIPS, "Fee below base");
            require(
                newTiers[i].decayHours > 0 && newTiers[i].decayHours <= 24,
                "Invalid decay"
            );

            feeSpikeTiers[i] = newTiers[i];
        }

        emit AllFeeTiersUpdated();
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                              HOOK IMPLEMENTATION                             */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Called before swap to collect fees on BUYS (ETH → MEMS)
    /// @dev Takes dynamic fee from input when users buy MEMS tokens
    function beforeSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        bytes calldata
    )
        external
        override
        onlyPoolManager
        returns (bytes4, BeforeSwapDelta, uint24)
    {
        // ANTI-SNIPE: Block ALL public swaps until strategy trading is enabled
        // This prevents direct PoolManager.unlock() bypass attacks
        // Strategy itself can always swap (for buybacks), owner-controlled addresses can swap
        try IStrategy(STRATEGY).tradingEnabled() returns (bool tradingActive) {
            if (!tradingActive) {
                // Only allow strategy itself and fee-exempt addresses (modules) to swap
                if (sender != address(STRATEGY) && !feeExempt[sender]) {
                    revert TradingNotEnabled();
                }
            }
        } catch {
            // If strategy call fails, assume trading is disabled (fail-safe)
            if (sender != address(STRATEGY) && !feeExempt[sender]) {
                revert TradingNotEnabled();
            }
        }

        // Phase 0: No fees during bundle
        // Strategy buybacks and whitelisted modules bypass fees (no double taxation)
        if (!feesEnabled || sender == address(STRATEGY) || feeExempt[sender]) {
            return (
                IHooks.beforeSwap.selector,
                BeforeSwapDeltaLibrary.ZERO_DELTA,
                0
            );
        }

        // Only collect fee when PUBLIC users BUY MEMS (ETH → MEMS)
        // zeroForOne = true means currency0 (ETH) → currency1 (MEMS)
        if (params.zeroForOne) {
            // Only support exact input swaps (amountSpecified < 0)
            if (params.amountSpecified >= 0) revert ExactOutputNotSupported();

            // User is buying MEMS, take fee from their ETH input
            // Convert negative amountSpecified to positive uint256 for clarity
            uint256 ethInput = uint256(-params.amountSpecified);

            // Calculate dynamic fee
            uint256 buyFeeBips = getCurrentFee(true);
            uint256 totalFeeU256 = (ethInput * buyFeeBips) / TOTAL_BIPS;

            // Defensive check: ensure fee fits in uint128 (practically always true)
            require(totalFeeU256 <= type(uint128).max, "Fee overflow");
            uint128 totalFee = uint128(totalFeeU256);

            // Split 80/20 (ensure sum equals total by calculating rake as remainder)
            uint128 strategyFee = (totalFee * STRATEGY_BIPS) / TOTAL_BIPS;
            uint128 rakeFee = totalFee - strategyFee;

            // Take ETH fee from PoolManager
            POOL_MANAGER.take(key.currency0, address(this), totalFee);

            emit FeeCollected(
                key.currency0,
                totalFee,
                strategyFee,
                rakeFee,
                buyFeeBips
            );

            // Accumulate fees for later flush (no external calls during swap)
            _accumulateStrategyFees(strategyFee);
            _accumulateRake(rakeFee);

            // Return delta - user pays additional ETH as fee
            // Use SafeCast for type conversion safety
            BeforeSwapDelta delta = toBeforeSwapDelta(
                uint256(totalFee).toInt128(),
                0
            );
            return (IHooks.beforeSwap.selector, delta, 0);
        }

        // User selling MEMS → ETH: handled in afterSwap
        return (
            IHooks.beforeSwap.selector,
            BeforeSwapDeltaLibrary.ZERO_DELTA,
            0
        );
    }

    /// @notice Called after swap to collect fees on SELLS (MEMS → ETH)
    /// @dev Takes dynamic fee from output when users sell MEMS tokens
    function afterSwap(
        address sender,
        PoolKey calldata key,
        SwapParams calldata params,
        BalanceDelta delta,
        bytes calldata
    ) external override onlyPoolManager returns (bytes4, int128) {
        // ANTI-SNIPE: Block ALL public swaps until strategy trading is enabled
        // This prevents direct PoolManager.unlock() bypass attacks
        try IStrategy(STRATEGY).tradingEnabled() returns (bool tradingActive) {
            if (!tradingActive) {
                // Only allow strategy itself and fee-exempt addresses (modules) to swap
                if (sender != address(STRATEGY) && !feeExempt[sender]) {
                    revert TradingNotEnabled();
                }
            }
        } catch {
            // If strategy call fails, assume trading is disabled (fail-safe)
            if (sender != address(STRATEGY) && !feeExempt[sender]) {
                revert TradingNotEnabled();
            }
        }

        // Phase 0: No fees during bundle
        // Strategy buybacks and whitelisted modules bypass fees (no double taxation)
        if (!feesEnabled || sender == address(STRATEGY) || feeExempt[sender]) {
            return (IHooks.afterSwap.selector, 0);
        }

        // Only collect fee when PUBLIC users SELL MEMS (MEMS → ETH)
        // zeroForOne = false means currency1 (MEMS) → currency0 (ETH)
        if (!params.zeroForOne) {
            // Only support exact input swaps (amountSpecified < 0)
            if (params.amountSpecified >= 0) revert ExactOutputNotSupported();

            // User is selling MEMS, take fee from their ETH output
            int128 ethOutput = delta.amount0();

            // Verify ETH output is positive (safety check)
            require(ethOutput > 0, "Unexpected negative delta");

            // Convert to uint128 then uint256 for arithmetic
            uint128 ethOut128 = ethOutput.toUint128();
            uint256 ethOut = uint256(ethOut128);

            // Calculate dynamic fee
            uint256 sellFeeBips = getCurrentFee(false);
            uint256 totalFeeU256 = (ethOut * sellFeeBips) / TOTAL_BIPS;

            // Defensive check: ensure fee fits in uint128 (practically always true)
            require(totalFeeU256 <= type(uint128).max, "Fee overflow");
            uint128 totalFee = uint128(totalFeeU256);

            // Split 80/20 (ensure sum equals total by calculating rake as remainder)
            uint128 strategyFee = (totalFee * STRATEGY_BIPS) / TOTAL_BIPS;
            uint128 rakeFee = totalFee - strategyFee;

            // Take ETH fee from PoolManager
            POOL_MANAGER.take(key.currency0, address(this), totalFee);

            emit FeeCollected(
                key.currency0,
                totalFee,
                strategyFee,
                rakeFee,
                sellFeeBips
            );

            // Accumulate fees for later flush (no external calls during swap)
            _accumulateStrategyFees(strategyFee);
            _accumulateRake(rakeFee);

            // Return delta - user receives less ETH (use SafeCast)
            return (IHooks.afterSwap.selector, uint256(totalFee).toInt128());
        }

        // User buying MEMS → ETH: already handled in beforeSwap
        return (IHooks.afterSwap.selector, 0);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                              FEE MANAGEMENT                                  */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Accumulate strategy fees (80% portion) - NO external calls during swap
    /// @dev Deferred settlement pattern: collect now, flush later (best practice for V4 hooks)
    function _accumulateStrategyFees(uint256 amount) internal {
        if (amount == 0) return;
        pendingStrategy += amount;
    }

    /// @notice Accumulate rake fees (20% portion) - NO external calls during swap
    /// @dev Deferred settlement pattern: collect now, flush later (best practice for V4 hooks)
    function _accumulateRake(uint256 amount) internal {
        if (amount == 0) return;
        pendingRake += amount;
    }

    /// @notice Flush accumulated strategy fees to MemeStrategy contract
    /// @dev Operator/Owner only - designed for automated keeper execution
    ///      External calls happen OUTSIDE swap path (keeps swaps deterministic & safe)
    function flushToStrategy() external onlyOwnerOrOperator {
        uint256 amt = pendingStrategy;
        if (amt == 0) return;

        // Reset before transfer (reentrancy guard)
        pendingStrategy = 0;

        // Try to send to strategy
        try IStrategy(STRATEGY).addFeesETH{value: amt}() {
            emit FeesFlushedToStrategy(amt);
        } catch {
            // Restore on failure
            pendingStrategy = amt;
            emit StrategyFlushFailed(amt);
        }
    }

    /// @notice Flush accumulated rake to treasury
    /// @dev Operator/Owner only - designed for automated keeper execution
    ///      External calls happen OUTSIDE swap path (keeps swaps deterministic & safe)
    function flushRake() external onlyOwnerOrOperator {
        uint256 amt = pendingRake;
        if (amt == 0) return;

        // Reset before transfer (reentrancy guard)
        pendingRake = 0;

        // Try to send to treasury with gas limit (protection against malicious treasury)
        (bool success, ) = TREASURY.call{value: amt, gas: 50000}("");

        if (!success) {
            // Restore on failure
            pendingRake = amt;
            emit RakeFlushFailed(amt);
            return;
        }

        emit RakeFlushed(TREASURY, amt);
    }

    /// @notice Flush all pending fees (strategy + rake) in one call
    /// @dev Convenience function for automated keepers
    function flushAllFees() external onlyOwnerOrOperator {
        // Flush strategy first (more important)
        if (pendingStrategy > 0) {
            uint256 stratAmt = pendingStrategy;
            pendingStrategy = 0;

            try IStrategy(STRATEGY).addFeesETH{value: stratAmt}() {
                emit FeesFlushedToStrategy(stratAmt);
            } catch {
                pendingStrategy = stratAmt;
                emit StrategyFlushFailed(stratAmt);
            }
        }

        // Then flush rake
        if (pendingRake > 0) {
            uint256 rakeAmt = pendingRake;
            pendingRake = 0;

            (bool success, ) = TREASURY.call{value: rakeAmt, gas: 50000}("");

            if (!success) {
                pendingRake = rakeAmt;
                emit RakeFlushFailed(rakeAmt);
            } else {
                emit RakeFlushed(TREASURY, rakeAmt);
            }
        }
    }

    /// @notice Get pending fee balances awaiting flush
    /// @dev Returns (pendingStrategy, pendingRake, totalInHook)
    function getPendingFees() external view returns (
        uint256 strategyPending,
        uint256 rakePending,
        uint256 totalBalance
    ) {
        return (pendingStrategy, pendingRake, address(this).balance);
    }

    /// @notice Emergency withdraw ETH from hook (owner only)
    /// @dev Use case: recover stuck ETH from failed deposits or manual sends
    /// @param to Recipient address
    /// @param amount Amount of ETH to withdraw
    function emergencyWithdrawETH(address to, uint256 amount) external {
        if (msg.sender != OWNER) revert OnlyOwner();
        if (to == address(0)) revert InvalidAddress();

        SafeTransferLib.safeTransferETH(to, amount);
        emit EmergencyWithdrawETH(to, amount);
    }

    /// @notice Hook can receive native ETH
    /// @dev Emits Received event for transparency and off-chain tracking
    receive() external payable {
        emit Received(msg.sender, msg.value);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                              VIEW FUNCTIONS                                  */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    /// @notice Get current phase information
    function getPhaseInfo()
        external
        view
        returns (uint8 phase, bool phase2Active, uint256 currentBaseFee)
    {
        phase = phase2Activated ? 2 : 1;
        phase2Active = phase2Activated;
        currentBaseFee = phase2Activated ? BASE_FEE_BIPS : PHASE1_FEE_BIPS;
    }

    /// @notice Get active spike information
    function getSpikeInfo()
        external
        view
        returns (
            bool isActive,
            uint256 currentSellFee,
            uint256 currentBuyFee,
            uint256 timeRemaining,
            uint256 decayProgress
        )
    {
        if (!phase2Activated || currentFeeSpike == 0) {
            return (false, BASE_FEE_BIPS, BASE_FEE_BIPS, 0, 100);
        }

        uint256 elapsed = block.timestamp - feeSpikeTriggerTime;

        if (elapsed >= feeDecayDuration) {
            return (false, BASE_FEE_BIPS, BASE_FEE_BIPS, 0, 100);
        }

        isActive = true;
        currentSellFee = getCurrentFee(false);
        currentBuyFee = getCurrentFee(true);
        timeRemaining = feeDecayDuration - elapsed;
        decayProgress = (elapsed * 100) / feeDecayDuration;
    }

    /// @notice Get tier information for ETH amount
    function getTierForAmount(
        uint256 ethAmount
    ) external view returns (uint256 feePercent, uint256 decayHours) {
        for (uint256 i = feeSpikeTiers.length; i > 0; i--) {
            FeeSpike memory tier = feeSpikeTiers[i - 1];
            if (ethAmount >= tier.triggerAmount) {
                return (tier.feePercent, tier.decayHours);
            }
        }
        // Below minimum tier
        return (BASE_FEE_BIPS, 0);
    }

    /* ═══════════════════════════════════════════════════════════════════════════ */
    /*                      IHOOKS INTERFACE - NOT IMPLEMENTED                      */
    /* ═══════════════════════════════════════════════════════════════════════════ */

    function beforeInitialize(
        address,
        PoolKey calldata,
        uint160
    ) external pure returns (bytes4) {
        revert HookNotImplemented();
    }

    function afterInitialize(
        address,
        PoolKey calldata,
        uint160,
        int24
    ) external pure returns (bytes4) {
        revert HookNotImplemented();
    }

    function beforeAddLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        bytes calldata
    ) external pure returns (bytes4) {
        revert HookNotImplemented();
    }

    function afterAddLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) external pure returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    function beforeRemoveLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        bytes calldata
    ) external pure returns (bytes4) {
        revert HookNotImplemented();
    }

    function afterRemoveLiquidity(
        address,
        PoolKey calldata,
        ModifyLiquidityParams calldata,
        BalanceDelta,
        BalanceDelta,
        bytes calldata
    ) external pure returns (bytes4, BalanceDelta) {
        revert HookNotImplemented();
    }

    // beforeSwap is implemented above

    function beforeDonate(
        address,
        PoolKey calldata,
        uint256,
        uint256,
        bytes calldata
    ) external pure returns (bytes4) {
        revert HookNotImplemented();
    }

    function afterDonate(
        address,
        PoolKey calldata,
        uint256,
        uint256,
        bytes calldata
    ) external pure returns (bytes4) {
        revert HookNotImplemented();
    }
}
Hooks.sol 340 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import {PoolKey} from "../types/PoolKey.sol";
import {IHooks} from "../interfaces/IHooks.sol";
import {SafeCast} from "./SafeCast.sol";
import {LPFeeLibrary} from "./LPFeeLibrary.sol";
import {BalanceDelta, toBalanceDelta, BalanceDeltaLibrary} from "../types/BalanceDelta.sol";
import {BeforeSwapDelta, BeforeSwapDeltaLibrary} from "../types/BeforeSwapDelta.sol";
import {IPoolManager} from "../interfaces/IPoolManager.sol";
import {ModifyLiquidityParams, SwapParams} from "../types/PoolOperation.sol";
import {ParseBytes} from "./ParseBytes.sol";
import {CustomRevert} from "./CustomRevert.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.
library Hooks {
    using LPFeeLibrary for uint24;
    using Hooks for IHooks;
    using SafeCast for int256;
    using BeforeSwapDeltaLibrary for BeforeSwapDelta;
    using ParseBytes for bytes;
    using CustomRevert for bytes4;

    uint160 internal constant ALL_HOOK_MASK = uint160((1 << 14) - 1);

    uint160 internal constant BEFORE_INITIALIZE_FLAG = 1 << 13;
    uint160 internal constant AFTER_INITIALIZE_FLAG = 1 << 12;

    uint160 internal constant BEFORE_ADD_LIQUIDITY_FLAG = 1 << 11;
    uint160 internal constant AFTER_ADD_LIQUIDITY_FLAG = 1 << 10;

    uint160 internal constant BEFORE_REMOVE_LIQUIDITY_FLAG = 1 << 9;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_FLAG = 1 << 8;

    uint160 internal constant BEFORE_SWAP_FLAG = 1 << 7;
    uint160 internal constant AFTER_SWAP_FLAG = 1 << 6;

    uint160 internal constant BEFORE_DONATE_FLAG = 1 << 5;
    uint160 internal constant AFTER_DONATE_FLAG = 1 << 4;

    uint160 internal constant BEFORE_SWAP_RETURNS_DELTA_FLAG = 1 << 3;
    uint160 internal constant AFTER_SWAP_RETURNS_DELTA_FLAG = 1 << 2;
    uint160 internal constant AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 1;
    uint160 internal constant AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG = 1 << 0;

    struct Permissions {
        bool beforeInitialize;
        bool afterInitialize;
        bool beforeAddLiquidity;
        bool afterAddLiquidity;
        bool beforeRemoveLiquidity;
        bool afterRemoveLiquidity;
        bool beforeSwap;
        bool afterSwap;
        bool beforeDonate;
        bool afterDonate;
        bool beforeSwapReturnDelta;
        bool afterSwapReturnDelta;
        bool afterAddLiquidityReturnDelta;
        bool afterRemoveLiquidityReturnDelta;
    }

    /// @notice Thrown if the address will not lead to the specified hook calls being called
    /// @param hooks The address of the hooks contract
    error HookAddressNotValid(address hooks);

    /// @notice Hook did not return its selector
    error InvalidHookResponse();

    /// @notice Additional context for ERC-7751 wrapped error when a hook call fails
    error HookCallFailed();

    /// @notice The hook's delta changed the swap from exactIn to exactOut or vice versa
    error HookDeltaExceedsSwapAmount();

    /// @notice Utility function intended to be used in hook constructors to ensure
    /// the deployed hooks address causes the intended hooks to be called
    /// @param permissions The hooks that are intended to be called
    /// @dev permissions param is memory as the function will be called from constructors
    function validateHookPermissions(IHooks self, Permissions memory permissions) internal pure {
        if (
            permissions.beforeInitialize != self.hasPermission(BEFORE_INITIALIZE_FLAG)
                || permissions.afterInitialize != self.hasPermission(AFTER_INITIALIZE_FLAG)
                || permissions.beforeAddLiquidity != self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)
                || permissions.afterAddLiquidity != self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)
                || permissions.beforeRemoveLiquidity != self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)
                || permissions.afterRemoveLiquidity != self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                || permissions.beforeSwap != self.hasPermission(BEFORE_SWAP_FLAG)
                || permissions.afterSwap != self.hasPermission(AFTER_SWAP_FLAG)
                || permissions.beforeDonate != self.hasPermission(BEFORE_DONATE_FLAG)
                || permissions.afterDonate != self.hasPermission(AFTER_DONATE_FLAG)
                || permissions.beforeSwapReturnDelta != self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterSwapReturnDelta != self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
                || permissions.afterAddLiquidityReturnDelta != self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                || permissions.afterRemoveLiquidityReturnDelta
                    != self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) {
            HookAddressNotValid.selector.revertWith(address(self));
        }
    }

    /// @notice Ensures that the hook address includes at least one hook flag or dynamic fees, or is the 0 address
    /// @param self The hook to verify
    /// @param fee The fee of the pool the hook is used with
    /// @return bool True if the hook address is valid
    function isValidHookAddress(IHooks self, uint24 fee) internal pure returns (bool) {
        // The hook can only have a flag to return a hook delta on an action if it also has the corresponding action flag
        if (!self.hasPermission(BEFORE_SWAP_FLAG) && self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_SWAP_FLAG) && self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)) return false;
        if (!self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG) && self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG))
        {
            return false;
        }
        if (
            !self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)
                && self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
        ) return false;

        // If there is no hook contract set, then fee cannot be dynamic
        // If a hook contract is set, it must have at least 1 flag set, or have a dynamic fee
        return address(self) == address(0)
            ? !fee.isDynamicFee()
            : (uint160(address(self)) & ALL_HOOK_MASK > 0 || fee.isDynamicFee());
    }

    /// @notice performs a hook call using the given calldata on the given hook that doesn't return a delta
    /// @return result The complete data returned by the hook
    function callHook(IHooks self, bytes memory data) internal returns (bytes memory result) {
        bool success;
        assembly ("memory-safe") {
            success := call(gas(), self, 0, add(data, 0x20), mload(data), 0, 0)
        }
        // Revert with FailedHookCall, containing any error message to bubble up
        if (!success) CustomRevert.bubbleUpAndRevertWith(address(self), bytes4(data), HookCallFailed.selector);

        // The call was successful, fetch the returned data
        assembly ("memory-safe") {
            // allocate result byte array from the free memory pointer
            result := mload(0x40)
            // store new free memory pointer at the end of the array padded to 32 bytes
            mstore(0x40, add(result, and(add(returndatasize(), 0x3f), not(0x1f))))
            // store length in memory
            mstore(result, returndatasize())
            // copy return data to result
            returndatacopy(add(result, 0x20), 0, returndatasize())
        }

        // Length must be at least 32 to contain the selector. Check expected selector and returned selector match.
        if (result.length < 32 || result.parseSelector() != data.parseSelector()) {
            InvalidHookResponse.selector.revertWith();
        }
    }

    /// @notice performs a hook call using the given calldata on the given hook
    /// @return int256 The delta returned by the hook
    function callHookWithReturnDelta(IHooks self, bytes memory data, bool parseReturn) internal returns (int256) {
        bytes memory result = callHook(self, data);

        // If this hook wasn't meant to return something, default to 0 delta
        if (!parseReturn) return 0;

        // A length of 64 bytes is required to return a bytes4, and a 32 byte delta
        if (result.length != 64) InvalidHookResponse.selector.revertWith();
        return result.parseReturnDelta();
    }

    /// @notice modifier to prevent calling a hook if they initiated the action
    modifier noSelfCall(IHooks self) {
        if (msg.sender != address(self)) {
            _;
        }
    }

    /// @notice calls beforeInitialize hook if permissioned and validates return value
    function beforeInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96) internal noSelfCall(self) {
        if (self.hasPermission(BEFORE_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeInitialize, (msg.sender, key, sqrtPriceX96)));
        }
    }

    /// @notice calls afterInitialize hook if permissioned and validates return value
    function afterInitialize(IHooks self, PoolKey memory key, uint160 sqrtPriceX96, int24 tick)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_INITIALIZE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterInitialize, (msg.sender, key, sqrtPriceX96, tick)));
        }
    }

    /// @notice calls beforeModifyLiquidity hook if permissioned and validates return value
    function beforeModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        ModifyLiquidityParams memory params,
        bytes calldata hookData
    ) internal noSelfCall(self) {
        if (params.liquidityDelta > 0 && self.hasPermission(BEFORE_ADD_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeAddLiquidity, (msg.sender, key, params, hookData)));
        } else if (params.liquidityDelta <= 0 && self.hasPermission(BEFORE_REMOVE_LIQUIDITY_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeRemoveLiquidity, (msg.sender, key, params, hookData)));
        }
    }

    /// @notice calls afterModifyLiquidity hook if permissioned and validates return value
    function afterModifyLiquidity(
        IHooks self,
        PoolKey memory key,
        ModifyLiquidityParams memory params,
        BalanceDelta delta,
        BalanceDelta feesAccrued,
        bytes calldata hookData
    ) internal returns (BalanceDelta callerDelta, BalanceDelta hookDelta) {
        if (msg.sender == address(self)) return (delta, BalanceDeltaLibrary.ZERO_DELTA);

        callerDelta = delta;
        if (params.liquidityDelta > 0) {
            if (self.hasPermission(AFTER_ADD_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterAddLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_ADD_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        } else {
            if (self.hasPermission(AFTER_REMOVE_LIQUIDITY_FLAG)) {
                hookDelta = BalanceDelta.wrap(
                    self.callHookWithReturnDelta(
                        abi.encodeCall(
                            IHooks.afterRemoveLiquidity, (msg.sender, key, params, delta, feesAccrued, hookData)
                        ),
                        self.hasPermission(AFTER_REMOVE_LIQUIDITY_RETURNS_DELTA_FLAG)
                    )
                );
                callerDelta = callerDelta - hookDelta;
            }
        }
    }

    /// @notice calls beforeSwap hook if permissioned and validates return value
    function beforeSwap(IHooks self, PoolKey memory key, SwapParams memory params, bytes calldata hookData)
        internal
        returns (int256 amountToSwap, BeforeSwapDelta hookReturn, uint24 lpFeeOverride)
    {
        amountToSwap = params.amountSpecified;
        if (msg.sender == address(self)) return (amountToSwap, BeforeSwapDeltaLibrary.ZERO_DELTA, lpFeeOverride);

        if (self.hasPermission(BEFORE_SWAP_FLAG)) {
            bytes memory result = callHook(self, abi.encodeCall(IHooks.beforeSwap, (msg.sender, key, params, hookData)));

            // A length of 96 bytes is required to return a bytes4, a 32 byte delta, and an LP fee
            if (result.length != 96) InvalidHookResponse.selector.revertWith();

            // dynamic fee pools that want to override the cache fee, return a valid fee with the override flag. If override flag
            // is set but an invalid fee is returned, the transaction will revert. Otherwise the current LP fee will be used
            if (key.fee.isDynamicFee()) lpFeeOverride = result.parseFee();

            // skip this logic for the case where the hook return is 0
            if (self.hasPermission(BEFORE_SWAP_RETURNS_DELTA_FLAG)) {
                hookReturn = BeforeSwapDelta.wrap(result.parseReturnDelta());

                // any return in unspecified is passed to the afterSwap hook for handling
                int128 hookDeltaSpecified = hookReturn.getSpecifiedDelta();

                // Update the swap amount according to the hook's return, and check that the swap type doesn't change (exact input/output)
                if (hookDeltaSpecified != 0) {
                    bool exactInput = amountToSwap < 0;
                    amountToSwap += hookDeltaSpecified;
                    if (exactInput ? amountToSwap > 0 : amountToSwap < 0) {
                        HookDeltaExceedsSwapAmount.selector.revertWith();
                    }
                }
            }
        }
    }

    /// @notice calls afterSwap hook if permissioned and validates return value
    function afterSwap(
        IHooks self,
        PoolKey memory key,
        SwapParams memory params,
        BalanceDelta swapDelta,
        bytes calldata hookData,
        BeforeSwapDelta beforeSwapHookReturn
    ) internal returns (BalanceDelta, BalanceDelta) {
        if (msg.sender == address(self)) return (swapDelta, BalanceDeltaLibrary.ZERO_DELTA);

        int128 hookDeltaSpecified = beforeSwapHookReturn.getSpecifiedDelta();
        int128 hookDeltaUnspecified = beforeSwapHookReturn.getUnspecifiedDelta();

        if (self.hasPermission(AFTER_SWAP_FLAG)) {
            hookDeltaUnspecified += self.callHookWithReturnDelta(
                abi.encodeCall(IHooks.afterSwap, (msg.sender, key, params, swapDelta, hookData)),
                self.hasPermission(AFTER_SWAP_RETURNS_DELTA_FLAG)
            ).toInt128();
        }

        BalanceDelta hookDelta;
        if (hookDeltaUnspecified != 0 || hookDeltaSpecified != 0) {
            hookDelta = (params.amountSpecified < 0 == params.zeroForOne)
                ? toBalanceDelta(hookDeltaSpecified, hookDeltaUnspecified)
                : toBalanceDelta(hookDeltaUnspecified, hookDeltaSpecified);

            // the caller has to pay for (or receive) the hook's delta
            swapDelta = swapDelta - hookDelta;
        }
        return (swapDelta, hookDelta);
    }

    /// @notice calls beforeDonate hook if permissioned and validates return value
    function beforeDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(BEFORE_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.beforeDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    /// @notice calls afterDonate hook if permissioned and validates return value
    function afterDonate(IHooks self, PoolKey memory key, uint256 amount0, uint256 amount1, bytes calldata hookData)
        internal
        noSelfCall(self)
    {
        if (self.hasPermission(AFTER_DONATE_FLAG)) {
            self.callHook(abi.encodeCall(IHooks.afterDonate, (msg.sender, key, amount0, amount1, hookData)));
        }
    }

    function hasPermission(IHooks self, uint160 flag) internal pure returns (bool) {
        return uint160(address(self)) & flag != 0;
    }
}
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;
}
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;
}
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)));
    }
}
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));
    }
}
SafeTransferLib.sol 683 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

/// @notice Safe ETH and ERC20 transfer library that gracefully handles missing return values.
/// @author Solady (https://github.com/vectorized/solady/blob/main/src/utils/SafeTransferLib.sol)
/// @author Modified from Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/SafeTransferLib.sol)
/// @author Permit2 operations from (https://github.com/Uniswap/permit2/blob/main/src/libraries/Permit2Lib.sol)
///
/// @dev Note:
/// - For ETH transfers, please use `forceSafeTransferETH` for DoS protection.
library SafeTransferLib {
    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       CUSTOM ERRORS                        */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev The ETH transfer has failed.
    error ETHTransferFailed();

    /// @dev The ERC20 `transferFrom` has failed.
    error TransferFromFailed();

    /// @dev The ERC20 `transfer` has failed.
    error TransferFailed();

    /// @dev The ERC20 `approve` has failed.
    error ApproveFailed();

    /// @dev The ERC20 `totalSupply` query has failed.
    error TotalSupplyQueryFailed();

    /// @dev The Permit2 operation has failed.
    error Permit2Failed();

    /// @dev The Permit2 amount must be less than `2**160 - 1`.
    error Permit2AmountOverflow();

    /// @dev The Permit2 approve operation has failed.
    error Permit2ApproveFailed();

    /// @dev The Permit2 lockdown operation has failed.
    error Permit2LockdownFailed();

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                         CONSTANTS                          */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Suggested gas stipend for contract receiving ETH that disallows any storage writes.
    uint256 internal constant GAS_STIPEND_NO_STORAGE_WRITES = 2300;

    /// @dev Suggested gas stipend for contract receiving ETH to perform a few
    /// storage reads and writes, but low enough to prevent griefing.
    uint256 internal constant GAS_STIPEND_NO_GRIEF = 100000;

    /// @dev The unique EIP-712 domain separator for the DAI token contract.
    bytes32 internal constant DAI_DOMAIN_SEPARATOR =
        0xdbb8cf42e1ecb028be3f3dbc922e1d878b963f411dc388ced501601c60f7c6f7;

    /// @dev The address for the WETH9 contract on Ethereum mainnet.
    address internal constant WETH9 = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;

    /// @dev The canonical Permit2 address.
    /// [Github](https://github.com/Uniswap/permit2)
    /// [Etherscan](https://etherscan.io/address/0x000000000022D473030F116dDEE9F6B43aC78BA3)
    address internal constant PERMIT2 = 0x000000000022D473030F116dDEE9F6B43aC78BA3;

    /// @dev The canonical address of the `SELFDESTRUCT` ETH mover.
    /// See: https://gist.github.com/Vectorized/1cb8ad4cf393b1378e08f23f79bd99fa
    /// [Etherscan](https://etherscan.io/address/0x00000000000073c48c8055bD43D1A53799176f0D)
    address internal constant ETH_MOVER = 0x00000000000073c48c8055bD43D1A53799176f0D;

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                       ETH OPERATIONS                       */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    // If the ETH transfer MUST succeed with a reasonable gas budget, use the force variants.
    //
    // The regular variants:
    // - Forwards all remaining gas to the target.
    // - Reverts if the target reverts.
    // - Reverts if the current contract has insufficient balance.
    //
    // The force variants:
    // - Forwards with an optional gas stipend
    //   (defaults to `GAS_STIPEND_NO_GRIEF`, which is sufficient for most cases).
    // - If the target reverts, or if the gas stipend is exhausted,
    //   creates a temporary contract to force send the ETH via `SELFDESTRUCT`.
    //   Future compatible with `SENDALL`: https://eips.ethereum.org/EIPS/eip-4758.
    // - Reverts if the current contract has insufficient balance.
    //
    // The try variants:
    // - Forwards with a mandatory gas stipend.
    // - Instead of reverting, returns whether the transfer succeeded.

    /// @dev Sends `amount` (in wei) ETH to `to`.
    function safeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gas(), to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`.
    function safeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // Transfer all the ETH and check if it succeeded or not.
            if iszero(call(gas(), to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function forceSafeTransferETH(address to, uint256 amount, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function forceSafeTransferAllETH(address to, uint256 gasStipend) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if iszero(call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends `amount` (in wei) ETH to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferETH(address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            if lt(selfbalance(), amount) {
                mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                revert(0x1c, 0x04)
            }
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, amount, codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(amount, 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Force sends all the ETH in the current contract to `to`, with `GAS_STIPEND_NO_GRIEF`.
    function forceSafeTransferAllETH(address to) internal {
        /// @solidity memory-safe-assembly
        assembly {
            // forgefmt: disable-next-item
            if iszero(call(GAS_STIPEND_NO_GRIEF, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)) {
                mstore(0x00, to) // Store the address in scratch space.
                mstore8(0x0b, 0x73) // Opcode `PUSH20`.
                mstore8(0x20, 0xff) // Opcode `SELFDESTRUCT`.
                if iszero(create(selfbalance(), 0x0b, 0x16)) { revert(codesize(), codesize()) } // For gas estimation.
            }
        }
    }

    /// @dev Sends `amount` (in wei) ETH to `to`, with a `gasStipend`.
    function trySafeTransferETH(address to, uint256 amount, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, amount, codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Sends all the ETH in the current contract to `to`, with a `gasStipend`.
    function trySafeTransferAllETH(address to, uint256 gasStipend)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            success := call(gasStipend, to, selfbalance(), codesize(), 0x00, codesize(), 0x00)
        }
    }

    /// @dev Force transfers ETH to `to`, without triggering the fallback (if any).
    /// This method attempts to use a separate contract to send via `SELFDESTRUCT`,
    /// and upon failure, deploys a minimal vault to accrue the ETH.
    function safeMoveETH(address to, uint256 amount) internal returns (address vault) {
        /// @solidity memory-safe-assembly
        assembly {
            to := shr(96, shl(96, to)) // Clean upper 96 bits.
            for { let mover := ETH_MOVER } iszero(eq(to, address())) {} {
                let selfBalanceBefore := selfbalance()
                if or(lt(selfBalanceBefore, amount), eq(to, mover)) {
                    mstore(0x00, 0xb12d13eb) // `ETHTransferFailed()`.
                    revert(0x1c, 0x04)
                }
                if extcodesize(mover) {
                    let balanceBefore := balance(to) // Check via delta, in case `SELFDESTRUCT` is bricked.
                    mstore(0x00, to)
                    pop(call(gas(), mover, amount, 0x00, 0x20, codesize(), 0x00))
                    // If `address(to).balance >= amount + balanceBefore`, skip vault workflow.
                    if iszero(lt(balance(to), add(amount, balanceBefore))) { break }
                    // Just in case `SELFDESTRUCT` is changed to not revert and do nothing.
                    if lt(selfBalanceBefore, selfbalance()) { invalid() }
                }
                let m := mload(0x40)
                // If the mover is missing or bricked, deploy a minimal vault
                // that withdraws all ETH to `to` when being called only by `to`.
                // forgefmt: disable-next-item
                mstore(add(m, 0x20), 0x33146025575b600160005260206000f35b3d3d3d3d47335af1601a5760003dfd)
                mstore(m, or(to, shl(160, 0x6035600b3d3960353df3fe73)))
                // Compute and store the bytecode hash.
                mstore8(0x00, 0xff) // Write the prefix.
                mstore(0x35, keccak256(m, 0x40))
                mstore(0x01, shl(96, address())) // Deployer.
                mstore(0x15, 0) // Salt.
                vault := keccak256(0x00, 0x55)
                pop(call(gas(), vault, amount, codesize(), 0x00, codesize(), 0x00))
                // The vault returns a single word on success. Failure reverts with empty data.
                if iszero(returndatasize()) {
                    if iszero(create2(0, m, 0x40, 0)) { revert(codesize(), codesize()) } // For gas estimation.
                }
                mstore(0x40, m) // Restore the free memory pointer.
                break
            }
        }
    }

    /*´:°•.°+.*•´.*:˚.°*.˚•´.°:°•.°•.*•´.*:˚.°*.˚•´.°:°•.°+.*•´.*:*/
    /*                      ERC20 OPERATIONS                      */
    /*.•°:°.´+˚.*°.˚:*.´•*.+°.•°:´*.´•*.•°.•°:°.´:•˚°.*°.˚:*.´+°.•*/

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for
    /// the current contract to manage.
    function safeTransferFrom(address token, address from, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function trySafeTransferFrom(address token, address from, address to, uint256 amount)
        internal
        returns (bool success)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x60, amount) // Store the `amount` argument.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x23b872dd000000000000000000000000) // `transferFrom(address,address,uint256)`.
            success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                success := lt(or(iszero(extcodesize(token)), returndatasize()), success)
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends all of ERC20 `token` from `from` to `to`.
    /// Reverts upon failure.
    ///
    /// The `from` account must have their entire balance approved for the current contract to manage.
    function safeTransferAllFrom(address token, address from, address to)
        internal
        returns (uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40) // Cache the free memory pointer.
            mstore(0x40, to) // Store the `to` argument.
            mstore(0x2c, shl(96, from)) // Store the `from` argument.
            mstore(0x0c, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x60, 0x20)
                )
            ) {
                mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x00, 0x23b872dd) // `transferFrom(address,address,uint256)`.
            amount := mload(0x60) // The `amount` is already at 0x60. We'll need to return it.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x1c, 0x64, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x7939f424) // `TransferFromFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x60, 0) // Restore the zero slot to zero.
            mstore(0x40, m) // Restore the free memory pointer.
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransfer(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sends all of ERC20 `token` from the current contract to `to`.
    /// Reverts upon failure.
    function safeTransferAll(address token, address to) internal returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x70a08231) // Store the function selector of `balanceOf(address)`.
            mstore(0x20, address()) // Store the address of the current contract.
            // Read the balance, reverting upon failure.
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x1c, 0x24, 0x34, 0x20)
                )
            ) {
                mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                revert(0x1c, 0x04)
            }
            mstore(0x14, to) // Store the `to` argument.
            amount := mload(0x34) // The `amount` is already at 0x34. We'll need to return it.
            mstore(0x00, 0xa9059cbb000000000000000000000000) // `transfer(address,uint256)`.
            // Perform the transfer, reverting upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x90b8ec18) // `TransferFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// Reverts upon failure.
    function safeApprove(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                    revert(0x1c, 0x04)
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Sets `amount` of ERC20 `token` for `to` to manage on behalf of the current contract.
    /// If the initial attempt to approve fails, attempts to reset the approved amount to zero,
    /// then retries the approval again (some tokens, e.g. USDT, requires this).
    /// Reverts upon failure.
    function safeApproveWithRetry(address token, address to, uint256 amount) internal {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, to) // Store the `to` argument.
            mstore(0x34, amount) // Store the `amount` argument.
            mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
            // Perform the approval, retrying upon failure.
            let success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
            if iszero(and(eq(mload(0x00), 1), success)) {
                if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                    mstore(0x34, 0) // Store 0 for the `amount`.
                    mstore(0x00, 0x095ea7b3000000000000000000000000) // `approve(address,uint256)`.
                    pop(call(gas(), token, 0, 0x10, 0x44, codesize(), 0x00)) // Reset the approval.
                    mstore(0x34, amount) // Store back the original `amount`.
                    // Retry the approval, reverting upon failure.
                    success := call(gas(), token, 0, 0x10, 0x44, 0x00, 0x20)
                    if iszero(and(eq(mload(0x00), 1), success)) {
                        // Check the `extcodesize` again just in case the token selfdestructs lol.
                        if iszero(lt(or(iszero(extcodesize(token)), returndatasize()), success)) {
                            mstore(0x00, 0x3e3f8f73) // `ApproveFailed()`.
                            revert(0x1c, 0x04)
                        }
                    }
                }
            }
            mstore(0x34, 0) // Restore the part of the free memory pointer that was overwritten.
        }
    }

    /// @dev Returns the amount of ERC20 `token` owned by `account`.
    /// Returns zero if the `token` does not exist.
    function balanceOf(address token, address account) internal view returns (uint256 amount) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            amount :=
                mul( // The arguments of `mul` are evaluated from right to left.
                    mload(0x20),
                    and( // The arguments of `and` are evaluated from right to left.
                        gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                        staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                    )
                )
        }
    }

    /// @dev Performs a `token.balanceOf(account)` check.
    /// `implemented` denotes whether the `token` does not implement `balanceOf`.
    /// `amount` is zero if the `token` does not implement `balanceOf`.
    function checkBalanceOf(address token, address account)
        internal
        view
        returns (bool implemented, uint256 amount)
    {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x14, account) // Store the `account` argument.
            mstore(0x00, 0x70a08231000000000000000000000000) // `balanceOf(address)`.
            implemented :=
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x1f), // At least 32 bytes returned.
                    staticcall(gas(), token, 0x10, 0x24, 0x20, 0x20)
                )
            amount := mul(mload(0x20), implemented)
        }
    }

    /// @dev Returns the total supply of the `token`.
    /// Reverts if the token does not exist or does not implement `totalSupply()`.
    function totalSupply(address token) internal view returns (uint256 result) {
        /// @solidity memory-safe-assembly
        assembly {
            mstore(0x00, 0x18160ddd) // `totalSupply()`.
            if iszero(
                and(gt(returndatasize(), 0x1f), staticcall(gas(), token, 0x1c, 0x04, 0x00, 0x20))
            ) {
                mstore(0x00, 0x54cd9435) // `TotalSupplyQueryFailed()`.
                revert(0x1c, 0x04)
            }
            result := mload(0x00)
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to`.
    /// If the initial attempt fails, try to use Permit2 to transfer the token.
    /// Reverts upon failure.
    ///
    /// The `from` account must have at least `amount` approved for the current contract to manage.
    function safeTransferFrom2(address token, address from, address to, uint256 amount) internal {
        if (!trySafeTransferFrom(token, from, to, amount)) {
            permit2TransferFrom(token, from, to, amount);
        }
    }

    /// @dev Sends `amount` of ERC20 `token` from `from` to `to` via Permit2.
    /// Reverts upon failure.
    function permit2TransferFrom(address token, address from, address to, uint256 amount)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(add(m, 0x74), shr(96, shl(96, token)))
            mstore(add(m, 0x54), amount)
            mstore(add(m, 0x34), to)
            mstore(add(m, 0x20), shl(96, from))
            // `transferFrom(address,address,uint160,address)`.
            mstore(m, 0x36c78516000000000000000000000000)
            let p := PERMIT2
            let exists := eq(chainid(), 1)
            if iszero(exists) { exists := iszero(iszero(extcodesize(p))) }
            if iszero(
                and(
                    call(gas(), p, 0, add(m, 0x10), 0x84, codesize(), 0x00),
                    lt(iszero(extcodesize(token)), exists) // Token has code and Permit2 exists.
                )
            ) {
                mstore(0x00, 0x7939f4248757f0fd) // `TransferFromFailed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(iszero(shr(160, amount))))), 0x04)
            }
        }
    }

    /// @dev Permit a user to spend a given amount of
    /// another user's tokens via native EIP-2612 permit if possible, falling
    /// back to Permit2 if native permit fails or is not implemented on the token.
    function permit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        bool success;
        /// @solidity memory-safe-assembly
        assembly {
            for {} shl(96, xor(token, WETH9)) {} {
                mstore(0x00, 0x3644e515) // `DOMAIN_SEPARATOR()`.
                if iszero(
                    and( // The arguments of `and` are evaluated from right to left.
                        lt(iszero(mload(0x00)), eq(returndatasize(), 0x20)), // Returns 1 non-zero word.
                        // Gas stipend to limit gas burn for tokens that don't refund gas when
                        // an non-existing function is called. 5K should be enough for a SLOAD.
                        staticcall(5000, token, 0x1c, 0x04, 0x00, 0x20)
                    )
                ) { break }
                // After here, we can be sure that token is a contract.
                let m := mload(0x40)
                mstore(add(m, 0x34), spender)
                mstore(add(m, 0x20), shl(96, owner))
                mstore(add(m, 0x74), deadline)
                if eq(mload(0x00), DAI_DOMAIN_SEPARATOR) {
                    mstore(0x14, owner)
                    mstore(0x00, 0x7ecebe00000000000000000000000000) // `nonces(address)`.
                    mstore(
                        add(m, 0x94),
                        lt(iszero(amount), staticcall(gas(), token, 0x10, 0x24, add(m, 0x54), 0x20))
                    )
                    mstore(m, 0x8fcbaf0c000000000000000000000000) // `IDAIPermit.permit`.
                    // `nonces` is already at `add(m, 0x54)`.
                    // `amount != 0` is already stored at `add(m, 0x94)`.
                    mstore(add(m, 0xb4), and(0xff, v))
                    mstore(add(m, 0xd4), r)
                    mstore(add(m, 0xf4), s)
                    success := call(gas(), token, 0, add(m, 0x10), 0x104, codesize(), 0x00)
                    break
                }
                mstore(m, 0xd505accf000000000000000000000000) // `IERC20Permit.permit`.
                mstore(add(m, 0x54), amount)
                mstore(add(m, 0x94), and(0xff, v))
                mstore(add(m, 0xb4), r)
                mstore(add(m, 0xd4), s)
                success := call(gas(), token, 0, add(m, 0x10), 0xe4, codesize(), 0x00)
                break
            }
        }
        if (!success) simplePermit2(token, owner, spender, amount, deadline, v, r, s);
    }

    /// @dev Simple permit on the Permit2 contract.
    function simplePermit2(
        address token,
        address owner,
        address spender,
        uint256 amount,
        uint256 deadline,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0x927da105) // `allowance(address,address,address)`.
            {
                let addressMask := shr(96, not(0))
                mstore(add(m, 0x20), and(addressMask, owner))
                mstore(add(m, 0x40), and(addressMask, token))
                mstore(add(m, 0x60), and(addressMask, spender))
                mstore(add(m, 0xc0), and(addressMask, spender))
            }
            let p := mul(PERMIT2, iszero(shr(160, amount)))
            if iszero(
                and( // The arguments of `and` are evaluated from right to left.
                    gt(returndatasize(), 0x5f), // Returns 3 words: `amount`, `expiration`, `nonce`.
                    staticcall(gas(), p, add(m, 0x1c), 0x64, add(m, 0x60), 0x60)
                )
            ) {
                mstore(0x00, 0x6b836e6b8757f0fd) // `Permit2Failed()` or `Permit2AmountOverflow()`.
                revert(add(0x18, shl(2, iszero(p))), 0x04)
            }
            mstore(m, 0x2b67b570) // `Permit2.permit` (PermitSingle variant).
            // `owner` is already `add(m, 0x20)`.
            // `token` is already at `add(m, 0x40)`.
            mstore(add(m, 0x60), amount)
            mstore(add(m, 0x80), 0xffffffffffff) // `expiration = type(uint48).max`.
            // `nonce` is already at `add(m, 0xa0)`.
            // `spender` is already at `add(m, 0xc0)`.
            mstore(add(m, 0xe0), deadline)
            mstore(add(m, 0x100), 0x100) // `signature` offset.
            mstore(add(m, 0x120), 0x41) // `signature` length.
            mstore(add(m, 0x140), r)
            mstore(add(m, 0x160), s)
            mstore(add(m, 0x180), shl(248, v))
            if iszero( // Revert if token does not have code, or if the call fails.
            mul(extcodesize(token), call(gas(), p, 0, add(m, 0x1c), 0x184, codesize(), 0x00))) {
                mstore(0x00, 0x6b836e6b) // `Permit2Failed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Approves `spender` to spend `amount` of `token` for `address(this)`.
    function permit2Approve(address token, address spender, uint160 amount, uint48 expiration)
        internal
    {
        /// @solidity memory-safe-assembly
        assembly {
            let addressMask := shr(96, not(0))
            let m := mload(0x40)
            mstore(m, 0x87517c45) // `approve(address,address,uint160,uint48)`.
            mstore(add(m, 0x20), and(addressMask, token))
            mstore(add(m, 0x40), and(addressMask, spender))
            mstore(add(m, 0x60), and(addressMask, amount))
            mstore(add(m, 0x80), and(0xffffffffffff, expiration))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x324f14ae) // `Permit2ApproveFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }

    /// @dev Revokes an approval for `token` and `spender` for `address(this)`.
    function permit2Lockdown(address token, address spender) internal {
        /// @solidity memory-safe-assembly
        assembly {
            let m := mload(0x40)
            mstore(m, 0xcc53287f) // `Permit2.lockdown`.
            mstore(add(m, 0x20), 0x20) // Offset of the `approvals`.
            mstore(add(m, 0x40), 1) // `approvals.length`.
            mstore(add(m, 0x60), shr(96, shl(96, token)))
            mstore(add(m, 0x80), shr(96, shl(96, spender)))
            if iszero(call(gas(), PERMIT2, 0, add(m, 0x1c), 0xa0, codesize(), 0x00)) {
                mstore(0x00, 0x96b3de23) // `Permit2LockdownFailed()`.
                revert(0x1c, 0x04)
            }
        }
    }
}
LPFeeLibrary.sol 79 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

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

/// @notice Library of helper functions for a pools LP fee
library LPFeeLibrary {
    using LPFeeLibrary for uint24;
    using CustomRevert for bytes4;

    /// @notice Thrown when the static or dynamic fee on a pool exceeds 100%.
    error LPFeeTooLarge(uint24 fee);

    /// @notice An lp fee of exactly 0b1000000... signals a dynamic fee pool. This isn't a valid static fee as it is > MAX_LP_FEE
    uint24 public constant DYNAMIC_FEE_FLAG = 0x800000;

    /// @notice the second bit of the fee returned by beforeSwap is used to signal if the stored LP fee should be overridden in this swap
    // only dynamic-fee pools can return a fee via the beforeSwap hook
    uint24 public constant OVERRIDE_FEE_FLAG = 0x400000;

    /// @notice mask to remove the override fee flag from a fee returned by the beforeSwaphook
    uint24 public constant REMOVE_OVERRIDE_MASK = 0xBFFFFF;

    /// @notice the lp fee is represented in hundredths of a bip, so the max is 100%
    uint24 public constant MAX_LP_FEE = 1000000;

    /// @notice returns true if a pool's LP fee signals that the pool has a dynamic fee
    /// @param self The fee to check
    /// @return bool True of the fee is dynamic
    function isDynamicFee(uint24 self) internal pure returns (bool) {
        return self == DYNAMIC_FEE_FLAG;
    }

    /// @notice returns true if an LP fee is valid, aka not above the maximum permitted fee
    /// @param self The fee to check
    /// @return bool True of the fee is valid
    function isValid(uint24 self) internal pure returns (bool) {
        return self <= MAX_LP_FEE;
    }

    /// @notice validates whether an LP fee is larger than the maximum, and reverts if invalid
    /// @param self The fee to validate
    function validate(uint24 self) internal pure {
        if (!self.isValid()) LPFeeTooLarge.selector.revertWith(self);
    }

    /// @notice gets and validates the initial LP fee for a pool. Dynamic fee pools have an initial fee of 0.
    /// @dev if a dynamic fee pool wants a non-0 initial fee, it should call `updateDynamicLPFee` in the afterInitialize hook
    /// @param self The fee to get the initial LP from
    /// @return initialFee 0 if the fee is dynamic, otherwise the fee (if valid)
    function getInitialLPFee(uint24 self) internal pure returns (uint24) {
        // the initial fee for a dynamic fee pool is 0
        if (self.isDynamicFee()) return 0;
        self.validate();
        return self;
    }

    /// @notice returns true if the fee has the override flag set (2nd highest bit of the uint24)
    /// @param self The fee to check
    /// @return bool True of the fee has the override flag set
    function isOverride(uint24 self) internal pure returns (bool) {
        return self & OVERRIDE_FEE_FLAG != 0;
    }

    /// @notice returns a fee with the override flag removed
    /// @param self The fee to remove the override flag from
    /// @return fee The fee without the override flag set
    function removeOverrideFlag(uint24 self) internal pure returns (uint24) {
        return self & REMOVE_OVERRIDE_MASK;
    }

    /// @notice Removes the override flag and validates the fee (reverts if the fee is too large)
    /// @param self The fee to remove the override flag from, and then validate
    /// @return fee The fee without the override flag set (if valid)
    function removeOverrideFlagAndValidate(uint24 self) internal pure returns (uint24 fee) {
        fee = self.removeOverrideFlag();
        fee.validate();
    }
}
ParseBytes.sol 29 lines
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.0;

/// @notice Parses bytes returned from hooks and the byte selector used to check return selectors from hooks.
/// @dev parseSelector also is used to parse the expected selector
/// For parsing hook returns, note that all hooks return either bytes4 or (bytes4, 32-byte-delta) or (bytes4, 32-byte-delta, uint24).
library ParseBytes {
    function parseSelector(bytes memory result) internal pure returns (bytes4 selector) {
        // equivalent: (selector,) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            selector := mload(add(result, 0x20))
        }
    }

    function parseFee(bytes memory result) internal pure returns (uint24 lpFee) {
        // equivalent: (,, lpFee) = abi.decode(result, (bytes4, int256, uint24));
        assembly ("memory-safe") {
            lpFee := mload(add(result, 0x60))
        }
    }

    function parseReturnDelta(bytes memory result) internal pure returns (int256 hookReturn) {
        // equivalent: (, hookReturnDelta) = abi.decode(result, (bytes4, int256));
        assembly ("memory-safe") {
            hookReturn := mload(add(result, 0x40))
        }
    }
}
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))
        }
    }
}
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);
}
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);
}
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)
        }
    }
}
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);
}
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);
}

Read Contract

BASE_FEE_BIPS 0xe0efe95c → uint128
BUY_SPIKE_RATIO 0x7f779adf → uint128
ETH_CURRENCY 0x9d934e1b → address
OWNER 0x117803e3 → address
PHASE1_FEE_BIPS 0x644f849e → uint128
POOL_MANAGER 0x62308e85 → address
RAKE_BIPS 0x54d82ebc → uint128
STRATEGY 0x185025ef → address
STRATEGY_BIPS 0x416677a5 → uint128
TOTAL_BIPS 0x7dc63812 → uint128
TREASURY 0x2d2c5565 → address
afterAddLiquidity 0xbc29bafc → bytes4, int256
afterDonate 0x1f29cf9d → bytes4
afterInitialize 0xb6d4944a → bytes4
afterRemoveLiquidity 0x606e8192 → bytes4, int256
beforeAddLiquidity 0xb772b8cc → bytes4
beforeDonate 0xd950bd74 → bytes4
beforeInitialize 0xebe1cdaf → bytes4
beforeRemoveLiquidity 0x5cb32d10 → bytes4
currentFeeSpike 0x1e0d8c3d → uint256
feeDecayDuration 0x52f58d87 → uint256
feeExempt 0x398daa85 → bool
feeSpikeTiers 0x69e10ac1 → uint256, uint256, uint256
feeSpikeTriggerTime 0xab814d6b → uint256
feesEnabled 0xa64e4f8a → bool
getCurrentFee 0xde4b5c5b → uint256
getPendingFees 0xc51c2d0e → uint256, uint256, uint256
getPhaseInfo 0xa6f8e722 → uint8, bool, uint256
getSpikeInfo 0x94071145 → bool, uint256, uint256, uint256, uint256
getTierForAmount 0x1237739b → uint256, uint256
operators 0x13e7c9d8 → bool
pendingRake 0xde90055a → uint256
pendingStrategy 0x465fc5d2 → uint256
phase2Activated 0xb7cbae87 → bool

Write Contract 20 functions

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

activatePhase2 0xa15467e0
uint256 initialSpikeAmount
addOperator 0x9870d7fe
address operator
afterSwap 0xc13d1c69
address sender
tuple key
tuple params
int256 delta
bytes
returns: bytes4, int128
beforeSwap 0x468ead2c
address sender
tuple key
tuple params
bytes
returns: bytes4, int256, uint24
disableFees 0xce404b23
No parameters
emergencyWithdrawETH 0xd79e8567
address to
uint256 amount
enableFees 0x368f5bd5
No parameters
flushAllFees 0x1004e0c5
No parameters
flushRake 0x0014ac03
No parameters
flushToStrategy 0xf7658820
No parameters
notifyFirstSale 0x92ddc510
uint256 saleAmount
removeOperator 0xac8a584a
address operator
renounceOwnership 0x715018a6
No parameters
setBaseFee 0x46860698
uint256 newBaseFee
setFeeExemption 0x751fd179
address account
bool exempt
setStrategy 0x33a100ca
address newStrategy
setTreasury 0xf0f44260
address newTreasury
triggerFeeSpike 0x19a1ccbb
uint256 saleAmount
updateAllFeeTiers 0x9be6c42b
tuple[10] newTiers
updateFeeTier 0xa5f408b4
uint256 index
uint256 triggerAmount
uint256 feePercent
uint256 decayHours

Recent Transactions

No transactions found for this address