Address Contract Verified
Address
0x2324bb9F7d651E0169B9df9194937759E08Acfa9
Balance
0 ETH
Nonce
1
Code Size
19491 bytes
Creator
0x2a355A6b...2155 at tx 0x78fb9522...f35066
Indexed Transactions
0
Contract Bytecode
19491 bytes
0x608080604052600436101561001357600080fd5b600090813560e01c90816305f53f4d14613a575750806306fdde03146139a557806309316dd3146138c15780631734163c146138a35780631959a002146138605780631c1cb32314613837578063200d2ed21461380857806336246db4146136175780633f4ba83a14613575578063481c6a751461354c5780634ebfc8141461350c57806359b6a0c9146134ee5780635c975abb146134cb5780635f67cc3614612b6b578063655ae37114612b4d5780636b5b96961461281c5780636d2b81111461274e5780636d34b618146123e05780636f307dc31461231a57806370480275146122ad5780637389250b14612226578063781c18db146121fd57806380f55605146121d45780638456cb591461216c578063863623bb146120e5578063871b689f146120c757806387b65207146120405780638ab1d68114611fd05780638fe0a86414611e9757806392b0f61f14611d35578063951e29c914611c0a5780639b19251a14611b3e5780639b39b0da14611b205780639d76ea5814611af75780639dd1cfb814611abe578063a3aad3aa14611aa0578063ad7a672f14611a7d578063b3ea322d146119b1578063b6b55f251461180b578063bd097e21146117e2578063c761d0b2146117a5578063c799940814611532578063c7ee91f114611514578063cc8dc34c146113b4578063d1012bc31461138b578063d936547e1461134c578063d94073d414611323578063dcf3e18b146112d5578063e1f06f541461115a578063e5a6b10f14611131578063e68fc0ee14611099578063f0d427c414610fc2578063f399efe814610deb578063f66a774914610ce4578063f677cf0d14610cbe578063f78705c314610bdc578063f851a44014610bb3578063f887ea4014610b8a5763f8a1154d146102aa57600080fd5b34610b875760031961016036820112610b83576004356001600160401b038111610b7f576102dc903690600401613e14565b916024356001600160401b038111610786576102fc903690600401613e14565b9290604435906001600160a01b0382168203610b7b5761031a613c0c565b93608435906001600160a01b0382168203610b6e576001600160401b0360c43511610b77576101c09060c43536030112610b735760e435946001600160a01b0386168603610b6e5761010435966001600160a01b0388168803610b6e5761012435936001600160a01b0385168503610b6e5761014435966001600160a01b0388168803610b6e57600d549a60ff8c60081c16159b8c809d610b61575b8015610b4a575b15610aee5760ff198116600117600d558c610adc575b5061040560ff600d5460081c166103e981614976565b6103f281614976565b6001600e5561040081614976565b614976565b60ff19607254166072556001600160401b038111610ac8576104318161042c60aa54613a7c565b613e7d565b8c918d601f8311600114610a44576104529390918361078a575b5050613f7f565b60aa555b6001600160401b038211610a305761046f60ab54613a7c565b601f81116109cf575b508a90601f83116001146109495761049992918c918361078a575050613f7f565b60ab555b60ac80546001600160a01b03199081166001600160a01b039384161790915560b0805482169383169390931790925560ae805483169382169390931790925560a43560b15560c8805482169383169390931790925560a780548316939091169290921790915560ad805490911633179055620f424060c43560040135111580610941575b1561090b5760e460c4350135428111156108ce5761010460c435013590808211156108915760c4356004013560b855602460c435013560b955604460c435013560ba55606460c435013560bb55608460c435013560bc5560a460c435013560bd5560c48035013560be5560bf5560c0556105a661012460c4350160c43560040161463d565b906001600160401b038211610809576105c9826105c460c154613a7c565b613ed3565b8590601f831160011461081d576105e9929187918361078a575050613f7f565b60c1555b60c43561014481013560c25561016481013560c3556106149061018481019060040161463d565b906001600160401b038211610809576106378261063260c454613a7c565b613f29565b8590601f831160011461079557610657929187918361078a575050613f7f565b60c4555b6101a460c435013560ff81168091036107865760c5805460ff191691909117905560a680546001600160a01b039283166001600160a01b03199182161790915560a88054939092169083168117909155604051630b2339af60e21b815291606091839160049183918816175afa801561077b5783918491610747575b5060a580546001600160a01b039283166001600160a01b03199182161790915560a4805493909216921691909117905561070e5780f35b61ff0019600d5416600d557f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb3847402498602060405160018152a180f35b905061076b915060603d606011610774575b6107638183613b95565b810190613f92565b915090386106d7565b503d610759565b6040513d85823e3d90fd5b8480fd5b01359050388061044b565b60c48752869291600080516020614bae83398151915291905b601f19841685106107f1576001945083601f198116106107d7575b505050811b0160c45561065b565b0135600019600384901b60f8161c191690553880806107c9565b818101358355602094850194600190930192016107ae565b634e487b7160e01b86526041600452602486fd5b60c18752869291600080516020614b8e83398151915291905b601f1984168510610879576001945083601f1981161061085f575b505050811b0160c1556105ed565b0135600019600384901b60f8161c19169055388080610851565b81810135835560209485019460019093019201610836565b60405162461bcd60e51b8152602060048201526015602482015274496e76616c6964206d61747572697479206461746560581b6044820152606490fd5b60405162461bcd60e51b8152602060048201526015602482015274496e76616c69642069737375616e6365206461746560581b6044820152606490fd5b60405162461bcd60e51b815260206004820152600e60248201526d24b73b30b634b21031b7bab837b760911b6044820152606490fd5b506001610521565b60ab8c528b92917ffc377260a69a39dd786235c89f4bcd5d9639157731cac38071a0508750eb115a91905b601f19841685106109b7576001945083601f1981161061099d575b505050811b0160ab5561049d565b0135600019600384901b60f8161c1916905538808061098f565b81810135835560209485019460019093019201610974565b60ab6000527ffc377260a69a39dd786235c89f4bcd5d9639157731cac38071a0508750eb115a601f840160051c810160208510610a29575b601f830160051c82018110610a1d575050610478565b60008155600101610a07565b5080610a07565b634e487b7160e01b8b52604160045260248bfd5b60aa8152927f550d3de95be0bd28a79c3eb4ea7f05692c60b0602e48b49461e703379b08a71a91905b601f1984168510610ab0576001945083601f19811610610a96575b505050811b0160aa55610456565b0135600019600384901b60f8161c19169055388080610a88565b81810135835560209485019460019093019201610a6d565b634e487b7160e01b8d52604160045260248dfd5b61ffff191661010117600d55386103d3565b60405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608490fd5b50303b1580156103bd5750600160ff8216146103bd565b50600160ff8216106103b6565b600080fd5b8780fd5b8880fd5b8680fd5b8280fd5b5080fd5b80fd5b5034610b875780600319360112610b875760a6546040516001600160a01b039091168152602090f35b5034610b875780600319360112610b875760af546040516001600160a01b039091168152602090f35b5034610b875780600319360112610b8757610bf561489a565b33815260c660205260016040822001548015610c7c57610c1e81610c1761458b565b1015614478565b60c854610c3790829033906001600160a01b031661485e565b33825260c66020528160016040822001556040519081527fa93ca044f00614b264735d8e3de7926662d07bed4788c17f6c2a348c4e5013d760203392a26001600e5580f35b60405162461bcd60e51b815260206004820152601a6024820152794e6f206f7074696f6e207061796f757420617661696c61626c6560301b6044820152606490fd5b5034610b875780600319360112610b8757602060ff60c85460a01c166040519015158152f35b5034610b875780600319360112610b87575460ff811660405160009060019160015492610d1084613a7c565b9081845260209485600182169182600014610dc9575050600114610d86575b505090610d4181610d7a930382613b95565b60ff60025416926040519585610d578897613df4565b865260081c6001600160a01b031690850152608060408501819052840190613bb6565b90151560608301520390f35b8491939250600160005281600020936000915b818310610db257509293508301019050610d4182610d2f565b855485840185015294850194869390920191610d99565b60ff19168187015292151560051b85019092019250610d419150839050610d2f565b5034610b87576040366003190112610b6e576004356001600160401b03808211610b6e5736602383011215610b6e5781600401356024610e2a82613c98565b93610e386040519586613b95565b828552602092828487019160051b83010191368311610b6e5783859101915b838310610faa57505050508035928311610b6e5736602384011215610b6e57826004013592610e8584613c98565b93610e936040519586613b95565b808552828486019160051b83010191368311610b6e5783859101915b838310610f9a5750505050610ec26148f0565b60ff60b75460a01c16906005821015610f8857506003610ee29114613fd3565b33845260c98152610ef960ff604086205416614538565b825192845b848110610f09578580f35b80610f1660019286614577565b51828060a01b039081610f298487614577565b5116895260c68652610f4060408a2091825461409a565b9055610f4c8285614577565b51167f1ff53d98ca6c89b5cdc064341cb02a3995830e24293105235c8a89339afe2dbb85610f7a8489614577565b51604051908152a201610efe565b634e487b7160e01b8652602160045285fd5b8235815291810191859101610eaf565b8190610fb584613c22565b8152019101908490610e57565b5034610b87576020366003190112610b875760043560ff60b75460a01c166005811015611085576004610ff59114614604565b60b0546001600160a01b03908116330361104e578161101b9160c8541630903390614934565b8060b4556040519081527ff4dcc33f40b3c2fd166eb92787bad1920dca20f18a25c11eb096ca0fa26cc03460203392a280f35b60405162461bcd60e51b815260206004820152600f60248201526e139bdd08185b88195e1dd85b1b195d608a1b6044820152606490fd5b634e487b7160e01b83526021600452602483fd5b5034610b875760209081600319360112610b87576110b5613bf6565b60ae546040516370a0823160e01b81526001600160a01b03928316600482015291849183916024918391165afa91821561112557916110f8575b50604051908152f35b90508181813d831161111e575b61110f8183613b95565b81010312610b6e5751386110ef565b503d611105565b604051903d90823e3d90fd5b5034610b875780600319360112610b875760c8546040516001600160a01b039091168152602090f35b5034610b875780600319360112610b875761117361489a565b60ff60b75460a01c1660058110156112c157600161119191146144fd565b60ae546040516370a0823160e01b8152336004820152906001600160a01b03908116602083602481845afa9283156112b6578493611282575b50803b1561127e5783806040518093632770a7eb60e21b82528183816111f48a3360048401613dd9565b03925af191821561127157849261125a575b505061121791339060c8541661485e565b6112238160b2546140a7565b60b2556040519081527fee1b5abe14e43ee34008f06f51efca5382c42fb48b0a040fd7a5f5c630cb558060203392a26001600e5580f35b611265919250613b4c565b610b7f57818338611206565b50604051903d90823e3d90fd5b8380fd5b9092506020813d6020116112ae575b8161129e60209383613b95565b81010312610b6e575191386111ca565b3d9150611291565b6040513d86823e3d90fd5b634e487b7160e01b82526021600452602482fd5b5034610b87576020366003190112610b875760043560c754811015610b83576112fd90613da4565b50805460019091015460405191829161131f916001600160a01b031683613dd9565b0390f35b5034610b875780600319360112610b875760a4546040516001600160a01b039091168152602090f35b5034610b87576020366003190112610b875760209060ff906040906001600160a01b03611377613bf6565b16815260c984522054166040519015158152f35b5034610b875780600319360112610b875760ad546040516001600160a01b039091168152602090f35b5034610b87576113c336613caf565b6113cb6148f0565b60ff60b75460a01c1660058110156115005760046113e99114614604565b33835260209160c9835261140360ff604086205416614538565b60b4548151906114ac575b509160405192604084016040855281518091528260608601920190865b81811061148f5750505083810382850152818084519283815201930191855b82811061147b57867f34dd8f516116a39a7930e2c19f3122c98ad22ab5270854728d63fd50488f191087870388a180f35b83518552938101939281019260010161144a565b82516001600160a01b03168452928401929184019160010161142b565b845b8181106114c15750508360b4553861140e565b806114ce60019286614577565b51828060a01b036114df8387614577565b5116885260c687526114f88360408a200191825461409a565b9055016114ae565b634e487b7160e01b84526021600452602484fd5b5034610b875780600319360112610b8757602060a954604051908152f35b5034610b875780600319360112610b875760ac546001600160a01b039061155c9082163314613e41565b60ff60b75460a01c16600581101561108557600461157a9114614604565b60c8549060ff8260a01c161561176e5760a4546040516370a0823160e01b815230600482015260209183168282602481845afa918215611763578692611734575b5085948660a95560ff60a01b191660c85581611601575b85600080516020614bce83398151915286868360b35560a654166115fb60405192839283613dd9565b0390a180f35b61162b94508183918560a654168860405180998195829463095ea7b360e01b845260048401613dd9565b03925af191821561172957611692946040936116fb575b50508260a654168360a55416918661165d8660a7541661481a565b938551978895869485936323f8ef1160e11b8552306004860152602485015260448401526080606484015260848301906140e7565b03925af1801561077b5783906116bb575b9150600080516020614bce83398151915238806115d2565b506040823d6040116116f3575b816116d560409383613b95565b81010312610b7f57600080516020614bce83398151915291516116a3565b3d91506116c8565b8161171a92903d10611722575b6117128183613b95565b8101906140b4565b503880611642565b503d611708565b6040513d87823e3d90fd5b9091508281813d831161175c575b61174c8183613b95565b81010312610b6e575190386115bb565b503d611742565b6040513d88823e3d90fd5b60405162461bcd60e51b815260206004820152600f60248201526e139bdd08191a5cdd1c9a589d5d1959608a1b6044820152606490fd5b5034610b87576020366003190112610b87576020906001906040906001600160a01b036117d0613bf6565b16815260c68452200154604051908152f35b5034610b875780600319360112610b875760b7546040516001600160a01b039091168152602090f35b5034610b87576020366003190112610b875760043561182861489a565b6118306148f0565b60ff60b75460a01c16600581101561108557600161184e91146144fd565b801561197d5761187c61185f61466f565b61186a81151561400c565b61187660b1549161406c565b90614043565b60b2549061188a838361409a565b1161194657816118999161409a565b60b2558160018060a01b036118b6838260c8541630903390614934565b60ae5416803b15610b83578160405180926340c10f1960e01b82528183816118e2893360048401613dd9565b03925af1801561193b57611927575b50506040519081527fe1fffcc4923d04b559f4d29a8bfc6cda04eb5b0d3c460751c2402c5c5cc9109c60203392a26001600e5580f35b61193090613b4c565b610b835781386118f1565b6040513d84823e3d90fd5b60405162461bcd60e51b815260206004820152600f60248201526e141c9bd91d58dd081a5cc8199d5b1b608a1b6044820152606490fd5b60405162461bcd60e51b815260206004820152600c60248201526b47726561746572207a65726f60a01b6044820152606490fd5b5034610b875780600319360112610b87576119ca6148f0565b33815260c96020526119e260ff604083205416614538565b60b75460ff8160a01c166005811015611085578015908115611a72575b5015611a3c5760ff60a01b1916600160a01b1760b7557fb63781dfbb31c3b8f6fe9a21184aa56a6e90decb52c36e061db99f13b89572b08180a180f35b60405162461bcd60e51b815260206004820152600e60248201526d496e76616c69642073746174757360901b6044820152606490fd5b6004915014386119ff565b5034610b875780600319360112610b87576020611a9861458b565b604051908152f35b5034610b875780600319360112610b8757602060b454604051908152f35b5034610b87576020366003190112610b87576020906040906001600160a01b03611ae6613bf6565b16815260c683522054604051908152f35b5034610b875780600319360112610b875760ae546040516001600160a01b039091168152602090f35b5034610b875780600319360112610b8757602060b254604051908152f35b5034610b87576020366003190112610b8757611b58613bf6565b60ac546001600160a01b039190611b729083163314613e41565b1680825260c960205260ff604083205416611bc55780825260c960205260408220805460ff191660011790557f6bc201575d15207e99d0768e5a03902307f4963938d08a25c182998691f3499d8280a280f35b60405162461bcd60e51b815260206004820152601e60248201527f4163636f756e7420697320616c72656164792077686974656c697374656400006044820152606490fd5b5034610b87576020366003190112610b875760043560ff60b75460a01c1660058110156110855760028114908115611d2a575b5015611ce957611c5860018060a01b0360ac54163314613e41565b620f424081111580611ce1575b15611c9c576020817f19daed5719dfd69b2d92b1d112721391243b2a08bedb471403fa7b7a8c995bc69260b855604051908152a180f35b60405162461bcd60e51b815260206004820152601f60248201527f4c657373207468616e2030206f722067726561746572207468616e20313030006044820152606490fd5b506001611c65565b60405162461bcd60e51b81526020600482015260196024820152784e656974686572204c6f636b6564206e6f72204d617475726560381b6044820152606490fd5b600491501438611c3d565b5034610b8757611d4436613caf565b9060ff60b75460a01c166005811015611500576003611d639114613fd3565b60af546001600160a01b039081163303611e6657815191845b838110611d87578580f35b82611d928284614577565b5116611d9e8287614577565b5160405191604083018381106001600160401b03821117611e505760405282526020820190815260c7908154600160401b811015611e3c57611de7906001938482019055613da4565b939093611e28575183546001600160a01b03191690871617835551910155600190611e128187614577565b51611e2060b591825461409a565b905501611d7c565b634e487b7160e01b8a5260048a905260248afd5b634e487b7160e01b8a52604160045260248afd5b634e487b7160e01b600052604160045260246000fd5b60405162461bcd60e51b81526020600482015260096024820152682737ba1030b236b4b760b91b6044820152606490fd5b5034610b875780600319360112610b875760ff60b75460a01c1660058110156112c1576003611ec69114613fd3565b60ac546001600160a01b0390611edf9082163314613e41565b60c890611ef78160c8541660b5549030903390614934565b60c75491835b838110611fa057848060b5558060b65560c7548160c75580611f4b575b507f6332227f4fb33cedf0599af0587fae2808ec10fe1fbac6bc3b889ac1403c8b09602060b554604051908152a180f35b60016001600160ff1b0382168203611f8c5760c78352602083209160011b8201915b828110611f7b575050611f1a565b808460029255848382015501611f6d565b634e487b7160e01b83526011600452602483fd5b600190611fca8484541685611fb484613da4565b50541684611fc185613da4565b5001549161485e565b01611efd565b5034610b87576020366003190112610b8757611fea613bf6565b60ac546001600160a01b0391906120049083163314613e41565b1680825260c960205260408220805460ff191690557f80f4d7be9d601c8487132194fd218772956b9b20b704060810edd362c193220c8280a280f35b5034610b875780600319360112610b87576120596148f0565b60b75460ff8160a01c1660058110156110855760036120789114613fd3565b33825260c960205261209060ff604084205416614538565b60ff60a01b1916600160a21b1760b7557f741032e4e76b366a60d04eb05f4c7eaecf05193e66cfa049095807de78a609608180a180f35b5034610b875780600319360112610b8757602060b354604051908152f35b5034610b875780600319360112610b87576120fe6148f0565b60b75460ff8160a01c16600581101561108557600261211d91146144c4565b33825260c960205261213560ff604084205416614538565b60ff60a01b1916600360a01b1760b7557f51137ebbd092d866dceadcf37e99e11e51d47a795872564b3d8e15aaff961a728180a180f35b5034610b875780600319360112610b875761219260018060a01b0360ac54163314613e41565b61219a6148f0565b600160ff1960725416176072557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586020604051338152a180f35b5034610b875780600319360112610b875760a8546040516001600160a01b039091168152602090f35b5034610b875780600319360112610b875760a5546040516001600160a01b039091168152602090f35b5034610b875780600319360112610b875761223f6148f0565b60b75460ff8160a01c16600581101561108557600161225e91146144fd565b33825260c960205261227660ff604084205416614538565b60ff60a01b1916600160a11b1760b7557f06080d11a902ce1934aa08a72556f22447623971f2253f80690572628d83d4ae8180a180f35b5034610b87576020366003190112610b87576122c7613bf6565b60ac546001600160a01b0391906122e19083163314613e41565b168060018060a01b031960af54161760af557fad6de4452a631e641cb59902236607946ce9272b9b981f2f80e8d129cb9084ba8280a280f35b5034610b875780600319360112610b875760405160ab5460008261233d83613a7c565b91828252602093600190856001821691826000146123c0575050600114612380575b5061236c92500383613b95565b61131f604051928284938452830190613bb6565b84915060ab60005281600020906000915b8583106123a857505061236c93508201018561235f565b80548389018501528794508693909201918101612391565b60ff19168582015261236c95151560051b850101925087915061235f9050565b5034610b875760206003198181360112610b7f5760043563ffffffff918282168092036107865760ac546001600160a01b0393906124219085163314613e41565b60ff60b75460a01c16600581101561273a57600261243f91146144c4565b60c8549060ff8260a01c166126ff576305f5e100918285116126ca5760ff60a01b198116600160a01b1760c855848303918083116126b65787908993169384612640575b5050506124956124be9160b2546140a7565b86818760a754168860a654168b60405180978195829463095ea7b360e01b845260048401613dd9565b03925af19081156126355760609261257f92612618575b508660a6541690898860a854168960a754166124ef6146e8565b50604051936124fd85613b5f565b8185528c85015260408401528186840152612516614736565b608084015261258f6040519889968795869463640fc23d60e11b8652306004870152602486015285604486015260085460648601526009546084860152600a5460a4860152600b5460c4860152600c5460e48601526101406101048601526101448501906140e7565b9083820301610124840152614169565b03925af1928315611763577fd9a754f76c93ebf46e457da10ca41104877828ed1d4c150b339142bd5397a8209360409388916125e7575b5060a95560b25460b3558460b054169460a65416958351928352820152a380f35b612609915060603d606011612611575b6126018183613b95565b8101906140cc565b5050386125c6565b503d6125f7565b61262e90893d8b11611722576117128183613b95565b50386124d5565b6040513d8a823e3d90fd5b61267793506126518560b254614043565b0480928860b054168b8a60405180988196829563a9059cbb60e01b845260048401613dd9565b0393165af1908115612635576124be9261249592612699575b88919350612483565b6126af90893d8b11611722576117128183613b95565b5038612690565b634e487b7160e01b89526011600452602489fd5b60405162461bcd60e51b815260048101889052600d60248201526c04c657373207468616e2031303609c1b6044820152606490fd5b60405162461bcd60e51b8152600481018790526013602482015272105b1c9958591e48191a5cdd1c9a589d5d1959606a1b6044820152606490fd5b634e487b7160e01b87526021600452602487fd5b5034610b875780600319360112610b875761276761489a565b33815260c6602052604081205480156127e15761278681610c1761458b565b60c85461279f90829033906001600160a01b031661485e565b33825260c66020528160408120556040519081527fd60c6c8c3aa538cabff497b8a8518310c5aa03e33306dba00a1b4d95e7f46da660203392a26001600e5580f35b60405162461bcd60e51b81526020600482015260136024820152724e6f20636f75706f6e20617661696c61626c6560681b6044820152606490fd5b5034610b875760206003198181360112610b7f576004359160ff60b75460a01c166005811015612b395760036128529114613fd3565b61285a61466f565b9061286682151561400c565b60c254926128748486614043565b600a61288f60c354926118766128898861406c565b85614043565b049460018060a01b03918260ae541695604051916370a0823160e01b835233600484015286836024818b5afa918215612b2e578a938c93612af5575b50600a916128e36128ef95966118766128e89461406c565b614043565b049061407a565b10612abc5761290c61290360a95487614043565b60b3549061407a565b936129198760b65461409a565b60b6556129288660b2546140a7565b60b255803b15610b7357876040518092632770a7eb60e21b82528183816129538c3360048401613dd9565b03925af1801561263557612aa9575b5061298f83858360a454168460a654168b60405180968195829463095ea7b360e01b845260048401613dd9565b03925af1801561263557612a8c575b5060606129f68260a654168360a854168a6129bc8660a7541661481a565b91612a0560405198899687958694631652a23360e21b865230600487015260248601528d604486015260a0606486015260a48501906140e7565b90838203016084840152614169565b03925af1908115612a8157612a27928892612a5e575b50339060c8541661485e565b60405193845283015260408201527fe90768c97e3dab1b6c2d329815945f65d700d4da35edf5fd11fa252a2b87364060603392a280f35b612a7891925060603d606011612611576126018183613b95565b50509038612a1b565b6040513d89823e3d90fd5b612aa290843d8611611722576117128183613b95565b503861299e565b612ab590979197613b4c565b9538612962565b60405162461bcd60e51b81526004810184905260116024820152704e6f7420656e6f75676820626c6f636b7360781b6044820152606490fd5b91935091508681813d8111612b27575b612b0f8183613b95565b81010312612b23575189929091600a6128cb565b8a80fd5b503d612b05565b6040513d8d823e3d90fd5b634e487b7160e01b85526021600452602485fd5b5034610b875780600319360112610b8757602060b554604051908152f35b5034610b8757600319608036820112610b83576004356001600160401b038111610b7f57612b9d903690600401613c51565b906001600160401b0360243511610b7f576101c0809160243536030112610b7f576040519081018181106001600160401b038211176134b75760409081526004602480359182013584528101356020840152604481013591830191909152606481013560608301526084810135608083015260a481013560a083015260c481013560c083015260e481013560e08301526101048101356101008301526001600160401b036101249091013511610b7f57612c633660243561012481013501600401613c51565b610120820152610144602435013561014082015261016460243501356101608201526001600160401b03610184602435013511610b7f57612cb03660243561018481013501600401613c51565b6101808201526101a4602435013560ff8116810361127e576101a08201526044356001600160a01b0381169003610b7f57612ce9613c0c565b9060ff60b75460a01c16600581101590816134a35760028114918215613496575b8215613485575b50501561343157612d2d60018060a01b0360ac54163314613e41565b60e08101514210156134005761010081015160e082015110156133cf57620f42408082511115806133c7575b1561339357620186a08060a084015111158061338b575b1561335a5760c0830151111580613352575b15613321576101208201515160028110159081613315575b50156132dd578060208301511115806132d5575b1561329b57806040830151111580613293575b1561325957806060830151111580613251575b1561321757608082015111158061320f575b156131d55782516001600160401b0381116131c157612e0a8161042c60aa54613a7c565b6020601f821160011461313e579080612e2a928791613133575b50613f7f565b60aa555b60a680546001600160a01b0360443581166001600160a01b03199283161790925560a880549285169290911682179055604051630b2339af60e21b815290606090829060049082905afa8015611729578591869161310f575b5060a580546001600160a01b039283166001600160a01b03199182161790915560a48054939092169216919091179055805160b85560a081015160bd5560c081015160be55602081015160b955604081015160ba55606081015160bb55608081015160bc5561014081015160c2556101208101518051906001600160401b03821161080957612f1b826105c460c154613a7c565b602090601f831160011461309e57612f3c9291879183612ff8575050613f7f565b60c1555b6101808101518051906001600160401b03821161080957612f668261063260c454613a7c565b602090601f83116001146130035792612fb283612fd79694610100947ff4b936bce2dcf5f3e5d76afaa02b4e3e52004fccec983fe1880848804b723e6c99978b92612ff8575050613f7f565b60c4555b60e081015160bf55015160c055604051928392606084526060840190613bb6565b6044356001600160a01b03908116602085015290911660408301520390a180f35b01519050388061044b565b60c48752600080516020614bae8339815191529190601f198416885b818110613086575093610100937ff4b936bce2dcf5f3e5d76afaa02b4e3e52004fccec983fe1880848804b723e6c98969360019383612fd79a981061306d575b505050811b0160c455612fb6565b015160001960f88460031b161c1916905538808061305f565b9293602060018192878601518155019501930161301f565b60c18752600080516020614b8e8339815191529190601f198416885b8181106130f757509084600195949392106130de575b505050811b0160c155612f40565b015160001960f88460031b161c191690553880806130d0565b929360206001819287860151815501950193016130ba565b905061312a915060603d606011610774576107638183613b95565b91509038612e87565b905085015138612e24565b60aa86528591907f550d3de95be0bd28a79c3eb4ea7f05692c60b0602e48b49461e703379b08a71a905b601f19831684106131a9576001935082601f19811610613190575b5050811b0160aa55612e2e565b86015160001960f88460031b161c191690553880613183565b86810151825560209384019360019092019101613168565b634e487b7160e01b85526041600452602485fd5b60405162461bcd60e51b8152602060048201526012602482015271115c9c9bdc881cdd1c9a5ad9541c9a58d94d60721b6044820152606490fd5b506001612de6565b60405162461bcd60e51b81526020600482015260126024820152714572726f7220737472696b6550726963653360701b6044820152606490fd5b506001612dd4565b60405162461bcd60e51b815260206004820152601260248201527122b93937b91039ba3934b5b2a83934b1b29960711b6044820152606490fd5b506001612dc1565b60405162461bcd60e51b81526020600482015260126024820152714572726f7220737472696b6550726963653160701b6044820152606490fd5b506001612dae565b60405162461bcd60e51b815260206004820152601060248201526f08ae4e4dee440c2e0f240d8cadccee8d60831b6044820152606490fd5b600c9150111538612d9a565b60405162461bcd60e51b815260206004820152600960248201526822b93937b9103a391960b91b6044820152606490fd5b506001612d82565b60405162461bcd60e51b81526020600482015260096024820152684572726f722074723160b81b6044820152606490fd5b506001612d70565b60405162461bcd60e51b815260206004820152600c60248201526b22b93937b91031b7bab837b760a11b6044820152606490fd5b506001612d59565b60405162461bcd60e51b815260206004820152600960248201526826aa103134b3b3b2b960b91b6044820152606490fd5b60405162461bcd60e51b815260206004820152600960248201526824a2103134b3b3b2b960b91b6044820152606490fd5b60405162461bcd60e51b815260206004820152602660248201527f4e656974686572204163636570746564206e6f72204c6f636b6564206e6f72206044820152654d617475726560d01b6064820152608490fd5b909150612b39576001143880612d11565b5060048114915085612d0a565b634e487b7160e01b86526021600452602486fd5b634e487b7160e01b84526041600452602484fd5b5034610b875780600319360112610b8757602060ff607254166040519015158152f35b5034610b875780600319360112610b8757602060b154604051908152f35b5034610b875780600319360112610b875760a0600854600954600a54600b5490600c54926040519485526020850152604084015260608301526080820152f35b5034610b875780600319360112610b875760ac546040516001600160a01b039091168152602090f35b5034610b875780600319360112610b875761359b60018060a01b0360ac54163314613e41565b60725460ff8116156135db5760ff19166072557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa6020604051338152a180f35b60405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606490fd5b5034610b875780600319360112610b875760b85460b9549060ba549260bb549160bc5460bd549160be549060bf5460c0549060405193878560c1549161365c83613a7c565b80835292600181169081156137e9575060011461379d575b61368092500386613b95565b60c2549660c354966040518a819b9060c4549061369c82613a7c565b808552916001811690811561377f5750600114613739575b5050036136c1908b613b95565b60c55460ff169a6040519d8e809e6101c099825260208201526040015260608d015260808c015260a08b015260c08a015260e089015261010088015280610120880152860161370f91613bb6565b9161014086015261016085015283810361018085015261372e91613bb6565b906101a08301520390f35b60c481529150600080516020614bae8339815191525b818310613764575050810160200138806136b4565b80602092948385600194549201015201910190918c9261374f565b9150506020925060ff191682840152151560051b82010138806136b4565b5060c18a52908990600080516020614b8e8339815191525b8183106137cd57505090602061368092820101613674565b6020919350806001915483858c010152019101909187926137b5565b6020925061368094915060ff191682840152151560051b820101613674565b5034610b875780600319360112610b875760ff60b75460a01c1660405190600581101561108557602092508152f35b5034610b875780600319360112610b875760a7546040516001600160a01b039091168152602090f35b5034610b87576020366003190112610b875760409081906001600160a01b03613887613bf6565b16815260c6602052206001815491015482519182526020820152f35b5034610b875780600319360112610b8757602060b654604051908152f35b5034610b875780600319360112610b875760035460045460405160075493926001600160a01b031691836138f486613a7c565b9081845260209687916001916001811690816000146139825750600114613946575b5050505061392a8261131f94950383613b95565b6040519485948552840152606060408401526060830190613bb6565b92919650600783528683205b82841061396f5750505082019093019261392a8561131f84613916565b8054868501890152928701928101613952565b60ff19168488015250505090151560051b830101935061392a8561131f84613916565b5034610b875780600319360112610b875760405190808260aa54916139c983613a7c565b9283835260209460019186600182169182600014613a355750506001146139f9575b505061236c92500383613b95565b9085925060aa82528282205b858310613a1d57505061236c935082010138806139eb565b80548389018501528794508693909201918101613a05565b925093505061236c94915060ff191682840152151560051b82010138806139eb565b905034610b835781600319360112610b835760b0546001600160a01b03168152602090f35b90600182811c92168015613aac575b6020831014613a9657565b634e487b7160e01b600052602260045260246000fd5b91607f1691613a8b565b805460009392613ac582613a7c565b91828252602093600191600181169081600014613b2d5750600114613aec575b5050505050565b90939495506000929192528360002092846000945b838610613b1957505050500101903880808080613ae5565b805485870183015294019385908201613b01565b60ff19168685015250505090151560051b010191503880808080613ae5565b6001600160401b038111611e5057604052565b60a081019081106001600160401b03821117611e5057604052565b608081019081106001600160401b03821117611e5057604052565b90601f801991011681019081106001600160401b03821117611e5057604052565b919082519283825260005b848110613be2575050826000602080949584010152601f8019910116010190565b602081830181015184830182015201613bc1565b600435906001600160a01b0382168203610b6e57565b606435906001600160a01b0382168203610b6e57565b35906001600160a01b0382168203610b6e57565b6001600160401b038111611e5057601f01601f191660200190565b81601f82011215610b6e57803590613c6882613c36565b92613c766040519485613b95565b82845260208383010111610b6e57816000926020809301838601378301015290565b6001600160401b038111611e505760051b60200190565b906040600319830112610b6e576001600160401b03600435818111610b6e5783602382011215610b6e57806004013590613ce882613c98565b90613cf66040519283613b95565b82825260209260248484019160051b83010191878311610b6e576024859101915b838310613d8c575050505093602435928311610b6e5780602384011215610b6e578260040135613d4681613c98565b93613d546040519586613b95565b81855260248486019260051b820101928311610b6e57602401905b828210613d7d575050505090565b81358152908301908301613d6f565b8190613d9784613c22565b8152019101908490613d17565b60c754811015613dc35760c760005260206000209060011b0190600090565b634e487b7160e01b600052603260045260246000fd5b6001600160a01b039091168152602081019190915260400190565b60041115613dfe57565b634e487b7160e01b600052602160045260246000fd5b9181601f84011215610b6e578235916001600160401b038311610b6e5760208381860195010111610b6e57565b15613e4857565b60405162461bcd60e51b815260206004820152600d60248201526c2737ba10309036b0b730b3b2b960991b6044820152606490fd5b601f8111613e89575050565b60009060aa6000526020600020906020601f850160051c83019410613ec9575b601f0160051c01915b828110613ebe57505050565b818155600101613eb2565b9092508290613ea9565b601f8111613edf575050565b60009060c16000526020600020906020601f850160051c83019410613f1f575b601f0160051c01915b828110613f1457505050565b818155600101613f08565b9092508290613eff565b601f8111613f35575050565b60009060c46000526020600020906020601f850160051c83019410613f75575b601f0160051c01915b828110613f6a57505050565b818155600101613f5e565b9092508290613f55565b8160011b916000199060031b1c19161790565b90816060910312610b6e5780516001600160a01b0392908381168103610b6e579260208301518181168103610b6e576040909301519081168103610b6e5790565b15613fda57565b60405162461bcd60e51b815260206004820152600a602482015269139bdd081a5cdcdd595960b21b6044820152606490fd5b1561401357565b60405162461bcd60e51b8152602060048201526008602482015267446563696d616c7360c01b6044820152606490fd5b8181029291811591840414171561405657565b634e487b7160e01b600052601160045260246000fd5b604d811161405657600a0a90565b8115614084570490565b634e487b7160e01b600052601260045260246000fd5b9190820180921161405657565b9190820391821161405657565b90816020910312610b6e57518015158103610b6e5790565b90816060910312610b6e578051916040602083015192015190565b90608060018060a01b03928381511683526020810151602084015283604082015116604084015283606082015116606084015201519160a06080830152825161412f81613df4565b60a083015260208301511660c0820152610100606061415e6040850151608060e0860152610120850190613bb6565b930151151591015290565b60a081019060018060a01b03600354168152600454602082015260a0604082015260055480925260c0810160c08360051b8301019260056000526020600020916000905b82821061438f57505050508082036060820152600654808352602083019060208160051b8501019360066000526020600020926000915b8383106142a457505050505060808183039101526000906007549061420882613a7c565b808252916001908181169081156142835750600114614228575b50505090565b600760009081529293507fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c6885b84841061426b575050602092500101388080614222565b80546020858501810191909152909301928101614254565b9150506020935060ff929192191683830152151560051b0101388080614222565b90919293956020600d600192601f198582030186526060815289546060820152838a0154608082015260028a015460a082015260038a015460ff81166142e981613df4565b60c083015260a085901b859003600891821c811660e084015260048c0154811661010084015260058c0154811661012084015260068c01541661014083015260078b01546101608301528a01546101808083019190915260098b01546101a08301526101c08201526143756143656101e08301600a8d01613ab6565b82810385840152600b8c01613ab6565b906040600c8c0154910152980193019301919392906141e4565b909192946020600d60019260bf198882030185526060808252895490820152838901546080820152600289015460a0820152600389015460ff81166143d381613df4565b60c083015260a085901b859003600891821c811660e084015260048b0154811661010084015260058b0154811661012084015260068b01541661014083015260078a01546101608301528901546101808083019190915260098a01546101a08301526101c082015261445f61444f6101e08301600a8c01613ab6565b82810385840152600b8b01613ab6565b906040600c8b01549101529701920192019092916141ad565b1561447f57565b60405162461bcd60e51b815260206004820152601d60248201527f496e73756666696369656e7420636f6e74726163742062616c616e63650000006044820152606490fd5b156144cb57565b60405162461bcd60e51b815260206004820152600a602482015269139bdd081b1bd8dad95960b21b6044820152606490fd5b1561450457565b60405162461bcd60e51b815260206004820152600c60248201526b139bdd081858d8d95c1d195960a21b6044820152606490fd5b1561453f57565b60405162461bcd60e51b815260206004820152601060248201526f13db9b1e481dda1a5d195b1a5cdd195960821b6044820152606490fd5b8051821015613dc35760209160051b010190565b60c8546040516370a0823160e01b815230600482015290602090829060249082906001600160a01b03165afa9081156145f8576000916145c9575090565b90506020813d6020116145f0575b816145e460209383613b95565b81010312610b6e575190565b3d91506145d7565b6040513d6000823e3d90fd5b1561460b57565b60405162461bcd60e51b815260206004820152600a6024820152694e6f74206d617475726560b01b6044820152606490fd5b903590601e1981360301821215610b6e57018035906001600160401b038211610b6e57602001918136038313610b6e57565b60c85460405163313ce56760e01b815290602090829060049082906001600160a01b03165afa9081156145f8576000916146ab575b5060ff1690565b6020813d6020116146e0575b816146c460209383613b95565b81010312610b8357519060ff82168203610b87575060ff6146a4565b3d91506146b7565b604051906146f582613b5f565b8160806000918281528260208201528260408201528260608201526040519261471d84613b7a565b8084528060208501526060604085015260608401520152565b6040519061474382613b7a565b8160005460ff811661475481613df4565b825260209060018060a01b039060081c168183015260405190816000600180549061477e82613a7c565b80855291600181169081156147fa57506001146147b8575b50506147a492500382613b95565b6040820152606060ff600254161515910152565b90939150600160005281600020936000915b8183106147e25750506147a493508201013880614796565b855487840185015294850194869450918301916147ca565b9150506147a494925060ff191682840152151560051b8201013880614796565b6148226146e8565b506040519061483082613b5f565b60018060a01b031680825260006020830152604082015260006060820152614856614736565b608082015290565b614893614898939261488560405194859263a9059cbb60e01b602085015260248401613dd9565b03601f198101845283613b95565b6149d6565b565b6002600e54146148ab576002600e55565b60405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606490fd5b60ff607254166148fc57565b60405162461bcd60e51b815260206004820152601060248201526f14185d5cd8589b194e881c185d5cd95960821b6044820152606490fd5b6040516323b872dd60e01b60208201526001600160a01b0392831660248201529290911660448301526064808301939093529181526148989161489382613b5f565b1561497d57565b60405162461bcd60e51b815260206004820152602b60248201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960448201526a6e697469616c697a696e6760a81b6064820152608490fd5b60408051908101916001600160a01b03166001600160401b03831182841017611e5057614a64926040526000806020958685527f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c656487860152868151910182855af13d15614aec573d91614a4883613c36565b92614a566040519485613b95565b83523d60008785013e614af0565b805190828215928315614ad4575b50505015614a7d5750565b6084906040519062461bcd60e51b82526004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152fd5b614ae493508201810191016140b4565b388281614a72565b6060915b91929015614b525750815115614b04575090565b3b15614b0d5790565b60405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606490fd5b825190915015614b655750805190602001fd5b60405162461bcd60e51b815260206004820152908190614b89906024830190613bb6565b0390fdfea4c9b5d989fa12d608052e66dc5a37a431d679e93d0ed25572f97f67460bb1572bde9b0c0857aee2cffdea6b8723eaf59894499ec278c18f020edd3c2295e42427b002e09d2e05c13790fd77dec4babc548a10605eaa8c352a2840b174c3340aa2646970667358221220a4a247fe01265f5395fd40b39303bdfe970eacda94320300c02e6b103d75649864736f6c63430008170033
Verified Source Code Full Match
Compiler: v0.8.23+commit.f704f362
EVM: paris
Optimization: Yes (50 runs)
Initializable.sol 166 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```solidity
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
*
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts.
*
* Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a
* constructor.
*
* Emits an {Initialized} event.
*/
modifier initializer() {
bool isTopLevelCall = !_initializing;
require(
(isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),
"Initializable: contract is already initialized"
);
_initialized = 1;
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* A reinitializer may be used after the original initialization step. This is essential to configure modules that
* are added through upgrades and that require initialization.
*
* When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer`
* cannot be nested. If one is invoked in the context of another, execution will revert.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*
* WARNING: setting the version to 255 will prevent any future reinitialization.
*
* Emits an {Initialized} event.
*/
modifier reinitializer(uint8 version) {
require(!_initializing && _initialized < version, "Initializable: contract is already initialized");
_initialized = version;
_initializing = true;
_;
_initializing = false;
emit Initialized(version);
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*
* Emits an {Initialized} event the first time it is successfully executed.
*/
function _disableInitializers() internal virtual {
require(!_initializing, "Initializable: contract is initializing");
if (_initialized != type(uint8).max) {
_initialized = type(uint8).max;
emit Initialized(type(uint8).max);
}
}
/**
* @dev Returns the highest version that has been initialized. See {reinitializer}.
*/
function _getInitializedVersion() internal view returns (uint8) {
return _initialized;
}
/**
* @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}.
*/
function _isInitializing() internal view returns (bool) {
return _initializing;
}
}
PausableUpgradeable.sol 117 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
ReentrancyGuardUpgradeable.sol 89 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
IERC20MetadataUpgradeable.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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);
}
IERC20PermitUpgradeable.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
IERC20Upgradeable.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 IERC20Upgradeable {
/**
* @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);
}
SafeERC20Upgradeable.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../extensions/IERC20PermitUpgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20PermitUpgradeable token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20Upgradeable token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && AddressUpgradeable.isContract(address(token));
}
}
AddressUpgradeable.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
ContextUpgradeable.sol 41 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.4) (utils/Context.sol)
pragma solidity ^0.8.0;
import {Initializable} from "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
function _contextSuffixLength() internal view virtual returns (uint256) {
return 0;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
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 184 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;
}
// @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) / market.totalLp;
} else {
lpToAccount = netLpBySy;
syUsed = syDesired;
ptUsed = (market.totalPt * lpToAccount) / 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;
}
}
IPActionAddRemoveLiqV3.sol 232 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../router/base/MarketApproxLib.sol";
import "./IPAllActionTypeV3.sol";
/*
*******************************************************************************************************************
*******************************************************************************************************************
* NOTICE *
* Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
* TokenInput, TokenOutput, ApproxParams, LimitOrderData
* It's recommended to use Pendle's Hosted SDK to generate the params
*******************************************************************************************************************
*******************************************************************************************************************
*/
interface IPActionAddRemoveLiqV3 {
event AddLiquidityDualSyAndPt(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netSyUsed,
uint256 netPtUsed,
uint256 netLpOut
);
event AddLiquidityDualTokenAndPt(
address indexed caller,
address indexed market,
address indexed tokenIn,
address receiver,
uint256 netTokenUsed,
uint256 netPtUsed,
uint256 netLpOut,
uint256 netSyInterm
);
event AddLiquiditySinglePt(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netPtIn,
uint256 netLpOut
);
event AddLiquiditySingleSy(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netSyIn,
uint256 netLpOut
);
event AddLiquiditySingleToken(
address indexed caller,
address indexed market,
address indexed token,
address receiver,
uint256 netTokenIn,
uint256 netLpOut,
uint256 netSyInterm
);
event AddLiquiditySingleSyKeepYt(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netSyIn,
uint256 netSyMintPy,
uint256 netLpOut,
uint256 netYtOut
);
event AddLiquiditySingleTokenKeepYt(
address indexed caller,
address indexed market,
address indexed token,
address receiver,
uint256 netTokenIn,
uint256 netLpOut,
uint256 netYtOut,
uint256 netSyMintPy,
uint256 netSyInterm
);
event RemoveLiquidityDualSyAndPt(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netLpToRemove,
uint256 netPtOut,
uint256 netSyOut
);
event RemoveLiquidityDualTokenAndPt(
address indexed caller,
address indexed market,
address indexed tokenOut,
address receiver,
uint256 netLpToRemove,
uint256 netPtOut,
uint256 netTokenOut,
uint256 netSyInterm
);
event RemoveLiquiditySinglePt(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netLpToRemove,
uint256 netPtOut
);
event RemoveLiquiditySingleSy(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netLpToRemove,
uint256 netSyOut
);
event RemoveLiquiditySingleToken(
address indexed caller,
address indexed market,
address indexed token,
address receiver,
uint256 netLpToRemove,
uint256 netTokenOut,
uint256 netSyInterm
);
function addLiquidityDualTokenAndPt(
address receiver,
address market,
TokenInput calldata input,
uint256 netPtDesired,
uint256 minLpOut
) external payable returns (uint256 netLpOut, uint256 netPtUsed, uint256 netSyInterm);
function addLiquidityDualSyAndPt(
address receiver,
address market,
uint256 netSyDesired,
uint256 netPtDesired,
uint256 minLpOut
) external returns (uint256 netLpOut, uint256 netSyUsed, uint256 netPtUsed);
function addLiquiditySinglePt(
address receiver,
address market,
uint256 netPtIn,
uint256 minLpOut,
ApproxParams calldata guessPtSwapToSy,
LimitOrderData calldata limit
) external returns (uint256 netLpOut, uint256 netSyFee);
function addLiquiditySingleToken(
address receiver,
address market,
uint256 minLpOut,
ApproxParams calldata guessPtReceivedFromSy,
TokenInput calldata input,
LimitOrderData calldata limit
) external payable returns (uint256 netLpOut, uint256 netSyFee, uint256 netSyInterm);
function addLiquiditySingleSy(
address receiver,
address market,
uint256 netSyIn,
uint256 minLpOut,
ApproxParams calldata guessPtReceivedFromSy,
LimitOrderData calldata limit
) external returns (uint256 netLpOut, uint256 netSyFee);
function addLiquiditySingleTokenKeepYt(
address receiver,
address market,
uint256 minLpOut,
uint256 minYtOut,
TokenInput calldata input
) external payable returns (uint256 netLpOut, uint256 netYtOut, uint256 netSyMintPy, uint256 netSyInterm);
function addLiquiditySingleSyKeepYt(
address receiver,
address market,
uint256 netSyIn,
uint256 minLpOut,
uint256 minYtOut
) external returns (uint256 netLpOut, uint256 netYtOut, uint256 netSyMintPy);
function removeLiquidityDualTokenAndPt(
address receiver,
address market,
uint256 netLpToRemove,
TokenOutput calldata output,
uint256 minPtOut
) external returns (uint256 netTokenOut, uint256 netPtOut, uint256 netSyInterm);
function removeLiquidityDualSyAndPt(
address receiver,
address market,
uint256 netLpToRemove,
uint256 minSyOut,
uint256 minPtOut
) external returns (uint256 netSyOut, uint256 netPtOut);
function removeLiquiditySinglePt(
address receiver,
address market,
uint256 netLpToRemove,
uint256 minPtOut,
ApproxParams calldata guessPtReceivedFromSy,
LimitOrderData calldata limit
) external returns (uint256 netPtOut, uint256 netSyFee);
function removeLiquiditySingleToken(
address receiver,
address market,
uint256 netLpToRemove,
TokenOutput calldata output,
LimitOrderData calldata limit
) external returns (uint256 netTokenOut, uint256 netSyFee, uint256 netSyInterm);
function removeLiquiditySingleSy(
address receiver,
address market,
uint256 netLpToRemove,
uint256 minSyOut,
LimitOrderData calldata limit
) external returns (uint256 netSyOut, uint256 netSyFee);
}
IPActionCallbackV3.sol 7 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./IPMarketSwapCallback.sol";
import "./IPLimitRouter.sol";
interface IPActionCallbackV3 is IPMarketSwapCallback, IPLimitRouterCallback {}
IPActionMiscV3.sol 250 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../router/base/MarketApproxLib.sol";
import "./IPAllActionTypeV3.sol";
/*
*******************************************************************************************************************
*******************************************************************************************************************
* NOTICE *
* Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
* TokenInput, TokenOutput, ApproxParams, LimitOrderData
* It's recommended to use Pendle's Hosted SDK to generate the params
*******************************************************************************************************************
*******************************************************************************************************************
*/
interface IPActionMiscV3 {
struct Call3 {
bool allowFailure;
bytes callData;
}
struct Result {
bool success;
bytes returnData;
}
struct ExitPreExpReturnParams {
uint256 netPtFromRemove;
uint256 netSyFromRemove;
uint256 netPyRedeem;
uint256 netSyFromRedeem;
uint256 netPtSwap;
uint256 netYtSwap;
uint256 netSyFromSwap;
uint256 netSyFee;
uint256 totalSyOut;
}
struct ExitPostExpReturnParams {
uint256 netPtFromRemove;
uint256 netSyFromRemove;
uint256 netPtRedeem;
uint256 netSyFromRedeem;
uint256 totalSyOut;
}
event MintSyFromToken(
address indexed caller,
address indexed tokenIn,
address indexed SY,
address receiver,
uint256 netTokenIn,
uint256 netSyOut
);
event RedeemSyToToken(
address indexed caller,
address indexed tokenOut,
address indexed SY,
address receiver,
uint256 netSyIn,
uint256 netTokenOut
);
event MintPyFromSy(
address indexed caller,
address indexed receiver,
address indexed YT,
uint256 netSyIn,
uint256 netPyOut
);
event RedeemPyToSy(
address indexed caller,
address indexed receiver,
address indexed YT,
uint256 netPyIn,
uint256 netSyOut
);
event MintPyFromToken(
address indexed caller,
address indexed tokenIn,
address indexed YT,
address receiver,
uint256 netTokenIn,
uint256 netPyOut,
uint256 netSyInterm
);
event RedeemPyToToken(
address indexed caller,
address indexed tokenOut,
address indexed YT,
address receiver,
uint256 netPyIn,
uint256 netTokenOut,
uint256 netSyInterm
);
event ExitPreExpToToken(
address indexed caller,
address indexed market,
address indexed token,
address receiver,
uint256 netLpIn,
uint256 totalTokenOut,
ExitPreExpReturnParams params
);
event ExitPreExpToSy(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netLpIn,
ExitPreExpReturnParams params
);
event ExitPostExpToToken(
address indexed caller,
address indexed market,
address indexed token,
address receiver,
uint256 netLpIn,
uint256 totalTokenOut,
ExitPostExpReturnParams params
);
event ExitPostExpToSy(
address indexed caller,
address indexed market,
address indexed receiver,
uint256 netLpIn,
ExitPostExpReturnParams params
);
function mintSyFromToken(
address receiver,
address SY,
uint256 minSyOut,
TokenInput calldata input
) external payable returns (uint256 netSyOut);
function redeemSyToToken(
address receiver,
address SY,
uint256 netSyIn,
TokenOutput calldata output
) external returns (uint256 netTokenOut);
function mintPyFromToken(
address receiver,
address YT,
uint256 minPyOut,
TokenInput calldata input
) external payable returns (uint256 netPyOut, uint256 netSyInterm);
function redeemPyToToken(
address receiver,
address YT,
uint256 netPyIn,
TokenOutput calldata output
) external returns (uint256 netTokenOut, uint256 netSyInterm);
function mintPyFromSy(
address receiver,
address YT,
uint256 netSyIn,
uint256 minPyOut
) external returns (uint256 netPyOut);
function redeemPyToSy(
address receiver,
address YT,
uint256 netPyIn,
uint256 minSyOut
) external returns (uint256 netSyOut);
function redeemDueInterestAndRewards(
address user,
address[] calldata sys,
address[] calldata yts,
address[] calldata markets
) external;
function swapTokenToToken(
address receiver,
uint256 minTokenOut,
TokenInput calldata inp
) external payable returns (uint256 netTokenOut);
function swapTokenToTokenViaSy(
address receiver,
address SY,
TokenInput calldata input,
address tokenRedeemSy,
uint256 minTokenOut
) external payable returns (uint256 netTokenOut, uint256 netSyInterm);
function exitPreExpToToken(
address receiver,
address market,
uint256 netPtIn,
uint256 netYtIn,
uint256 netLpIn,
TokenOutput calldata output,
LimitOrderData calldata limit
) external returns (uint256 netTokenOut, ExitPreExpReturnParams memory params);
function exitPreExpToSy(
address receiver,
address market,
uint256 netPtIn,
uint256 netYtIn,
uint256 netLpIn,
uint256 minSyOut,
LimitOrderData calldata limit
) external returns (ExitPreExpReturnParams memory params);
function exitPostExpToToken(
address receiver,
address market,
uint256 netPtIn,
uint256 netLpIn,
TokenOutput calldata output
) external returns (uint256 netTokenOut, ExitPostExpReturnParams memory params);
function exitPostExpToSy(
address receiver,
address market,
uint256 netPtIn,
uint256 netLpIn,
uint256 minSyOut
) external returns (ExitPostExpReturnParams memory params);
function callAndReflect(
address payable reflector,
bytes calldata selfCall1,
bytes calldata selfCall2,
bytes calldata reflectCall
) external payable returns (bytes memory selfRes1, bytes memory selfRes2, bytes memory reflectRes);
function boostMarkets(address[] memory markets) external;
function multicall(Call3[] calldata calls) external payable returns (Result[] memory res);
function simulate(address target, bytes calldata data) external payable;
}
IPActionStorageV4.sol 25 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
interface IPActionStorageV4 {
struct SelectorsToFacet {
address facet;
bytes4[] selectors;
}
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event SelectorToFacetSet(bytes4 indexed selector, address indexed facet);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function transferOwnership(address newOwner, bool direct, bool renounce) external;
function claimOwnership() external;
function setSelectorToFacets(SelectorsToFacet[] calldata arr) external;
function selectorToFacet(bytes4 selector) external view returns (address);
}
IPActionSwapPTV3.sol 70 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../router/base/MarketApproxLib.sol";
import "./IPAllActionTypeV3.sol";
/*
*******************************************************************************************************************
*******************************************************************************************************************
* NOTICE *
* Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
* TokenInput, TokenOutput, ApproxParams, LimitOrderData
* It's recommended to use Pendle's Hosted SDK to generate the params
*******************************************************************************************************************
*******************************************************************************************************************
*/
interface IPActionSwapPTV3 {
event SwapPtAndSy(
address indexed caller,
address indexed market,
address indexed receiver,
int256 netPtToAccount,
int256 netSyToAccount
);
event SwapPtAndToken(
address indexed caller,
address indexed market,
address indexed token,
address receiver,
int256 netPtToAccount,
int256 netTokenToAccount,
uint256 netSyInterm
);
function swapExactTokenForPt(
address receiver,
address market,
uint256 minPtOut,
ApproxParams calldata guessPtOut,
TokenInput calldata input,
LimitOrderData calldata limit
) external payable returns (uint256 netPtOut, uint256 netSyFee, uint256 netSyInterm);
function swapExactSyForPt(
address receiver,
address market,
uint256 exactSyIn,
uint256 minPtOut,
ApproxParams calldata guessPtOut,
LimitOrderData calldata limit
) external returns (uint256 netPtOut, uint256 netSyFee);
function swapExactPtForToken(
address receiver,
address market,
uint256 exactPtIn,
TokenOutput calldata output,
LimitOrderData calldata limit
) external returns (uint256 netTokenOut, uint256 netSyFee, uint256 netSyInterm);
function swapExactPtForSy(
address receiver,
address market,
uint256 exactPtIn,
uint256 minSyOut,
LimitOrderData calldata limit
) external returns (uint256 netSyOut, uint256 netSyFee);
}
IPActionSwapYTV3.sol 94 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../router/base/MarketApproxLib.sol";
import "./IPAllActionTypeV3.sol";
/*
*******************************************************************************************************************
*******************************************************************************************************************
* NOTICE *
* Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
* TokenInput, TokenOutput, ApproxParams, LimitOrderData
* It's recommended to use Pendle's Hosted SDK to generate the params
*******************************************************************************************************************
*******************************************************************************************************************
*/
interface IPActionSwapYTV3 {
event SwapYtAndSy(
address indexed caller,
address indexed market,
address indexed receiver,
int256 netYtToAccount,
int256 netSyToAccount
);
event SwapYtAndToken(
address indexed caller,
address indexed market,
address indexed token,
address receiver,
int256 netYtToAccount,
int256 netTokenToAccount,
uint256 netSyInterm
);
event SwapPtAndYt(
address indexed caller,
address indexed market,
address indexed receiver,
int256 netPtToAccount,
int256 netYtToAccount
);
function swapExactTokenForYt(
address receiver,
address market,
uint256 minYtOut,
ApproxParams calldata guessYtOut,
TokenInput calldata input,
LimitOrderData calldata limit
) external payable returns (uint256 netYtOut, uint256 netSyFee, uint256 netSyInterm);
function swapExactSyForYt(
address receiver,
address market,
uint256 exactSyIn,
uint256 minYtOut,
ApproxParams calldata guessYtOut,
LimitOrderData calldata limit
) external returns (uint256 netYtOut, uint256 netSyFee);
function swapExactYtForToken(
address receiver,
address market,
uint256 exactYtIn,
TokenOutput calldata output,
LimitOrderData calldata limit
) external returns (uint256 netTokenOut, uint256 netSyFee, uint256 netSyInterm);
function swapExactYtForSy(
address receiver,
address market,
uint256 exactYtIn,
uint256 minSyOut,
LimitOrderData calldata limit
) external returns (uint256 netSyOut, uint256 netSyFee);
function swapExactPtForYt(
address receiver,
address market,
uint256 exactPtIn,
uint256 minYtOut,
ApproxParams calldata guessTotalPtToSwap
) external returns (uint256 netYtOut, uint256 netSyFee);
function swapExactYtForPt(
address receiver,
address market,
uint256 exactYtIn,
uint256 minPtOut,
ApproxParams calldata guessTotalPtFromSwap
) external returns (uint256 netPtOut, uint256 netSyFee);
}
IPAllActionTypeV3.sol 45 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../router/swap-aggregator/IPSwapAggregator.sol";
import "./IPLimitRouter.sol";
/*
*******************************************************************************************************************
*******************************************************************************************************************
* NOTICE *
* Refer to https://docs.pendle.finance/Developers/Contracts/PendleRouter for more information on
* TokenInput, TokenOutput, ApproxParams, LimitOrderData
* It's recommended to use Pendle's Hosted SDK to generate the params
*******************************************************************************************************************
*******************************************************************************************************************
*/
struct TokenInput {
// TOKEN DATA
address tokenIn;
uint256 netTokenIn;
address tokenMintSy;
// AGGREGATOR DATA
address pendleSwap;
SwapData swapData;
}
struct TokenOutput {
// TOKEN DATA
address tokenOut;
uint256 minTokenOut;
address tokenRedeemSy;
// AGGREGATOR DATA
address pendleSwap;
SwapData swapData;
}
struct LimitOrderData {
address limitRouter;
uint256 epsSkipMarket; // only used for swap operations, will be ignored otherwise
FillOrderParams[] normalFills;
FillOrderParams[] flashFills;
bytes optData;
}
IPAllActionV3.sol 19 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./IPActionAddRemoveLiqV3.sol";
import "./IPActionSwapPTV3.sol";
import "./IPActionSwapYTV3.sol";
import "./IPActionMiscV3.sol";
import "./IPActionCallbackV3.sol";
import "./IPActionStorageV4.sol";
interface IPAllActionV3 is
IPActionAddRemoveLiqV3,
IPActionSwapPTV3,
IPActionSwapYTV3,
IPActionMiscV3,
IPActionCallbackV3,
IPActionStorageV4
{}
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);
}
IPLimitRouter.sol 134 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../core/StandardizedYield/PYIndex.sol";
interface IPLimitOrderType {
enum OrderType {
SY_FOR_PT,
PT_FOR_SY,
SY_FOR_YT,
YT_FOR_SY
}
// Fixed-size order part with core information
struct StaticOrder {
uint256 salt;
uint256 expiry;
uint256 nonce;
OrderType orderType;
address token;
address YT;
address maker;
address receiver;
uint256 makingAmount;
uint256 lnImpliedRate;
uint256 failSafeRate;
}
struct FillResults {
uint256 totalMaking;
uint256 totalTaking;
uint256 totalFee;
uint256 totalNotionalVolume;
uint256[] netMakings;
uint256[] netTakings;
uint256[] netFees;
uint256[] notionalVolumes;
}
}
struct Order {
uint256 salt;
uint256 expiry;
uint256 nonce;
IPLimitOrderType.OrderType orderType;
address token;
address YT;
address maker;
address receiver;
uint256 makingAmount;
uint256 lnImpliedRate;
uint256 failSafeRate;
bytes permit;
}
struct FillOrderParams {
Order order;
bytes signature;
uint256 makingAmount;
}
interface IPLimitRouterCallback is IPLimitOrderType {
function limitRouterCallback(
uint256 actualMaking,
uint256 actualTaking,
uint256 totalFee,
bytes memory data
) external returns (bytes memory);
}
interface IPLimitRouter is IPLimitOrderType {
struct OrderStatus {
uint128 filledAmount;
uint128 remaining;
}
event OrderCanceled(address indexed maker, bytes32 indexed orderHash);
event OrderFilledV2(
bytes32 indexed orderHash,
OrderType indexed orderType,
address indexed YT,
address token,
uint256 netInputFromMaker,
uint256 netOutputToMaker,
uint256 feeAmount,
uint256 notionalVolume,
address maker,
address taker
);
// @dev actualMaking, actualTaking are in the SY form
function fill(
FillOrderParams[] memory params,
address receiver,
uint256 maxTaking,
bytes calldata optData,
bytes calldata callback
) external returns (uint256 actualMaking, uint256 actualTaking, uint256 totalFee, bytes memory callbackReturn);
function feeRecipient() external view returns (address);
function hashOrder(Order memory order) external view returns (bytes32);
function cancelSingle(Order calldata order) external;
function cancelBatch(Order[] calldata orders) external;
function orderStatusesRaw(
bytes32[] memory orderHashes
) external view returns (uint256[] memory remainingsRaw, uint256[] memory filledAmounts);
function orderStatuses(
bytes32[] memory orderHashes
) external view returns (uint256[] memory remainings, uint256[] memory filledAmounts);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function simulate(address target, bytes calldata data) external payable;
/* --- Deprecated events --- */
// deprecate on 7/1/2024, prior to official launch
event OrderFilled(
bytes32 indexed orderHash,
OrderType indexed orderType,
address indexed YT,
address token,
uint256 netInputFromMaker,
uint256 netOutputToMaker,
uint256 feeAmount,
uint256 notionalVolume
);
}
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
);
}
IPMarketSwapCallback.sol 6 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
interface IPMarketSwapCallback {
function swapCallback(int256 ptToAccount, int256 syToAccount, bytes calldata data) external;
}
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);
}
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);
}
MarketApproxLib.sol 554 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../core/libraries/math/PMath.sol";
import "../../core/Market/MarketMathCore.sol";
struct ApproxParams {
uint256 guessMin;
uint256 guessMax;
uint256 guessOffchain; // pass 0 in to skip this variable
uint256 maxIteration; // every iteration, the diff between guessMin and guessMax will be divided by 2
uint256 eps; // the max eps between the returned result & the correct result, base 1e18. Normally this number will be set
// to 1e15 (1e18/1000 = 0.1%)
}
/// Further explanation of the eps. Take swapExactSyForPt for example. To calc the corresponding amount of Pt to swap out,
/// it's necessary to run an approximation algorithm, because by default there only exists the Pt to Sy formula
/// To approx, the 5 values above will have to be provided, and the approx process will run as follows:
/// mid = (guessMin + guessMax) / 2 // mid here is the current guess of the amount of Pt out
/// netSyNeed = calcSwapSyForExactPt(mid)
/// if (netSyNeed > exactSyIn) guessMax = mid - 1 // since the maximum Sy in can't exceed the exactSyIn
/// else guessMin = mid (1)
/// For the (1), since netSyNeed <= exactSyIn, the result might be usable. If the netSyNeed is within eps of
/// exactSyIn (ex eps=0.1% => we have used 99.9% the amount of Sy specified), mid will be chosen as the final guess result
/// for guessOffchain, this is to provide a shortcut to guessing. The offchain SDK can precalculate the exact result
/// before the tx is sent. When the tx reaches the contract, the guessOffchain will be checked first, and if it satisfies the
/// approximation, it will be used (and save all the guessing). It's expected that this shortcut will be used in most cases
/// except in cases that there is a trade in the same market right before the tx
library MarketApproxPtInLib {
using MarketMathCore for MarketState;
using PYIndexLib for PYIndex;
using PMath for uint256;
using PMath for int256;
using LogExpMath for int256;
/**
* @dev algorithm:
* - Bin search the amount of PT to swap in
* - Try swapping & get netSyOut
* - Stop when netSyOut greater & approx minSyOut
* - guess & approx is for netPtIn
*/
function approxSwapPtForExactSy(
MarketState memory market,
PYIndex index,
uint256 minSyOut,
uint256 blockTime,
ApproxParams memory approx
) internal pure returns (uint256, /*netPtIn*/ uint256, /*netSyOut*/ uint256 /*netSyFee*/) {
MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
if (approx.guessOffchain == 0) {
// no limit on min
approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp));
validateApprox(approx);
}
for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
uint256 guess = nextGuess(approx, iter);
(uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess);
if (netSyOut >= minSyOut) {
if (PMath.isAGreaterApproxB(netSyOut, minSyOut, approx.eps)) {
return (guess, netSyOut, netSyFee);
}
approx.guessMax = guess;
} else {
approx.guessMin = guess;
}
}
revert("Slippage: APPROX_EXHAUSTED");
}
/**
* @dev algorithm:
* - Bin search the amount of PT to swap in
* - Flashswap the corresponding amount of SY out
* - Pair those amount with exactSyIn SY to tokenize into PT & YT
* - PT to repay the flashswap, YT transferred to user
* - Stop when the amount of SY to be pulled to tokenize PT to repay loan approx the exactSyIn
* - guess & approx is for netYtOut (also netPtIn)
*/
function approxSwapExactSyForYt(
MarketState memory market,
PYIndex index,
uint256 exactSyIn,
uint256 blockTime,
ApproxParams memory approx
) internal pure returns (uint256, /*netYtOut*/ uint256 /*netSyFee*/) {
MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
if (approx.guessOffchain == 0) {
approx.guessMin = PMath.max(approx.guessMin, index.syToAsset(exactSyIn));
approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp));
validateApprox(approx);
}
// at minimum we will flashswap exactSyIn since we have enough SY to payback the PT loan
for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
uint256 guess = nextGuess(approx, iter);
(uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess);
uint256 netSyToTokenizePt = index.assetToSyUp(guess);
// for sure netSyToTokenizePt >= netSyOut since we are swapping PT to SY
uint256 netSyToPull = netSyToTokenizePt - netSyOut;
if (netSyToPull <= exactSyIn) {
if (PMath.isASmallerApproxB(netSyToPull, exactSyIn, approx.eps)) {
return (guess, netSyFee);
}
approx.guessMin = guess;
} else {
approx.guessMax = guess - 1;
}
}
revert("Slippage: APPROX_EXHAUSTED");
}
struct Args5 {
MarketState market;
PYIndex index;
uint256 totalPtIn;
uint256 netSyHolding;
uint256 blockTime;
ApproxParams approx;
}
/**
* @dev algorithm:
* - Bin search the amount of PT to swap to SY
* - Swap PT to SY
* - Pair the remaining PT with the SY to add liquidity
* - Stop when the ratio of PT / totalPt & SY / totalSy is approx
* - guess & approx is for netPtSwap
*/
function approxSwapPtToAddLiquidity(
MarketState memory _market,
PYIndex _index,
uint256 _totalPtIn,
uint256 _netSyHolding,
uint256 _blockTime,
ApproxParams memory approx
) internal pure returns (uint256, /*netPtSwap*/ uint256, /*netSyFromSwap*/ uint256 /*netSyFee*/) {
Args5 memory a = Args5(_market, _index, _totalPtIn, _netSyHolding, _blockTime, approx);
MarketPreCompute memory comp = a.market.getMarketPreCompute(a.index, a.blockTime);
if (approx.guessOffchain == 0) {
// no limit on min
approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(a.market, comp));
approx.guessMax = PMath.min(approx.guessMax, a.totalPtIn);
validateApprox(approx);
require(a.market.totalLp != 0, "no existing lp");
}
for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
uint256 guess = nextGuess(approx, iter);
(uint256 syNumerator, uint256 ptNumerator, uint256 netSyOut, uint256 netSyFee, ) = calcNumerators(
a.market,
a.index,
a.totalPtIn,
a.netSyHolding,
comp,
guess
);
if (PMath.isAApproxB(syNumerator, ptNumerator, approx.eps)) {
return (guess, netSyOut, netSyFee);
}
if (syNumerator <= ptNumerator) {
// needs more SY --> swap more PT
approx.guessMin = guess + 1;
} else {
// needs less SY --> swap less PT
approx.guessMax = guess - 1;
}
}
revert("Slippage: APPROX_EXHAUSTED");
}
function calcNumerators(
MarketState memory market,
PYIndex index,
uint256 totalPtIn,
uint256 netSyHolding,
MarketPreCompute memory comp,
uint256 guess
)
internal
pure
returns (uint256 syNumerator, uint256 ptNumerator, uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve)
{
(netSyOut, netSyFee, netSyToReserve) = calcSyOut(market, comp, index, guess);
uint256 newTotalPt = uint256(market.totalPt) + guess;
uint256 newTotalSy = (uint256(market.totalSy) - netSyOut - netSyToReserve);
// it is desired that
// (netSyOut + netSyHolding) / newTotalSy = netPtRemaining / newTotalPt
// which is equivalent to
// (netSyOut + netSyHolding) * newTotalPt = netPtRemaining * newTotalSy
syNumerator = (netSyOut + netSyHolding) * newTotalPt;
ptNumerator = (totalPtIn - guess) * newTotalSy;
}
/**
* @dev algorithm:
* - Bin search the amount of PT to swap to SY
* - Flashswap the corresponding amount of SY out
* - Tokenize all the SY into PT + YT
* - PT to repay the flashswap, YT transferred to user
* - Stop when the additional amount of PT to pull to repay the loan approx the exactPtIn
* - guess & approx is for totalPtToSwap
*/
function approxSwapExactPtForYt(
MarketState memory market,
PYIndex index,
uint256 exactPtIn,
uint256 blockTime,
ApproxParams memory approx
) internal pure returns (uint256, /*netYtOut*/ uint256, /*totalPtToSwap*/ uint256 /*netSyFee*/) {
MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
if (approx.guessOffchain == 0) {
approx.guessMin = PMath.max(approx.guessMin, exactPtIn);
approx.guessMax = PMath.min(approx.guessMax, calcMaxPtIn(market, comp));
validateApprox(approx);
}
for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
uint256 guess = nextGuess(approx, iter);
(uint256 netSyOut, uint256 netSyFee, ) = calcSyOut(market, comp, index, guess);
uint256 netAssetOut = index.syToAsset(netSyOut);
// guess >= netAssetOut since we are swapping PT to SY
uint256 netPtToPull = guess - netAssetOut;
if (netPtToPull <= exactPtIn) {
if (PMath.isASmallerApproxB(netPtToPull, exactPtIn, approx.eps)) {
return (netAssetOut, guess, netSyFee);
}
approx.guessMin = guess;
} else {
approx.guessMax = guess - 1;
}
}
revert("Slippage: APPROX_EXHAUSTED");
}
////////////////////////////////////////////////////////////////////////////////
function calcSyOut(
MarketState memory market,
MarketPreCompute memory comp,
PYIndex index,
uint256 netPtIn
) internal pure returns (uint256 netSyOut, uint256 netSyFee, uint256 netSyToReserve) {
(int256 _netSyOut, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade(comp, index, -int256(netPtIn));
netSyOut = uint256(_netSyOut);
netSyFee = uint256(_netSyFee);
netSyToReserve = uint256(_netSyToReserve);
}
function nextGuess(ApproxParams memory approx, uint256 iter) internal pure returns (uint256) {
if (iter == 0 && approx.guessOffchain != 0) return approx.guessOffchain;
if (approx.guessMin <= approx.guessMax) return (approx.guessMin + approx.guessMax) / 2;
revert("Slippage: guessMin > guessMax");
}
/// INTENDED TO BE CALLED BY WHEN GUESS.OFFCHAIN == 0 ONLY ///
function validateApprox(ApproxParams memory approx) internal pure {
if (approx.guessMin > approx.guessMax || approx.eps > PMath.ONE) revert("Internal: INVALID_APPROX_PARAMS");
}
function calcMaxPtIn(MarketState memory market, MarketPreCompute memory comp) internal pure returns (uint256) {
uint256 low = 0;
uint256 hi = uint256(comp.totalAsset) - 1;
while (low != hi) {
uint256 mid = (low + hi + 1) / 2;
if (calcSlope(comp, market.totalPt, int256(mid)) < 0) hi = mid - 1;
else low = mid;
}
low = PMath.min(
low,
(MarketMathCore.MAX_MARKET_PROPORTION.mulDown(market.totalPt + comp.totalAsset) - market.totalPt).Uint()
);
return low;
}
function calcSlope(MarketPreCompute memory comp, int256 totalPt, int256 ptToMarket) internal pure returns (int256) {
int256 diffAssetPtToMarket = comp.totalAsset - ptToMarket;
int256 sumPt = ptToMarket + totalPt;
require(diffAssetPtToMarket > 0 && sumPt > 0, "invalid ptToMarket");
int256 part1 = (ptToMarket * (totalPt + comp.totalAsset)).divDown(sumPt * diffAssetPtToMarket);
int256 part2 = sumPt.divDown(diffAssetPtToMarket).ln();
int256 part3 = PMath.IONE.divDown(comp.rateScalar);
return comp.rateAnchor - (part1 - part2).mulDown(part3);
}
}
library MarketApproxPtOutLib {
using MarketMathCore for MarketState;
using PYIndexLib for PYIndex;
using PMath for uint256;
using PMath for int256;
using LogExpMath for int256;
/**
* @dev algorithm:
* - Bin search the amount of PT to swapExactOut
* - Calculate the amount of SY needed
* - Stop when the netSyIn is smaller approx exactSyIn
* - guess & approx is for netSyIn
*/
function approxSwapExactSyForPt(
MarketState memory market,
PYIndex index,
uint256 exactSyIn,
uint256 blockTime,
ApproxParams memory approx
) internal pure returns (uint256, /*netPtOut*/ uint256 /*netSyFee*/) {
MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
if (approx.guessOffchain == 0) {
// no limit on min
approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt));
validateApprox(approx);
}
for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
uint256 guess = nextGuess(approx, iter);
(uint256 netSyIn, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess);
if (netSyIn <= exactSyIn) {
if (PMath.isASmallerApproxB(netSyIn, exactSyIn, approx.eps)) {
return (guess, netSyFee);
}
approx.guessMin = guess;
} else {
approx.guessMax = guess - 1;
}
}
revert("Slippage: APPROX_EXHAUSTED");
}
/**
* @dev algorithm:
* - Bin search the amount of PT to swapExactOut
* - Flashswap that amount of PT & pair with YT to redeem SY
* - Use the SY to repay the flashswap debt and the remaining is transferred to user
* - Stop when the netSyOut is greater approx the minSyOut
* - guess & approx is for netSyOut
*/
function approxSwapYtForExactSy(
MarketState memory market,
PYIndex index,
uint256 minSyOut,
uint256 blockTime,
ApproxParams memory approx
) internal pure returns (uint256, /*netYtIn*/ uint256, /*netSyOut*/ uint256 /*netSyFee*/) {
MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
if (approx.guessOffchain == 0) {
// no limit on min
approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt));
validateApprox(approx);
}
for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
uint256 guess = nextGuess(approx, iter);
(uint256 netSyOwed, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess);
uint256 netAssetToRepay = index.syToAssetUp(netSyOwed);
uint256 netSyOut = index.assetToSy(guess - netAssetToRepay);
if (netSyOut >= minSyOut) {
if (PMath.isAGreaterApproxB(netSyOut, minSyOut, approx.eps)) {
return (guess, netSyOut, netSyFee);
}
approx.guessMax = guess;
} else {
approx.guessMin = guess + 1;
}
}
revert("Slippage: APPROX_EXHAUSTED");
}
struct Args6 {
MarketState market;
PYIndex index;
uint256 totalSyIn;
uint256 netPtHolding;
uint256 blockTime;
ApproxParams approx;
}
/**
* @dev algorithm:
* - Bin search the amount of PT to swapExactOut
* - Swap that amount of PT out
* - Pair the remaining PT with the SY to add liquidity
* - Stop when the ratio of PT / totalPt & SY / totalSy is approx
* - guess & approx is for netPtFromSwap
*/
function approxSwapSyToAddLiquidity(
MarketState memory _market,
PYIndex _index,
uint256 _totalSyIn,
uint256 _netPtHolding,
uint256 _blockTime,
ApproxParams memory _approx
) internal pure returns (uint256, /*netPtFromSwap*/ uint256, /*netSySwap*/ uint256 /*netSyFee*/) {
Args6 memory a = Args6(_market, _index, _totalSyIn, _netPtHolding, _blockTime, _approx);
MarketPreCompute memory comp = a.market.getMarketPreCompute(a.index, a.blockTime);
if (a.approx.guessOffchain == 0) {
// no limit on min
a.approx.guessMax = PMath.min(a.approx.guessMax, calcMaxPtOut(comp, a.market.totalPt));
validateApprox(a.approx);
require(a.market.totalLp != 0, "no existing lp");
}
for (uint256 iter = 0; iter < a.approx.maxIteration; ++iter) {
uint256 guess = nextGuess(a.approx, iter);
(uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) = calcSyIn(a.market, comp, a.index, guess);
if (netSyIn > a.totalSyIn) {
a.approx.guessMax = guess - 1;
continue;
}
uint256 syNumerator;
uint256 ptNumerator;
{
uint256 newTotalPt = uint256(a.market.totalPt) - guess;
uint256 netTotalSy = uint256(a.market.totalSy) + netSyIn - netSyToReserve;
// it is desired that
// (netPtFromSwap + netPtHolding) / newTotalPt = netSyRemaining / netTotalSy
// which is equivalent to
// (netPtFromSwap + netPtHolding) * netTotalSy = netSyRemaining * newTotalPt
ptNumerator = (guess + a.netPtHolding) * netTotalSy;
syNumerator = (a.totalSyIn - netSyIn) * newTotalPt;
}
if (PMath.isAApproxB(ptNumerator, syNumerator, a.approx.eps)) {
return (guess, netSyIn, netSyFee);
}
if (ptNumerator <= syNumerator) {
// needs more PT
a.approx.guessMin = guess + 1;
} else {
// needs less PT
a.approx.guessMax = guess - 1;
}
}
revert("Slippage: APPROX_EXHAUSTED");
}
/**
* @dev algorithm:
* - Bin search the amount of PT to swapExactOut
* - Flashswap that amount of PT out
* - Pair all the PT with the YT to redeem SY
* - Use the SY to repay the flashswap debt
* - Stop when the amount of YT required to pair with PT is approx exactYtIn
* - guess & approx is for netPtFromSwap
*/
function approxSwapExactYtForPt(
MarketState memory market,
PYIndex index,
uint256 exactYtIn,
uint256 blockTime,
ApproxParams memory approx
) internal pure returns (uint256, /*netPtOut*/ uint256, /*totalPtSwapped*/ uint256 /*netSyFee*/) {
MarketPreCompute memory comp = market.getMarketPreCompute(index, blockTime);
if (approx.guessOffchain == 0) {
approx.guessMin = PMath.max(approx.guessMin, exactYtIn);
approx.guessMax = PMath.min(approx.guessMax, calcMaxPtOut(comp, market.totalPt));
validateApprox(approx);
}
for (uint256 iter = 0; iter < approx.maxIteration; ++iter) {
uint256 guess = nextGuess(approx, iter);
(uint256 netSyOwed, uint256 netSyFee, ) = calcSyIn(market, comp, index, guess);
uint256 netYtToPull = index.syToAssetUp(netSyOwed);
if (netYtToPull <= exactYtIn) {
if (PMath.isASmallerApproxB(netYtToPull, exactYtIn, approx.eps)) {
return (guess - netYtToPull, guess, netSyFee);
}
approx.guessMin = guess;
} else {
approx.guessMax = guess - 1;
}
}
revert("Slippage: APPROX_EXHAUSTED");
}
////////////////////////////////////////////////////////////////////////////////
function calcSyIn(
MarketState memory market,
MarketPreCompute memory comp,
PYIndex index,
uint256 netPtOut
) internal pure returns (uint256 netSyIn, uint256 netSyFee, uint256 netSyToReserve) {
(int256 _netSyIn, int256 _netSyFee, int256 _netSyToReserve) = market.calcTrade(comp, index, int256(netPtOut));
// all safe since totalPt and totalSy is int128
netSyIn = uint256(-_netSyIn);
netSyFee = uint256(_netSyFee);
netSyToReserve = uint256(_netSyToReserve);
}
function calcMaxPtOut(MarketPreCompute memory comp, int256 totalPt) internal pure returns (uint256) {
int256 logitP = (comp.feeRate - comp.rateAnchor).mulDown(comp.rateScalar).exp();
int256 proportion = logitP.divDown(logitP + PMath.IONE);
int256 numerator = proportion.mulDown(totalPt + comp.totalAsset);
int256 maxPtOut = totalPt - numerator;
// only get 99.9% of the theoretical max to accommodate some precision issues
return (uint256(maxPtOut) * 999) / 1000;
}
function nextGuess(ApproxParams memory approx, uint256 iter) internal pure returns (uint256) {
if (iter == 0 && approx.guessOffchain != 0) return approx.guessOffchain;
if (approx.guessMin <= approx.guessMax) return (approx.guessMin + approx.guessMax) / 2;
revert("Slippage: guessMin > guessMax");
}
function validateApprox(ApproxParams memory approx) internal pure {
if (approx.guessMin > approx.guessMax || approx.eps > PMath.ONE) revert("Internal: INVALID_APPROX_PARAMS");
}
}
IPSwapAggregator.sol 21 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
struct SwapData {
SwapType swapType;
address extRouter;
bytes extCalldata;
bool needScale;
}
enum SwapType {
NONE,
KYBERSWAP,
ONE_INCH,
// ETH_WETH not used in Aggregator
ETH_WETH
}
interface IPSwapAggregator {
function swap(address tokenIn, uint256 amountIn, SwapData calldata swapData) external payable;
}
IERC20Token.sol 9 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
interface IERC20Token {
function mint(address to, uint256 amount) external;
function burn(address account,uint256 amount) external;
function balanceOf(address account) external view returns (uint256);
function getUsers() external view returns (address[] memory);
}
DataTypes.sol 31 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
library DataTypes {
/// @notice Struct representing issuance cycle
struct IssuanceCycle {
uint256 coupon;
uint256 strikePrice1;
uint256 strikePrice2;
uint256 strikePrice3;
uint256 strikePrice4;
uint256 tr1;
uint256 tr2;
uint256 issuanceDate;
uint256 maturityDate;
string apy;
uint256 underlyingSpotRef;
uint256 optionMinOrderSize;
string subAccountId;
uint8 participation;
}
/// @notice Enum representing product status
enum Status {
Pending,
Accepted,
Locked,
Issued,
Mature
}
}
EventFunctions.sol 109 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
contract EventFunctions {
event FundAccept();
event FundLock();
event Issuance();
event Mature();
event Deposit(
address indexed user,
uint256 amount
);
event WithdrawPrincipal(
address indexed user,
uint256 amount
);
event WithdrawCoupon(
address indexed user,
uint256 amount
);
event WithdrawOption(
address indexed user,
uint256 amount
);
event RedeemOptionPayout(
address indexed from,
uint256 amount
);
event DistributeFunds(
address indexed qredoDeribit,
uint256 optionRate,
address indexed pendleRouter,
uint32 yieldRate
);
event RedeemYield(
address pendleRouter,
uint256 amount
);
event EarlyWithdraw(
address indexed user,
uint256 noOfBlock,
uint256 exactPtIn,
uint256 earlyWithdrawUser
);
event UserOptionPositionPaid(uint256 totalOptionPosition);
/// @notice Event emitted when new issuance cycle is updated
event UpdateParameters(
string name,
address router,
address market
);
event UpdateStructure(
uint256 strikePrice1,
uint256 strikePrice2,
uint256 strikePrice3,
uint256 strikePrice4,
uint256 tr1,
uint256 tr2,
string apy,
uint256 underlyingSpotRef
);
event Coupon(
address indexed user,
uint256 amount
);
event OptionPayout(
address indexed user,
uint256 amount
);
event UpdateCoupon(
uint256 newCoupon
);
event AddOptionProfitList(
address[] userList,
uint256[] amountList
);
event WhiteList(
address indexed account
);
event RemoveFromWhiteList(
address indexed account
);
event AddAdmin(
address indexed account
);
}
SHProduct.sol 616 lines
// SPDX-License-Identifier: MIT
pragma solidity 0.8.23;
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@pendle/core-v2/contracts/interfaces/IPAllActionV3.sol";
import "@pendle/core-v2/contracts/interfaces/IPMarket.sol";
import "./StructGen.sol";
import "./interfaces/IERC20Token.sol";
import "./libraries/DataTypes.sol";
import "./libraries/EventFunctions.sol";
/**
* @title SHProduct
* @notice A structured product contract that manages deposits, withdrawals, and yield generation
* @dev Inherits from StructGen, ReentrancyGuardUpgradeable, PausableUpgradeable, and EventFunctions
*/
contract SHProduct is StructGen,ReentrancyGuardUpgradeable,PausableUpgradeable,EventFunctions {
IPPrincipalToken public PT;
IPYieldToken public YT;
IPAllActionV3 public router;
address public currencyAddress;
IPMarket public market;
using SafeERC20Upgradeable for IERC20Upgradeable;
uint256 public netPtOut;
struct UserInfo {
uint256 coupon;
uint256 optionPayout;
}
struct UserOptionPosition {
address userAddress;
uint256 value;
}
string public name;
string public underlying;
address public manager;
address public shFactory;
address public tokenAddress;
address public admin;
address public exWallet;
uint256 public maxCapacity;
uint256 public currentCapacity;
uint256 public totalFundBalance;
uint256 public optionProfit;
uint256 public totalOptionPosition;
uint256 public totalNumberOfBlocks;
address public fundContract;
DataTypes.Status public status;
DataTypes.IssuanceCycle public issuanceCycle;
mapping(address => UserInfo) public userInfo;
UserOptionPosition[] public UserOptionPositions;
IERC20Upgradeable public currency;
bool public isDistributed;
mapping(address => bool) public whitelisted;
/**
* @notice Initializes the contract
* @param _name Product name
* @param _underlying Underlying asset name
* @param _currency Underlying asset token
* @param _manager Manager address
* @param _exWallet External wallet address
* @param _maxCapacity Maximum capacity of the product
* @param _issuanceCycle Issuance cycle parameters
* @param _router Router address
* @param _market Market address
* @param _tokenAddress ERC20 token address
* @param _currencyAddress Currency address
*/
function initialize(
string calldata _name,
string calldata _underlying,
IERC20Upgradeable _currency,
address _manager,
address _exWallet,
uint256 _maxCapacity,
DataTypes.IssuanceCycle calldata _issuanceCycle,
address _router,
address _market,
address _tokenAddress,
address _currencyAddress
) external initializer {
__ReentrancyGuard_init();
__Pausable_init();
name = _name;
underlying = _underlying;
manager = _manager;
exWallet = _exWallet;
tokenAddress = _tokenAddress;
maxCapacity = _maxCapacity;
currency = _currency;
currencyAddress = _currencyAddress;
shFactory = msg.sender;
require(_issuanceCycle.coupon <= 1000000 && _issuanceCycle.coupon >= 0, "Invalid coupon");
require(_issuanceCycle.issuanceDate > block.timestamp, "Invalid issuance date");
require(_issuanceCycle.maturityDate > _issuanceCycle.issuanceDate, "Invalid maturity date");
issuanceCycle = _issuanceCycle;
router = IPAllActionV3(_router);
market = IPMarket(_market);
(, PT,YT) = IPMarket(market).readTokens();
}
/**
* @notice Modifier for functions restricted to whitelisted addresses
*/
modifier onlyWhitelisted() {
require(whitelisted[msg.sender], "Only whitelisted");
_;
}
/**
* @notice Modifier for functions restricted to manager
*/
modifier onlyManager() {
require(msg.sender == manager, "Not a manager");
_;
}
/**
* @notice Modifier for functions restricted to the admin
*/
modifier onlyAdmin() {
require(msg.sender == admin, "Not admin");
_;
}
/**
* @notice Modifier for functions restricted to products in Accepted status
*/
modifier onlyAccepted() {
require(status == DataTypes.Status.Accepted, "Not accepted");
_;
}
/**
* @notice Modifier for functions restricted to products in Locked status
*/
modifier onlyLocked() {
require(status == DataTypes.Status.Locked, "Not locked");
_;
}
/**
* @notice Modifier for functions restricted to products in Issued status
*/
modifier onlyIssued() {
require(status == DataTypes.Status.Issued, "Not issued");
_;
}
/**
* @notice Modifier for functions restricted to products in Mature status
*/
modifier onlyMature() {
require(status == DataTypes.Status.Mature, "Not mature");
_;
}
/**
* @notice Modifier for functions restricted to products in Locked or Mature status
*/
modifier LockedOrMature() {
require(status == DataTypes.Status.Locked || status == DataTypes.Status.Mature, "Neither Locked nor Mature");
_;
}
/**
* @notice Modifier for functions restricted to products in Locked, Mature, or Accepted status
*/
modifier AcceptedOrLockedOrMature() {
require(status == DataTypes.Status.Locked || status == DataTypes.Status.Mature || status == DataTypes.Status.Accepted, "Neither Accepted nor Locked nor Mature");
_;
}
/**
* @notice Whitelists the additional accounts to call the automation functions.
*/
function whitelist(address _account) external onlyManager {
require(!whitelisted[_account], "Account is already whitelisted");
whitelisted[_account] = true;
emit WhiteList(_account);
}
/**
* @notice Remove the additional callers from whitelist.
*/
function removeFromWhitelist(address _account) external onlyManager {
delete whitelisted[_account];
emit RemoveFromWhiteList(_account);
}
/**
* @notice Adds an admin to the contract
* @param _account Address of the admin to add
* @dev Only callable by manager
*/
function addAdmin(address _account) external onlyManager {
admin = _account;
emit AddAdmin(_account);
}
/**
* @notice Changes the product status to Accepted
* @dev Only callable by whitelisted addresses when contract is not paused
* @dev Product must be in Pending or Mature status
*/
function fundAccept() external whenNotPaused onlyWhitelisted {
require(status == DataTypes.Status.Pending || status == DataTypes.Status.Mature, "Invalid status");
status = DataTypes.Status.Accepted;
emit FundAccept();
}
/**
* @notice Distributes option profits to a list of users
* @param _userList Array of user addresses to receive profits
* @param _amountList Array of amounts to distribute to each user
* @dev Only callable by whitelisted addresses when contract is not paused and in Accepted status
*/
function addOptionProfitList(address[] memory _userList, uint256[] memory _amountList) external whenNotPaused onlyMature onlyWhitelisted {
uint256 _optionProfit = optionProfit;
uint256 length = _userList.length;
if (_optionProfit > 0) {
for (uint256 i = 0; i < length; i++) {
userInfo[_userList[i]].optionPayout += _amountList[i];
}
optionProfit = 0;
}
emit AddOptionProfitList(_userList, _amountList);
}
/**
* @notice Changes the product status to Locked
* @dev Only callable by whitelisted addresses when contract is not paused and in Accepted status
*/
function fundLock() external whenNotPaused onlyAccepted onlyWhitelisted {
status = DataTypes.Status.Locked;
emit FundLock();
}
/**
* @notice Changes the product status to Issued
* @dev Only callable by whitelisted addresses when contract is not paused and in Locked status
*/
function issuance() external whenNotPaused onlyLocked onlyWhitelisted {
status = DataTypes.Status.Issued;
emit Issuance();
}
/**
* @notice Changes the product status to Mature
* @dev Only callable by whitelisted addresses when contract is not paused and in Issued status
*/
function mature() external whenNotPaused onlyIssued onlyWhitelisted {
status = DataTypes.Status.Mature;
emit Mature();
}
/**
* @notice Updates users' coupon balances
* @param _userList Array of user addresses to receive coupons
* @param _amountList Array of coupon amounts to distribute
* @dev Only callable by whitelisted addresses when contract is not paused and in Issued status
*/
function coupon(address[] memory _userList, uint256[] memory _amountList) external whenNotPaused onlyIssued onlyWhitelisted{
uint256 length = _userList.length;
for (uint256 i = 0; i < length; i++) {
userInfo[_userList[i]].coupon += _amountList[i];
emit Coupon(
_userList[i],
_amountList[i]
);
}
}
/**
* @notice Updates the coupon rate for the product
* @param _newCoupon New weekly coupon rate in basis points (e.g., 10 = 0.10%/week)
* @dev Only callable by manager when product is in Locked or Mature status
* @dev Coupon rate must be between 0 and 100
*/
function updateCoupon(
uint256 _newCoupon
) external LockedOrMature onlyManager {
require(_newCoupon <= 1000000 && _newCoupon >= 0, "Less than 0 or greater than 100");
issuanceCycle.coupon = _newCoupon;
emit UpdateCoupon(_newCoupon);
}
/**
* @notice Updates all parameters for the next issuance cycle
* @param _name New name for the product
* @param _issuanceCycle New issuance cycle parameters
* @param _router New router address
* @param _market New market address
* @dev Only callable by manager when product is in Accepted status
*/
function updateParameters(string memory _name, DataTypes.IssuanceCycle memory _issuanceCycle,address _router,address _market) external AcceptedOrLockedOrMature onlyManager {
require(_issuanceCycle.issuanceDate > block.timestamp, "ID bigger");
require(_issuanceCycle.maturityDate > _issuanceCycle.issuanceDate, "MT bigger");
require(_issuanceCycle.coupon <= 1000000 && _issuanceCycle.coupon >= 0, "Error coupon");
require(_issuanceCycle.tr1 <= 100000 && _issuanceCycle.tr1 >= 0, "Error tr1");
require(_issuanceCycle.tr2 <= 100000 && _issuanceCycle.tr2 >= 0, "Error tr2");
require(bytes(_issuanceCycle.apy).length >= 2 && bytes(_issuanceCycle.apy).length <= 12, "Error apy length");
require(_issuanceCycle.strikePrice1 <= 1000000 && _issuanceCycle.strikePrice1 >= 0, "Error strikePrice1");
require(_issuanceCycle.strikePrice2 <= 1000000 && _issuanceCycle.strikePrice2 >= 0, "Error strikePrice2");
require(_issuanceCycle.strikePrice3 <= 1000000 && _issuanceCycle.strikePrice3 >= 0, "Error strikePrice3");
require(_issuanceCycle.strikePrice4 <= 1000000 && _issuanceCycle.strikePrice4 >= 0, "Error strikePrice4");
name = _name;
router = IPAllActionV3(_router);
market = IPMarket(_market);
(,PT,YT) = IPMarket(market).readTokens();
issuanceCycle.coupon = _issuanceCycle.coupon;
issuanceCycle.tr1 = _issuanceCycle.tr1;
issuanceCycle.tr2 = _issuanceCycle.tr2;
issuanceCycle.strikePrice1 = _issuanceCycle.strikePrice1;
issuanceCycle.strikePrice2 = _issuanceCycle.strikePrice2;
issuanceCycle.strikePrice3 = _issuanceCycle.strikePrice3;
issuanceCycle.strikePrice4 = _issuanceCycle.strikePrice4;
issuanceCycle.underlyingSpotRef = _issuanceCycle.underlyingSpotRef;
issuanceCycle.apy = _issuanceCycle.apy;
issuanceCycle.subAccountId = _issuanceCycle.subAccountId;
issuanceCycle.issuanceDate = _issuanceCycle.issuanceDate;
issuanceCycle.maturityDate = _issuanceCycle.maturityDate;
emit UpdateParameters(
_name,
_router,
_market
);
}
/**
* @notice Deposits currency into the structured product and mints ERC20 tokens
* @param _amount Amount of currency to deposit
* @dev Only callable when contract is not paused and in Accepted status
* @dev Amount must be greater than 0 and not exceed remaining capacity
*/
function deposit(uint256 _amount) external nonReentrant whenNotPaused onlyAccepted {
require(_amount > 0, "Greater zero");
uint256 decimals = _currencyDecimals();
require(decimals > 0, "Decimals");
uint256 amountToDeposit = _amount;
require((maxCapacity * 10 ** decimals) >= (currentCapacity + amountToDeposit), "Product is full");
currentCapacity += amountToDeposit;
currency.safeTransferFrom(msg.sender, address(this), _amount);
IERC20Token(tokenAddress).mint(msg.sender,_amount);
emit Deposit(msg.sender, _amount);
}
/**
* @notice Withdraws principal by burning product tokens
* @dev Only callable when product is in Accepted status
* @dev Burns user's entire token balance and returns equivalent currency
*/
function withdrawPrincipal() external nonReentrant onlyAccepted {
uint256 currentToken = IERC20(tokenAddress).balanceOf(msg.sender);
IERC20Token(tokenAddress).burn(msg.sender,currentToken);
currency.safeTransfer(msg.sender, currentToken);
currentCapacity -= currentToken;
emit WithdrawPrincipal(
msg.sender,
currentToken
);
}
/**
* @notice Withdraws accumulated coupon payments
* @dev Transfers all accumulated coupon payments to user
* @dev Requires positive coupon balance and sufficient contract balance
*/
function withdrawCoupon() external nonReentrant {
uint256 _couponAmount = userInfo[msg.sender].coupon;
require(_couponAmount > 0, "No coupon available");
require(totalBalance() >= _couponAmount, "Insufficient contract balance");
currency.safeTransfer(msg.sender, _couponAmount);
userInfo[msg.sender].coupon = 0;
emit WithdrawCoupon(msg.sender, _couponAmount);
}
/**
* @notice Withdraws accumulated option payouts
* @dev Transfers all accumulated option payouts to user
* @dev Requires positive option payout balance and sufficient contract balance
*/
function withdrawOption() external nonReentrant {
uint256 _optionAmount = userInfo[msg.sender].optionPayout;
require(_optionAmount > 0, "No option payout available");
require(totalBalance() >= _optionAmount, "Insufficient contract balance");
currency.safeTransfer(msg.sender, _optionAmount);
userInfo[msg.sender].optionPayout = 0;
emit WithdrawOption(msg.sender, _optionAmount);
}
/**
* @notice Distributes locked funds between yield generation and options
* @param _yieldRate Percentage of funds to allocate to yield generation (0-100)
* @dev Only callable by manager when product is in Locked status
* @dev Remaining percentage (100 - _yieldRate) goes to options wallet
*/
function distributeFunds(uint32 _yieldRate) external onlyManager onlyLocked {
require(!isDistributed, "Already distributed");
require(_yieldRate <= 100_000_000, "Less than 100");
isDistributed = true;
uint32 optionRate = 100_000_000 - _yieldRate;
uint256 optionAmount;
if (optionRate > 0) {
optionAmount = currentCapacity * optionRate / 100_000_000;
currency.transfer(exWallet, optionAmount);
}
uint256 yieldAmount = currentCapacity - optionAmount;
IERC20(currencyAddress).approve(address(router), yieldAmount);
(uint256 _netPtOut,,) = router.swapExactTokenForPt(
address(this), address(market), 0, defaultApprox, createTokenInputStruct(currencyAddress, yieldAmount), emptyLimit
);
netPtOut = _netPtOut;
totalFundBalance = currentCapacity;
emit DistributeFunds(exWallet, optionRate, address(router), _yieldRate);
}
/**
* @notice Redeems yield tokens from Pendle protocol
* @dev Only callable by manager when product is in Mature status
* @dev Requires funds to have been previously distributed
*/
function redeemYield() external onlyManager onlyMature {
require(isDistributed, "Not distributed");
uint256 exactPtIn = IERC20(PT).balanceOf(address(this));
uint256 netTokenOut;
netPtOut = 0;
isDistributed = false;
if (exactPtIn > 0)
{
IERC20(PT).approve(address(router), exactPtIn);
(netTokenOut,) = router.redeemPyToToken(address(this), address(YT), exactPtIn, createTokenOutputStruct(currencyAddress, 0));
}
totalFundBalance = 0;
emit RedeemYield(address(router), netTokenOut);
}
/**
* @notice Allows users to withdraw funds early
* @param _noOfBlock Number of blocks to withdraw early
* @dev Only callable when product is in Issued status
* @dev Burns corresponding tokens and returns proportional amount of underlying assets
*/
function earlyWithdraw(uint256 _noOfBlock) external onlyIssued {
uint256 exactPtIn = 0;
uint256 decimals = _currencyDecimals();
require(decimals > 0, "Decimals");
uint256 earlyWithdrawUser = ((_noOfBlock * issuanceCycle.underlyingSpotRef) *(issuanceCycle.optionMinOrderSize * 10**(decimals)))/10;
uint256 currentToken = IERC20(tokenAddress).balanceOf(msg.sender);
uint256 withdrawBlockSize = (issuanceCycle.underlyingSpotRef * 10**(decimals) * issuanceCycle.optionMinOrderSize)/10;
uint256 totalBlock = currentToken / withdrawBlockSize;
require(totalBlock >= _noOfBlock, "Not enough blocks");
exactPtIn = (earlyWithdrawUser * netPtOut / totalFundBalance);
totalNumberOfBlocks+=_noOfBlock;
currentCapacity -= earlyWithdrawUser;
IERC20Token(tokenAddress).burn(msg.sender,earlyWithdrawUser);
IERC20(PT).approve(address(router), exactPtIn);
(uint256 netTokenOut,,) = router.swapExactPtForToken(
address(this), address(market), exactPtIn, createTokenOutputStruct(currencyAddress, 0), emptyLimit);
currency.safeTransfer(msg.sender, netTokenOut);
emit EarlyWithdraw(msg.sender, _noOfBlock, exactPtIn, earlyWithdrawUser);
}
/**
* @notice Stores option positions for users
* @param _userList Array of user addresses
* @param _amountList Array of option position amounts
* @dev Only callable by admin when product is in Issued status
*/
function storageOptionPosition(address[] memory _userList, uint256[] memory _amountList) external onlyIssued onlyAdmin {
uint256 length = _userList.length;
for (uint256 i = 0; i < length; i++)
{
UserOptionPositions.push(UserOptionPosition({
userAddress: _userList[i],
value: _amountList[i]
}));
totalOptionPosition += _amountList[i];
}
}
/**
* @notice Pays out option positions to users
* @dev Only callable by manager when product is in Issued status
* @dev Transfers stored option positions to respective users
*/
function userOptionPositionPaid() external onlyIssued onlyManager {
currency.safeTransferFrom(msg.sender, address(this), totalOptionPosition);
uint256 length = UserOptionPositions.length;
for (uint256 i = 0; i < length; i++)
{
currency.safeTransfer(UserOptionPositions[i].userAddress, UserOptionPositions[i].value);
}
totalOptionPosition = 0;
totalNumberOfBlocks = 0;
delete UserOptionPositions;
emit UserOptionPositionPaid(totalOptionPosition);
}
/**
* @notice Allows external wallet to transfer option profits to the contract
* @param _optionProfit Amount of option profit to transfer
* @dev Only callable by external wallet when product is in Mature status
*/
function redeemOptionPayout(uint256 _optionProfit) external onlyMature {
require(msg.sender == exWallet, "Not an exwallet");
currency.safeTransferFrom(msg.sender, address(this), _optionProfit);
optionProfit = _optionProfit;
emit RedeemOptionPayout(msg.sender, _optionProfit);
}
/**
* @notice Gets the principal balance of a user
* @param _user Address of the user
* @return uint256 Amount of principal tokens held by the user
*/
function principalBalance(address _user) external view returns (uint256) {
return IERC20(tokenAddress).balanceOf(_user);
}
/**
* @notice Gets the coupon balance of a user
* @param _user Address of the user
* @return uint256 Amount of unclaimed coupon payments
*/
function couponBalance(address _user) external view returns (uint256) {
return userInfo[_user].coupon;
}
/**
* @notice Gets the option payout balance of a user
* @param _user Address of the user
* @return uint256 Amount of unclaimed option payouts
*/
function optionBalance(address _user) external view returns (uint256) {
return userInfo[_user].optionPayout;
}
/**
* @notice Gets the total balance of the underlying currency in the contract
* @return uint256 Total balance of the contract
*/
function totalBalance() public view returns (uint256) {
return currency.balanceOf(address(this));
}
/**
* @notice Gets the number of decimals for the underlying currency
* @return uint256 Number of decimals
* @dev Internal helper function
*/
function _currencyDecimals() internal view returns (uint256) {
return IERC20MetadataUpgradeable(address(currency)).decimals();
}
/**
* @notice Pauses all contract operations
* @dev Only callable by manager
*/
function pause() external onlyManager {
_pause();
}
/**
* @notice Unpauses contract operations
* @dev Only callable by manager
*/
function unpause() external onlyManager {
_unpause();
}
}
StructGen.sol 48 lines
// SPDX-License-Identifier: UNLICENSED
// pragma solidity >=0.8.23 <0.9.0;
pragma solidity 0.8.23;
import "@pendle/core-v2/contracts/interfaces/IPAllActionV3.sol";
import "@pendle/core-v2/contracts/interfaces/IPMarket.sol";
abstract contract StructGen {
// EmptySwap means no swap aggregator is involved
SwapData public emptySwap;
// EmptyLimit means no limit order is involved
LimitOrderData public emptyLimit;
// DefaultApprox means no off-chain preparation is involved, more gas consuming (~ 180k gas)
ApproxParams public defaultApprox = ApproxParams(0, type(uint256).max, 0, 256, 1e14);
/// @notice create a simple TokenInput struct without using any aggregators. For more info please refer to
/// IPAllActionTypeV3.sol
function createTokenInputStruct(address tokenIn, uint256 netTokenIn) internal view returns (TokenInput memory) {
return TokenInput({
tokenIn: tokenIn,
netTokenIn: netTokenIn,
tokenMintSy: tokenIn,
pendleSwap: address(0),
swapData: emptySwap
});
}
/// @notice create a simple TokenOutput struct without using any aggregators. For more info please refer to
/// IPAllActionTypeV3.sol
function createTokenOutputStruct(
address tokenOut,
uint256 minTokenOut
)
internal
view
returns (TokenOutput memory)
{
return TokenOutput({
tokenOut: tokenOut,
minTokenOut: minTokenOut,
tokenRedeemSy: tokenOut,
pendleSwap: address(0),
swapData: emptySwap
});
}
}
Read Contract
PT 0xd94073d4 → address
UserOptionPositions 0xdcf3e18b → address, uint256
YT 0x781c18db → address
admin 0xf851a440 → address
couponBalance 0x9dd1cfb8 → uint256
currency 0xe5a6b10f → address
currencyAddress 0x1c1cb323 → address
currentCapacity 0x9b39b0da → uint256
defaultApprox 0x4ebfc814 → uint256, uint256, uint256, uint256, uint256
emptyLimit 0x09316dd3 → address, uint256, bytes
emptySwap 0xf66a7749 → uint8, address, bytes, bool
exWallet 0x05f53f4d → address
fundContract 0xbd097e21 → address
isDistributed 0xf677cf0d → bool
issuanceCycle 0x36246db4 → uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, uint256, string, uint256, uint256, string, uint8
manager 0x481c6a75 → address
market 0x80f55605 → address
maxCapacity 0x59b6a0c9 → uint256
name 0x06fdde03 → string
netPtOut 0xc7ee91f1 → uint256
optionBalance 0xc761d0b2 → uint256
optionProfit 0xa3aad3aa → uint256
paused 0x5c975abb → bool
principalBalance 0xe68fc0ee → uint256
router 0xf887ea40 → address
shFactory 0xd1012bc3 → address
status 0x200d2ed2 → uint8
tokenAddress 0x9d76ea58 → address
totalBalance 0xad7a672f → uint256
totalFundBalance 0x871b689f → uint256
totalNumberOfBlocks 0x1734163c → uint256
totalOptionPosition 0x655ae371 → uint256
underlying 0x6f307dc3 → string
userInfo 0x1959a002 → uint256, uint256
whitelisted 0xd936547e → bool
Write Contract 24 functions
These functions modify contract state and require a wallet transaction to execute.
addAdmin 0x70480275
address _account
addOptionProfitList 0xcc8dc34c
address[] _userList
uint256[] _amountList
coupon 0xf399efe8
address[] _userList
uint256[] _amountList
deposit 0xb6b55f25
uint256 _amount
distributeFunds 0x6d34b618
uint32 _yieldRate
earlyWithdraw 0x6b5b9696
uint256 _noOfBlock
fundAccept 0xb3ea322d
No parameters
fundLock 0x7389250b
No parameters
initialize 0xf79aebfa
string _name
string _underlying
address _currency
address _manager
address _exWallet
uint256 _maxCapacity
tuple _issuanceCycle
address _router
address _market
address _tokenAddress
address _currencyAddress
issuance 0x863623bb
No parameters
mature 0x87b65207
No parameters
pause 0x8456cb59
No parameters
redeemOptionPayout 0xf0d427c4
uint256 _optionProfit
redeemYield 0xc7999408
No parameters
removeFromWhitelist 0x8ab1d681
address _account
storageOptionPosition 0x92b0f61f
address[] _userList
uint256[] _amountList
unpause 0x3f4ba83a
No parameters
updateCoupon 0x951e29c9
uint256 _newCoupon
updateParameters 0x4043e9fe
string _name
tuple _issuanceCycle
address _router
address _market
userOptionPositionPaid 0x8fe0a864
No parameters
whitelist 0x9b19251a
address _account
withdrawCoupon 0x6d2b8111
No parameters
withdrawOption 0xf78705c3
No parameters
withdrawPrincipal 0xe1f06f54
No parameters
Recent Transactions
No transactions found for this address