Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0x2A73e899389cABa2a2f648BaBA35e67f5C00EFee
Balance 0 ETH
Nonce 69
Code Size 15400 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

15400 bytes
0x60806040526004361015610011575f80fd5b5f3560e01c80630b5af9f8146103e25780631bdfe053146103785780632d9a4a9d14610365578063451d27b8146101865780638ca06ea614610118578063ca6ec89a146100d6578063e233c366146100995763e54f48df14610071575f80fd5b3461009557602061008d61008436610592565b929190916108a4565b604051908152f35b5f80fd5b34610095576100aa61008436610592565b5f526001602052602073ffffffffffffffffffffffffffffffffffffffff60405f205416604051908152f35b34610095576100ed6100e736610527565b91610814565b5f525f602052602073ffffffffffffffffffffffffffffffffffffffff60405f205416604051908152f35b34610095575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261009557602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000009a9fa8338dd5e5b2188006f1cd2ef26d921650c2168152f35b346100955761019436610592565b926101a1848385846108a4565b93845f52600160205273ffffffffffffffffffffffffffffffffffffffff60405f20541661033d576101d384836106b5565b604051611b438082019082821067ffffffffffffffff83111761031057838688878695610204956120b08839610860565b03905ff080156103055773ffffffffffffffffffffffffffffffffffffffff1693855f52600160205260405f2073ffffffffffffffffffffffffffffffffffffffff86167fffffffffffffffffffffffff000000000000000000000000000000000000000082541617905560028410156102d857606073ffffffffffffffffffffffffffffffffffffffff63ffffffff7f0c00ff77242aa7973d8bb5cb73ecc1733bf615b0aaf967a50c2b7672f9110da3936020998360405197168752898b880152604087015216941692a4604051908152f35b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b6040513d5f823e3d90fd5b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b7f63ed5285000000000000000000000000000000000000000000000000000000005f5260045ffd5b3461009557602061008d6100e736610527565b346100955760407ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100955760043573ffffffffffffffffffffffffffffffffffffffff811681036100955760243563ffffffff81168103610095576103e0916106b5565b005b34610095576103f036610527565b6103fd8183859495610814565b91825f525f60205273ffffffffffffffffffffffffffffffffffffffff60405f20541661033d5761042e84826106b5565b6040516117f180820182811067ffffffffffffffff8211176103105784878561045d9386956108bf873961062b565b03905ff080156103055773ffffffffffffffffffffffffffffffffffffffff1692805f525f60205260405f2073ffffffffffffffffffffffffffffffffffffffff85167fffffffffffffffffffffffff000000000000000000000000000000000000000082541617905560028310156102d8577f1f9e05a536e40324537d577d17a8b32d1d2a2894f53cce4c730bc82235d6ab58604073ffffffffffffffffffffffffffffffffffffffff63ffffffff6020988351958987528a87015216941692a4604051908152f35b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc60609101126100955760043573ffffffffffffffffffffffffffffffffffffffff81168103610095579060243563ffffffff81168103610095579060443560028110156100955790565b7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc60809101126100955760043573ffffffffffffffffffffffffffffffffffffffff81168103610095579060243563ffffffff8116810361009557906044356002811015610095579060643573ffffffffffffffffffffffffffffffffffffffff811681036100955790565b9060028210156102d85752565b60409063ffffffff610665949695939673ffffffffffffffffffffffffffffffffffffffff6060840198168352166020820152019061061e565b565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff82111761031057604052565b5190811515820361009557565b9063ffffffff9073ffffffffffffffffffffffffffffffffffffffff604051937f873e960000000000000000000000000000000000000000000000000000000000855216600484015216602482015260608160448173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000009a9fa8338dd5e5b2188006f1cd2ef26d921650c2165afa908115610305575f5f915f936107b9575b5061078957501561076157565b7f39db717e000000000000000000000000000000000000000000000000000000005f5260045ffd5b61ffff907f80b1d95f000000000000000000000000000000000000000000000000000000005f521660045260245ffd5b925050506060813d60601161080c575b816107d660609383610667565b81010312610095576107e7816106a8565b60208201519161ffff8316830361009557604061080491016106a8565b91905f610754565b3d91506107c9565b919061085a9061082e60405193849260208401968761062b565b037fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe08101835282610667565b51902090565b929361089e73ffffffffffffffffffffffffffffffffffffffff92969563ffffffff60609585608089019a168852166020870152604086019061061e565b16910152565b929061082e61085a9260405194859360208501978861086056fe6101608060405234610106576060816117f18038038091610020828561010a565b8339810103126101065761003381610141565b9060208101519063ffffffff82168203610106576040015160028110156101065760ff61007e61007761008593868496336080528160a05260c0528160e052610185565b9416610155565b9216610155565b6101205261010052610095610368565b6101405260405161143090816103c1823960805181610193015260a05181818161027d0152610d72015260c0518181816104d80152610d94015260e0518161052c0152610100518181816104420152610e220152610120518181816101260152610e4901526101405181610db50152f35b5f80fd5b601f909101601f19168101906001600160401b0382119082101761012d57604052565b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b038216820361010657565b604d811161016357600a0a90565b634e487b7160e01b5f52601160045260245ffd5b519060ff8216820361010657565b604051630b2339af60e21b81529192915f91829190606090829060049082906001600160a01b03165afa9081156102b1575f916102fd575b5060405163313ce56760e01b81526001600160a01b039190911694602082600481895afa9182156102b1575f926102bc575b50606060049660405197888092630a40bee560e41b82525afa9586156102b1575f9661025b575b506002811015610247576001810361023057505050508190565b5f9591929493955015610241575050565b93509150565b634e487b7160e01b5f52602160045260245ffd5b9095506060813d6060116102a9575b816102776060938361010a565b81010312610106576002815110156101065760408161029b60206102a29401610141565b5001610177565b945f610216565b3d915061026a565b6040513d5f823e3d90fd5b9591506020863d6020116102f5575b816102d86020938361010a565b810103126101065760606102ed600497610177565b9296506101ef565b3d91506102cb565b90506060813d606011610360575b816103186060938361010a565b81010312610106578051906001600160a01b03821682036101065760208101516001600160a01b0381160361010657604001516001600160a01b03811603610106575f6101bd565b3d915061030b565b60e0516002811015610247578061037f5750600290565b60010361038b57600190565b60405162461bcd60e51b815260206004820152600d60248201526c1b9bdd081cdd5c1c1bdc9d1959609a1b6044820152606490fdfe6080806040526004361015610012575f80fd5b5f3560e01c9081630aa33a24146104fc5750806326d895451461049e578063313ce567146104655780634ae5fa9b1461040d57806354fd4d50146103d45780637284e416146102a157806380f55605146102335780639a6fc8f5146101b7578063c45a015514610149578063ee81d997146100f15763feaf968c14610095575f80fd5b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed5760a06100cd610d5b565b604051905f825260208201525f60408201524260608201525f6080820152f35b5f80fd5b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed5760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed57602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346100ed5760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed5760043569ffffffffffffffffffff81168091036100ed5761020b5760a06100cd610d5b565b7fbfbe031f000000000000000000000000000000000000000000000000000000005f5260045ffd5b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed57602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed576040516060810181811067ffffffffffffffff8211176103a757604052602281527f50656e646c6520436861696e6c696e6b2d636f6d70617469626c65204f72616360208201527f6c6500000000000000000000000000000000000000000000000000000000000060408201526040519060208252818151918260208301525f5b83811061038f5750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f835f604080968601015201168101030190f35b60208282018101516040878401015285935001610350565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed57602060405160018152f35b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed5760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed57602060405160128152f35b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed57602060405163ffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346100ed575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126100ed577f000000000000000000000000000000000000000000000000000000000000000090600282101561055c576020918152f35b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b8181029291811591840414171561059c57565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b81156105d3570490565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b9061060a826106b1565b9081811061062057505061061d91610a04565b90565b610631610636929361061d95610a04565b610589565b6105c9565b610644816106b1565b909190808310610661575061061d9261065c91610a04565b610d30565b915061061d9261065c91610a04565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff8211176103a757604052565b90606073ffffffffffffffffffffffffffffffffffffffff926004604051809581937f2c8ce6bc000000000000000000000000000000000000000000000000000000008352165afa9182156108c0575f905f9361096e575b50602073ffffffffffffffffffffffffffffffffffffffff916004604051809481937f3ba0b9a9000000000000000000000000000000000000000000000000000000008352165afa9081156108c0575f9161093c575b5073ffffffffffffffffffffffffffffffffffffffff81931690604051917fd2a3584e000000000000000000000000000000000000000000000000000000008352602083600481845afa9283156108c0575f93610908575b50604051907f516399df000000000000000000000000000000000000000000000000000000008252602082600481845afa9182156108c0575f926108cb575b5081610819575b5015610807575090565b9080821115610814575090565b905090565b60049150602090604051928380927f60e0a9e10000000000000000000000000000000000000000000000000000000082525afa9081156108c0575f91610875575b506fffffffffffffffffffffffffffffffff1643145f6107fd565b90506020813d6020116108b8575b8161089060209383610670565b810103126100ed57516fffffffffffffffffffffffffffffffff811681036100ed575f61085a565b3d9150610883565b6040513d5f823e3d90fd5b9091506020813d602011610900575b816108e760209383610670565b810103126100ed575180151581036100ed57905f6107f6565b3d91506108da565b9092506020813d602011610934575b8161092460209383610670565b810103126100ed5751915f6107b7565b3d9150610917565b90506020813d602011610966575b8161095760209383610670565b810103126100ed57515f61075f565b3d915061094a565b9250506060823d6060116109fc575b8161098a60609383610670565b810103126100ed5781519173ffffffffffffffffffffffffffffffffffffffff831683036100ed57602081015173ffffffffffffffffffffffffffffffffffffffff8116036100ed57604001519173ffffffffffffffffffffffffffffffffffffffff831683036100ed576020610709565b3d915061097d565b73ffffffffffffffffffffffffffffffffffffffff16604051907fe184c9be000000000000000000000000000000000000000000000000000000008252602082600481845afa9182156108c0575f92610cfc575b50428211610a6f57505050670de0b6b3a764000090565b60405190610a7e606083610670565b600282526020820191604036843763ffffffff610a9a82610eae565b95168095526040519283917f883bdbfd000000000000000000000000000000000000000000000000000000008352602483019060206004850152518091526044830191905f5b818110610cdd575050509181805f9403915afa9081156108c0575f91610c1d575b50805160011015610bf0577affffffffffffffffffffffffffffffffffffffffffffffffffffff610b388160408401511692610eae565b511690037affffffffffffffffffffffffffffffffffffffffffffffffffffff811161059c5782156105d35742820391821161059c57610b98927affffffffffffffffffffffffffffffffffffffffffffffffffffff8092160416610589565b6301e1338090047f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81116100ed57610bcf90610f3a565b5f81126100ed5780156105d3576ec097ce7bc90715b34b9f10000000000490565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b90503d805f833e610c2e8183610670565b8101906020818303126100ed5780519067ffffffffffffffff82116100ed570181601f820112156100ed5780519167ffffffffffffffff83116103a7578260051b916020830193610c826040519586610670565b84526020808501938201019182116100ed57602001915b818310610ca9575050505f610b01565b82517affffffffffffffffffffffffffffffffffffffffffffffffffffff811681036100ed57815260209283019201610c99565b825163ffffffff16845286945060209384019390920191600101610ae0565b9091506020813d602011610d28575b81610d1860209383610670565b810103126100ed5751905f610a58565b3d9150610d0b565b90670de0b6b3a7640000820291808304670de0b6b3a7640000149015171561059c5761061d916105c9565b73ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000167f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000080600114610e9857600214610e10577f4e487b71000000000000000000000000000000000000000000000000000000005f52605160045260245ffd5b610e20610e4791610e6e9361063b565b7f000000000000000000000000000000000000000000000000000000000000000090610589565b7f0000000000000000000000000000000000000000000000000000000000000000906105c9565b7f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff81116100ed5790565b50610ea9610e4791610e6e93610600565b610e20565b805115610bf05760200190565b15610ec257565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f496e76616c6964206578706f6e656e74000000000000000000000000000000006044820152fd5b80156105d3576ec097ce7bc90715b34b9f10000000000590565b7ffffffffffffffffffffffffffffffffffffffffffffffffdc702bd3a30fc0000811215806113e7575b610f6d90610ebb565b5f81126113d35761061d906806f05b59d3b2000000811261137c577ffffffffffffffffffffffffffffffffffffffffffffffff90fa4a62c4e000000016111456064770195e54c5dd42177f53a27172fa9ec630262827000000000925b0268056bc75e2d631000009068ad78ebc5ac62000000811215611343575b6856bc75e2d6310000008112156112f9575b682b5e3af16b188000008112156112b1575b6815af1d78b58c400000811215611269575b680ad78ebc5ac6200000811215611222575b68056bc75e2d631000008112156111db575b6802b5e3af16b1880000811215611194575b68015af1d78b58c4000081121561114d575b600268056bc75e2d631000008280020505600368056bc75e2d631000008383020505600468056bc75e2d631000008483020505600568056bc75e2d631000008583020505600668056bc75e2d631000008683020505600768056bc75e2d63100000878302050590600868056bc75e2d63100000888402050592600968056bc75e2d6310000089860205059468056bc75e2d63100000600a8a88028290050597600b68056bc75e2d631000008c8b02050599600c68056bc75e2d631000008d8d0205059b0101010101010101010101010268056bc75e2d63100000900590565b026064900590565b6806f5f17757889379377ffffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c000061118e9201920268056bc75e2d63100000900590565b90611066565b6808f00f760a4b2db55d7ffffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800006111d59201920268056bc75e2d63100000900590565b90611054565b680ebc5fb417461211107ffffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf0000061121c9201920268056bc75e2d63100000900590565b90611042565b68280e60114edb805d037ffffffffffffffffffffffffffffffffffffffffffffffff5287143a539e000006112639201920268056bc75e2d63100000900590565b90611030565b690127fa27722cc06cc5e27fffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c000006112ab9201920268056bc75e2d63100000900590565b9061101e565b693f1fce3da636ea5cf8507fffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e78000006112f39201920268056bc75e2d63100000900590565b9061100c565b6b02df0ab5a80a22c61ab5a7007fffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf00000061133d9201920268056bc75e2d63100000900590565b90610ffa565b6e01855144814a7ff805980ff008400091507fffffffffffffffffffffffffffffffffffffffffffffff5287143a539e00000001610fe8565b6803782dace9d900000081126113c6577ffffffffffffffffffffffffffffffffffffffffffffffffc87d25316270000000161114560646b1425982cf597cd205cef738092610fca565b6111456064600192610fca565b6113de905f03610f3a565b61061d90610f20565b5068070c1cc73b00c80000811315610f6456fea2646970667358221220e03ad7d4459225a4606885e8d874eb777e6871727c57469b68f82ecb4ec6637e64736f6c634300081b00336101a0806040523461018a57608081611b43803803809161002082856101e7565b83398101031261018a576100338161021e565b602082015163ffffffff8116810361018a57604083015191600283101561018a5761009560ff61008e6100876020968395610072606060049b0161021e565b97336080528160a05260c0528160e05261024e565b9416610240565b9216610240565b61012052610100526100a5610426565b6101405261016081905260405163313ce56760e01b815292839182906001600160a01b03165afa80156101dc575f906101a2575b60ff915016604d811161018e57600a0a6001600160ff1b03811161018a57610180526040516116c4908161047f8239608051816101c7015260a0518181816102b20152610853015260c05181818161057b0152610875015260e05181610627015261010051818181610477015261090301526101205181818161015a015261092a0152610140518161089601526101605181818161051d01526108070152610180518181816105d401526109b30152f35b5f80fd5b634e487b7160e01b5f52601160045260245ffd5b506020813d6020116101d4575b816101bc602093836101e7565b8101031261018a576101cf60ff91610232565b6100d9565b3d91506101af565b6040513d5f823e3d90fd5b601f909101601f19168101906001600160401b0382119082101761020a57604052565b634e487b7160e01b5f52604160045260245ffd5b51906001600160a01b038216820361018a57565b519060ff8216820361018a57565b604d811161018e57600a0a90565b604051630b2339af60e21b81529192915f91829190606090829060049082906001600160a01b03165afa9081156101dc575f916103bb575b5060405163313ce56760e01b81526001600160a01b039190911694602082600481895afa9182156101dc575f9261037a575b50606060049660405197888092630a40bee560e41b82525afa9586156101dc575f96610324575b50600281101561031057600181036102f957505050508190565b5f959192949395501561030a575050565b93509150565b634e487b7160e01b5f52602160045260245ffd5b9095506060813d606011610372575b81610340606093836101e7565b8101031261018a5760028151101561018a57604081610364602061036b940161021e565b5001610232565b945f6102df565b3d9150610333565b9591506020863d6020116103b3575b81610396602093836101e7565b8101031261018a5760606103ab600497610232565b9296506102b8565b3d9150610389565b90506060813d60601161041e575b816103d6606093836101e7565b8101031261018a578051906001600160a01b038216820361018a5760208101516001600160a01b0381160361018a57604001516001600160a01b0381160361018a575f610286565b3d91506103c9565b60e0516002811015610310578061043d5750600290565b60010361044957600190565b60405162461bcd60e51b815260206004820152600d60248201526c1b9bdd081cdd5c1c1bdc9d1959609a1b6044820152606490fdfe6080806040526004361015610012575f80fd5b5f3560e01c9081630aa33a24146105f757508063172009a61461059f57806326d8954514610541578063289d77cc146104d3578063313ce5671461049a5780634ae5fa9b1461044257806354fd4d50146104095780637284e416146102d657806380f55605146102685780639a6fc8f5146101eb578063c45a01551461017d578063ee81d997146101255763feaf968c146100ab575f80fd5b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101215761011d6100e46107c3565b6040805169ffffffffffffffffffff968716815260208101959095528401929092526060830152909116608082015290819060a0820190565b0390f35b5f80fd5b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101215760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261012157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b346101215760207ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101215760043569ffffffffffffffffffff8116809103610121576102405761011d6100e46107c3565b7fbfbe031f000000000000000000000000000000000000000000000000000000005f5260045ffd5b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261012157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610121576040516060810181811067ffffffffffffffff8211176103dc57604052602281527f50656e646c6520436861696e6c696e6b2d636f6d70617469626c65204f72616360208201527f6c6500000000000000000000000000000000000000000000000000000000000060408201526040519060208252818151918260208301525f5b8381106103c45750507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f835f604080968601015201168101030190f35b60208282018101516040878401015285935001610385565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52604160045260245ffd5b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261012157602060405160018152f35b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101215760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261012157602060405160128152f35b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261012157602060405173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc36011261012157602060405163ffffffff7f0000000000000000000000000000000000000000000000000000000000000000168152f35b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc3601126101215760206040517f00000000000000000000000000000000000000000000000000000000000000008152f35b34610121575f7ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc360112610121577f0000000000000000000000000000000000000000000000000000000000000000906002821015610657576020918152f35b7f4e487b71000000000000000000000000000000000000000000000000000000005f52602160045260245ffd5b8181029291811591840414171561069757565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601160045260245ffd5b81156106ce570490565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52601260045260245ffd5b9061070582610aa3565b9081811061071b57505061071891610deb565b90565b61072c610731929361071895610deb565b610684565b6106c4565b61073f81610aa3565b90919080831061075c57506107189261075791610deb565b611117565b91506107189261075791610deb565b90601f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0910116810190811067ffffffffffffffff8211176103dc57604052565b519069ffffffffffffffffffff8216820361012157565b604051907ffeaf968c00000000000000000000000000000000000000000000000000000000825260a08260048173ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000165afa908115610a98575f925f92610a42575b505f9273ffffffffffffffffffffffffffffffffffffffff7f0000000000000000000000000000000000000000000000000000000000000000167f00000000000000000000000000000000000000000000000000000000000000007f000000000000000000000000000000000000000000000000000000000000000080600114610a2c576002146108f1577f4e487b71000000000000000000000000000000000000000000000000000000005f52605160045260245ffd5b6109016109289161094f93610736565b7f000000000000000000000000000000000000000000000000000000000000000090610684565b7f0000000000000000000000000000000000000000000000000000000000000000906106c4565b7f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff811161012157818102917f800000000000000000000000000000000000000000000000000000000000000081145f831216610697578183051490151715610697577f00000000000000000000000000000000000000000000000000000000000000009081156106ce577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff82147f80000000000000000000000000000000000000000000000000000000000000008214166106975705915f915f90565b50610a3d6109289161094f936106fb565b610901565b9250905060a0823d60a011610a90575b81610a5f60a0938361076b565b8101031261012157610a70826107ac565b506020820151610a876080606085015194016107ac565b5091905f610839565b3d9150610a52565b6040513d5f823e3d90fd5b90606073ffffffffffffffffffffffffffffffffffffffff926004604051809581937f2c8ce6bc000000000000000000000000000000000000000000000000000000008352165afa918215610a98575f905f93610d55575b50602073ffffffffffffffffffffffffffffffffffffffff916004604051809481937f3ba0b9a9000000000000000000000000000000000000000000000000000000008352165afa908115610a98575f91610d23575b5073ffffffffffffffffffffffffffffffffffffffff81931690604051917fd2a3584e000000000000000000000000000000000000000000000000000000008352602083600481845afa928315610a98575f93610cef575b50604051907f516399df000000000000000000000000000000000000000000000000000000008252602082600481845afa918215610a98575f92610cb2575b5081610c0b575b5015610bf9575090565b9080821115610c06575090565b905090565b60049150602090604051928380927f60e0a9e10000000000000000000000000000000000000000000000000000000082525afa908115610a98575f91610c67575b506fffffffffffffffffffffffffffffffff1643145f610bef565b90506020813d602011610caa575b81610c826020938361076b565b8101031261012157516fffffffffffffffffffffffffffffffff81168103610121575f610c4c565b3d9150610c75565b9091506020813d602011610ce7575b81610cce6020938361076b565b810103126101215751801515810361012157905f610be8565b3d9150610cc1565b9092506020813d602011610d1b575b81610d0b6020938361076b565b810103126101215751915f610ba9565b3d9150610cfe565b90506020813d602011610d4d575b81610d3e6020938361076b565b8101031261012157515f610b51565b3d9150610d31565b9250506060823d606011610de3575b81610d716060938361076b565b810103126101215781519173ffffffffffffffffffffffffffffffffffffffff8316830361012157602081015173ffffffffffffffffffffffffffffffffffffffff81160361012157604001519173ffffffffffffffffffffffffffffffffffffffff83168303610121576020610afb565b3d9150610d64565b73ffffffffffffffffffffffffffffffffffffffff16604051907fe184c9be000000000000000000000000000000000000000000000000000000008252602082600481845afa918215610a98575f926110e3575b50428211610e5657505050670de0b6b3a764000090565b60405190610e6560608361076b565b600282526020820191604036843763ffffffff610e8182611142565b95168095526040519283917f883bdbfd000000000000000000000000000000000000000000000000000000008352602483019060206004850152518091526044830191905f5b8181106110c4575050509181805f9403915afa908115610a98575f91611004575b50805160011015610fd7577affffffffffffffffffffffffffffffffffffffffffffffffffffff610f1f8160408401511692611142565b511690037affffffffffffffffffffffffffffffffffffffffffffffffffffff81116106975782156106ce5742820391821161069757610f7f927affffffffffffffffffffffffffffffffffffffffffffffffffffff8092160416610684565b6301e1338090047f7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff811161012157610fb6906111ce565b5f81126101215780156106ce576ec097ce7bc90715b34b9f10000000000490565b7f4e487b71000000000000000000000000000000000000000000000000000000005f52603260045260245ffd5b90503d805f833e611015818361076b565b8101906020818303126101215780519067ffffffffffffffff8211610121570181601f820112156101215780519167ffffffffffffffff83116103dc578260051b916020830193611069604051958661076b565b845260208085019382010191821161012157602001915b818310611090575050505f610ee8565b82517affffffffffffffffffffffffffffffffffffffffffffffffffffff8116810361012157815260209283019201611080565b825163ffffffff16845286945060209384019390920191600101610ec7565b9091506020813d60201161110f575b816110ff6020938361076b565b810103126101215751905f610e3f565b3d91506110f2565b90670de0b6b3a7640000820291808304670de0b6b3a7640000149015171561069757610718916106c4565b805115610fd75760200190565b1561115657565b60646040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601060248201527f496e76616c6964206578706f6e656e74000000000000000000000000000000006044820152fd5b80156106ce576ec097ce7bc90715b34b9f10000000000590565b7ffffffffffffffffffffffffffffffffffffffffffffffffdc702bd3a30fc00008112158061167b575b6112019061114f565b5f811261166757610718906806f05b59d3b20000008112611610577ffffffffffffffffffffffffffffffffffffffffffffffff90fa4a62c4e000000016113d96064770195e54c5dd42177f53a27172fa9ec630262827000000000925b0268056bc75e2d631000009068ad78ebc5ac620000008112156115d7575b6856bc75e2d63100000081121561158d575b682b5e3af16b18800000811215611545575b6815af1d78b58c4000008112156114fd575b680ad78ebc5ac62000008112156114b6575b68056bc75e2d6310000081121561146f575b6802b5e3af16b1880000811215611428575b68015af1d78b58c400008112156113e1575b600268056bc75e2d631000008280020505600368056bc75e2d631000008383020505600468056bc75e2d631000008483020505600568056bc75e2d631000008583020505600668056bc75e2d631000008683020505600768056bc75e2d63100000878302050590600868056bc75e2d63100000888402050592600968056bc75e2d6310000089860205059468056bc75e2d63100000600a8a88028290050597600b68056bc75e2d631000008c8b02050599600c68056bc75e2d631000008d8d0205059b0101010101010101010101010268056bc75e2d63100000900590565b026064900590565b6806f5f17757889379377ffffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c00006114229201920268056bc75e2d63100000900590565b906112fa565b6808f00f760a4b2db55d7ffffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e7800006114699201920268056bc75e2d63100000900590565b906112e8565b680ebc5fb417461211107ffffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf000006114b09201920268056bc75e2d63100000900590565b906112d6565b68280e60114edb805d037ffffffffffffffffffffffffffffffffffffffffffffffff5287143a539e000006114f79201920268056bc75e2d63100000900590565b906112c4565b690127fa27722cc06cc5e27fffffffffffffffffffffffffffffffffffffffffffffffea50e2874a73c0000061153f9201920268056bc75e2d63100000900590565b906112b2565b693f1fce3da636ea5cf8507fffffffffffffffffffffffffffffffffffffffffffffffd4a1c50e94e78000006115879201920268056bc75e2d63100000900590565b906112a0565b6b02df0ab5a80a22c61ab5a7007fffffffffffffffffffffffffffffffffffffffffffffffa9438a1d29cf0000006115d19201920268056bc75e2d63100000900590565b9061128e565b6e01855144814a7ff805980ff008400091507fffffffffffffffffffffffffffffffffffffffffffffff5287143a539e0000000161127c565b6803782dace9d9000000811261165a577ffffffffffffffffffffffffffffffffffffffffffffffffc87d2531627000000016113d960646b1425982cf597cd205cef73809261125e565b6113d9606460019261125e565b611672905f036111ce565b610718906111b4565b5068070c1cc73b00c800008113156111f856fea2646970667358221220db2ecd3ee882e3d20b069a55e4f58330ab5ebfeb5a49b684c38c682e3bf50f8e64736f6c634300081b0033a2646970667358221220a70227712fb2f6e55f53287eabf2e75e3a4f25ba8a8c1be97c72bdb0b7617ba264736f6c634300081b0033

Verified Source Code Full Match

Compiler: v0.8.27+commit.40a35a09 EVM: shanghai Optimization: Yes (1000000 runs)
AggregatorV3Interface.sol 32 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface AggregatorV3Interface {
  function decimals() external view returns (uint8);

  function description() external view returns (string memory);

  function version() external view returns (uint256);

  function getRoundData(uint80 _roundId)
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );

  function latestRoundData()
    external
    view
    returns (
      uint80 roundId,
      int256 answer,
      uint256 startedAt,
      uint256 updatedAt,
      uint80 answeredInRound
    );
}
IERC20Metadata.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

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

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @dev Emitted when `value` tokens are moved from one account (`from`) to
     * another (`to`).
     *
     * Note that `value` may be zero.
     */
    event Transfer(address indexed from, address indexed to, uint256 value);

    /**
     * @dev Emitted when the allowance of a `spender` for an `owner` is set by
     * a call to {approve}. `value` is the new allowance.
     */
    event Approval(address indexed owner, address indexed spender, uint256 value);

    /**
     * @dev Returns the amount of tokens in existence.
     */
    function totalSupply() external view returns (uint256);

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

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

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

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

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
Errors.sol 182 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

library Errors {
    // BulkSeller
    error BulkInsufficientSyForTrade(uint256 currentAmount, uint256 requiredAmount);
    error BulkInsufficientTokenForTrade(uint256 currentAmount, uint256 requiredAmount);
    error BulkInSufficientSyOut(uint256 actualSyOut, uint256 requiredSyOut);
    error BulkInSufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut);
    error BulkInsufficientSyReceived(uint256 actualBalance, uint256 requiredBalance);
    error BulkNotMaintainer();
    error BulkNotAdmin();
    error BulkSellerAlreadyExisted(address token, address SY, address bulk);
    error BulkSellerInvalidToken(address token, address SY);
    error BulkBadRateTokenToSy(uint256 actualRate, uint256 currentRate, uint256 eps);
    error BulkBadRateSyToToken(uint256 actualRate, uint256 currentRate, uint256 eps);

    // APPROX
    error ApproxFail();
    error ApproxParamsInvalid(uint256 guessMin, uint256 guessMax, uint256 eps);
    error ApproxBinarySearchInputInvalid(
        uint256 approxGuessMin,
        uint256 approxGuessMax,
        uint256 minGuessMin,
        uint256 maxGuessMax
    );

    // MARKET + MARKET MATH CORE
    error MarketExpired();
    error MarketZeroAmountsInput();
    error MarketZeroAmountsOutput();
    error MarketZeroLnImpliedRate();
    error MarketInsufficientPtForTrade(int256 currentAmount, int256 requiredAmount);
    error MarketInsufficientPtReceived(uint256 actualBalance, uint256 requiredBalance);
    error MarketInsufficientSyReceived(uint256 actualBalance, uint256 requiredBalance);
    error MarketZeroTotalPtOrTotalAsset(int256 totalPt, int256 totalAsset);
    error MarketExchangeRateBelowOne(int256 exchangeRate);
    error MarketProportionMustNotEqualOne();
    error MarketRateScalarBelowZero(int256 rateScalar);
    error MarketScalarRootBelowZero(int256 scalarRoot);
    error MarketProportionTooHigh(int256 proportion, int256 maxProportion);

    error OracleUninitialized();
    error OracleTargetTooOld(uint32 target, uint32 oldest);
    error OracleZeroCardinality();

    error MarketFactoryExpiredPt();
    error MarketFactoryInvalidPt();
    error MarketFactoryMarketExists();

    error MarketFactoryLnFeeRateRootTooHigh(uint80 lnFeeRateRoot, uint256 maxLnFeeRateRoot);
    error MarketFactoryOverriddenFeeTooHigh(uint80 overriddenFee, uint256 marketLnFeeRateRoot);
    error MarketFactoryReserveFeePercentTooHigh(uint8 reserveFeePercent, uint8 maxReserveFeePercent);
    error MarketFactoryZeroTreasury();
    error MarketFactoryInitialAnchorTooLow(int256 initialAnchor, int256 minInitialAnchor);
    error MFNotPendleMarket(address addr);

    // ROUTER
    error RouterInsufficientLpOut(uint256 actualLpOut, uint256 requiredLpOut);
    error RouterInsufficientSyOut(uint256 actualSyOut, uint256 requiredSyOut);
    error RouterInsufficientPtOut(uint256 actualPtOut, uint256 requiredPtOut);
    error RouterInsufficientYtOut(uint256 actualYtOut, uint256 requiredYtOut);
    error RouterInsufficientPYOut(uint256 actualPYOut, uint256 requiredPYOut);
    error RouterInsufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut);
    error RouterInsufficientSyRepay(uint256 actualSyRepay, uint256 requiredSyRepay);
    error RouterInsufficientPtRepay(uint256 actualPtRepay, uint256 requiredPtRepay);
    error RouterNotAllSyUsed(uint256 netSyDesired, uint256 netSyUsed);

    error RouterTimeRangeZero();
    error RouterCallbackNotPendleMarket(address caller);
    error RouterInvalidAction(bytes4 selector);
    error RouterInvalidFacet(address facet);

    error RouterKyberSwapDataZero();

    error SimulationResults(bool success, bytes res);

    // YIELD CONTRACT
    error YCExpired();
    error YCNotExpired();
    error YieldContractInsufficientSy(uint256 actualSy, uint256 requiredSy);
    error YCNothingToRedeem();
    error YCPostExpiryDataNotSet();
    error YCNoFloatingSy();

    // YieldFactory
    error YCFactoryInvalidExpiry();
    error YCFactoryYieldContractExisted();
    error YCFactoryZeroExpiryDivisor();
    error YCFactoryZeroTreasury();
    error YCFactoryInterestFeeRateTooHigh(uint256 interestFeeRate, uint256 maxInterestFeeRate);
    error YCFactoryRewardFeeRateTooHigh(uint256 newRewardFeeRate, uint256 maxRewardFeeRate);

    // SY
    error SYInvalidTokenIn(address token);
    error SYInvalidTokenOut(address token);
    error SYZeroDeposit();
    error SYZeroRedeem();
    error SYInsufficientSharesOut(uint256 actualSharesOut, uint256 requiredSharesOut);
    error SYInsufficientTokenOut(uint256 actualTokenOut, uint256 requiredTokenOut);

    // SY-specific
    error SYQiTokenMintFailed(uint256 errCode);
    error SYQiTokenRedeemFailed(uint256 errCode);
    error SYQiTokenRedeemRewardsFailed(uint256 rewardAccruedType0, uint256 rewardAccruedType1);
    error SYQiTokenBorrowRateTooHigh(uint256 borrowRate, uint256 borrowRateMax);

    error SYCurveInvalidPid();
    error SYCurve3crvPoolNotFound();

    error SYApeDepositAmountTooSmall(uint256 amountDeposited);
    error SYBalancerInvalidPid();
    error SYInvalidRewardToken(address token);

    error SYStargateRedeemCapExceeded(uint256 amountLpDesired, uint256 amountLpRedeemable);

    error SYBalancerReentrancy();

    error NotFromTrustedRemote(uint16 srcChainId, bytes path);

    error ApxETHNotEnoughBuffer();

    // Liquidity Mining
    error VCInactivePool(address pool);
    error VCPoolAlreadyActive(address pool);
    error VCZeroVePendle(address user);
    error VCExceededMaxWeight(uint256 totalWeight, uint256 maxWeight);
    error VCEpochNotFinalized(uint256 wTime);
    error VCPoolAlreadyAddAndRemoved(address pool);

    error VEInvalidNewExpiry(uint256 newExpiry);
    error VEExceededMaxLockTime();
    error VEInsufficientLockTime();
    error VENotAllowedReduceExpiry();
    error VEZeroAmountLocked();
    error VEPositionNotExpired();
    error VEZeroPosition();
    error VEZeroSlope(uint128 bias, uint128 slope);
    error VEReceiveOldSupply(uint256 msgTime);

    error GCNotPendleMarket(address caller);
    error GCNotVotingController(address caller);

    error InvalidWTime(uint256 wTime);
    error ExpiryInThePast(uint256 expiry);
    error ChainNotSupported(uint256 chainId);

    error FDTotalAmountFundedNotMatch(uint256 actualTotalAmount, uint256 expectedTotalAmount);
    error FDEpochLengthMismatch();
    error FDInvalidPool(address pool);
    error FDPoolAlreadyExists(address pool);
    error FDInvalidNewFinishedEpoch(uint256 oldFinishedEpoch, uint256 newFinishedEpoch);
    error FDInvalidStartEpoch(uint256 startEpoch);
    error FDInvalidWTimeFund(uint256 lastFunded, uint256 wTime);
    error FDFutureFunding(uint256 lastFunded, uint256 currentWTime);

    error BDInvalidEpoch(uint256 epoch, uint256 startTime);

    // Cross-Chain
    error MsgNotFromSendEndpoint(uint16 srcChainId, bytes path);
    error MsgNotFromReceiveEndpoint(address sender);
    error InsufficientFeeToSendMsg(uint256 currentFee, uint256 requiredFee);
    error ApproxDstExecutionGasNotSet();
    error InvalidRetryData();

    // GENERIC MSG
    error ArrayLengthMismatch();
    error ArrayEmpty();
    error ArrayOutOfBounds();
    error ZeroAddress();
    error FailedToSendEther();
    error InvalidMerkleProof();

    error OnlyLayerZeroEndpoint();
    error OnlyYT();
    error OnlyYCFactory();
    error OnlyWhitelisted();

    // Swap Aggregator
    error SAInsufficientTokenIn(address tokenIn, uint256 amountExpected, uint256 amountActual);
    error UnsupportedSelector(uint256 aggregatorType, bytes4 selector);
}
LogExpMath.sol 495 lines
// SPDX-License-Identifier: GPL-3.0-or-later
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
// documentation files (the “Software”), to deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
// Software.

// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

pragma solidity ^0.8.0;

/* solhint-disable */

/**
 * @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
 *
 * Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
 * exponentiation and logarithm (where the base is Euler's number).
 *
 * @author Fernando Martinelli - @fernandomartinelli
 * @author Sergio Yuhjtman - @sergioyuhjtman
 * @author Daniel Fernandez - @dmf7z
 */
library LogExpMath {
    // All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
    // two numbers, and multiply by ONE when dividing them.

    // All arguments and return values are 18 decimal fixed point numbers.
    int256 constant ONE_18 = 1e18;

    // Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
    // case of ln36, 36 decimals.
    int256 constant ONE_20 = 1e20;
    int256 constant ONE_36 = 1e36;

    // The domain of natural exponentiation is bound by the word size and number of decimals used.
    //
    // Because internally the result will be stored using 20 decimals, the largest possible result is
    // (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
    // The smallest possible result is 10^(-18), which makes largest negative argument
    // ln(10^(-18)) = -41.446531673892822312.
    // We use 130.0 and -41.0 to have some safety margin.
    int256 constant MAX_NATURAL_EXPONENT = 130e18;
    int256 constant MIN_NATURAL_EXPONENT = -41e18;

    // Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
    // 256 bit integer.
    int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
    int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;

    uint256 constant MILD_EXPONENT_BOUND = 2 ** 254 / uint256(ONE_20);

    // 18 decimal constants
    int256 constant x0 = 128000000000000000000; // 2ˆ7
    int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
    int256 constant x1 = 64000000000000000000; // 2ˆ6
    int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)

    // 20 decimal constants
    int256 constant x2 = 3200000000000000000000; // 2ˆ5
    int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
    int256 constant x3 = 1600000000000000000000; // 2ˆ4
    int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
    int256 constant x4 = 800000000000000000000; // 2ˆ3
    int256 constant a4 = 298095798704172827474000; // eˆ(x4)
    int256 constant x5 = 400000000000000000000; // 2ˆ2
    int256 constant a5 = 5459815003314423907810; // eˆ(x5)
    int256 constant x6 = 200000000000000000000; // 2ˆ1
    int256 constant a6 = 738905609893065022723; // eˆ(x6)
    int256 constant x7 = 100000000000000000000; // 2ˆ0
    int256 constant a7 = 271828182845904523536; // eˆ(x7)
    int256 constant x8 = 50000000000000000000; // 2ˆ-1
    int256 constant a8 = 164872127070012814685; // eˆ(x8)
    int256 constant x9 = 25000000000000000000; // 2ˆ-2
    int256 constant a9 = 128402541668774148407; // eˆ(x9)
    int256 constant x10 = 12500000000000000000; // 2ˆ-3
    int256 constant a10 = 113314845306682631683; // eˆ(x10)
    int256 constant x11 = 6250000000000000000; // 2ˆ-4
    int256 constant a11 = 106449445891785942956; // eˆ(x11)

    /**
     * @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
     *
     * Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
     */
    function exp(int256 x) internal pure returns (int256) {
        unchecked {
            require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "Invalid exponent");

            if (x < 0) {
                // We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
                // fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
                // Fixed point division requires multiplying by ONE_18.
                return ((ONE_18 * ONE_18) / exp(-x));
            }

            // First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
            // where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
            // because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
            // decomposition.
            // At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
            // decomposition, which will be lower than the smallest x_n.
            // exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
            // We mutate x by subtracting x_n, making it the remainder of the decomposition.

            // The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
            // intermediate overflows. Instead we store them as plain integers, with 0 decimals.
            // Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
            // decomposition.

            // For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
            // it and compute the accumulated product.

            int256 firstAN;
            if (x >= x0) {
                x -= x0;
                firstAN = a0;
            } else if (x >= x1) {
                x -= x1;
                firstAN = a1;
            } else {
                firstAN = 1; // One with no decimal places
            }

            // We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
            // smaller terms.
            x *= 100;

            // `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
            // one. Recall that fixed point multiplication requires dividing by ONE_20.
            int256 product = ONE_20;

            if (x >= x2) {
                x -= x2;
                product = (product * a2) / ONE_20;
            }
            if (x >= x3) {
                x -= x3;
                product = (product * a3) / ONE_20;
            }
            if (x >= x4) {
                x -= x4;
                product = (product * a4) / ONE_20;
            }
            if (x >= x5) {
                x -= x5;
                product = (product * a5) / ONE_20;
            }
            if (x >= x6) {
                x -= x6;
                product = (product * a6) / ONE_20;
            }
            if (x >= x7) {
                x -= x7;
                product = (product * a7) / ONE_20;
            }
            if (x >= x8) {
                x -= x8;
                product = (product * a8) / ONE_20;
            }
            if (x >= x9) {
                x -= x9;
                product = (product * a9) / ONE_20;
            }

            // x10 and x11 are unnecessary here since we have high enough precision already.

            // Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
            // expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).

            int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
            int256 term; // Each term in the sum, where the nth term is (x^n / n!).

            // The first term is simply x.
            term = x;
            seriesSum += term;

            // Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
            // multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.

            term = ((term * x) / ONE_20) / 2;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 3;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 4;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 5;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 6;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 7;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 8;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 9;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 10;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 11;
            seriesSum += term;

            term = ((term * x) / ONE_20) / 12;
            seriesSum += term;

            // 12 Taylor terms are sufficient for 18 decimal precision.

            // We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
            // approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
            // all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
            // and then drop two digits to return an 18 decimal value.

            return (((product * seriesSum) / ONE_20) * firstAN) / 100;
        }
    }

    /**
     * @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
     */
    function ln(int256 a) internal pure returns (int256) {
        unchecked {
            // The real natural logarithm is not defined for negative numbers or zero.
            require(a > 0, "out of bounds");
            if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
                return _ln_36(a) / ONE_18;
            } else {
                return _ln(a);
            }
        }
    }

    /**
     * @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
     *
     * Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
     */
    function pow(uint256 x, uint256 y) internal pure returns (uint256) {
        unchecked {
            if (y == 0) {
                // We solve the 0^0 indetermination by making it equal one.
                return uint256(ONE_18);
            }

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

            // Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
            // arrive at that r`esult. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
            // x^y = exp(y * ln(x)).

            // The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
            require(x < 2 ** 255, "x out of bounds");
            int256 x_int256 = int256(x);

            // We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
            // both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.

            // This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
            require(y < MILD_EXPONENT_BOUND, "y out of bounds");
            int256 y_int256 = int256(y);

            int256 logx_times_y;
            if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
                int256 ln_36_x = _ln_36(x_int256);

                // ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
                // bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
                // multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
                // (downscaled) last 18 decimals.
                logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
            } else {
                logx_times_y = _ln(x_int256) * y_int256;
            }
            logx_times_y /= ONE_18;

            // Finally, we compute exp(y * ln(x)) to arrive at x^y
            require(
                MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
                "product out of bounds"
            );

            return uint256(exp(logx_times_y));
        }
    }

    /**
     * @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
     */
    function _ln(int256 a) private pure returns (int256) {
        unchecked {
            if (a < ONE_18) {
                // Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
                // than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
                // Fixed point division requires multiplying by ONE_18.
                return (-_ln((ONE_18 * ONE_18) / a));
            }

            // First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
            // we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
            // ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
            // be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
            // At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
            // decomposition, which will be lower than the smallest a_n.
            // ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
            // We mutate a by subtracting a_n, making it the remainder of the decomposition.

            // For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
            // numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
            // ONE_18 to convert them to fixed point.
            // For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
            // by it and compute the accumulated sum.

            int256 sum = 0;
            if (a >= a0 * ONE_18) {
                a /= a0; // Integer, not fixed point division
                sum += x0;
            }

            if (a >= a1 * ONE_18) {
                a /= a1; // Integer, not fixed point division
                sum += x1;
            }

            // All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
            sum *= 100;
            a *= 100;

            // Because further a_n are  20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.

            if (a >= a2) {
                a = (a * ONE_20) / a2;
                sum += x2;
            }

            if (a >= a3) {
                a = (a * ONE_20) / a3;
                sum += x3;
            }

            if (a >= a4) {
                a = (a * ONE_20) / a4;
                sum += x4;
            }

            if (a >= a5) {
                a = (a * ONE_20) / a5;
                sum += x5;
            }

            if (a >= a6) {
                a = (a * ONE_20) / a6;
                sum += x6;
            }

            if (a >= a7) {
                a = (a * ONE_20) / a7;
                sum += x7;
            }

            if (a >= a8) {
                a = (a * ONE_20) / a8;
                sum += x8;
            }

            if (a >= a9) {
                a = (a * ONE_20) / a9;
                sum += x9;
            }

            if (a >= a10) {
                a = (a * ONE_20) / a10;
                sum += x10;
            }

            if (a >= a11) {
                a = (a * ONE_20) / a11;
                sum += x11;
            }

            // a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
            // that converges rapidly for values of `a` close to one - the same one used in ln_36.
            // Let z = (a - 1) / (a + 1).
            // ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))

            // Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
            // division by ONE_20.
            int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
            int256 z_squared = (z * z) / ONE_20;

            // num is the numerator of the series: the z^(2 * n + 1) term
            int256 num = z;

            // seriesSum holds the accumulated sum of each term in the series, starting with the initial z
            int256 seriesSum = num;

            // In each step, the numerator is multiplied by z^2
            num = (num * z_squared) / ONE_20;
            seriesSum += num / 3;

            num = (num * z_squared) / ONE_20;
            seriesSum += num / 5;

            num = (num * z_squared) / ONE_20;
            seriesSum += num / 7;

            num = (num * z_squared) / ONE_20;
            seriesSum += num / 9;

            num = (num * z_squared) / ONE_20;
            seriesSum += num / 11;

            // 6 Taylor terms are sufficient for 36 decimal precision.

            // Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
            seriesSum *= 2;

            // We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
            // with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
            // value.

            return (sum + seriesSum) / 100;
        }
    }

    /**
     * @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
     * for x close to one.
     *
     * Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
     */
    function _ln_36(int256 x) private pure returns (int256) {
        unchecked {
            // Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
            // worthwhile.

            // First, we transform x to a 36 digit fixed point value.
            x *= ONE_18;

            // We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
            // ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))

            // Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
            // division by ONE_36.
            int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
            int256 z_squared = (z * z) / ONE_36;

            // num is the numerator of the series: the z^(2 * n + 1) term
            int256 num = z;

            // seriesSum holds the accumulated sum of each term in the series, starting with the initial z
            int256 seriesSum = num;

            // In each step, the numerator is multiplied by z^2
            num = (num * z_squared) / ONE_36;
            seriesSum += num / 3;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 5;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 7;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 9;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 11;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 13;

            num = (num * z_squared) / ONE_36;
            seriesSum += num / 15;

            // 8 Taylor terms are sufficient for 36 decimal precision.

            // All that remains is multiplying by 2 (non fixed point).
            return seriesSum * 2;
        }
    }
}
PMath.sol 220 lines
// SPDX-License-Identifier: GPL-3.0-or-later
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

pragma solidity ^0.8.0;

/* solhint-disable private-vars-leading-underscore, reason-string */

library PMath {
    uint256 internal constant ONE = 1e18; // 18 decimal places
    int256 internal constant IONE = 1e18; // 18 decimal places

    function subMax0(uint256 a, uint256 b) internal pure returns (uint256) {
        unchecked {
            return (a >= b ? a - b : 0);
        }
    }

    function subNoNeg(int256 a, int256 b) internal pure returns (int256) {
        require(a >= b, "negative");
        return a - b; // no unchecked since if b is very negative, a - b might overflow
    }

    function mulDown(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 product = a * b;
        unchecked {
            return product / ONE;
        }
    }

    function mulDown(int256 a, int256 b) internal pure returns (int256) {
        int256 product = a * b;
        unchecked {
            return product / IONE;
        }
    }

    function divDown(uint256 a, uint256 b) internal pure returns (uint256) {
        uint256 aInflated = a * ONE;
        unchecked {
            return aInflated / b;
        }
    }

    function divDown(int256 a, int256 b) internal pure returns (int256) {
        int256 aInflated = a * IONE;
        unchecked {
            return aInflated / b;
        }
    }

    function rawDivUp(uint256 a, uint256 b) internal pure returns (uint256) {
        return (a + b - 1) / b;
    }

    function rawDivUp(int256 a, int256 b) internal pure returns (int256) {
        return (a + b - 1) / b;
    }

    function tweakUp(uint256 a, uint256 factor) internal pure returns (uint256) {
        return mulDown(a, ONE + factor);
    }

    function tweakDown(uint256 a, uint256 factor) internal pure returns (uint256) {
        return mulDown(a, ONE - factor);
    }

    /// @return res = min(a + b, bound)
    /// @dev This function should handle arithmetic operation and bound check without overflow/underflow
    function addWithUpperBound(uint256 a, uint256 b, uint256 bound) internal pure returns (uint256 res) {
        unchecked {
            if (type(uint256).max - b < a) res = bound;
            else res = min(bound, a + b);
        }
    }

    /// @return res = max(a - b, bound)
    /// @dev This function should handle arithmetic operation and bound check without overflow/underflow
    function subWithLowerBound(uint256 a, uint256 b, uint256 bound) internal pure returns (uint256 res) {
        unchecked {
            if (b > a) res = bound;
            else res = max(a - b, bound);
        }
    }

    function clamp(uint256 x, uint256 lower, uint256 upper) internal pure returns (uint256 res) {
        res = x;
        if (x < lower) res = lower;
        else if (x > upper) res = upper;
    }

    // @author Uniswap
    function sqrt(uint256 y) internal pure returns (uint256 z) {
        if (y > 3) {
            z = y;
            uint256 x = y / 2 + 1;
            while (x < z) {
                z = x;
                x = (y / x + x) / 2;
            }
        } else if (y != 0) {
            z = 1;
        }
    }

    function square(uint256 x) internal pure returns (uint256) {
        return x * x;
    }

    function squareDown(uint256 x) internal pure returns (uint256) {
        return mulDown(x, x);
    }

    function abs(int256 x) internal pure returns (uint256) {
        return uint256(x > 0 ? x : -x);
    }

    function neg(int256 x) internal pure returns (int256) {
        return x * (-1);
    }

    function neg(uint256 x) internal pure returns (int256) {
        return Int(x) * (-1);
    }

    function max(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x > y ? x : y);
    }

    function max(int256 x, int256 y) internal pure returns (int256) {
        return (x > y ? x : y);
    }

    function min(uint256 x, uint256 y) internal pure returns (uint256) {
        return (x < y ? x : y);
    }

    function min(int256 x, int256 y) internal pure returns (int256) {
        return (x < y ? x : y);
    }

    /*///////////////////////////////////////////////////////////////
                               SIGNED CASTS
    //////////////////////////////////////////////////////////////*/

    function Int(uint256 x) internal pure returns (int256) {
        require(x <= uint256(type(int256).max));
        return int256(x);
    }

    function Int128(int256 x) internal pure returns (int128) {
        require(type(int128).min <= x && x <= type(int128).max);
        return int128(x);
    }

    function Int128(uint256 x) internal pure returns (int128) {
        return Int128(Int(x));
    }

    /*///////////////////////////////////////////////////////////////
                               UNSIGNED CASTS
    //////////////////////////////////////////////////////////////*/

    function Uint(int256 x) internal pure returns (uint256) {
        require(x >= 0);
        return uint256(x);
    }

    function Uint32(uint256 x) internal pure returns (uint32) {
        require(x <= type(uint32).max);
        return uint32(x);
    }

    function Uint64(uint256 x) internal pure returns (uint64) {
        require(x <= type(uint64).max);
        return uint64(x);
    }

    function Uint112(uint256 x) internal pure returns (uint112) {
        require(x <= type(uint112).max);
        return uint112(x);
    }

    function Uint96(uint256 x) internal pure returns (uint96) {
        require(x <= type(uint96).max);
        return uint96(x);
    }

    function Uint128(uint256 x) internal pure returns (uint128) {
        require(x <= type(uint128).max);
        return uint128(x);
    }

    function Uint192(uint256 x) internal pure returns (uint192) {
        require(x <= type(uint192).max);
        return uint192(x);
    }

    function isAApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
        return mulDown(b, ONE - eps) <= a && a <= mulDown(b, ONE + eps);
    }

    function isAGreaterApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
        return a >= b && a <= mulDown(b, ONE + eps);
    }

    function isASmallerApproxB(uint256 a, uint256 b, uint256 eps) internal pure returns (bool) {
        return a <= b && a >= mulDown(b, ONE - eps);
    }
}
MiniHelpers.sol 16 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

library MiniHelpers {
    function isCurrentlyExpired(uint256 expiry) internal view returns (bool) {
        return (expiry <= block.timestamp);
    }

    function isExpired(uint256 expiry, uint256 blockTime) internal pure returns (bool) {
        return (expiry <= blockTime);
    }

    function isTimeInThePast(uint256 timestamp) internal view returns (bool) {
        return (timestamp <= block.timestamp); // same definition as isCurrentlyExpired
    }
}
MarketMathCore.sol 417 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "../libraries/math/PMath.sol";
import "../libraries/math/LogExpMath.sol";

import "../StandardizedYield/PYIndex.sol";
import "../libraries/MiniHelpers.sol";
import "../libraries/Errors.sol";

struct MarketState {
    int256 totalPt;
    int256 totalSy;
    int256 totalLp;
    address treasury;
    /// immutable variables ///
    int256 scalarRoot;
    uint256 expiry;
    /// fee data ///
    uint256 lnFeeRateRoot;
    uint256 reserveFeePercent; // base 100
    /// last trade data ///
    uint256 lastLnImpliedRate;
}

// params that are expensive to compute, therefore we pre-compute them
struct MarketPreCompute {
    int256 rateScalar;
    int256 totalAsset;
    int256 rateAnchor;
    int256 feeRate;
}

// solhint-disable ordering
library MarketMathCore {
    using PMath for uint256;
    using PMath for int256;
    using LogExpMath for int256;
    using PYIndexLib for PYIndex;

    int256 internal constant MINIMUM_LIQUIDITY = 10 ** 3;
    int256 internal constant PERCENTAGE_DECIMALS = 100;
    uint256 internal constant DAY = 86400;
    uint256 internal constant IMPLIED_RATE_TIME = 365 * DAY;

    int256 internal constant MAX_MARKET_PROPORTION = (1e18 * 96) / 100;

    using PMath for uint256;
    using PMath for int256;

    /*///////////////////////////////////////////////////////////////
                UINT FUNCTIONS TO PROXY TO CORE FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    function addLiquidity(
        MarketState memory market,
        uint256 syDesired,
        uint256 ptDesired,
        uint256 blockTime
    ) internal pure returns (uint256 lpToReserve, uint256 lpToAccount, uint256 syUsed, uint256 ptUsed) {
        (int256 _lpToReserve, int256 _lpToAccount, int256 _syUsed, int256 _ptUsed) = addLiquidityCore(
            market,
            syDesired.Int(),
            ptDesired.Int(),
            blockTime
        );

        lpToReserve = _lpToReserve.Uint();
        lpToAccount = _lpToAccount.Uint();
        syUsed = _syUsed.Uint();
        ptUsed = _ptUsed.Uint();
    }

    function removeLiquidity(
        MarketState memory market,
        uint256 lpToRemove
    ) internal pure returns (uint256 netSyToAccount, uint256 netPtToAccount) {
        (int256 _syToAccount, int256 _ptToAccount) = removeLiquidityCore(market, lpToRemove.Int());

        netSyToAccount = _syToAccount.Uint();
        netPtToAccount = _ptToAccount.Uint();
    }

    function swapExactPtForSy(
        MarketState memory market,
        PYIndex index,
        uint256 exactPtToMarket,
        uint256 blockTime
    ) internal pure returns (uint256 netSyToAccount, uint256 netSyFee, uint256 netSyToReserve) {
        (int256 _netSyToAccount, int256 _netSyFee, int256 _netSyToReserve) = executeTradeCore(
            market,
            index,
            exactPtToMarket.neg(),
            blockTime
        );

        netSyToAccount = _netSyToAccount.Uint();
        netSyFee = _netSyFee.Uint();
        netSyToReserve = _netSyToReserve.Uint();
    }

    function swapSyForExactPt(
        MarketState memory market,
        PYIndex index,
        uint256 exactPtToAccount,
        uint256 blockTime
    ) internal pure returns (uint256 netSyToMarket, uint256 netSyFee, uint256 netSyToReserve) {
        (int256 _netSyToAccount, int256 _netSyFee, int256 _netSyToReserve) = executeTradeCore(
            market,
            index,
            exactPtToAccount.Int(),
            blockTime
        );

        netSyToMarket = _netSyToAccount.neg().Uint();
        netSyFee = _netSyFee.Uint();
        netSyToReserve = _netSyToReserve.Uint();
    }

    /*///////////////////////////////////////////////////////////////
                    CORE FUNCTIONS
    //////////////////////////////////////////////////////////////*/

    function addLiquidityCore(
        MarketState memory market,
        int256 syDesired,
        int256 ptDesired,
        uint256 blockTime
    ) internal pure returns (int256 lpToReserve, int256 lpToAccount, int256 syUsed, int256 ptUsed) {
        /// ------------------------------------------------------------
        /// CHECKS
        /// ------------------------------------------------------------
        if (syDesired == 0 || ptDesired == 0) revert Errors.MarketZeroAmountsInput();
        if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();

        /// ------------------------------------------------------------
        /// MATH
        /// ------------------------------------------------------------
        if (market.totalLp == 0) {
            lpToAccount = PMath.sqrt((syDesired * ptDesired).Uint()).Int() - MINIMUM_LIQUIDITY;
            lpToReserve = MINIMUM_LIQUIDITY;
            syUsed = syDesired;
            ptUsed = ptDesired;
        } else {
            int256 netLpByPt = (ptDesired * market.totalLp) / market.totalPt;
            int256 netLpBySy = (syDesired * market.totalLp) / market.totalSy;
            if (netLpByPt < netLpBySy) {
                lpToAccount = netLpByPt;
                ptUsed = ptDesired;
                syUsed = (market.totalSy * lpToAccount).rawDivUp(market.totalLp);
            } else {
                lpToAccount = netLpBySy;
                syUsed = syDesired;
                ptUsed = (market.totalPt * lpToAccount).rawDivUp(market.totalLp);
            }
        }

        if (lpToAccount <= 0 || syUsed <= 0 || ptUsed <= 0) revert Errors.MarketZeroAmountsOutput();

        /// ------------------------------------------------------------
        /// WRITE
        /// ------------------------------------------------------------
        market.totalSy += syUsed;
        market.totalPt += ptUsed;
        market.totalLp += lpToAccount + lpToReserve;
    }

    function removeLiquidityCore(
        MarketState memory market,
        int256 lpToRemove
    ) internal pure returns (int256 netSyToAccount, int256 netPtToAccount) {
        /// ------------------------------------------------------------
        /// CHECKS
        /// ------------------------------------------------------------
        if (lpToRemove == 0) revert Errors.MarketZeroAmountsInput();

        /// ------------------------------------------------------------
        /// MATH
        /// ------------------------------------------------------------
        netSyToAccount = (lpToRemove * market.totalSy) / market.totalLp;
        netPtToAccount = (lpToRemove * market.totalPt) / market.totalLp;

        if (netSyToAccount == 0 && netPtToAccount == 0) revert Errors.MarketZeroAmountsOutput();

        /// ------------------------------------------------------------
        /// WRITE
        /// ------------------------------------------------------------
        market.totalLp = market.totalLp.subNoNeg(lpToRemove);
        market.totalPt = market.totalPt.subNoNeg(netPtToAccount);
        market.totalSy = market.totalSy.subNoNeg(netSyToAccount);
    }

    function executeTradeCore(
        MarketState memory market,
        PYIndex index,
        int256 netPtToAccount,
        uint256 blockTime
    ) internal pure returns (int256 netSyToAccount, int256 netSyFee, int256 netSyToReserve) {
        /// ------------------------------------------------------------
        /// CHECKS
        /// ------------------------------------------------------------
        if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();
        if (market.totalPt <= netPtToAccount)
            revert Errors.MarketInsufficientPtForTrade(market.totalPt, netPtToAccount);

        /// ------------------------------------------------------------
        /// MATH
        /// ------------------------------------------------------------
        MarketPreCompute memory comp = getMarketPreCompute(market, index, blockTime);

        (netSyToAccount, netSyFee, netSyToReserve) = calcTrade(market, comp, index, netPtToAccount);

        /// ------------------------------------------------------------
        /// WRITE
        /// ------------------------------------------------------------
        _setNewMarketStateTrade(market, comp, index, netPtToAccount, netSyToAccount, netSyToReserve, blockTime);
    }

    function getMarketPreCompute(
        MarketState memory market,
        PYIndex index,
        uint256 blockTime
    ) internal pure returns (MarketPreCompute memory res) {
        if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();

        uint256 timeToExpiry = market.expiry - blockTime;

        res.rateScalar = _getRateScalar(market, timeToExpiry);
        res.totalAsset = index.syToAsset(market.totalSy);

        if (market.totalPt == 0 || res.totalAsset == 0)
            revert Errors.MarketZeroTotalPtOrTotalAsset(market.totalPt, res.totalAsset);

        res.rateAnchor = _getRateAnchor(
            market.totalPt,
            market.lastLnImpliedRate,
            res.totalAsset,
            res.rateScalar,
            timeToExpiry
        );
        res.feeRate = _getExchangeRateFromImpliedRate(market.lnFeeRateRoot, timeToExpiry);
    }

    function calcTrade(
        MarketState memory market,
        MarketPreCompute memory comp,
        PYIndex index,
        int256 netPtToAccount
    ) internal pure returns (int256 netSyToAccount, int256 netSyFee, int256 netSyToReserve) {
        int256 preFeeExchangeRate = _getExchangeRate(
            market.totalPt,
            comp.totalAsset,
            comp.rateScalar,
            comp.rateAnchor,
            netPtToAccount
        );

        int256 preFeeAssetToAccount = netPtToAccount.divDown(preFeeExchangeRate).neg();
        int256 fee = comp.feeRate;

        if (netPtToAccount > 0) {
            int256 postFeeExchangeRate = preFeeExchangeRate.divDown(fee);
            if (postFeeExchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(postFeeExchangeRate);

            fee = preFeeAssetToAccount.mulDown(PMath.IONE - fee);
        } else {
            fee = ((preFeeAssetToAccount * (PMath.IONE - fee)) / fee).neg();
        }

        int256 netAssetToReserve = (fee * market.reserveFeePercent.Int()) / PERCENTAGE_DECIMALS;
        int256 netAssetToAccount = preFeeAssetToAccount - fee;

        netSyToAccount = netAssetToAccount < 0
            ? index.assetToSyUp(netAssetToAccount)
            : index.assetToSy(netAssetToAccount);
        netSyFee = index.assetToSy(fee);
        netSyToReserve = index.assetToSy(netAssetToReserve);
    }

    function _setNewMarketStateTrade(
        MarketState memory market,
        MarketPreCompute memory comp,
        PYIndex index,
        int256 netPtToAccount,
        int256 netSyToAccount,
        int256 netSyToReserve,
        uint256 blockTime
    ) internal pure {
        uint256 timeToExpiry = market.expiry - blockTime;

        market.totalPt = market.totalPt.subNoNeg(netPtToAccount);
        market.totalSy = market.totalSy.subNoNeg(netSyToAccount + netSyToReserve);

        market.lastLnImpliedRate = _getLnImpliedRate(
            market.totalPt,
            index.syToAsset(market.totalSy),
            comp.rateScalar,
            comp.rateAnchor,
            timeToExpiry
        );

        if (market.lastLnImpliedRate == 0) revert Errors.MarketZeroLnImpliedRate();
    }

    function _getRateAnchor(
        int256 totalPt,
        uint256 lastLnImpliedRate,
        int256 totalAsset,
        int256 rateScalar,
        uint256 timeToExpiry
    ) internal pure returns (int256 rateAnchor) {
        int256 newExchangeRate = _getExchangeRateFromImpliedRate(lastLnImpliedRate, timeToExpiry);

        if (newExchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(newExchangeRate);

        {
            int256 proportion = totalPt.divDown(totalPt + totalAsset);

            int256 lnProportion = _logProportion(proportion);

            rateAnchor = newExchangeRate - lnProportion.divDown(rateScalar);
        }
    }

    /// @notice Calculates the current market implied rate.
    /// @return lnImpliedRate the implied rate
    function _getLnImpliedRate(
        int256 totalPt,
        int256 totalAsset,
        int256 rateScalar,
        int256 rateAnchor,
        uint256 timeToExpiry
    ) internal pure returns (uint256 lnImpliedRate) {
        // This will check for exchange rates < PMath.IONE
        int256 exchangeRate = _getExchangeRate(totalPt, totalAsset, rateScalar, rateAnchor, 0);

        // exchangeRate >= 1 so its ln >= 0
        uint256 lnRate = exchangeRate.ln().Uint();

        lnImpliedRate = (lnRate * IMPLIED_RATE_TIME) / timeToExpiry;
    }

    /// @notice Converts an implied rate to an exchange rate given a time to expiry. The
    /// formula is E = e^rt
    function _getExchangeRateFromImpliedRate(
        uint256 lnImpliedRate,
        uint256 timeToExpiry
    ) internal pure returns (int256 exchangeRate) {
        uint256 rt = (lnImpliedRate * timeToExpiry) / IMPLIED_RATE_TIME;

        exchangeRate = LogExpMath.exp(rt.Int());
    }

    function _getExchangeRate(
        int256 totalPt,
        int256 totalAsset,
        int256 rateScalar,
        int256 rateAnchor,
        int256 netPtToAccount
    ) internal pure returns (int256 exchangeRate) {
        int256 numerator = totalPt.subNoNeg(netPtToAccount);

        int256 proportion = (numerator.divDown(totalPt + totalAsset));

        if (proportion > MAX_MARKET_PROPORTION)
            revert Errors.MarketProportionTooHigh(proportion, MAX_MARKET_PROPORTION);

        int256 lnProportion = _logProportion(proportion);

        exchangeRate = lnProportion.divDown(rateScalar) + rateAnchor;

        if (exchangeRate < PMath.IONE) revert Errors.MarketExchangeRateBelowOne(exchangeRate);
    }

    function _logProportion(int256 proportion) internal pure returns (int256 res) {
        if (proportion == PMath.IONE) revert Errors.MarketProportionMustNotEqualOne();

        int256 logitP = proportion.divDown(PMath.IONE - proportion);

        res = logitP.ln();
    }

    function _getRateScalar(MarketState memory market, uint256 timeToExpiry) internal pure returns (int256 rateScalar) {
        rateScalar = (market.scalarRoot * IMPLIED_RATE_TIME.Int()) / timeToExpiry.Int();
        if (rateScalar <= 0) revert Errors.MarketRateScalarBelowZero(rateScalar);
    }

    function setInitialLnImpliedRate(
        MarketState memory market,
        PYIndex index,
        int256 initialAnchor,
        uint256 blockTime
    ) internal pure {
        /// ------------------------------------------------------------
        /// CHECKS
        /// ------------------------------------------------------------
        if (MiniHelpers.isExpired(market.expiry, blockTime)) revert Errors.MarketExpired();

        /// ------------------------------------------------------------
        /// MATH
        /// ------------------------------------------------------------
        int256 totalAsset = index.syToAsset(market.totalSy);
        uint256 timeToExpiry = market.expiry - blockTime;
        int256 rateScalar = _getRateScalar(market, timeToExpiry);

        /// ------------------------------------------------------------
        /// WRITE
        /// ------------------------------------------------------------
        market.lastLnImpliedRate = _getLnImpliedRate(
            market.totalPt,
            totalAsset,
            rateScalar,
            initialAnchor,
            timeToExpiry
        );
    }
}
PYIndex.sol 50 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../interfaces/IPYieldToken.sol";
import "../../interfaces/IPPrincipalToken.sol";

import "./SYUtils.sol";
import "../libraries/math/PMath.sol";

type PYIndex is uint256;

library PYIndexLib {
    using PMath for uint256;
    using PMath for int256;

    function newIndex(IPYieldToken YT) internal returns (PYIndex) {
        return PYIndex.wrap(YT.pyIndexCurrent());
    }

    function syToAsset(PYIndex index, uint256 syAmount) internal pure returns (uint256) {
        return SYUtils.syToAsset(PYIndex.unwrap(index), syAmount);
    }

    function assetToSy(PYIndex index, uint256 assetAmount) internal pure returns (uint256) {
        return SYUtils.assetToSy(PYIndex.unwrap(index), assetAmount);
    }

    function assetToSyUp(PYIndex index, uint256 assetAmount) internal pure returns (uint256) {
        return SYUtils.assetToSyUp(PYIndex.unwrap(index), assetAmount);
    }

    function syToAssetUp(PYIndex index, uint256 syAmount) internal pure returns (uint256) {
        uint256 _index = PYIndex.unwrap(index);
        return SYUtils.syToAssetUp(_index, syAmount);
    }

    function syToAsset(PYIndex index, int256 syAmount) internal pure returns (int256) {
        int256 sign = syAmount < 0 ? int256(-1) : int256(1);
        return sign * (SYUtils.syToAsset(PYIndex.unwrap(index), syAmount.abs())).Int();
    }

    function assetToSy(PYIndex index, int256 assetAmount) internal pure returns (int256) {
        int256 sign = assetAmount < 0 ? int256(-1) : int256(1);
        return sign * (SYUtils.assetToSy(PYIndex.unwrap(index), assetAmount.abs())).Int();
    }

    function assetToSyUp(PYIndex index, int256 assetAmount) internal pure returns (int256) {
        int256 sign = assetAmount < 0 ? int256(-1) : int256(1);
        return sign * (SYUtils.assetToSyUp(PYIndex.unwrap(index), assetAmount.abs())).Int();
    }
}
SYUtils.sol 22 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

library SYUtils {
    uint256 internal constant ONE = 1e18;

    function syToAsset(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) {
        return (syAmount * exchangeRate) / ONE;
    }

    function syToAssetUp(uint256 exchangeRate, uint256 syAmount) internal pure returns (uint256) {
        return (syAmount * exchangeRate + ONE - 1) / ONE;
    }

    function assetToSy(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) {
        return (assetAmount * ONE) / exchangeRate;
    }

    function assetToSyUp(uint256 exchangeRate, uint256 assetAmount) internal pure returns (uint256) {
        return (assetAmount * ONE + exchangeRate - 1) / exchangeRate;
    }
}
IPChainlinkOracle.sol 11 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

enum PendleOracleType {
    PT_TO_SY,
    PT_TO_ASSET
}

interface IPChainlinkOracle is AggregatorV3Interface {}
IPChainlinkOracleFactory.sol 22 lines
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./IPChainlinkOracle.sol";

interface IPChainlinkOracleFactory {
    event OracleCreated(
        address indexed market,
        uint32 indexed twapDuration,
        PendleOracleType indexed baseOracleType,
        address oracle,
        bytes32 oracleId
    );
    event OracleWithQuoteCreated(
        address indexed market,
        uint32 indexed twapDuration,
        PendleOracleType indexed baseOracleType,
        address quoteOracle,
        address oracle,
        bytes32 oracleId
    );
}
IPGauge.sol 11 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IPGauge {
    function totalActiveSupply() external view returns (uint256);

    function activeBalance(address user) external view returns (uint256);

    // only available for newer factories. please check the verified contracts
    event RedeemRewards(address indexed user, uint256[] rewardsOut);
}
IPInterestManagerYT.sol 8 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IPInterestManagerYT {
    event CollectInterestFee(uint256 amountInterestFee);

    function userInterest(address user) external view returns (uint128 lastPYIndex, uint128 accruedInterest);
}
IPMarket.sol 93 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IPPrincipalToken.sol";
import "./IPYieldToken.sol";
import "./IStandardizedYield.sol";
import "./IPGauge.sol";
import "../core/Market/MarketMathCore.sol";

interface IPMarket is IERC20Metadata, IPGauge {
    event Mint(address indexed receiver, uint256 netLpMinted, uint256 netSyUsed, uint256 netPtUsed);

    event Burn(
        address indexed receiverSy,
        address indexed receiverPt,
        uint256 netLpBurned,
        uint256 netSyOut,
        uint256 netPtOut
    );

    event Swap(
        address indexed caller,
        address indexed receiver,
        int256 netPtOut,
        int256 netSyOut,
        uint256 netSyFee,
        uint256 netSyToReserve
    );

    event UpdateImpliedRate(uint256 indexed timestamp, uint256 lnLastImpliedRate);

    event IncreaseObservationCardinalityNext(
        uint16 observationCardinalityNextOld,
        uint16 observationCardinalityNextNew
    );

    function mint(
        address receiver,
        uint256 netSyDesired,
        uint256 netPtDesired
    ) external returns (uint256 netLpOut, uint256 netSyUsed, uint256 netPtUsed);

    function burn(
        address receiverSy,
        address receiverPt,
        uint256 netLpToBurn
    ) external returns (uint256 netSyOut, uint256 netPtOut);

    function swapExactPtForSy(
        address receiver,
        uint256 exactPtIn,
        bytes calldata data
    ) external returns (uint256 netSyOut, uint256 netSyFee);

    function swapSyForExactPt(
        address receiver,
        uint256 exactPtOut,
        bytes calldata data
    ) external returns (uint256 netSyIn, uint256 netSyFee);

    function redeemRewards(address user) external returns (uint256[] memory);

    function readState(address router) external view returns (MarketState memory market);

    function observe(uint32[] memory secondsAgos) external view returns (uint216[] memory lnImpliedRateCumulative);

    function increaseObservationsCardinalityNext(uint16 cardinalityNext) external;

    function readTokens() external view returns (IStandardizedYield _SY, IPPrincipalToken _PT, IPYieldToken _YT);

    function getRewardTokens() external view returns (address[] memory);

    function isExpired() external view returns (bool);

    function expiry() external view returns (uint256);

    function observations(
        uint256 index
    ) external view returns (uint32 blockTimestamp, uint216 lnImpliedRateCumulative, bool initialized);

    function _storage()
        external
        view
        returns (
            int128 totalPt,
            int128 totalSy,
            uint96 lastLnImpliedRate,
            uint16 observationIndex,
            uint16 observationCardinality,
            uint16 observationCardinalityNext
        );
}
IPPrincipalToken.sol 21 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IPPrincipalToken is IERC20Metadata {
    function burnByYT(address user, uint256 amount) external;

    function mintByYT(address user, uint256 amount) external;

    function initialize(address _YT) external;

    function SY() external view returns (address);

    function YT() external view returns (address);

    function factory() external view returns (address);

    function expiry() external view returns (uint256);

    function isExpired() external view returns (bool);
}
IPPYLpOracle.sol 25 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IPPYLpOracle {
    event SetBlockCycleNumerator(uint16 newBlockCycleNumerator);

    function getPtToAssetRate(address market, uint32 duration) external view returns (uint256);

    function getYtToAssetRate(address market, uint32 duration) external view returns (uint256);

    function getLpToAssetRate(address market, uint32 duration) external view returns (uint256);

    function getPtToSyRate(address market, uint32 duration) external view returns (uint256);

    function getYtToSyRate(address market, uint32 duration) external view returns (uint256);

    function getLpToSyRate(address market, uint32 duration) external view returns (uint256);

    function getOracleState(address market, uint32 duration)
        external
        view
        returns (bool increaseCardinalityRequired, uint16 cardinalityRequired, bool oldestObservationSatisfied);

    function blockCycleNumerator() external view returns (uint16);
}
IPYieldToken.sol 62 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "./IRewardManager.sol";
import "./IPInterestManagerYT.sol";

interface IPYieldToken is IERC20Metadata, IRewardManager, IPInterestManagerYT {
    event NewInterestIndex(uint256 indexed newIndex);

    event Mint(
        address indexed caller,
        address indexed receiverPT,
        address indexed receiverYT,
        uint256 amountSyToMint,
        uint256 amountPYOut
    );

    event Burn(address indexed caller, address indexed receiver, uint256 amountPYToRedeem, uint256 amountSyOut);

    event RedeemRewards(address indexed user, uint256[] amountRewardsOut);

    event RedeemInterest(address indexed user, uint256 interestOut);

    event CollectRewardFee(address indexed rewardToken, uint256 amountRewardFee);

    function mintPY(address receiverPT, address receiverYT) external returns (uint256 amountPYOut);

    function redeemPY(address receiver) external returns (uint256 amountSyOut);

    function redeemPYMulti(
        address[] calldata receivers,
        uint256[] calldata amountPYToRedeems
    ) external returns (uint256[] memory amountSyOuts);

    function redeemDueInterestAndRewards(
        address user,
        bool redeemInterest,
        bool redeemRewards
    ) external returns (uint256 interestOut, uint256[] memory rewardsOut);

    function rewardIndexesCurrent() external returns (uint256[] memory);

    function pyIndexCurrent() external returns (uint256);

    function pyIndexStored() external view returns (uint256);

    function getRewardTokens() external view returns (address[] memory);

    function SY() external view returns (address);

    function PT() external view returns (address);

    function factory() external view returns (address);

    function expiry() external view returns (uint256);

    function isExpired() external view returns (bool);

    function doCacheIndexSameBlock() external view returns (bool);

    function pyIndexLastUpdatedBlock() external view returns (uint128);
}
IRewardManager.sol 6 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

interface IRewardManager {
    function userReward(address token, address user) external view returns (uint128 index, uint128 accrued);
}
IStandardizedYield.sol 167 lines
// SPDX-License-Identifier: GPL-3.0-or-later
/*
 * MIT License
 * ===========
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 */

pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IStandardizedYield is IERC20Metadata {
    /// @dev Emitted when any base tokens is deposited to mint shares
    event Deposit(
        address indexed caller,
        address indexed receiver,
        address indexed tokenIn,
        uint256 amountDeposited,
        uint256 amountSyOut
    );

    /// @dev Emitted when any shares are redeemed for base tokens
    event Redeem(
        address indexed caller,
        address indexed receiver,
        address indexed tokenOut,
        uint256 amountSyToRedeem,
        uint256 amountTokenOut
    );

    /// @dev check `assetInfo()` for more information
    enum AssetType {
        TOKEN,
        LIQUIDITY
    }

    /// @dev Emitted when (`user`) claims their rewards
    event ClaimRewards(address indexed user, address[] rewardTokens, uint256[] rewardAmounts);

    /**
     * @notice mints an amount of shares by depositing a base token.
     * @param receiver shares recipient address
     * @param tokenIn address of the base tokens to mint shares
     * @param amountTokenToDeposit amount of base tokens to be transferred from (`msg.sender`)
     * @param minSharesOut reverts if amount of shares minted is lower than this
     * @return amountSharesOut amount of shares minted
     * @dev Emits a {Deposit} event
     *
     * Requirements:
     * - (`tokenIn`) must be a valid base token.
     */
    function deposit(
        address receiver,
        address tokenIn,
        uint256 amountTokenToDeposit,
        uint256 minSharesOut
    ) external payable returns (uint256 amountSharesOut);

    /**
     * @notice redeems an amount of base tokens by burning some shares
     * @param receiver recipient address
     * @param amountSharesToRedeem amount of shares to be burned
     * @param tokenOut address of the base token to be redeemed
     * @param minTokenOut reverts if amount of base token redeemed is lower than this
     * @param burnFromInternalBalance if true, burns from balance of `address(this)`, otherwise burns from `msg.sender`
     * @return amountTokenOut amount of base tokens redeemed
     * @dev Emits a {Redeem} event
     *
     * Requirements:
     * - (`tokenOut`) must be a valid base token.
     */
    function redeem(
        address receiver,
        uint256 amountSharesToRedeem,
        address tokenOut,
        uint256 minTokenOut,
        bool burnFromInternalBalance
    ) external returns (uint256 amountTokenOut);

    /**
     * @notice exchangeRate * syBalance / 1e18 must return the asset balance of the account
     * @notice vice-versa, if a user uses some amount of tokens equivalent to X asset, the amount of sy
     he can mint must be X * exchangeRate / 1e18
     * @dev SYUtils's assetToSy & syToAsset should be used instead of raw multiplication
     & division
     */
    function exchangeRate() external view returns (uint256 res);

    /**
     * @notice claims reward for (`user`)
     * @param user the user receiving their rewards
     * @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens`
     * @dev
     * Emits a `ClaimRewards` event
     * See {getRewardTokens} for list of reward tokens
     */
    function claimRewards(address user) external returns (uint256[] memory rewardAmounts);

    /**
     * @notice get the amount of unclaimed rewards for (`user`)
     * @param user the user to check for
     * @return rewardAmounts an array of reward amounts in the same order as `getRewardTokens`
     */
    function accruedRewards(address user) external view returns (uint256[] memory rewardAmounts);

    function rewardIndexesCurrent() external returns (uint256[] memory indexes);

    function rewardIndexesStored() external view returns (uint256[] memory indexes);

    /**
     * @notice returns the list of reward token addresses
     */
    function getRewardTokens() external view returns (address[] memory);

    /**
     * @notice returns the address of the underlying yield token
     */
    function yieldToken() external view returns (address);

    /**
     * @notice returns all tokens that can mint this SY
     */
    function getTokensIn() external view returns (address[] memory res);

    /**
     * @notice returns all tokens that can be redeemed by this SY
     */
    function getTokensOut() external view returns (address[] memory res);

    function isValidTokenIn(address token) external view returns (bool);

    function isValidTokenOut(address token) external view returns (bool);

    function previewDeposit(
        address tokenIn,
        uint256 amountTokenToDeposit
    ) external view returns (uint256 amountSharesOut);

    function previewRedeem(
        address tokenOut,
        uint256 amountSharesToRedeem
    ) external view returns (uint256 amountTokenOut);

    /**
     * @notice This function contains information to interpret what the asset is
     * @return assetType the type of the asset (0 for ERC20 tokens, 1 for AMM liquidity tokens,
        2 for bridged yield bearing tokens like wstETH, rETH on Arbi whose the underlying asset doesn't exist on the chain)
     * @return assetAddress the address of the asset
     * @return assetDecimals the decimals of the asset
     */
    function assetInfo() external view returns (AssetType assetType, address assetAddress, uint8 assetDecimals);
}
PendleChainlinkOracle.sol 134 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import "../../../interfaces/IPChainlinkOracle.sol";
import "../PendleLpOracleLib.sol";

/**
 * @dev The round data returned from this contract will follow:
 * - There will be only one round (roundId=0)
 * - startedAt=0, updatedAt=block.timestamp
 */
contract PendleChainlinkOracle is IPChainlinkOracle {
    error InvalidRoundId();

    // solhint-disable immutable-vars-naming
    address public immutable factory;

    address public immutable market;
    uint32 public immutable twapDuration;
    PendleOracleType public immutable baseOracleType;

    uint256 public immutable fromTokenScale;
    uint256 public immutable toTokenScale;

    function(IPMarket, uint32) internal view returns (uint256) private immutable _getRawPendlePrice;

    modifier roundIdIsZero(uint80 roundId) {
        if (roundId != 0) {
            revert InvalidRoundId();
        }
        _;
    }

    constructor(address _market, uint32 _twapDuration, PendleOracleType _baseOracleType) {
        factory = msg.sender;
        market = _market;
        twapDuration = _twapDuration;
        baseOracleType = _baseOracleType;
        (uint256 fromTokenDecimals, uint256 toTokenDecimals) = _readDecimals(_market, _baseOracleType);
        (fromTokenScale, toTokenScale) = (10 ** fromTokenDecimals, 10 ** toTokenDecimals);
        _getRawPendlePrice = _getRawPendlePriceFunc();
    }

    // =================================================================
    //                          CHAINLINK INTERFACE
    // =================================================================

    /**
     * @notice The round data returned from this contract will follow:
     * - answer will satisfy 1 natural unit of PendleToken = (answer/1e18) natural unit of OutputToken
     * - In other words, 10**(PendleToken.decimals) = (answer/1e18) * 10**(OutputToken.decimals)
     * @param roundId always 0 for this contract
     * @param answer The answer (in 18 decimals)
     * @param startedAt always 0 for this contract
     * @param updatedAt always block.timestamp for this contract
     * @param answeredInRound always 0 for this contract
     */
    function latestRoundData()
        public
        view
        virtual
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
    {
        roundId = 0;
        answer = _getPendleTokenPrice();
        startedAt = 0;
        updatedAt = block.timestamp;
        answeredInRound = 0;
    }

    function getRoundData(
        uint80 roundId
    ) external view roundIdIsZero(roundId) returns (uint80, int256, uint256, uint256, uint80) {
        return latestRoundData();
    }

    function decimals() external pure returns (uint8) {
        return 18;
    }

    function description() external pure returns (string memory) {
        return "Pendle Chainlink-compatible Oracle";
    }

    function version() external pure returns (uint256) {
        return 1;
    }

    // =================================================================
    //                          PRICING FUNCTIONS
    // =================================================================

    function _getPendleTokenPrice() internal view returns (int256) {
        return _descalePrice(_getRawPendlePrice(IPMarket(market), twapDuration));
    }

    function _descalePrice(uint256 price) private view returns (int256 unwrappedPrice) {
        return PMath.Int((price * fromTokenScale) / toTokenScale);
    }

    // =================================================================
    //                          USE ONLY AT INITIALIZATION
    // =================================================================

    function _getRawPendlePriceFunc()
        internal
        view
        returns (function(IPMarket, uint32) internal view returns (uint256))
    {
        if (baseOracleType == PendleOracleType.PT_TO_SY) {
            return PendlePYOracleLib.getPtToSyRate;
        } else if (baseOracleType == PendleOracleType.PT_TO_ASSET) {
            return PendlePYOracleLib.getPtToAssetRate;
        } else {
            revert("not supported");
        }
    }

    function _readDecimals(
        address _market,
        PendleOracleType _oracleType
    ) internal view returns (uint8 _fromDecimals, uint8 _toDecimals) {
        (IStandardizedYield SY, , ) = IPMarket(_market).readTokens();

        uint8 syDecimals = SY.decimals();
        (, , uint8 assetDecimals) = SY.assetInfo();

        if (_oracleType == PendleOracleType.PT_TO_ASSET) {
            return (assetDecimals, assetDecimals);
        } else if (_oracleType == PendleOracleType.PT_TO_SY) {
            return (assetDecimals, syDecimals);
        }
    }
}
PendleChainlinkOracleFactory.sol 121 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import "./PendleChainlinkOracle.sol";
import "./PendleChainlinkOracleWithQuote.sol";
import "../../../interfaces/IPChainlinkOracleFactory.sol";
import "../../../interfaces/IPPYLpOracle.sol";

contract PendleChainlinkOracleFactory is IPChainlinkOracleFactory {
    error OracleAlreadyExists();

    error OracleIncreaseCardinalityRequired(uint32 cardinalityRequired);
    error OracleOldestObservationNotSatisfied();

    // [keccak256(market, duration, baseOracleType)]
    mapping(bytes32 oracleId => address oracleAddr) internal oracles;

    // [keccak256(market, duration, baseOracleType, quoteOracle)]
    mapping(bytes32 oracleId => address oracleAddr) internal oraclesWithQuote;

    address public immutable pyLpOracle;

    constructor(address _pyLpOracle) {
        pyLpOracle = _pyLpOracle;
    }

    // =================================================================
    //                          CREATE ORACLE
    // =================================================================

    function createOracle(
        address market,
        uint32 twapDuration,
        PendleOracleType baseOracleType
    ) external returns (address oracle) {
        bytes32 oracleId = getOracleId(market, twapDuration, baseOracleType);
        if (oracles[oracleId] != address(0)) revert OracleAlreadyExists();

        checkMarketOracleState(market, twapDuration);

        oracle = address(new PendleChainlinkOracle(market, twapDuration, baseOracleType));
        oracles[oracleId] = oracle;
        emit OracleCreated(market, twapDuration, baseOracleType, oracle, oracleId);
    }

    /**
     * @dev quoteOracle must has Chainlink-compatible interface
     */
    function createOracleWithQuote(
        address market,
        uint32 twapDuration,
        PendleOracleType baseOracleType,
        address quoteOracle
    ) external returns (address oracle) {
        bytes32 oracleId = getOracleWithQuoteId(market, twapDuration, baseOracleType, quoteOracle);
        if (oraclesWithQuote[oracleId] != address(0)) revert OracleAlreadyExists();

        checkMarketOracleState(market, twapDuration);

        oracle = address(new PendleChainlinkOracleWithQuote(market, twapDuration, baseOracleType, quoteOracle));
        oraclesWithQuote[oracleId] = oracle;
        emit OracleWithQuoteCreated(market, twapDuration, baseOracleType, quoteOracle, oracle, oracleId);
    }

    // =================================================================
    //                          GET ORACLE
    // =================================================================

    function getOracle(
        address market,
        uint32 twapDuration,
        PendleOracleType baseOracleType
    ) public view returns (address) {
        return oracles[getOracleId(market, twapDuration, baseOracleType)];
    }

    function getOracleWithQuote(
        address market,
        uint32 twapDuration,
        PendleOracleType baseOracleType,
        address quoteOracle
    ) public view returns (address) {
        return oraclesWithQuote[getOracleWithQuoteId(market, twapDuration, baseOracleType, quoteOracle)];
    }

    function getOracleId(
        address market,
        uint32 twapDuration,
        PendleOracleType baseOracleType
    ) public pure returns (bytes32) {
        return keccak256(abi.encode(market, twapDuration, baseOracleType));
    }

    function getOracleWithQuoteId(
        address market,
        uint32 twapDuration,
        PendleOracleType baseOracleType,
        address quoteOracle
    ) public pure returns (bytes32) {
        return keccak256(abi.encode(market, twapDuration, baseOracleType, quoteOracle));
    }

    // =================================================================
    //                          CHECK ORACLE STATE
    // =================================================================

    function checkMarketOracleState(address market, uint32 twapDuration) public view {
        (bool increaseCardinalityRequired, uint32 cardinalityRequired, bool oldestObservationSatisfied) = IPPYLpOracle(
            pyLpOracle
        ).getOracleState(market, twapDuration);

        if (increaseCardinalityRequired) {
            // call IPMarket(market).increaseObservationsCardinalityNext(cardinalityRequired) then wait for twapDuration seconds
            revert OracleIncreaseCardinalityRequired(cardinalityRequired);
        }
        if (!oldestObservationSatisfied) {
            // wait for twapDuration seconds
            revert OracleOldestObservationNotSatisfied();
        }
    }
}
PendleChainlinkOracleWithQuote.sol 50 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.17;

import "./PendleChainlinkOracle.sol";

/**
 * @dev The round data returned from this contract will follow:
 * - There will be only one round (roundId=0)
 * - startedAt=0, updatedAt=quoteOracle.updatedAt()
 */
contract PendleChainlinkOracleWithQuote is PendleChainlinkOracle {
    // solhint-disable immutable-vars-naming
    address public immutable quoteOracle;
    int256 public immutable quoteScale;

    constructor(
        address _market,
        uint32 _twapDuration,
        PendleOracleType _baseOracleType,
        address _quoteOracle
    ) PendleChainlinkOracle(_market, _twapDuration, _baseOracleType) {
        quoteOracle = _quoteOracle;
        quoteScale = PMath.Int(10 ** AggregatorV3Interface(_quoteOracle).decimals());
    }

    /**
     * @notice The round data returned from this contract will follow:
     * - answer will satisfy 1 natural unit of PendleToken = (answer/1e18) natural unit of quoteToken
     * - In other words, 10**(PendleToken.decimals) = (answer/1e18) * 10**(quoteToken.decimals)
     * @return roundId always 0 for this contract
     * @return answer The answer (in 18 decimals)
     * @return startedAt always 0 for this contract
     * @return updatedAt will be the same as quoteOracle.updatedAt()
     * @return answeredInRound always 0 for this contract
     */
    function latestRoundData()
        public
        view
        override
        returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound)
    {
        (, int256 quoteAnswer, , uint256 quoteUpdatedAt, ) = AggregatorV3Interface(quoteOracle).latestRoundData();

        roundId = 0;
        answer = (_getPendleTokenPrice() * quoteAnswer) / quoteScale;
        updatedAt = quoteUpdatedAt;
        startedAt = 0;
        answeredInRound = 0;
    }
}
PendleLpOracleLib.sol 86 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "./PendlePYOracleLib.sol";

library PendleLpOracleLib {
    using PendlePYOracleLib for IPMarket;
    using PMath for uint256;
    using PMath for int256;
    using MarketMathCore for MarketState;

    /**
      * This function returns the approximated twap rate LP/asset on market, but take into account the current rate of SY
     This is to account for special cases where underlying asset becomes insolvent and has decreasing exchangeRate
     * @param market market to get rate from
     * @param duration twap duration
     */
    function getLpToAssetRate(IPMarket market, uint32 duration) internal view returns (uint256) {
        (uint256 syIndex, uint256 pyIndex) = market.getSYandPYIndexCurrent();
        uint256 lpToAssetRateRaw = _getLpToAssetRateRaw(market, duration, pyIndex);
        if (syIndex >= pyIndex) {
            return lpToAssetRateRaw;
        } else {
            return (lpToAssetRateRaw * syIndex) / pyIndex;
        }
    }

    /**
      * This function returns the approximated twap rate LP/asset on market, but take into account the current rate of SY
     This is to account for special cases where underlying asset becomes insolvent and has decreasing exchangeRate
     * @param market market to get rate from
     * @param duration twap duration
     */
    function getLpToSyRate(IPMarket market, uint32 duration) internal view returns (uint256) {
        (uint256 syIndex, uint256 pyIndex) = market.getSYandPYIndexCurrent();
        uint256 lpToAssetRateRaw = _getLpToAssetRateRaw(market, duration, pyIndex);
        if (syIndex >= pyIndex) {
            return lpToAssetRateRaw.divDown(syIndex);
        } else {
            return lpToAssetRateRaw.divDown(pyIndex);
        }
    }

    function _getLpToAssetRateRaw(
        IPMarket market,
        uint32 duration,
        uint256 pyIndex
    ) private view returns (uint256 lpToAssetRateRaw) {
        MarketState memory state = market.readState(address(0));

        int256 totalHypotheticalAsset;
        if (state.expiry <= block.timestamp) {
            // 1 PT = 1 Asset post-expiry
            totalHypotheticalAsset = state.totalPt + PYIndexLib.syToAsset(PYIndex.wrap(pyIndex), state.totalSy);
        } else {
            MarketPreCompute memory comp = state.getMarketPreCompute(PYIndex.wrap(pyIndex), block.timestamp);

            (int256 rateOracle, int256 rateHypTrade) = _getPtRatesRaw(market, state, duration);
            int256 cParam = LogExpMath.exp(comp.rateScalar.mulDown((rateOracle - comp.rateAnchor)));

            int256 tradeSize = (cParam.mulDown(comp.totalAsset) - state.totalPt).divDown(
                PMath.IONE + cParam.divDown(rateHypTrade)
            );

            totalHypotheticalAsset =
                comp.totalAsset -
                tradeSize.divDown(rateHypTrade) +
                (state.totalPt + tradeSize).divDown(rateOracle);
        }

        lpToAssetRateRaw = totalHypotheticalAsset.divDown(state.totalLp).Uint();
    }

    function _getPtRatesRaw(
        IPMarket market,
        MarketState memory state,
        uint32 duration
    ) private view returns (int256 rateOracle, int256 rateHypTrade) {
        uint256 lnImpliedRate = market.getMarketLnImpliedRate(duration);
        uint256 timeToExpiry = state.expiry - block.timestamp;
        rateOracle = MarketMathCore._getExchangeRateFromImpliedRate(lnImpliedRate, timeToExpiry);

        int256 rateLastTrade = MarketMathCore._getExchangeRateFromImpliedRate(state.lastLnImpliedRate, timeToExpiry);
        rateHypTrade = (rateLastTrade + rateOracle) / 2;
    }
}
PendlePYOracleLib.sol 102 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;

import "../../interfaces/IPMarket.sol";
import "../../core/libraries/math/PMath.sol";

// This library can & should be integrated directly for optimal gas usage.
// If you prefer not to integrate it directly, the PendlePtOracle contract (a pre-deployed version of this contract) can be used.
library PendlePYOracleLib {
    using PMath for uint256;
    using PMath for int256;

    /**
     * This function returns the twap rate PT/Asset on market, but take into account the current rate of SY
     This is to account for special cases where underlying asset becomes insolvent and has decreasing exchangeRate
     * @param market market to get rate from
     * @param duration twap duration
     */
    function getPtToAssetRate(IPMarket market, uint32 duration) internal view returns (uint256) {
        (uint256 syIndex, uint256 pyIndex) = getSYandPYIndexCurrent(market);
        if (syIndex >= pyIndex) {
            return getPtToAssetRateRaw(market, duration);
        } else {
            return (getPtToAssetRateRaw(market, duration) * syIndex) / pyIndex;
        }
    }

    /**
     * This function returns the twap rate YT/Asset on market, but take into account the current rate of SY
     This is to account for special cases where underlying asset becomes insolvent and has decreasing exchangeRate
     * @param market market to get rate from
     * @param duration twap duration
     */
    function getYtToAssetRate(IPMarket market, uint32 duration) internal view returns (uint256) {
        (uint256 syIndex, uint256 pyIndex) = getSYandPYIndexCurrent(market);
        if (syIndex >= pyIndex) {
            return getYtToAssetRateRaw(market, duration);
        } else {
            return (getYtToAssetRateRaw(market, duration) * syIndex) / pyIndex;
        }
    }

    /// @notice Similar to getPtToAsset but returns the rate in SY instead
    function getPtToSyRate(IPMarket market, uint32 duration) internal view returns (uint256) {
        (uint256 syIndex, uint256 pyIndex) = getSYandPYIndexCurrent(market);
        if (syIndex >= pyIndex) {
            return getPtToAssetRateRaw(market, duration).divDown(syIndex);
        } else {
            return getPtToAssetRateRaw(market, duration).divDown(pyIndex);
        }
    }

    /// @notice Similar to getPtToAsset but returns the rate in SY instead
    function getYtToSyRate(IPMarket market, uint32 duration) internal view returns (uint256) {
        (uint256 syIndex, uint256 pyIndex) = getSYandPYIndexCurrent(market);
        if (syIndex >= pyIndex) {
            return getYtToAssetRateRaw(market, duration).divDown(syIndex);
        } else {
            return getYtToAssetRateRaw(market, duration).divDown(pyIndex);
        }
    }

    /// @notice returns the raw rate without taking into account whether SY is solvent
    function getPtToAssetRateRaw(IPMarket market, uint32 duration) internal view returns (uint256) {
        uint256 expiry = market.expiry();

        if (expiry <= block.timestamp) {
            return PMath.ONE;
        } else {
            uint256 lnImpliedRate = getMarketLnImpliedRate(market, duration);
            uint256 timeToExpiry = expiry - block.timestamp;
            uint256 assetToPtRate = MarketMathCore._getExchangeRateFromImpliedRate(lnImpliedRate, timeToExpiry).Uint();
            return PMath.ONE.divDown(assetToPtRate);
        }
    }

    /// @notice returns the raw rate without taking into account whether SY is solvent
    function getYtToAssetRateRaw(IPMarket market, uint32 duration) internal view returns (uint256) {
        return PMath.ONE - getPtToAssetRateRaw(market, duration);
    }

    function getSYandPYIndexCurrent(IPMarket market) internal view returns (uint256 syIndex, uint256 pyIndex) {
        (IStandardizedYield SY, , IPYieldToken YT) = market.readTokens();

        syIndex = SY.exchangeRate();
        uint256 pyIndexStored = YT.pyIndexStored();

        if (YT.doCacheIndexSameBlock() && YT.pyIndexLastUpdatedBlock() == block.number) {
            pyIndex = pyIndexStored;
        } else {
            pyIndex = PMath.max(syIndex, pyIndexStored);
        }
    }

    function getMarketLnImpliedRate(IPMarket market, uint32 duration) internal view returns (uint256) {
        uint32[] memory durations = new uint32[](2);
        durations[0] = duration;

        uint216[] memory lnImpliedRateCumulative = market.observe(durations);
        return (lnImpliedRateCumulative[1] - lnImpliedRateCumulative[0]) / duration;
    }
}

Read Contract

checkMarketOracleState 0x1bdfe053
getOracle 0xca6ec89a → address
getOracleId 0x2d9a4a9d → bytes32
getOracleWithQuote 0xe233c366 → address
getOracleWithQuoteId 0xe54f48df → bytes32
pyLpOracle 0x8ca06ea6 → address

Write Contract 2 functions

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

createOracle 0x0b5af9f8
address market
uint32 twapDuration
uint8 baseOracleType
returns: address
createOracleWithQuote 0x451d27b8
address market
uint32 twapDuration
uint8 baseOracleType
address quoteOracle
returns: address

Recent Transactions

No transactions found for this address