Address Contract Verified
Address
0x0E89538Ab556Ca69e2F1d4884029128D6c5bF6Cd
Balance
0 ETH
Nonce
1
Code Size
10640 bytes
Creator
0x22211a0d...bfb4 at tx 0x79ee95e0...8de14e
Indexed Transactions
0
Contract Bytecode
10640 bytes
0x6080806040526004361015610012575f80fd5b5f905f3560e01c90816306def80214611fab5750806323df13a714611f8c5780632cdf7d8314611f155780632d6b3a6b14611ed15780632e1a7d4d146117d2578063342c00b31461135d57806345b05d0914610fc35780634e71d92d14610ed35780634ec508f914610e965780636382d9ad14610ca4578063660d0d6714610c5f5780636c93022814610c2e5780637008b54814610a7f578063809dab6a14610c1357806389b8799814610bf05780639750730a14610ac45780639f4bc3c3146101835780639fd0506d14610a7f578063aabd4ac114610a64578063b6b55f25146104b3578063c561d4b71461041f578063dc9293531461034b578063de4303bc146101ef578063e6aa216c146101c8578063fdcb6068146101835763fe58265e1461013c575f80fd5b346101805780600319360112610180576040517f000000000000000000000000a99da8f18c15f7afa1072b1667dfbf54ff3388656001600160a01b03168152602090f35b80fd5b50346101805780600319360112610180576040517f000000000000000000000000889d4580b7f5220038b62b44bcd76d58f37f45666001600160a01b03168152602090f35b503461018057806003193601126101805760406101e3612539565b82519182526020820152f35b50346101805780600319360112610180576001600160a01b03610210612595565b604051633790c0ef60e21b81529116602082600481845afa91821561030b578392610316575b50602060049160405192838092637bb146c760e01b82525afa90811561030b5783916102d5575b50670de0b6b3a7640000820291808304670de0b6b3a764000014901517156102c157670de0b6b3a76400000391670de0b6b3a764000083116102ad5760206102a58484612108565b604051908152f35b634e487b7160e01b81526011600452602490fd5b634e487b7160e01b83526011600452602483fd5b90506020813d602011610303575b816102f0602093836120a9565b810103126102ff57515f61025d565b5f80fd5b3d91506102e3565b6040513d85823e3d90fd5b9091506020813d602011610343575b81610332602093836120a9565b810103126102ff5751906020610236565b3d9150610325565b503461018057806003193601126101805760025460035461037461036f8284612126565b612498565b92805b838310610390576040518061038c8782611ff5565b0390f35b610417600191848452836020526040842060ff6006604051926103b284612079565b868060a01b03815416845286810154602085015260028101546040850152600381015460608501528260048201541615156080850152600581015460a0850152015416151560c08201526104068289612511565b526104118188612511565b506122b5565b920191610377565b5034610180578060031936011261018057600460206001600160a01b03610444612595565b166040519283809263c561d4b760e01b82525afa9081156104a8576020929161047b575b506040516001600160a01b039091168152f35b61049b9150823d84116104a1575b61049381836120a9565b810190612226565b5f610468565b503d610489565b6040513d84823e3d90fd5b5034610180576020366003190112610180576004356104d3811515612245565b60405163939e8d0f60e01b81527f87a7811f4bfedea3d341ad165680ae306b01aaeacc205d227629cf157dd9f82160048201526020816024817f00000000000000000000000015e953be163841d0cfd676a6b98fd674d5c241af6001600160a01b03165afa90811561030b578391610a35575b50610a0257600460206001600160a01b0361055f612595565b1660405192838092632cdf7d8360e01b82525afa90811561030b5783916109e3575b506001600160a01b0316156109d457600460406001600160a01b036105a4612595565b168151928380926339aa885b60e21b82525afa90811561030b5783916109b4575b50156109a557600460206001600160a01b036105df612595565b166040519283809263c561d4b760e01b82525afa90811561030b578391610986575b506001600160a01b031615610977576001600160a01b03610620612595565b16604051637bb146c760e01b8152602081600481855afa9081156108a957849161093d575b50670de0b6b3a764000061065c61066392856120e1565b0483612126565b604051633790c0ef60e21b815290602082600481865afa918215610822578592610909575b50106108b457604051639642366360e01b8152602081600481855afa9081156108a957849161088a575b5060405163c561d4b760e01b815290602082600481865afa918215610822578592610869575b5061070e6106e5856122c3565b939150936106f3858361287e565b6106fd8588612126565b9133906001600160a01b031661289e565b604051632cdf7d8360e01b81528590602081600481885afa9081156104a857829161084a575b506001600160a01b0316803b15610846576040516340c10f1960e01b8152336004820152602481018490529082908290604490829084905af180156104a85761082d575b5050604080516339aa885b60e21b815293849060049082905afa918215610822577f7162984403f6c73c8639375d45a9187dfd04602231bd8e587c415718b5f7e5f99386936107ec575b50604080519586526020860192909252908401919091526060830152339180608081015b0390a280f35b6107e69193506108139060403d60401161081b575b61080b81836120a9565b8101906120cb565b5092906107c2565b503d610801565b6040513d87823e3d90fd5b81610837916120a9565b61084257845f610778565b8480fd5b5080fd5b610863915060203d6020116104a15761049381836120a9565b5f610734565b61088391925060203d6020116104a15761049381836120a9565b905f6106d8565b6108a3915060203d6020116104a15761049381836120a9565b5f6106b2565b6040513d86823e3d90fd5b60405162461bcd60e51b815260206004820152602760248201527f4e6574206465706f73697420616d6f756e74206973206c657373207468616e206044820152666d696e696d756d60c81b6064820152608490fd5b9091506020813d602011610935575b81610925602093836120a9565b810103126102ff5751905f610688565b3d9150610918565b90506020813d60201161096f575b81610958602093836120a9565b810103126102ff5751670de0b6b3a7640000610645565b3d915061094b565b632c65d67160e11b8252600482fd5b61099f915060203d6020116104a15761049381836120a9565b5f610601565b6362f216e560e01b8252600482fd5b6109cd915060403d60401161081b5761080b81836120a9565b505f6105c5565b637090a51d60e11b8252600482fd5b6109fc915060203d6020116104a15761049381836120a9565b5f610581565b63b81fa1e360e01b82527f87a7811f4bfedea3d341ad165680ae306b01aaeacc205d227629cf157dd9f821600452602482fd5b610a57915060203d602011610a5d575b610a4f81836120a9565b810190612290565b5f610546565b503d610a45565b503461018057806003193601126101805760206102a561269a565b50346101805780600319360112610180576040517f00000000000000000000000015e953be163841d0cfd676a6b98fd674d5c241af6001600160a01b03168152602090f35b503461018057602036600319011261018057600435801515808203610bec57827f000000000000000000000000889d4580b7f5220038b62b44bcd76d58f37f45666001600160a01b0316803b156108465781604491604051928380926312d9a6ad60e01b82527f1d7d8843f0c1e1a93c132cfc3744403b38e2dc280a9cbff83c6f1219b210cf0260048301523360248301525afa80156104a857610bd7575b505060ff8019600654169116176006555f14610ba8576040514281527f5d76a6f36d1d17bd1bfe840fcae82ea9b394b919565dc42af9f259755a1b43cc60203392a280f35b6040514281527fa4dab9d55fb9027bdebb1472f91ddd3fb2c011b24653c2f90f0936e30f34a4a760203392a280f35b81610be1916120a9565b610bec57825f610b63565b8280fd5b5034610180578060031936011261018057602060ff600654166040519015158152f35b503461018057806003193601126101805760206102a56123a5565b50346101805760203660031901126101805761038c610c53610c4e611fdf565b61277a565b60405191829182611ff5565b50346101805780600319360112610180576040517f000000000000000000000000a99da8f18c15f7afa1072b1667dfbf54ff3388656001600160a01b03168152602090f35b503461018057604036600319011261018057610cbe611fdf565b6024356001600160a01b03811691828203610e9257837f000000000000000000000000889d4580b7f5220038b62b44bcd76d58f37f45666001600160a01b0316803b156108465781604491604051928380926312d9a6ad60e01b82527f76b1a12ac8d9ed64de3c0f66c2a19b21c0a3f9a1afec3f75bcd45f7b0794a1de60048301523360248301525afa80156104a857610e7d575b50508215610e44576040516370a0823160e01b81523060048201526001600160a01b039190911691602082602481865afa918215610822578592610e10575b508115610dd25781610dc87ff24ef89f38eadc1bde50701ad6e4d6d11a2dc24f7cf834a486991f38833285049360209386612739565b604051908152a380f35b60405162461bcd60e51b81526020600482015260166024820152754e6f2062616c616e636520746f20776974686472617760501b6044820152606490fd5b9091506020813d602011610e3c575b81610e2c602093836120a9565b810103126102ff5751905f610d92565b3d9150610e1f565b60405162461bcd60e51b8152602060048201526011602482015270125b9d985b1a59081c9958da5c1a595b9d607a1b6044820152606490fd5b81610e87916120a9565b610e9257835f610d53565b8380fd5b50346101805760203660031901126101805761038c610eb66004356122c3565b604080519384526020840192909252908201529081906060820190565b5034610180578060031936011261018057338152600460205260408120548015610fb45733825260046020818152604084208490556001600160a01b03610f18612595565b1660405192838092639642366360e01b82525afa90811561030b57610f609183918591610f95575b50610f4d82600554612126565b60055533906001600160a01b0316612739565b6040519081524260208201527f2d43eb174787155132b52ddb6b346e2dca99302eac3df4466dbeff953d3c84d160403392a280f35b610fae915060203d6020116104a15761049381836120a9565b5f610f40565b630f67b52b60e11b8252600482fd5b5034610180576020366003190112610180576004358082528160205260408220908060038301541480159061134c575b61133d5781546001600160a01b0316330361132e5760ff60048301541661131f57600682019182549260ff84166113105784906001600160a01b03611036612595565b16906040519363cd981a2160e01b8552602085600481865afa9485156108a95784956112d4575b50916020916001611088670de0b6b3a7640000611080836004980154998a6120e1565b048098612126565b60ff19909916179055604051632cdf7d8360e01b815292839182905afa9081156104a85782916112b5575b506001600160a01b0316803b15610846576040516340c10f1960e01b815233600482015260248101869052828160448183865af190811561030b5783916112a0575b50508261123e575b505033845260016020526040842092845b845480821015611231578461112383886126fc565b90549060031b1c14611138575060010161110e565b5f959293949519810190811161121d579061116761115961117f93856126fc565b90549060031b1c91846126fc565b90919082549060031b91821b915f19901b1916179055565b8054801561120957908492915f19019061119982826126fc565b8154905f199060031b1b19169055555b6040519081527f609802616efe88a6b73a266ced98c5dfd07c25e64549e620527605107ea30e8160203392a360405191825260208201527f7b9804f3283c7a8265b3b814f8e4c16f1d6d93e0854c062dad1fe3af05a2612460403392a280f35b634e487b7160e01b86526031600452602486fd5b634e487b7160e01b87526011600452602487fd5b50508293509190916111a9565b611246612624565b90803b15610bec576040516340c10f1960e01b81526001600160a01b039290921660048301526024820184905282908290604490829084905af180156104a857156110fd5781611295916120a9565b610e9257835f6110fd565b816112aa916120a9565b61084657815f6110f5565b6112ce915060203d6020116104a15761049381836120a9565b5f6110b3565b9192935093506020813d602011611308575b816112f3602093836120a9565b810103126102ff57519286929190602061105d565b3d91506112e6565b6379925f6560e01b8552600485fd5b6312c84d0160e11b8352600483fd5b63517907dd60e01b8352600483fd5b63514447b560e01b8352600483fd5b506113563361277a565b5115610ff3565b50346101805760203660031901126101805760043560ff600654166117c357600460206001600160a01b03611390612595565b1660405192838092632cdf7d8360e01b82525afa90811561030b5783916117a4575b506001600160a01b0316156109d457600460406001600160a01b036113d5612595565b168151928380926339aa885b60e21b82525afa90811561030b578391611784575b50156109a557600460206001600160a01b03611410612595565b166040519283809263c561d4b760e01b82525afa90811561030b578391611765575b506001600160a01b0316156109775760405163939e8d0f60e01b81525f51602061293b5f395f51905f5260048201526020816024817f00000000000000000000000015e953be163841d0cfd676a6b98fd674d5c241af6001600160a01b03165afa90811561030b578391611746575b50611726578015611717576003549060025482101561170857600460206001600160a01b036114ce612595565b1660405192838092639642366360e01b82525afa9081156108a95784916116e9575b5090919083908180806115016123a5565b9388965b6002548110806116e0575b156116ad57808a528960205260408a2060ff600682015416158061169e575b61154d575b50611541611547916122b5565b976122b5565b96611505565b949360018697929701936115618554612133565b969197909a8886106116325788611577916122a8565b9a611581916122a8565b88546001600160a01b03168e52600460205260408e2080549199916115a79089906122a8565b905560048101805460ff191660011790556005810187905580546003909101549154604080519182526020820189905242908201526001600160a01b03909116907f0d136f5b20cf8cb815dc6ccab1583338dea7e0c38d762e233652e649f0c6e35890606090a3611617906122b5565b93611621916122a8565b9361162b91612126565b945f611534565b5096505097509592505092507f5a63c49da545ba99ae56821711c59f0fb701cd6b01e6816c8c9339779c3466bf9650604095505b6003558061168e575b505061167d816005546122a8565b60055582519182526020820152a180f35b61169791612711565b5f8061166f565b5060ff6004820154161561152f565b919550929193507f5a63c49da545ba99ae56821711c59f0fb701cd6b01e6816c8c9339779c3466bf965060409550611666565b50888810611510565b611702915060203d6020116104a15761049381836120a9565b5f6114f0565b633fbd0fd160e11b8352600483fd5b636b86fdef60e11b8252600482fd5b63b81fa1e360e01b82525f51602061293b5f395f51905f52600452602482fd5b61175f915060203d602011610a5d57610a4f81836120a9565b5f6114a1565b61177e915060203d6020116104a15761049381836120a9565b5f611432565b61179d915060403d60401161081b5761080b81836120a9565b505f6113f6565b6117bd915060203d6020116104a15761049381836120a9565b5f6113b2565b63a91e0aa360e01b8252600482fd5b50346102ff5760203660031901126102ff57600435906117f3821515612245565b60405163939e8d0f60e01b81525f51602061293b5f395f51905f5260048201526020816024817f00000000000000000000000015e953be163841d0cfd676a6b98fd674d5c241af6001600160a01b03165afa908115611cad575f91611eb2575b50611e925760ff60065416611e8357600460206001600160a01b03611876612595565b1660405192838092632cdf7d8360e01b82525afa908115611cad575f91611e64575b506001600160a01b031615611e5557600460406001600160a01b036118bb612595565b168151928380926339aa885b60e21b82525afa908115611cad575f91611e35575b5015611e2657600460206001600160a01b036118f6612595565b166040519283809263c561d4b760e01b82525afa908115611cad575f91611e07575b506001600160a01b031615611df8576001600160a01b03611937612595565b1691604051632cdf7d8360e01b8152602081600481875afa908115611cad575f91611dd9575b506040516370a0823160e01b81523360048201526001600160a01b03919091169390602081602481885afa8015611cad5783915f91611da4575b5010611d5f576119a682612133565b91604093919351637a94f2e560e11b8152602081600481865afa908115611cad575f91611d2d575b508110611cd957604051639642366360e01b815290602082600481865afa918215611cad575f92611cb8575b50611a036123a5565b97803b156102ff57604051632770a7eb60e21b815233600482015260248101889052905f908290604490829084905af18015611cad57611c96575b509596949560049510611ad75790611a6d8383611a5d87604096612711565b33906001600160a01b0316612739565b81516339aa885b60e21b815294859182905afa918215610822577fe08737ac48a1dab4b1a46c7dc9398bd5bfc6d7ad6fabb7cd8caa254de14def359386936107ec5750604080519586526020860192909252908401919091526060830152339180608081016107e6565b509150506020611ae561269a565b9160405193848092632037781d60e21b82525afa9182156108a9578492611c62575b501015611c535760025490611bc8604051611b2181612079565b33815260066020820184815260408301428152611bac6060850188815260808601908a825260a08701938b855260c08801958c87528b8d528c60205260408d209860018060a01b039051166bffffffffffffffffffffffff60a01b8a5416178955516001890155516002880155516003870155511515600486019060ff801983541691151516179055565b51600584015551151591019060ff801983541691151516179055565b33835260016020526040832080549068010000000000000000821015611c3f576111678285926001611bfc950181556126fc565b6040519081524260208201527f328b544541befb6692d6eba0b20703cc99d169c531e7f12c7b40518d55f1a9b860403392a3611c396002546122b5565b60025580f35b634e487b7160e01b85526041600452602485fd5b638af0b3af60e01b8252600482fd5b9091506020813d602011611c8e575b81611c7e602093836120a9565b810103126102ff5751905f611b07565b3d9150611c71565b60049697505f611ca5916120a9565b5f9695611a3e565b6040513d5f823e3d90fd5b611cd291925060203d6020116104a15761049381836120a9565b905f6119fa565b60405162461bcd60e51b815260206004820152602660248201527f5769746864726177616c20616d6f756e74206973206c657373207468616e206d604482015265696e696d756d60d01b6064820152608490fd5b90506020813d602011611d57575b81611d48602093836120a9565b810103126102ff57515f6119ce565b3d9150611d3b565b60405162461bcd60e51b815260206004820152601a60248201527f496e73756666696369656e742073686172652062616c616e63650000000000006044820152606490fd5b9150506020813d602011611dd1575b81611dc0602093836120a9565b810103126102ff578290515f611997565b3d9150611db3565b611df2915060203d6020116104a15761049381836120a9565b5f61195d565b632c65d67160e11b5f5260045ffd5b611e20915060203d6020116104a15761049381836120a9565b5f611918565b6362f216e560e01b5f5260045ffd5b611e4e915060403d60401161081b5761080b81836120a9565b505f6118dc565b637090a51d60e11b5f5260045ffd5b611e7d915060203d6020116104a15761049381836120a9565b5f611898565b63a91e0aa360e01b5f5260045ffd5b63b81fa1e360e01b5f525f51602061293b5f395f51905f5260045260245ffd5b611ecb915060203d602011610a5d57610a4f81836120a9565b5f611853565b346102ff575f3660031901126102ff576040517f00000000000000000000000097126771e887ef57f5562db332843f6d1890aee06001600160a01b03168152602090f35b346102ff575f3660031901126102ff57600460206001600160a01b03611f39612595565b1660405192838092632cdf7d8360e01b82525afa8015611cad576020915f91611f6f57506040516001600160a01b039091168152f35b611f869150823d84116104a15761049381836120a9565b82610468565b346102ff5760203660031901126102ff5761038c610eb6600435612133565b346102ff5760203660031901126102ff576020906001600160a01b03611fcf611fdf565b165f526004825260405f20548152f35b600435906001600160a01b03821682036102ff57565b60206040818301928281528451809452019201905f5b8181106120185750505090565b909192602060e060019260c08751858060a01b0381511683528481015185840152604081015160408401526060810151606084015260808101511515608084015260a081015160a08401520151151560c0820152019401910191909161200b565b60e0810190811067ffffffffffffffff82111761209557604052565b634e487b7160e01b5f52604160045260245ffd5b90601f8019910116810190811067ffffffffffffffff82111761209557604052565b91908260409103126102ff576020825192015190565b818102929181159184041417156120f457565b634e487b7160e01b5f52601160045260245ffd5b8115612112570490565b634e487b7160e01b5f52601260045260245ffd5b919082039182116120f457565b6001600160a01b03612143612595565b166040516339aa885b60e21b8152604081600481855afa908115611cad575f91612206575b508015611e2657602060049260405193848092630659bb1560e41b82525afa918215611cad575f926121cd575b5064e8d4a51000670de0b6b3a76400006121b46121bd938295966120e1565b040492836120e1565b04906121c98282612126565b9092565b91506020823d6020116121fe575b816121e8602093836120a9565b810103126102ff5790519064e8d4a51000612195565b3d91506121db565b61221f915060403d60401161081b5761080b81836120a9565b505f612168565b908160209103126102ff57516001600160a01b03811681036102ff5790565b1561224c57565b606460405162461bcd60e51b815260206004820152602060248201527f416d6f756e74206d7573742062652067726561746572207468616e207a65726f6044820152fd5b908160209103126102ff575180151581036102ff5790565b919082018092116120f457565b5f1981146120f45760010190565b600460206001600160a01b036122d7612595565b1660405192838092637bb146c760e01b82525afa908115611cad575f9161236b575b50670de0b6b3a764000061231061231892846120e1565b048092612126565b612320612539565b50670de0b6b3a7640000820291808304670de0b6b3a764000014901517156120f45761234b91612108565b9164e8d4a5100083029280840464e8d4a5100014901517156120f4578290565b90506020813d60201161239d575b81612386602093836120a9565b810103126102ff5751670de0b6b3a76400006122f9565b3d9150612379565b600460206001600160a01b036123b9612595565b1660405192838092639642366360e01b82525afa908115611cad576024916020915f91612463575b506040516370a0823160e01b815230600482015292839182906001600160a01b03165afa908115611cad575f91612431575b506005548082111561242b5761242891612126565b90565b50505f90565b90506020813d60201161245b575b8161244c602093836120a9565b810103126102ff57515f612413565b3d915061243f565b61247a9150823d84116104a15761049381836120a9565b5f6123e1565b67ffffffffffffffff81116120955760051b60200190565b906124a282612480565b6124af60405191826120a9565b82815280926124c0601f1991612480565b01905f5b8281106124d057505050565b6020906040516124df81612079565b5f81525f838201525f60408201525f60608201525f60808201525f60a08201525f60c0820152828285010152016124c4565b80518210156125255760209160051b010190565b634e487b7160e01b5f52603260045260245ffd5b60049060406001600160a01b0361254e612595565b168151938480926339aa885b60e21b82525afa918215611cad575f905f9361257557509190565b905061259191925060403d60401161081b5761080b81836120a9565b9091565b604051630d2020dd60e01b81527f5600185b051f65d311a9e3e3329905fc2fa701a8b22f3bbf8dfcbc10ccb6807160048201526020816024817f00000000000000000000000097126771e887ef57f5562db332843f6d1890aee06001600160a01b03165afa908115611cad575f9161260b575090565b612428915060203d6020116104a15761049381836120a9565b604051630d2020dd60e01b81527f06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb760048201526020816024817f00000000000000000000000097126771e887ef57f5562db332843f6d1890aee06001600160a01b03165afa908115611cad575f9161260b575090565b5f90600354600254905b8181106126af575050565b805f525f60205260405f2060ff6004820154161590816126ec575b506126d8575b6001016126a4565b926126e46001916122b5565b9390506126d0565b60ff91506006015416155f6126ca565b8054821015612525575f5260205f2001905f90565b9080156127355761273391612724612624565b906001600160a01b0316612739565b565b5050565b60405163a9059cbb60e01b60208201526001600160a01b03929092166024830152604480830193909352918152612733916127756064836120a9565b6128e2565b60018060a01b03165f52600160205260405f20604051808260208294549384815201905f5260205f20925f5b8181106128655750506127bb925003826120a9565b6127c58151612498565b905f5b815181101561286057806127de60019284612511565b515f525f60205260405f2060ff6006604051926127fa84612079565b858060a01b03815416845285810154602085015260028101546040850152600381015460608501528260048201541615156080850152600581015460a0850152015416151560c082015261284e8286612511565b526128598185612511565b50016127c8565b505090565b84548352600194850194869450602090930192016127a6565b9080156127355761273391612891612624565b9033906001600160a01b03165b6040516323b872dd60e01b60208201526001600160a01b039283166024820152929091166044830152606480830193909352918152612733916127756084836120a9565b905f602091828151910182855af115611cad575f513d61293157506001600160a01b0381163b155b6129115750565b635274afe760e01b5f9081526001600160a01b0391909116600452602490fd5b6001141561290a56fe738128fe393bef1bcd8a524796fff40618b938cd467c71fcf37850ab0ba4f7d7a2646970667358221220e6261eb0dd7db738a3ceb5f18f6c63c615aab6bcecf7a7ffb796b82ab3b62d0a64736f6c634300081e0033
Verified Source Code Full Match
Compiler: v0.8.30+commit.73712a01
EVM: prague
Optimization: Yes (200 runs)
SPRVault.sol 462 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {BaseContract} from "common-contracts/base-contracts/BaseContract.sol";
import "common-contracts/constants/MathConstants.sol";
import {VaultToken} from "@src/common/contracts/VaultToken.sol";
import "@src/common/constants/Contracts.sol";
import {DEPOSIT_SCOPE, WITHDRAWAL_SCOPE} from "@src/common/constants/Scopes.sol";
import {ISPRVault} from "./ISPRVault.sol";
import {IVaultManagerRepository} from "@src/spreads-vault/repositories/IVaultManagerRepository.sol";
import {WithdrawalRequest} from "@src/spreads-vault/structs/WithdrawalRequest.sol";
import {ExchangeRate} from "@src/spreads-vault/structs/ExchangeRate.sol";
import "@src/spreads-vault/events/EventsV2.sol";
import "@src/spreads-vault/errors/ErrorsV2.sol";
import {OPERATOR_ROLE, EMERGENCY_ROLE} from "@src/common/access-management/Roles.sol";
contract SPRVault is BaseContract, ISPRVault {
using SafeERC20 for ERC20;
mapping(uint256 => WithdrawalRequest) private withdrawalRequests;
mapping(address => uint256[]) private userWithdrawalRequestIds;
uint256 private nextRequestId;
uint256 private firstUnprocessedRequestId;
mapping(address => uint256) private allocatedBalances;
uint256 private currentAllocatedBalance;
bool private queuePaused;
modifier nonZero(uint256 _amount) {
require(_amount > 0, "Amount must be greater than zero");
_;
}
modifier requireSPRTokenInitialized() {
IVaultManagerRepository repo = IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
if (repo.getSPRToken() == address(0)) {
revert SPRTokenNotInitialized();
}
_;
}
modifier exchangeRateSet() {
IVaultManagerRepository repo = IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
(uint256 rate,) = repo.getExchangeRate();
if (rate == 0) revert ExchangeRateNotSet();
_;
}
modifier custodianSet() {
IVaultManagerRepository repo = IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
if (repo.getCustodian() == address(0)) revert CustodianNotSet();
_;
}
modifier whenQueueNotPaused() {
if (queuePaused) revert QueuePausedError();
_;
}
constructor(address _beaconAddress) BaseContract(_beaconAddress) {}
function deposit(uint256 _amount)
external
nonZero(_amount)
whenScopeNotPaused(DEPOSIT_SCOPE)
requireSPRTokenInitialized
exchangeRateSet
custodianSet
{
IVaultManagerRepository _vaultManagerRepository =
IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
_validateDepositAmount(_vaultManagerRepository, _amount);
address _collateralToken = _vaultManagerRepository.getCollateralToken();
address custodian = _vaultManagerRepository.getCustodian();
(, uint256 fee, uint256 netShares) = calculateDeposit(_amount);
_collectDepositFee(_collateralToken, fee);
uint256 _depositAmount = _amount - fee;
ERC20(_collateralToken).safeTransferFrom(msg.sender, custodian, _depositAmount);
address SPRToken = _vaultManagerRepository.getSPRToken();
VaultToken(SPRToken).mint(msg.sender, netShares);
(uint256 currentRate,) = _vaultManagerRepository.getExchangeRate();
emit Deposit(msg.sender, _amount, netShares, currentRate, fee);
}
function withdraw(uint256 _shareAmount)
external
nonZero(_shareAmount)
whenScopeNotPaused(WITHDRAWAL_SCOPE)
whenQueueNotPaused
requireSPRTokenInitialized
exchangeRateSet
custodianSet
{
IVaultManagerRepository _vaultManagerRepository =
IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
address SPRToken = _vaultManagerRepository.getSPRToken();
require(VaultToken(SPRToken).balanceOf(msg.sender) >= _shareAmount, "Insufficient share balance");
(uint256 collateralAmount, uint256 fee, uint256 netCollateral) = calculateWithdrawal(_shareAmount);
_validateWithdrawalAmount(_vaultManagerRepository, collateralAmount);
address _collateralToken = _vaultManagerRepository.getCollateralToken();
uint256 availableBalance = getAvailableBalance();
VaultToken(SPRToken).burn(msg.sender, _shareAmount);
if (availableBalance >= collateralAmount) {
_collectWithdrawalFee(_collateralToken, fee);
ERC20(_collateralToken).safeTransfer(msg.sender, netCollateral);
(uint256 currentRate,) = _vaultManagerRepository.getExchangeRate();
emit Withdraw(msg.sender, _shareAmount, netCollateral, currentRate, fee);
} else {
uint256 currentQueueSize = _getPendingWithdrawalCount();
uint256 maxQueueSize = _vaultManagerRepository.getMaxQueueSize();
if (currentQueueSize >= maxQueueSize) {
revert QueueAtCapacity();
}
_queueWithdrawalRequest(msg.sender, _shareAmount);
}
}
function claim() external {
uint256 claimableAmount = allocatedBalances[msg.sender];
if (claimableAmount == 0) revert NoAllocationToClaim();
allocatedBalances[msg.sender] = 0;
IVaultManagerRepository _vaultManagerRepository =
IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
address _collateralToken = _vaultManagerRepository.getCollateralToken();
currentAllocatedBalance -= claimableAmount;
ERC20(_collateralToken).safeTransfer(msg.sender, claimableAmount);
emit WithdrawalClaimed(msg.sender, claimableAmount, block.timestamp);
}
function cancelWithdrawalRequest(uint256 _requestId) external {
WithdrawalRequest storage request = withdrawalRequests[_requestId];
if (request.requestId != _requestId || _getUserWithdrawalRequests(msg.sender).length == 0) {
revert WithdrawalRequestNotFound();
}
if (request.requester != msg.sender) revert NotRequestOwner();
if (request.allocated) revert RequestAlreadyAllocated();
if (request.canceled) revert RequestAlreadyCanceled();
IVaultManagerRepository _vaultManagerRepository =
IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
uint256 cancellationFeeFactor = _vaultManagerRepository.getCancellationFeeFactor();
uint256 cancellationFee = (request.shareAmount * cancellationFeeFactor) / PRECISION;
uint256 sharesToReturn = request.shareAmount - cancellationFee;
request.canceled = true;
address _sprToken = _vaultManagerRepository.getSPRToken();
VaultToken(_sprToken).mint(msg.sender, sharesToReturn);
if (cancellationFee > 0) {
address treasury = _getContractAddress(TREASURY_CONTRACT);
VaultToken(_sprToken).mint(treasury, cancellationFee);
}
_removeUserRequestId(msg.sender, _requestId);
emit WithdrawalCancelled(msg.sender, _requestId, sharesToReturn);
emit CancellationFeeCollected(msg.sender, _requestId, cancellationFee);
}
function processWithdrawalQueue(uint256 _maxRequests)
external
whenQueueNotPaused // NEW: Check queue is not paused
requireSPRTokenInitialized
exchangeRateSet
custodianSet
whenScopeNotPaused(WITHDRAWAL_SCOPE)
{
require(_maxRequests > 0, ZeroMaxRequests());
if (firstUnprocessedRequestId >= nextRequestId) {
revert WithdrawalQueueEmpty();
}
IVaultManagerRepository _vaultManagerRepository =
IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
address _collateralToken = _vaultManagerRepository.getCollateralToken();
uint256 requestsAllocated = 0;
uint256 totalCollateralAllocated = 0;
uint256 totalFeesCollected = 0;
uint256 totalCollateralNeeded = 0;
uint256 availableBalance = getAvailableBalance();
uint256 requestsProcessed = 0;
uint256 currentRequestId = firstUnprocessedRequestId;
while (currentRequestId < nextRequestId && requestsProcessed < _maxRequests) {
WithdrawalRequest storage request = withdrawalRequests[currentRequestId];
if (!request.canceled && !request.allocated) {
(uint256 collateralAmount, uint256 fee, uint256 netCollateral) =
calculateWithdrawal(request.shareAmount);
if (availableBalance < collateralAmount) {
break;
}
totalCollateralNeeded += collateralAmount;
totalFeesCollected += fee;
allocatedBalances[request.requester] += netCollateral;
request.allocated = true;
request.allocatedAmount = netCollateral;
emit WithdrawalAllocated(
request.requester, request.requestId, request.shareAmount, netCollateral, block.timestamp
);
requestsAllocated++;
totalCollateralAllocated += netCollateral;
availableBalance -= collateralAmount;
}
currentRequestId++;
requestsProcessed++;
}
firstUnprocessedRequestId = currentRequestId;
if (totalFeesCollected > 0) {
_collectWithdrawalFee(_collateralToken, totalFeesCollected);
}
currentAllocatedBalance += totalCollateralAllocated;
emit QueueProcessed(requestsAllocated, totalCollateralAllocated);
}
function getPendingWithdrawalCount() external view returns (uint256 count) {
return _getPendingWithdrawalCount();
}
function _getPendingWithdrawalCount() internal view returns (uint256 count) {
for (uint256 i = firstUnprocessedRequestId; i < nextRequestId; i++) {
WithdrawalRequest storage request = withdrawalRequests[i];
if (!request.allocated && !request.canceled) {
count++;
}
}
}
function getUserWithdrawalRequests(address _user) external view returns (WithdrawalRequest[] memory) {
return _getUserWithdrawalRequests(_user);
}
function _getUserWithdrawalRequests(address _user) internal view returns (WithdrawalRequest[] memory) {
uint256[] memory requestIds = userWithdrawalRequestIds[_user];
WithdrawalRequest[] memory requests = new WithdrawalRequest[](requestIds.length);
for (uint256 i = 0; i < requestIds.length; i++) {
requests[i] = withdrawalRequests[requestIds[i]];
}
return requests;
}
function getAllWithdrawalRequests() external view returns (WithdrawalRequest[] memory) {
uint256 totalRequests = nextRequestId - firstUnprocessedRequestId;
WithdrawalRequest[] memory requests = new WithdrawalRequest[](totalRequests);
uint256 index = 0;
for (uint256 i = firstUnprocessedRequestId; i < nextRequestId; i++) {
requests[index] = withdrawalRequests[i];
index++;
}
return requests;
}
function getExchangeRate() public view returns (uint256 rate, uint256 lastUpdated) {
IVaultManagerRepository repo = IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
return repo.getExchangeRate();
}
function calculateDeposit(uint256 depositAmount)
public
view
returns (uint256 shareAmount, uint256 fee, uint256 netShares)
{
IVaultManagerRepository repo = IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
uint256 depositFeeFactor = repo.getDepositFeeFactor();
fee = (depositAmount * depositFeeFactor) / PRECISION;
uint256 netDeposit = depositAmount - fee;
(uint256 currentExchangeRate,) = getExchangeRate();
shareAmount = ((netDeposit * PRECISION) / currentExchangeRate) * 1e12; // Scale up from 6 to 18 decimals
netShares = shareAmount;
}
function calculateWithdrawal(uint256 _shareAmount)
public
view
returns (uint256 collateralAmount, uint256 fee, uint256 netCollateral)
{
IVaultManagerRepository _vaultManagerRepository =
IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
(uint256 exchangeRate,) = _vaultManagerRepository.getExchangeRate();
if (exchangeRate == 0) revert ExchangeRateNotSet();
uint256 _withdrawalFeeFactor = _vaultManagerRepository.getWithdrawalFeeFactor();
uint256 totalCollateral = ((_shareAmount * exchangeRate) / PRECISION) / 1e12;
fee = (totalCollateral * _withdrawalFeeFactor) / PRECISION;
netCollateral = totalCollateral - fee;
collateralAmount = totalCollateral;
}
function getAvailableBalance() public view returns (uint256 unallocatedBalance) {
address _collateralToken =
IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT)).getCollateralToken();
uint256 balance = ERC20(_collateralToken).balanceOf(address(this));
if (balance > currentAllocatedBalance) {
unallocatedBalance = balance - currentAllocatedBalance;
} else {
unallocatedBalance = 0;
}
}
function getClaimableBalance(address _user) external view returns (uint256 amount) {
return allocatedBalances[_user];
}
function _queueWithdrawalRequest(address _requester, uint256 _shareAmount) private {
uint256 requestId = nextRequestId;
withdrawalRequests[requestId] = WithdrawalRequest({
requester: _requester,
shareAmount: _shareAmount,
requestTimestamp: block.timestamp,
requestId: requestId,
allocated: false,
allocatedAmount: 0,
canceled: false
});
userWithdrawalRequestIds[_requester].push(requestId);
emit WithdrawalQueued(_requester, requestId, _shareAmount, block.timestamp);
nextRequestId++;
}
function _removeUserRequestId(address _user, uint256 _requestId) private {
uint256[] storage requestIds = userWithdrawalRequestIds[_user];
for (uint256 i = 0; i < requestIds.length; i++) {
if (requestIds[i] == _requestId) {
requestIds[i] = requestIds[requestIds.length - 1];
requestIds.pop();
break;
}
}
}
function getMinimumDepositAmount() external view returns (uint256 minimumDeposit) {
IVaultManagerRepository _vaultManagerRepository =
IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
uint256 minimumNetDeposit = _vaultManagerRepository.getMinimumDepositAmount();
uint256 depositFeeFactor = _vaultManagerRepository.getDepositFeeFactor();
minimumDeposit = (minimumNetDeposit * PRECISION) / (PRECISION - depositFeeFactor);
}
function _validateDepositAmount(IVaultManagerRepository _vaultManagerRepository, uint256 _amount) private view {
uint256 depositFeeFactor = _vaultManagerRepository.getDepositFeeFactor();
uint256 fee = (_amount * depositFeeFactor) / PRECISION;
uint256 netDeposit = _amount - fee;
uint256 minimumDepositAmount = _vaultManagerRepository.getMinimumDepositAmount();
require(netDeposit >= minimumDepositAmount, "Net deposit amount is less than minimum");
}
function _collectDepositFee(address _collateralToken, uint256 _depositFee) private {
if (_depositFee == 0) return;
address _treasury = _getContractAddress(TREASURY_CONTRACT);
ERC20(_collateralToken).safeTransferFrom(msg.sender, _treasury, _depositFee);
}
function _validateWithdrawalAmount(IVaultManagerRepository _vaultManagerRepository, uint256 _amount) private view {
uint256 minimumWithdrawalAmount = _vaultManagerRepository.getMinimumWithdrawalAmount();
require(_amount >= minimumWithdrawalAmount, "Withdrawal amount is less than minimum");
}
function _collectWithdrawalFee(address _collateralToken, uint256 _withdrawalFee) private {
if (_withdrawalFee == 0) return;
address _treasury = _getContractAddress(TREASURY_CONTRACT);
ERC20(_collateralToken).safeTransfer(_treasury, _withdrawalFee);
}
function getCustodian() external view returns (address) {
IVaultManagerRepository repo = IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
return repo.getCustodian();
}
function getSPRToken() external view returns (address) {
IVaultManagerRepository repo = IVaultManagerRepository(_getContractAddress(VAULT_MANAGER_REPO_CONTRACT));
return repo.getSPRToken();
}
function setQueuePaused(bool _paused) external onlySystem {
queuePaused = _paused;
if (_paused) {
emit QueuePaused(msg.sender, block.timestamp);
} else {
emit QueueUnpaused(msg.sender, block.timestamp);
}
}
function isQueuePaused() external view returns (bool) {
return queuePaused;
}
function emergencyWithdraw(address token, address recipient) external onlyRole(EMERGENCY_ROLE) {
require(recipient != address(0), "Invalid recipient");
uint256 balance = ERC20(token).balanceOf(address(this));
require(balance > 0, "No balance to withdraw");
ERC20(token).safeTransfer(recipient, balance);
emit EmergencyWithdraw(token, recipient, balance);
}
}
ERC20.sol 305 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "./IERC20.sol";
import {IERC20Metadata} from "./extensions/IERC20Metadata.sol";
import {Context} from "../../utils/Context.sol";
import {IERC20Errors} from "../../interfaces/draft-IERC6093.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC-20
* applications.
*/
abstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {
mapping(address account => uint256) private _balances;
mapping(address account => mapping(address spender => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* Both values are immutable: they can only be set once during construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return 18;
}
/// @inheritdoc IERC20
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/// @inheritdoc IERC20
function balanceOf(address account) public view virtual returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `value`.
*/
function transfer(address to, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_transfer(owner, to, value);
return true;
}
/// @inheritdoc IERC20
function allowance(address owner, address spender) public view virtual returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `value` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Skips emitting an {Approval} event indicating an allowance update. This is not
* required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `value`.
* - the caller must have allowance for ``from``'s tokens of at least
* `value`.
*/
function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, value);
_transfer(from, to, value);
return true;
}
/**
* @dev Moves a `value` amount of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _transfer(address from, address to, uint256 value) internal {
if (from == address(0)) {
revert ERC20InvalidSender(address(0));
}
if (to == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(from, to, value);
}
/**
* @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`
* (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding
* this function.
*
* Emits a {Transfer} event.
*/
function _update(address from, address to, uint256 value) internal virtual {
if (from == address(0)) {
// Overflow check required: The rest of the code assumes that totalSupply never overflows
_totalSupply += value;
} else {
uint256 fromBalance = _balances[from];
if (fromBalance < value) {
revert ERC20InsufficientBalance(from, fromBalance, value);
}
unchecked {
// Overflow not possible: value <= fromBalance <= totalSupply.
_balances[from] = fromBalance - value;
}
}
if (to == address(0)) {
unchecked {
// Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.
_totalSupply -= value;
}
} else {
unchecked {
// Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.
_balances[to] += value;
}
}
emit Transfer(from, to, value);
}
/**
* @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).
* Relies on the `_update` mechanism
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead.
*/
function _mint(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidReceiver(address(0));
}
_update(address(0), account, value);
}
/**
* @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.
* Relies on the `_update` mechanism.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* NOTE: This function is not virtual, {_update} should be overridden instead
*/
function _burn(address account, uint256 value) internal {
if (account == address(0)) {
revert ERC20InvalidSender(address(0));
}
_update(account, address(0), value);
}
/**
* @dev Sets `value` as the allowance of `spender` over the `owner`'s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*
* Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.
*/
function _approve(address owner, address spender, uint256 value) internal {
_approve(owner, spender, value, true);
}
/**
* @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.
*
* By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by
* `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any
* `Approval` event during `transferFrom` operations.
*
* Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to
* true using the following override:
*
* ```solidity
* function _approve(address owner, address spender, uint256 value, bool) internal virtual override {
* super._approve(owner, spender, value, true);
* }
* ```
*
* Requirements are the same as {_approve}.
*/
function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {
if (owner == address(0)) {
revert ERC20InvalidApprover(address(0));
}
if (spender == address(0)) {
revert ERC20InvalidSpender(address(0));
}
_allowances[owner][spender] = value;
if (emitEvent) {
emit Approval(owner, spender, value);
}
}
/**
* @dev Updates `owner`'s allowance for `spender` based on spent `value`.
*
* Does not update the allowance value in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Does not emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 value) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance < type(uint256).max) {
if (currentAllowance < value) {
revert ERC20InsufficientAllowance(spender, currentAllowance, value);
}
unchecked {
_approve(owner, spender, currentAllowance - value, false);
}
}
}
}
SafeERC20.sol 212 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC1363} from "../../../interfaces/IERC1363.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC-20 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 SafeERC20 {
/**
* @dev An operation with an ERC-20 token failed.
*/
error SafeERC20FailedOperation(address token);
/**
* @dev Indicates a failed `decreaseAllowance` request.
*/
error SafeERC20FailedDecreaseAllowance(address spender, uint256 currentAllowance, uint256 requestedDecrease);
/**
* @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(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transfer, (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(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeCall(token.transferFrom, (from, to, value)));
}
/**
* @dev Variant of {safeTransfer} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransfer(IERC20 token, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transfer, (to, value)));
}
/**
* @dev Variant of {safeTransferFrom} that returns a bool instead of reverting if the operation is not successful.
*/
function trySafeTransferFrom(IERC20 token, address from, address to, uint256 value) internal returns (bool) {
return _callOptionalReturnBool(token, abi.encodeCall(token.transferFrom, (from, to, 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.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
forceApprove(token, spender, oldAllowance + value);
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `requestedDecrease`. If `token` returns no
* value, non-reverting calls are assumed to be successful.
*
* IMPORTANT: If the token implements ERC-7674 (ERC-20 with temporary allowance), and if the "client"
* smart contract uses ERC-7674 to set temporary allowances, then the "client" smart contract should avoid using
* this function. Performing a {safeIncreaseAllowance} or {safeDecreaseAllowance} operation on a token contract
* that has a non-zero temporary allowance (for that particular owner-spender) will result in unexpected behavior.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 requestedDecrease) internal {
unchecked {
uint256 currentAllowance = token.allowance(address(this), spender);
if (currentAllowance < requestedDecrease) {
revert SafeERC20FailedDecreaseAllowance(spender, currentAllowance, requestedDecrease);
}
forceApprove(token, spender, currentAllowance - requestedDecrease);
}
}
/**
* @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.
*
* NOTE: If the token implements ERC-7674, this function will not modify any temporary allowance. This function
* only sets the "standard" allowance. Any temporary allowance will remain active, in addition to the value being
* set here.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeCall(token.approve, (spender, value));
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeCall(token.approve, (spender, 0)));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Performs an {ERC1363} transferAndCall, with a fallback to the simple {ERC20} transfer if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
safeTransfer(token, to, value);
} else if (!token.transferAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} transferFromAndCall, with a fallback to the simple {ERC20} transferFrom if the target
* has no code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* Reverts if the returned value is other than `true`.
*/
function transferFromAndCallRelaxed(
IERC1363 token,
address from,
address to,
uint256 value,
bytes memory data
) internal {
if (to.code.length == 0) {
safeTransferFrom(token, from, to, value);
} else if (!token.transferFromAndCall(from, to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @dev Performs an {ERC1363} approveAndCall, with a fallback to the simple {ERC20} approve if the target has no
* code. This can be used to implement an {ERC721}-like safe transfer that rely on {ERC1363} checks when
* targeting contracts.
*
* NOTE: When the recipient address (`to`) has no code (i.e. is an EOA), this function behaves as {forceApprove}.
* Opposedly, when the recipient address (`to`) has code, this function only attempts to call {ERC1363-approveAndCall}
* once without retrying, and relies on the returned value to be true.
*
* Reverts if the returned value is other than `true`.
*/
function approveAndCallRelaxed(IERC1363 token, address to, uint256 value, bytes memory data) internal {
if (to.code.length == 0) {
forceApprove(token, to, value);
} else if (!token.approveAndCall(to, value, data)) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 {_callOptionalReturnBool} that reverts if call fails to meet the requirements.
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
let success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
// bubble errors
if iszero(success) {
let ptr := mload(0x40)
returndatacopy(ptr, 0, returndatasize())
revert(ptr, returndatasize())
}
returnSize := returndatasize()
returnValue := mload(0)
}
if (returnSize == 0 ? address(token).code.length == 0 : returnValue != 1) {
revert SafeERC20FailedOperation(address(token));
}
}
/**
* @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 silently catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
bool success;
uint256 returnSize;
uint256 returnValue;
assembly ("memory-safe") {
success := call(gas(), token, 0, add(data, 0x20), mload(data), 0, 0x20)
returnSize := returndatasize()
returnValue := mload(0)
}
return success && (returnSize == 0 ? address(token).code.length > 0 : returnValue == 1);
}
}
Math.sol 749 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.3.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
import {Panic} from "../Panic.sol";
import {SafeCast} from "./SafeCast.sol";
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Return the 512-bit addition of two uint256.
*
* The result is stored in two 256 variables such that sum = high * 2²⁵⁶ + low.
*/
function add512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
assembly ("memory-safe") {
low := add(a, b)
high := lt(low, a)
}
}
/**
* @dev Return the 512-bit multiplication of two uint256.
*
* The result is stored in two 256 variables such that product = high * 2²⁵⁶ + low.
*/
function mul512(uint256 a, uint256 b) internal pure returns (uint256 high, uint256 low) {
// 512-bit multiply [high low] = x * y. Compute the product mod 2²⁵⁶ and mod 2²⁵⁶ - 1, then use
// the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = high * 2²⁵⁶ + low.
assembly ("memory-safe") {
let mm := mulmod(a, b, not(0))
low := mul(a, b)
high := sub(sub(mm, low), lt(mm, low))
}
}
/**
* @dev Returns the addition of two unsigned integers, with a success flag (no overflow).
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a + b;
success = c >= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with a success flag (no overflow).
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a - b;
success = c <= a;
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with a success flag (no overflow).
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
uint256 c = a * b;
assembly ("memory-safe") {
// Only true when the multiplication doesn't overflow
// (c / a == b) || (a == 0)
success := or(eq(div(c, a), b), iszero(a))
}
// equivalent to: success ? c : 0
result = c * SafeCast.toUint(success);
}
}
/**
* @dev Returns the division of two unsigned integers, with a success flag (no division by zero).
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `DIV` opcode returns zero when the denominator is 0.
result := div(a, b)
}
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a success flag (no division by zero).
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool success, uint256 result) {
unchecked {
success = b > 0;
assembly ("memory-safe") {
// The `MOD` opcode returns zero when the denominator is 0.
result := mod(a, b)
}
}
}
/**
* @dev Unsigned saturating addition, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingAdd(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryAdd(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Unsigned saturating subtraction, bounds to zero instead of overflowing.
*/
function saturatingSub(uint256 a, uint256 b) internal pure returns (uint256) {
(, uint256 result) = trySub(a, b);
return result;
}
/**
* @dev Unsigned saturating multiplication, bounds to `2²⁵⁶ - 1` instead of overflowing.
*/
function saturatingMul(uint256 a, uint256 b) internal pure returns (uint256) {
(bool success, uint256 result) = tryMul(a, b);
return ternary(success, result, type(uint256).max);
}
/**
* @dev Branchless ternary evaluation for `a ? b : c`. Gas costs are constant.
*
* IMPORTANT: This function may reduce bytecode size and consume less gas when used standalone.
* However, the compiler may optimize Solidity ternary operations (i.e. `a ? b : c`) to only compute
* one branch when needed, making this function more expensive.
*/
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256) {
unchecked {
// branchless ternary works because:
// b ^ (a ^ b) == a
// b ^ 0 == b
return b ^ ((a ^ b) * SafeCast.toUint(condition));
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a > b, a, b);
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return ternary(a < b, a, b);
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow.
return (a & b) + (a ^ b) / 2;
}
/**
* @dev Returns the ceiling of the division of two numbers.
*
* This differs from standard division with `/` in that it rounds towards infinity instead
* of rounding towards zero.
*/
function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
if (b == 0) {
// Guarantee the same behavior as in a regular Solidity division.
Panic.panic(Panic.DIVISION_BY_ZERO);
}
// The following calculation ensures accurate ceiling division without overflow.
// Since a is non-zero, (a - 1) / b will not overflow.
// The largest possible result occurs when (a - 1) / b is type(uint256).max,
// but the largest value we can obtain is type(uint256).max - 1, which happens
// when a = type(uint256).max and b = 1.
unchecked {
return SafeCast.toUint(a > 0) * ((a - 1) / b + 1);
}
}
/**
* @dev Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
*
* Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv) with further edits by
* Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
// Handle non-overflow cases, 256 by 256 division.
if (high == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return low / denominator;
}
// Make sure the result is less than 2²⁵⁶. Also prevents denominator == 0.
if (denominator <= high) {
Panic.panic(ternary(denominator == 0, Panic.DIVISION_BY_ZERO, Panic.UNDER_OVERFLOW));
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [high low].
uint256 remainder;
assembly ("memory-safe") {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
high := sub(high, gt(remainder, low))
low := sub(low, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator.
// Always >= 1. See https://cs.stackexchange.com/q/138556/92363.
uint256 twos = denominator & (0 - denominator);
assembly ("memory-safe") {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [high low] by twos.
low := div(low, twos)
// Flip twos such that it is 2²⁵⁶ / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from high into low.
low |= high * twos;
// Invert denominator mod 2²⁵⁶. Now that denominator is an odd number, it has an inverse modulo 2²⁵⁶ such
// that denominator * inv ≡ 1 mod 2²⁵⁶. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv ≡ 1 mod 2⁴.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also
// works in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2⁸
inverse *= 2 - denominator * inverse; // inverse mod 2¹⁶
inverse *= 2 - denominator * inverse; // inverse mod 2³²
inverse *= 2 - denominator * inverse; // inverse mod 2⁶⁴
inverse *= 2 - denominator * inverse; // inverse mod 2¹²⁸
inverse *= 2 - denominator * inverse; // inverse mod 2²⁵⁶
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2²⁵⁶. Since the preconditions guarantee that the outcome is
// less than 2²⁵⁶, this is the final result. We don't need to compute the high bits of the result and high
// is no longer required.
result = low * inverse;
return result;
}
}
/**
* @dev Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
return mulDiv(x, y, denominator) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0);
}
/**
* @dev Calculates floor(x * y >> n) with full precision. Throws if result overflows a uint256.
*/
function mulShr(uint256 x, uint256 y, uint8 n) internal pure returns (uint256 result) {
unchecked {
(uint256 high, uint256 low) = mul512(x, y);
if (high >= 1 << n) {
Panic.panic(Panic.UNDER_OVERFLOW);
}
return (high << (256 - n)) | (low >> n);
}
}
/**
* @dev Calculates x * y >> n with full precision, following the selected rounding direction.
*/
function mulShr(uint256 x, uint256 y, uint8 n, Rounding rounding) internal pure returns (uint256) {
return mulShr(x, y, n) + SafeCast.toUint(unsignedRoundsUp(rounding) && mulmod(x, y, 1 << n) > 0);
}
/**
* @dev Calculate the modular multiplicative inverse of a number in Z/nZ.
*
* If n is a prime, then Z/nZ is a field. In that case all elements are inversible, except 0.
* If n is not a prime, then Z/nZ is not a field, and some elements might not be inversible.
*
* If the input value is not inversible, 0 is returned.
*
* NOTE: If you know for sure that n is (big) a prime, it may be cheaper to use Fermat's little theorem and get the
* inverse using `Math.modExp(a, n - 2, n)`. See {invModPrime}.
*/
function invMod(uint256 a, uint256 n) internal pure returns (uint256) {
unchecked {
if (n == 0) return 0;
// The inverse modulo is calculated using the Extended Euclidean Algorithm (iterative version)
// Used to compute integers x and y such that: ax + ny = gcd(a, n).
// When the gcd is 1, then the inverse of a modulo n exists and it's x.
// ax + ny = 1
// ax = 1 + (-y)n
// ax ≡ 1 (mod n) # x is the inverse of a modulo n
// If the remainder is 0 the gcd is n right away.
uint256 remainder = a % n;
uint256 gcd = n;
// Therefore the initial coefficients are:
// ax + ny = gcd(a, n) = n
// 0a + 1n = n
int256 x = 0;
int256 y = 1;
while (remainder != 0) {
uint256 quotient = gcd / remainder;
(gcd, remainder) = (
// The old remainder is the next gcd to try.
remainder,
// Compute the next remainder.
// Can't overflow given that (a % gcd) * (gcd // (a % gcd)) <= gcd
// where gcd is at most n (capped to type(uint256).max)
gcd - remainder * quotient
);
(x, y) = (
// Increment the coefficient of a.
y,
// Decrement the coefficient of n.
// Can overflow, but the result is casted to uint256 so that the
// next value of y is "wrapped around" to a value between 0 and n - 1.
x - y * int256(quotient)
);
}
if (gcd != 1) return 0; // No inverse exists.
return ternary(x < 0, n - uint256(-x), uint256(x)); // Wrap the result if it's negative.
}
}
/**
* @dev Variant of {invMod}. More efficient, but only works if `p` is known to be a prime greater than `2`.
*
* From https://en.wikipedia.org/wiki/Fermat%27s_little_theorem[Fermat's little theorem], we know that if p is
* prime, then `a**(p-1) ≡ 1 mod p`. As a consequence, we have `a * a**(p-2) ≡ 1 mod p`, which means that
* `a**(p-2)` is the modular multiplicative inverse of a in Fp.
*
* NOTE: this function does NOT check that `p` is a prime greater than `2`.
*/
function invModPrime(uint256 a, uint256 p) internal view returns (uint256) {
unchecked {
return Math.modExp(a, p - 2, p);
}
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m)
*
* Requirements:
* - modulus can't be zero
* - underlying staticcall to precompile must succeed
*
* IMPORTANT: The result is only valid if the underlying call succeeds. When using this function, make
* sure the chain you're using it on supports the precompiled contract for modular exponentiation
* at address 0x05 as specified in https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise,
* the underlying function will succeed given the lack of a revert, but the result may be incorrectly
* interpreted as 0.
*/
function modExp(uint256 b, uint256 e, uint256 m) internal view returns (uint256) {
(bool success, uint256 result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Returns the modular exponentiation of the specified base, exponent and modulus (b ** e % m).
* It includes a success flag indicating if the operation succeeded. Operation will be marked as failed if trying
* to operate modulo 0 or if the underlying precompile reverted.
*
* IMPORTANT: The result is only valid if the success flag is true. When using this function, make sure the chain
* you're using it on supports the precompiled contract for modular exponentiation at address 0x05 as specified in
* https://eips.ethereum.org/EIPS/eip-198[EIP-198]. Otherwise, the underlying function will succeed given the lack
* of a revert, but the result may be incorrectly interpreted as 0.
*/
function tryModExp(uint256 b, uint256 e, uint256 m) internal view returns (bool success, uint256 result) {
if (m == 0) return (false, 0);
assembly ("memory-safe") {
let ptr := mload(0x40)
// | Offset | Content | Content (Hex) |
// |-----------|------------|--------------------------------------------------------------------|
// | 0x00:0x1f | size of b | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x20:0x3f | size of e | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x40:0x5f | size of m | 0x0000000000000000000000000000000000000000000000000000000000000020 |
// | 0x60:0x7f | value of b | 0x<.............................................................b> |
// | 0x80:0x9f | value of e | 0x<.............................................................e> |
// | 0xa0:0xbf | value of m | 0x<.............................................................m> |
mstore(ptr, 0x20)
mstore(add(ptr, 0x20), 0x20)
mstore(add(ptr, 0x40), 0x20)
mstore(add(ptr, 0x60), b)
mstore(add(ptr, 0x80), e)
mstore(add(ptr, 0xa0), m)
// Given the result < m, it's guaranteed to fit in 32 bytes,
// so we can use the memory scratch space located at offset 0.
success := staticcall(gas(), 0x05, ptr, 0xc0, 0x00, 0x20)
result := mload(0x00)
}
}
/**
* @dev Variant of {modExp} that supports inputs of arbitrary length.
*/
function modExp(bytes memory b, bytes memory e, bytes memory m) internal view returns (bytes memory) {
(bool success, bytes memory result) = tryModExp(b, e, m);
if (!success) {
Panic.panic(Panic.DIVISION_BY_ZERO);
}
return result;
}
/**
* @dev Variant of {tryModExp} that supports inputs of arbitrary length.
*/
function tryModExp(
bytes memory b,
bytes memory e,
bytes memory m
) internal view returns (bool success, bytes memory result) {
if (_zeroBytes(m)) return (false, new bytes(0));
uint256 mLen = m.length;
// Encode call args in result and move the free memory pointer
result = abi.encodePacked(b.length, e.length, mLen, b, e, m);
assembly ("memory-safe") {
let dataPtr := add(result, 0x20)
// Write result on top of args to avoid allocating extra memory.
success := staticcall(gas(), 0x05, dataPtr, mload(result), dataPtr, mLen)
// Overwrite the length.
// result.length > returndatasize() is guaranteed because returndatasize() == m.length
mstore(result, mLen)
// Set the memory pointer after the returned data.
mstore(0x40, add(dataPtr, mLen))
}
}
/**
* @dev Returns whether the provided byte array is zero.
*/
function _zeroBytes(bytes memory byteArray) private pure returns (bool) {
for (uint256 i = 0; i < byteArray.length; ++i) {
if (byteArray[i] != 0) {
return false;
}
}
return true;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* This method is based on Newton's method for computing square roots; the algorithm is restricted to only
* using integer operations.
*/
function sqrt(uint256 a) internal pure returns (uint256) {
unchecked {
// Take care of easy edge cases when a == 0 or a == 1
if (a <= 1) {
return a;
}
// In this function, we use Newton's method to get a root of `f(x) := x² - a`. It involves building a
// sequence x_n that converges toward sqrt(a). For each iteration x_n, we also define the error between
// the current value as `ε_n = | x_n - sqrt(a) |`.
//
// For our first estimation, we consider `e` the smallest power of 2 which is bigger than the square root
// of the target. (i.e. `2**(e-1) ≤ sqrt(a) < 2**e`). We know that `e ≤ 128` because `(2¹²⁸)² = 2²⁵⁶` is
// bigger than any uint256.
//
// By noticing that
// `2**(e-1) ≤ sqrt(a) < 2**e → (2**(e-1))² ≤ a < (2**e)² → 2**(2*e-2) ≤ a < 2**(2*e)`
// we can deduce that `e - 1` is `log2(a) / 2`. We can thus compute `x_n = 2**(e-1)` using a method similar
// to the msb function.
uint256 aa = a;
uint256 xn = 1;
if (aa >= (1 << 128)) {
aa >>= 128;
xn <<= 64;
}
if (aa >= (1 << 64)) {
aa >>= 64;
xn <<= 32;
}
if (aa >= (1 << 32)) {
aa >>= 32;
xn <<= 16;
}
if (aa >= (1 << 16)) {
aa >>= 16;
xn <<= 8;
}
if (aa >= (1 << 8)) {
aa >>= 8;
xn <<= 4;
}
if (aa >= (1 << 4)) {
aa >>= 4;
xn <<= 2;
}
if (aa >= (1 << 2)) {
xn <<= 1;
}
// We now have x_n such that `x_n = 2**(e-1) ≤ sqrt(a) < 2**e = 2 * x_n`. This implies ε_n ≤ 2**(e-1).
//
// We can refine our estimation by noticing that the middle of that interval minimizes the error.
// If we move x_n to equal 2**(e-1) + 2**(e-2), then we reduce the error to ε_n ≤ 2**(e-2).
// This is going to be our x_0 (and ε_0)
xn = (3 * xn) >> 1; // ε_0 := | x_0 - sqrt(a) | ≤ 2**(e-2)
// From here, Newton's method give us:
// x_{n+1} = (x_n + a / x_n) / 2
//
// One should note that:
// x_{n+1}² - a = ((x_n + a / x_n) / 2)² - a
// = ((x_n² + a) / (2 * x_n))² - a
// = (x_n⁴ + 2 * a * x_n² + a²) / (4 * x_n²) - a
// = (x_n⁴ + 2 * a * x_n² + a² - 4 * a * x_n²) / (4 * x_n²)
// = (x_n⁴ - 2 * a * x_n² + a²) / (4 * x_n²)
// = (x_n² - a)² / (2 * x_n)²
// = ((x_n² - a) / (2 * x_n))²
// ≥ 0
// Which proves that for all n ≥ 1, sqrt(a) ≤ x_n
//
// This gives us the proof of quadratic convergence of the sequence:
// ε_{n+1} = | x_{n+1} - sqrt(a) |
// = | (x_n + a / x_n) / 2 - sqrt(a) |
// = | (x_n² + a - 2*x_n*sqrt(a)) / (2 * x_n) |
// = | (x_n - sqrt(a))² / (2 * x_n) |
// = | ε_n² / (2 * x_n) |
// = ε_n² / | (2 * x_n) |
//
// For the first iteration, we have a special case where x_0 is known:
// ε_1 = ε_0² / | (2 * x_0) |
// ≤ (2**(e-2))² / (2 * (2**(e-1) + 2**(e-2)))
// ≤ 2**(2*e-4) / (3 * 2**(e-1))
// ≤ 2**(e-3) / 3
// ≤ 2**(e-3-log2(3))
// ≤ 2**(e-4.5)
//
// For the following iterations, we use the fact that, 2**(e-1) ≤ sqrt(a) ≤ x_n:
// ε_{n+1} = ε_n² / | (2 * x_n) |
// ≤ (2**(e-k))² / (2 * 2**(e-1))
// ≤ 2**(2*e-2*k) / 2**e
// ≤ 2**(e-2*k)
xn = (xn + a / xn) >> 1; // ε_1 := | x_1 - sqrt(a) | ≤ 2**(e-4.5) -- special case, see above
xn = (xn + a / xn) >> 1; // ε_2 := | x_2 - sqrt(a) | ≤ 2**(e-9) -- general case with k = 4.5
xn = (xn + a / xn) >> 1; // ε_3 := | x_3 - sqrt(a) | ≤ 2**(e-18) -- general case with k = 9
xn = (xn + a / xn) >> 1; // ε_4 := | x_4 - sqrt(a) | ≤ 2**(e-36) -- general case with k = 18
xn = (xn + a / xn) >> 1; // ε_5 := | x_5 - sqrt(a) | ≤ 2**(e-72) -- general case with k = 36
xn = (xn + a / xn) >> 1; // ε_6 := | x_6 - sqrt(a) | ≤ 2**(e-144) -- general case with k = 72
// Because e ≤ 128 (as discussed during the first estimation phase), we know have reached a precision
// ε_6 ≤ 2**(e-144) < 1. Given we're operating on integers, then we can ensure that xn is now either
// sqrt(a) or sqrt(a) + 1.
return xn - SafeCast.toUint(xn > a / xn);
}
}
/**
* @dev Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && result * result < a);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// If upper 8 bits of 16-bit half set, add 8 to result
r |= SafeCast.toUint((x >> r) > 0xff) << 3;
// If upper 4 bits of 8-bit half set, add 4 to result
r |= SafeCast.toUint((x >> r) > 0xf) << 2;
// Shifts value right by the current result and use it as an index into this lookup table:
//
// | x (4 bits) | index | table[index] = MSB position |
// |------------|---------|-----------------------------|
// | 0000 | 0 | table[0] = 0 |
// | 0001 | 1 | table[1] = 0 |
// | 0010 | 2 | table[2] = 1 |
// | 0011 | 3 | table[3] = 1 |
// | 0100 | 4 | table[4] = 2 |
// | 0101 | 5 | table[5] = 2 |
// | 0110 | 6 | table[6] = 2 |
// | 0111 | 7 | table[7] = 2 |
// | 1000 | 8 | table[8] = 3 |
// | 1001 | 9 | table[9] = 3 |
// | 1010 | 10 | table[10] = 3 |
// | 1011 | 11 | table[11] = 3 |
// | 1100 | 12 | table[12] = 3 |
// | 1101 | 13 | table[13] = 3 |
// | 1110 | 14 | table[14] = 3 |
// | 1111 | 15 | table[15] = 3 |
//
// The lookup table is represented as a 32-byte value with the MSB positions for 0-15 in the last 16 bytes.
assembly ("memory-safe") {
r := or(r, byte(shr(r, x), 0x0000010102020202030303030303030300000000000000000000000000000000))
}
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << result < value);
}
}
/**
* @dev Return the log in base 10 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 10 ** result < value);
}
}
/**
* @dev Return the log in base 256 of a positive value rounded towards zero.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 x) internal pure returns (uint256 r) {
// If value has upper 128 bits set, log2 result is at least 128
r = SafeCast.toUint(x > 0xffffffffffffffffffffffffffffffff) << 7;
// If upper 64 bits of 128-bit half set, add 64 to result
r |= SafeCast.toUint((x >> r) > 0xffffffffffffffff) << 6;
// If upper 32 bits of 64-bit half set, add 32 to result
r |= SafeCast.toUint((x >> r) > 0xffffffff) << 5;
// If upper 16 bits of 32-bit half set, add 16 to result
r |= SafeCast.toUint((x >> r) > 0xffff) << 4;
// Add 1 if upper 8 bits of 16-bit half set, and divide accumulated result by 8
return (r >> 3) | SafeCast.toUint((x >> r) > 0xff);
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + SafeCast.toUint(unsignedRoundsUp(rounding) && 1 << (result << 3) < value);
}
}
/**
* @dev Returns whether a provided rounding mode is considered rounding up for unsigned integers.
*/
function unsignedRoundsUp(Rounding rounding) internal pure returns (bool) {
return uint8(rounding) % 2 == 1;
}
}
BaseContract.sol 30 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {SecureAccess} from "../access-management/SecureAccess.sol";
import {DataReader} from "../data/DataReader.sol";
import {BeaconWatcher} from "../beacon/BeaconWatcher.sol";
import {Pausable} from "../pausable/Pausable.sol";
/**
* @title BaseContract
* @dev This contract serves as the base contract for other contracts in the system.
* It inherits from the SecureAccess and DataReader contracts and provides a constructor
* to initialize the access manager and data store address.
*/
abstract contract BaseContract is
SecureAccess,
DataReader,
BeaconWatcher,
Pausable
{
constructor(
address _beaconAddress
)
BeaconWatcher(_beaconAddress)
SecureAccess(SecureAccess(_beaconAddress).getAccessManager())
DataReader(DataReader(_beaconAddress).getDataStore())
Pausable(Pausable(_beaconAddress).getPauser())
{}
}
MathConstants.sol 12 lines
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.26; uint256 constant BASIS_POINTS_DIVISOR = 10000; uint256 constant MIN_FEE_PRECISION = 100000; uint256 constant CONTRACTS_PRECISION = 100; uint256 constant HIGH_PRECISION = 10 ** 27; uint256 constant PRECISION = 10 ** 18; uint256 constant MID_PRECISION = 10 ** 9; uint256 constant ONE_HOUR = 3600;
VaultToken.sol 23 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
import {SecureAccess} from "common-contracts/access-management/SecureAccess.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
contract VaultToken is ERC20, SecureAccess {
//reward trackers array
constructor(address _accessManager, string memory _name, string memory _symbol)
SecureAccess(_accessManager)
ERC20(_name, _symbol)
{}
function mint(address _to, uint256 _value) external onlySystem {
_mint(_to, _value);
}
function burn(address _from, uint256 _value) external onlySystem {
_burn(_from, _value);
}
}
Contracts.sol 28 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.26;
// SPREADS Contracts
bytes32 constant SPREADS_VAULT_MANAGER_REPO_CONTRACT = keccak256("SPREADS_VAULT_MANAGER_REPO");
bytes32 constant SPREADS_VAULT_CALCULATOR_CONTRACT = keccak256("SPREADS_VAULT_CALCULATOR");
bytes32 constant SPREADS_VAULT_CONTRACT = keccak256("SPREADS_VAULT");
bytes32 constant SPREADS_VAULT_MANAGER_CONTRACT = keccak256("SPREADS_VAULT_MANAGER");
bytes32 constant STRATEGY_MANAGER = keccak256("STRATEGY_MANAGER");
bytes32 constant STRATEGY_MANAGER_REPO_CONTRACT = keccak256("STRATEGY_MANAGER_REPOSITORY");
bytes32 constant DERIVE_STRATEGY_REPO_CONTRACT = keccak256("DERIVE_STRATEGY_REPOSITORY");
bytes32 constant DERIVE_MULTISIG_CONTRACT = keccak256("DERIVE_MULTISIG");
bytes32 constant DERIVE_BRIDGE_REPO_CONTRACT = keccak256("DERIVE_BRIDGE_REPOSITORY");
bytes32 constant DERIVE_BRIDGE_CONTRACT = keccak256("DERIVE_BRIDGE");
// Additional contract constants for SPRVault
bytes32 constant VAULT_MANAGER_REPO_CONTRACT = keccak256("VAULT_MANAGER_REPO");
bytes32 constant SWAPPER_CONTRACT = keccak256("SWAPPER");
bytes32 constant TREASURY_CONTRACT = keccak256("TREASURY");
bytes32 constant STAKER_CONTRACT = keccak256("STAKER");
bytes32 constant WATERFALL_ACCOUNTING_CONTRACT = keccak256("WATERFALL_ACCOUNTING");
// Vault contracts
bytes32 constant YIELD_VAULT_CONTRACT = keccak256("YIELD_VAULT");
bytes32 constant AIRDROP_VAULT_CONTRACT = keccak256("AIRDROP_VAULT");
bytes32 constant SPR_VAULT_CONTRACT = keccak256("SPR_VAULT");
bytes32 constant VAULT_MANAGER_V2_CONTRACT = keccak256("VAULT_MANAGER_V2");
Scopes.sol 8 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
bytes32 constant DEPOSIT_SCOPE = keccak256("DEPOSIT");
bytes32 constant WITHDRAWAL_SCOPE = keccak256("WITHDRAWAL");
bytes32 constant LOCK_SCOPE = keccak256("LOCK");
bytes32 constant UNLOCK_SCOPE = keccak256("UNLOCK");
ISPRVault.sol 135 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
import {WithdrawalRequest} from "@src/spreads-vault/structs/WithdrawalRequest.sol";
interface ISPRVault {
/**
* @dev Deposit collateral and receive shares based on the current exchange rate.
* @param _amount The amount of collateral to deposit.
* Emits a {DepositV2} event.
*/
function deposit(uint256 _amount) external;
/**
* @dev Withdraw shares for collateral based on the current exchange rate.
* If vault has sufficient balance, immediate withdrawal occurs.
* Otherwise, a withdrawal request is queued for later allocation.
* @param _shareAmount The amount of shares to withdraw.
* Emits either {WithdrawV2} or {WithdrawalQueued} event.
*/
function withdraw(uint256 _shareAmount) external;
/**
* @dev Claim allocated collateral from processed withdrawal requests.
* Emits a {WithdrawalClaimed} event.
*/
function claim() external;
/**
* @dev Cancel a pending withdrawal request.
* @param _requestId The ID of the withdrawal request to cancel.
* Emits a {WithdrawalCancelled} event.
*/
function cancelWithdrawalRequest(uint256 _requestId) external;
/**
* @dev Process pending withdrawal requests in the queue.
* Allocates collateral to as many requests as possible with available vault balance.
* Users must then call claim() to receive their allocated funds.
* Emits {WithdrawalAllocated} events for each processed request.
* Emits a {QueueProcessed} event at the end.
*/
function processWithdrawalQueue(uint256 _maxRequests) external;
/**
* @dev Get pending withdrawal requests for a specific user.
* @param _user The address of the user.
* @return Array of withdrawal requests for the user.
*/
function getUserWithdrawalRequests(address _user) external view returns (WithdrawalRequest[] memory);
/**
* @dev Get all pending withdrawal requests in the queue.
* @return Array of all withdrawal requests.
*/
function getAllWithdrawalRequests() external view returns (WithdrawalRequest[] memory);
/**
* @dev Get the current exchange rate.
* @return rate The current exchange rate.
* @return lastUpdated Timestamp of last update.
*/
function getExchangeRate() external view returns (uint256 rate, uint256 lastUpdated);
/**
* @dev Calculate shares to mint for a given collateral amount.
* @param _collateralAmount The amount of collateral.
* @return shareAmount The amount of shares to mint (before fees).
* @return fee The deposit fee amount.
* @return netShares The net shares after fees.
*/
function calculateDeposit(uint256 _collateralAmount)
external
view
returns (uint256 shareAmount, uint256 fee, uint256 netShares);
/**
* @dev Calculate collateral to return for a given share amount.
* @param _shareAmount The amount of shares.
* @return collateralAmount The amount of collateral (before fees).
* @return fee The withdrawal fee amount.
* @return netCollateral The net collateral after fees.
*/
function calculateWithdrawal(uint256 _shareAmount)
external
view
returns (uint256 collateralAmount, uint256 fee, uint256 netCollateral);
/**
* @dev Get the available collateral balance in the vault.
* @return balance The available collateral balance.
*/
function getAvailableBalance() external view returns (uint256 balance);
/**
* @dev Get the total number of pending withdrawal requests.
* @return count The number of pending requests.
*/
function getPendingWithdrawalCount() external view returns (uint256 count);
/**
* @dev Get the claimable collateral balance for a user.
* @param _user The address of the user.
* @return amount The claimable collateral amount.
*/
function getClaimableBalance(address _user) external view returns (uint256 amount);
/**
* @dev Get the share token address.
* @return The address of the share token contract.
*/
function getSPRToken() external view returns (address);
function getMinimumDepositAmount() external view returns (uint256 minimumDeposit);
/**
* @dev Set the queue paused state.
* @param _paused Whether to pause the queue.
*/
function setQueuePaused(bool _paused) external;
/**
* @dev Get the current queue paused state.
* @return Whether the queue is paused.
*/
function isQueuePaused() external view returns (bool);
// /**
// * @dev Transfer collateral for rebalancing purposes (WaterfallAccounting only).
// * @param _recipient The address to transfer collateral to.
// * @param _amount The amount of collateral to transfer.
// */
// function transferForRebalance(address _recipient, uint256 _amount) external;
}
IVaultManagerRepository.sol 318 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
import {ReceiptTokens} from "@src/spreads-vault/structs/ReceiptTokens.sol";
interface IVaultManagerRepository {
/**
* @dev Set the collateral token for the vault.
* @param _token The address of the collateral token.
*/
function setCollateralToken(address _token) external;
/**
* @dev Set the receipt tokens for the vault that will be minted at deposit.
* @param _tokens An array of addresses of the receipt tokens.
*/
function setReceiptTokens(ReceiptTokens[] memory _tokens) external;
/**
* @dev Set the deposit fee factor for the vault.
* @param _depositFeeFactor The deposit fee factor(PRECISION).
*/
function setDepositFeeFactor(uint256 _depositFeeFactor) external;
/**
* @dev Set the withdrawal fee factor for the vault.
* @param _withdrawalFeeFactor The withdrawal fee factor(PRECISION).
*/
function setWithdrawalFeeFactor(uint256 _withdrawalFeeFactor) external;
/**
* @dev Set the minimum deposit amount for the vault.
* @param _minimumDepositAmount The minimum deposit amount.
*/
function setMinimumDepositAmount(uint256 _minimumDepositAmount) external;
/**
* @dev Set the minimum withdrawal amount for the vault.
* @param _minimumWithdrawalAmount The minimum withdrawal amount.
*/
function setMinimumWithdrawalAmount(uint256 _minimumWithdrawalAmount) external;
/**
* @dev Set the desired token for fees for swap.
* @param _feesDesiredToken The address of the desired token for fees.
*/
function setFeesDesiredToken(address _feesDesiredToken) external;
/**
* @dev Get the collateral token for the vault.
* @return The address of the collateral token.
*/
function getCollateralToken() external view returns (address);
/**
* @dev Get the receipt tokens for the vault that will be minted at deposit.
* @return An array of addresses of the receipt tokens.
*/
function getReceiptTokens() external view returns (ReceiptTokens[] memory);
/**
* @dev Get the receipt tokens list for the vault.
* @return An array of addresses of the receipt tokens.
*/
function getReceiptTokensAddresses() external view returns (address[] memory);
/**
* @dev Get the deposit fee factor for the vault.
* @return The deposit fee factor(PRECISION).
*/
function getDepositFeeFactor() external view returns (uint256);
/**
* @dev Get the withdrawal fee factor for the vault.
* @return The withdrawal fee factor(PRECISION).
*/
function getWithdrawalFeeFactor() external view returns (uint256);
/**
* @dev Get the minimum deposit amount for the vault.
* @return The minimum deposit amount.
*/
function getMinimumDepositAmount() external view returns (uint256);
/**
* @dev Get the minimum withdrawal amount for the vault.
* @return The minimum withdrawal amount.
*/
function getMinimumWithdrawalAmount() external view returns (uint256);
/**
* @dev Get the address of the desired token for fees.
* @return The address of the desired token for fees.
*/
function getFeesDesiredToken() external view returns (address);
/**
* @dev Set the cancellation fee factor for withdrawal requests.
*/
function getCancellationFeeFactor() external view returns (uint256);
/**
* @dev Get the cancellation fee factor for withdrawal requests.
* @param _cancellationFeeFactor The cancellation fee factor (PRECISION).
*/
function setCancellationFeeFactor(uint256 _cancellationFeeFactor) external;
//****------------------- AirDropVault Parameters -------------------****//
/**
* @dev Set the maximum lock duration for the vault.
* @param _weeks The maximum lock duration in weeks.
*/
function setMaxLockDuration(uint256 _weeks) external;
/**
* @dev Set the minimum lock duration for the vault.
* @param _weeks The minimum lock duration in weeks.
*/
function setMinLockDuration(uint256 _weeks) external;
/**
* @dev Set the daily point emission for the vault.
* @param _points The daily point emission.
*/
function setDailyPointEmission(uint256 _points) external;
/**
* @dev Set the points distributor for the vault.
* @param _distributor The address of the points distributor.
*/
function setPointsDistributor(address _distributor) external;
/**
* @dev Set the minimum lock amount for the vault.
* @param _amount The minimum lock amount.
*/
function setMinimumLockAmount(uint256 _amount) external;
/**
* @dev Set the early unlock penalty rate for the vault.
* @param _rate The early unlock penalty rate.
*/
function setEarlyUnlockPenaltyRate(uint256 _rate) external;
/**
* @dev Get the maximum lock duration for the vault.
* @return The maximum lock duration in weeks.
*/
function getMaxLockDuration() external view returns (uint256);
/**
* @dev Get the minimum lock duration for the vault.
* @return The minimum lock duration in weeks.
*/
function getMinLockDuration() external view returns (uint256);
/**
* @dev Get the daily point emission for the vault.
* @return The daily point emission.
*/
function getDailyPointEmission() external view returns (uint256);
/**
* @dev Get the points distributor for the vault.
* @return The address of the points distributor.
*/
function getPointsDistributor() external view returns (address);
/**
* @dev Get the minimum lock amount for the vault.
* @return The minimum lock amount.
*/
function getMinimumLockAmount() external view returns (uint256);
/**
* @dev Get the early unlock penalty rate for the vault.
* @return The early unlock penalty rate.
*/
function getEarlyUnlockPenaltyRate() external view returns (uint256);
// ==================== SPR TOKEN ====================
/**
* @dev Set the SPR token address
* @param _sprToken The address of the SPR token
*/
function setSPRToken(address _sprToken) external;
/**
* @dev Get the SPR token address
* @return The address of the SPR token
*/
function getSPRToken() external view returns (address);
// ==================== REWARD DISTRIBUTORS ====================
/**
* @dev Set the reward distributor for FarmVault
* @param _distributor The address of the reward distributor
*/
function setFarmVaultRewardDistributor(address _distributor) external;
/**
* @dev Get the reward distributor for FarmVault
* @return The address of the reward distributor
*/
function getFarmVaultRewardDistributor() external view returns (address);
/**
* @dev Set the reward distributor for AirdropVault
* @param _distributor The address of the reward distributor
*/
function setAirdropVaultRewardDistributor(address _distributor) external;
/**
* @dev Get the reward distributor for AirdropVault
* @return The address of the reward distributor
*/
function getAirdropVaultRewardDistributor() external view returns (address);
function setCustodian(address _custodian) external;
function getCustodian() external view returns (address);
// ==================== DEPLOYMENT CONFIGURATION ====================
/// @notice Set waterfall base APR
function setWaterfallBaseAPR(uint256 _baseAPR) external;
/// @notice Get waterfall base APR
function getWaterfallBaseAPR() external view returns (uint256);
/// @notice Set waterfall cap ratio
function setWaterfallCapRatio(uint256 _capRatio) external;
/// @notice Get waterfall cap ratio
function getWaterfallCapRatio() external view returns (uint256);
/// @notice Set initial exchange rate
function setInitialExchangeRate(uint256 _rate) external;
/// @notice Get initial exchange rate
function getInitialExchangeRate() external view returns (uint256);
/// @notice Set farm vault fee rate
function setFarmVaultFeeRate(uint256 _feeRate) external;
/// @notice Get farm vault fee rate
function getFarmVaultFeeRate() external view returns (uint256);
// ==================== AIRDROP VAULT CONFIGURATION ====================
/// @notice Set maximum locks per user
function setMaxLocksPerUser(uint256 _maxLocks) external;
/// @notice Get maximum locks per user
function getMaxLocksPerUser() external view returns (uint256);
/// @notice Set minimum lock weight
function setMinLockWeight(uint256 _minWeight) external;
/// @notice Get minimum lock weight
function getMinLockWeight() external view returns (uint256);
/// @notice Set maximum lock weight
function setMaxLockWeight(uint256 _maxWeight) external;
/// @notice Get maximum lock weight
function getMaxLockWeight() external view returns (uint256);
/// @notice Set optimal lock duration
function setOptimalLockDuration(uint256 _weeks) external;
/// @notice Get optimal lock duration
function getOptimalLockDuration() external view returns (uint256);
// ==================== QUEUE CONFIGURATION ====================
/**
* @dev Set the maximum queue size for the vault.
* @param _maxQueueSize The maximum queue size.
*/
function setMaxQueueSize(uint256 _maxQueueSize) external;
/**
* @dev Get the maximum queue size for the vault.
* @return The maximum queue size.
*/
function getMaxQueueSize() external view returns (uint256);
// ==================== EXCHANGE RATE ====================
/**
* @dev Set the exchange rate for the vault.
* @param _rate The exchange rate.
* @param _timestamp The timestamp when the rate was set.
*/
function setExchangeRate(uint256 _rate, uint256 _timestamp) external;
/**
* @dev Get the exchange rate for the vault.
* @return rate The exchange rate.
* @return lastUpdated The timestamp when the rate was last updated.
*/
function getExchangeRate() external view returns (uint256 rate, uint256 lastUpdated);
// ==================== SHARE TOKEN ====================
/**
* @dev Set the share token address
* @param _shareToken The address of the share token
*/
function setShareToken(address _shareToken) external;
/**
* @dev Get the share token address
* @return The address of the share token
*/
function getShareToken() external view returns (address);
}
WithdrawalRequest.sol 13 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
struct WithdrawalRequest {
address requester;
uint256 shareAmount;
uint256 requestTimestamp;
uint256 requestId;
bool allocated;
uint256 allocatedAmount;
bool canceled; // Flag to mark the request as canceled
}
ExchangeRate.sol 9 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
struct ExchangeRate {
uint256 rate;
uint256 lastUpdated;
address updater;
}
EventsV2.sol 97 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
import {WithdrawalRequest} from "@src/spreads-vault/structs/WithdrawalRequest.sol";
import {ReceiptTokens} from "@src/spreads-vault/structs/ReceiptTokens.sol";
event ExchangeRateUpdated(uint256 indexed rate, address indexed updater, uint256 timestamp);
event Deposit(
address indexed depositor, uint256 collateralAmount, uint256 sharesMinted, uint256 exchangeRate, uint256 fee
);
event Withdraw(
address indexed withdrawer, uint256 sharesAmount, uint256 collateralReceived, uint256 exchangeRate, uint256 fee
);
event WithdrawalQueued(address indexed requester, uint256 indexed requestId, uint256 shareAmount, uint256 timestamp);
event WithdrawalAllocated(
address indexed requester,
uint256 indexed requestId,
uint256 shareAmount,
uint256 collateralAmount,
uint256 timestamp
);
event WithdrawalClaimed(address indexed requester, uint256 collateralAmount, uint256 timestamp);
event WithdrawalCancelled(address indexed requester, uint256 indexed requestId, uint256 shareAmount);
event QueueProcessed(uint256 requestsAllocated, uint256 totalCollateralAllocated);
event SPRTokenInitialized(address indexed sprToken);
event Initialized(address sprToken, address rewardDistributor);
event RewardsClaimed(address indexed user, uint256 amount);
event Staked(address indexed user, uint256 sprAmount, uint256 shares);
event Unstaked(address indexed user, uint256 shares, uint256 sprAmount);
event RewardsDistributed(address indexed distributor, uint256 totalSPRMinted);
event EmergencyPaused();
event EmergencyUnpaused();
event EmergencyWithdraw(address indexed token, address indexed recipient, uint256 amount);
event SPRTokenSet(address indexed sprToken);
event CustodianSet(address indexed custodian);
event CustodianSet(address indexed custodian, address indexed setter);
event CancellationFeeCollected(address indexed user, uint256 requestId, uint256 feeAmount);
event MaxLocksPerUserSet(uint256 maxLocks);
event MinLockWeightSet(uint256 minWeight);
event MaxLockWeightSet(uint256 maxWeight);
event OptimalLockDurationSet(uint256 weekCount);
event WaterfallBaseAPRSet(uint256 baseAPR);
event WaterfallCapRatioSet(uint256 capRatio);
event InitialExchangeRateSet(uint256 rate);
event FarmVaultFeeRateSet(uint256 feeRate);
event CancellationFeeFactorSet(uint256 cancellationFeeFactor);
event CollateralTokenSet(address indexed token);
event ReceiptTokensSet(ReceiptTokens[] tokens);
event FarmVaultRewardDistributorSet(address indexed distributor);
event AirdropVaultRewardDistributorSet(address indexed distributor);
event RequestsCleaned(uint256 requestsRemoved);
event QueuePaused(address indexed pauser, uint256 timestamp);
event QueueUnpaused(address indexed unpauser, uint256 timestamp);
event MaxQueueSizeSet(uint256 maxSize);
event ExchangeRateUpdated(address indexed updater, uint256 indexed rate, uint256 timestamp);
event CollateralRewardsConverted(uint256 amount);
ErrorsV2.sol 36 lines
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.29; error InvalidExchangeRate(); error ExchangeRateNotSet(); error WithdrawalRequestNotFound(); error InsufficientVaultBalance(); error InvalidRequestId(); error WithdrawalQueueEmpty(); error NotRequestOwner(); error ShareTokenAlreadyInitialized(); error ShareTokenNotInitialized(); error NoAllocationToClaim(); error RequestAlreadyAllocated(); error AlreadyInitialized(); error NotInitialized(); error ZeroAmount(); error InvalidDuration(); error LockNotFound(); error InsufficientAmount(); error TooManyLocks(); error InvalidLockId(); error InvalidTimestamp(); error CustodianNotSet(); error CustodianAlreadySet(); error InvalidCustodianAddress(); error RequestAlreadyCanceled(); error ZeroMaxRequests(); error QueueAtCapacity(); error QueueAlreadyPaused(); error QueueNotPaused(); error QueuePausedError(); error SPRTokenNotInitialized(); error ZeroAddress(); error FactorGtPrecision();
Roles.sol 7 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
bytes32 constant OPERATOR_ROLE = keccak256("OPERATOR");
bytes32 constant SYSTEM_ROLE = keccak256("SYSTEM");
bytes32 constant EMERGENCY_ROLE = keccak256("EMERGENCY");
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/IERC20.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-20 standard as defined in the ERC.
*/
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 value of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the value of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves a `value` amount of 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 value) 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 a `value` amount of tokens 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 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the
* allowance mechanism. `value` 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 value) external returns (bool);
}
IERC20Metadata.sol 26 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity >=0.6.2;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC-20 standard.
*/
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);
}
Context.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)
pragma solidity ^0.8.20;
/**
* @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 Context {
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;
}
}
draft-IERC6093.sol 161 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/draft-IERC6093.sol)
pragma solidity >=0.8.4;
/**
* @dev Standard ERC-20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.
*/
interface IERC20Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC20InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC20InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.
* @param spender Address that may be allowed to operate on tokens without being their owner.
* @param allowance Amount of tokens a `spender` is allowed to operate with.
* @param needed Minimum amount required to perform a transfer.
*/
error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC20InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `spender` to be approved. Used in approvals.
* @param spender Address that may be allowed to operate on tokens without being their owner.
*/
error ERC20InvalidSpender(address spender);
}
/**
* @dev Standard ERC-721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.
* Used in balance queries.
* @param owner Address of the current owner of a token.
*/
error ERC721InvalidOwner(address owner);
/**
* @dev Indicates a `tokenId` whose `owner` is the zero address.
* @param tokenId Identifier number of a token.
*/
error ERC721NonexistentToken(uint256 tokenId);
/**
* @dev Indicates an error related to the ownership over a particular token. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param tokenId Identifier number of a token.
* @param owner Address of the current owner of a token.
*/
error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC721InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC721InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param tokenId Identifier number of a token.
*/
error ERC721InsufficientApproval(address operator, uint256 tokenId);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC721InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC721InvalidOperator(address operator);
}
/**
* @dev Standard ERC-1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.
*/
interface IERC1155Errors {
/**
* @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
* @param balance Current balance for the interacting account.
* @param needed Minimum amount required to perform a transfer.
* @param tokenId Identifier number of a token.
*/
error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);
/**
* @dev Indicates a failure with the token `sender`. Used in transfers.
* @param sender Address whose tokens are being transferred.
*/
error ERC1155InvalidSender(address sender);
/**
* @dev Indicates a failure with the token `receiver`. Used in transfers.
* @param receiver Address to which tokens are being transferred.
*/
error ERC1155InvalidReceiver(address receiver);
/**
* @dev Indicates a failure with the `operator`’s approval. Used in transfers.
* @param operator Address that may be allowed to operate on tokens without being their owner.
* @param owner Address of the current owner of a token.
*/
error ERC1155MissingApprovalForAll(address operator, address owner);
/**
* @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.
* @param approver Address initiating an approval operation.
*/
error ERC1155InvalidApprover(address approver);
/**
* @dev Indicates a failure with the `operator` to be approved. Used in approvals.
* @param operator Address that may be allowed to operate on tokens without being their owner.
*/
error ERC1155InvalidOperator(address operator);
/**
* @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.
* Used in batch transfers.
* @param idsLength Length of the array of token identifiers
* @param valuesLength Length of the array of token amounts
*/
error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);
}
IERC1363.sol 86 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC1363.sol)
pragma solidity >=0.6.2;
import {IERC20} from "./IERC20.sol";
import {IERC165} from "./IERC165.sol";
/**
* @title IERC1363
* @dev Interface of the ERC-1363 standard as defined in the https://eips.ethereum.org/EIPS/eip-1363[ERC-1363].
*
* Defines an extension interface for ERC-20 tokens that supports executing code on a recipient contract
* after `transfer` or `transferFrom`, or code on a spender contract after `approve`, in a single transaction.
*/
interface IERC1363 is IERC20, IERC165 {
/*
* Note: the ERC-165 identifier for this interface is 0xb0202a11.
* 0xb0202a11 ===
* bytes4(keccak256('transferAndCall(address,uint256)')) ^
* bytes4(keccak256('transferAndCall(address,uint256,bytes)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256)')) ^
* bytes4(keccak256('transferFromAndCall(address,address,uint256,bytes)')) ^
* bytes4(keccak256('approveAndCall(address,uint256)')) ^
* bytes4(keccak256('approveAndCall(address,uint256,bytes)'))
*/
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from the caller's account to `to`
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value) external returns (bool);
/**
* @dev Moves a `value` amount of tokens from `from` to `to` using the allowance mechanism
* and then calls {IERC1363Receiver-onTransferReceived} on `to`.
* @param from The address which you want to send tokens from.
* @param to The address which you want to transfer to.
* @param value The amount of tokens to be transferred.
* @param data Additional data with no specified format, sent in call to `to`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function transferFromAndCall(address from, address to, uint256 value, bytes calldata data) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value) external returns (bool);
/**
* @dev Sets a `value` amount of tokens as the allowance of `spender` over the
* caller's tokens and then calls {IERC1363Spender-onApprovalReceived} on `spender`.
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
* @param data Additional data with no specified format, sent in call to `spender`.
* @return A boolean value indicating whether the operation succeeded unless throwing.
*/
function approveAndCall(address spender, uint256 value, bytes calldata data) external returns (bool);
}
Panic.sol 57 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/Panic.sol)
pragma solidity ^0.8.20;
/**
* @dev Helper library for emitting standardized panic codes.
*
* ```solidity
* contract Example {
* using Panic for uint256;
*
* // Use any of the declared internal constants
* function foo() { Panic.GENERIC.panic(); }
*
* // Alternatively
* function foo() { Panic.panic(Panic.GENERIC); }
* }
* ```
*
* Follows the list from https://github.com/ethereum/solidity/blob/v0.8.24/libsolutil/ErrorCodes.h[libsolutil].
*
* _Available since v5.1._
*/
// slither-disable-next-line unused-state
library Panic {
/// @dev generic / unspecified error
uint256 internal constant GENERIC = 0x00;
/// @dev used by the assert() builtin
uint256 internal constant ASSERT = 0x01;
/// @dev arithmetic underflow or overflow
uint256 internal constant UNDER_OVERFLOW = 0x11;
/// @dev division or modulo by zero
uint256 internal constant DIVISION_BY_ZERO = 0x12;
/// @dev enum conversion error
uint256 internal constant ENUM_CONVERSION_ERROR = 0x21;
/// @dev invalid encoding in storage
uint256 internal constant STORAGE_ENCODING_ERROR = 0x22;
/// @dev empty array pop
uint256 internal constant EMPTY_ARRAY_POP = 0x31;
/// @dev array out of bounds access
uint256 internal constant ARRAY_OUT_OF_BOUNDS = 0x32;
/// @dev resource error (too large allocation or too large array)
uint256 internal constant RESOURCE_ERROR = 0x41;
/// @dev calling invalid internal function
uint256 internal constant INVALID_INTERNAL_FUNCTION = 0x51;
/// @dev Reverts with a panic code. Recommended to use with
/// the internal constants with predefined codes.
function panic(uint256 code) internal pure {
assembly ("memory-safe") {
mstore(0x00, 0x4e487b71)
mstore(0x20, code)
revert(0x1c, 0x24)
}
}
}
SafeCast.sol 1162 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.1.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.20;
/**
* @dev Wrappers over Solidity's uintXX/intXX/bool casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeCast {
/**
* @dev Value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value);
/**
* @dev An int value doesn't fit in an uint of `bits` size.
*/
error SafeCastOverflowedIntToUint(int256 value);
/**
* @dev Value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedIntDowncast(uint8 bits, int256 value);
/**
* @dev An uint value doesn't fit in an int of `bits` size.
*/
error SafeCastOverflowedUintToInt(uint256 value);
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toUint248(uint256 value) internal pure returns (uint248) {
if (value > type(uint248).max) {
revert SafeCastOverflowedUintDowncast(248, value);
}
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toUint240(uint256 value) internal pure returns (uint240) {
if (value > type(uint240).max) {
revert SafeCastOverflowedUintDowncast(240, value);
}
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toUint232(uint256 value) internal pure returns (uint232) {
if (value > type(uint232).max) {
revert SafeCastOverflowedUintDowncast(232, value);
}
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
if (value > type(uint224).max) {
revert SafeCastOverflowedUintDowncast(224, value);
}
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toUint216(uint256 value) internal pure returns (uint216) {
if (value > type(uint216).max) {
revert SafeCastOverflowedUintDowncast(216, value);
}
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 value) internal pure returns (uint208) {
if (value > type(uint208).max) {
revert SafeCastOverflowedUintDowncast(208, value);
}
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toUint200(uint256 value) internal pure returns (uint200) {
if (value > type(uint200).max) {
revert SafeCastOverflowedUintDowncast(200, value);
}
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toUint192(uint256 value) internal pure returns (uint192) {
if (value > type(uint192).max) {
revert SafeCastOverflowedUintDowncast(192, value);
}
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toUint184(uint256 value) internal pure returns (uint184) {
if (value > type(uint184).max) {
revert SafeCastOverflowedUintDowncast(184, value);
}
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toUint176(uint256 value) internal pure returns (uint176) {
if (value > type(uint176).max) {
revert SafeCastOverflowedUintDowncast(176, value);
}
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toUint168(uint256 value) internal pure returns (uint168) {
if (value > type(uint168).max) {
revert SafeCastOverflowedUintDowncast(168, value);
}
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toUint160(uint256 value) internal pure returns (uint160) {
if (value > type(uint160).max) {
revert SafeCastOverflowedUintDowncast(160, value);
}
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toUint152(uint256 value) internal pure returns (uint152) {
if (value > type(uint152).max) {
revert SafeCastOverflowedUintDowncast(152, value);
}
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toUint144(uint256 value) internal pure returns (uint144) {
if (value > type(uint144).max) {
revert SafeCastOverflowedUintDowncast(144, value);
}
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toUint136(uint256 value) internal pure returns (uint136) {
if (value > type(uint136).max) {
revert SafeCastOverflowedUintDowncast(136, value);
}
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
if (value > type(uint128).max) {
revert SafeCastOverflowedUintDowncast(128, value);
}
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toUint120(uint256 value) internal pure returns (uint120) {
if (value > type(uint120).max) {
revert SafeCastOverflowedUintDowncast(120, value);
}
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toUint112(uint256 value) internal pure returns (uint112) {
if (value > type(uint112).max) {
revert SafeCastOverflowedUintDowncast(112, value);
}
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toUint104(uint256 value) internal pure returns (uint104) {
if (value > type(uint104).max) {
revert SafeCastOverflowedUintDowncast(104, value);
}
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
if (value > type(uint96).max) {
revert SafeCastOverflowedUintDowncast(96, value);
}
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toUint88(uint256 value) internal pure returns (uint88) {
if (value > type(uint88).max) {
revert SafeCastOverflowedUintDowncast(88, value);
}
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toUint80(uint256 value) internal pure returns (uint80) {
if (value > type(uint80).max) {
revert SafeCastOverflowedUintDowncast(80, value);
}
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toUint72(uint256 value) internal pure returns (uint72) {
if (value > type(uint72).max) {
revert SafeCastOverflowedUintDowncast(72, value);
}
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
if (value > type(uint64).max) {
revert SafeCastOverflowedUintDowncast(64, value);
}
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toUint56(uint256 value) internal pure returns (uint56) {
if (value > type(uint56).max) {
revert SafeCastOverflowedUintDowncast(56, value);
}
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toUint48(uint256 value) internal pure returns (uint48) {
if (value > type(uint48).max) {
revert SafeCastOverflowedUintDowncast(48, value);
}
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
if (value > type(uint40).max) {
revert SafeCastOverflowedUintDowncast(40, value);
}
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
if (value > type(uint32).max) {
revert SafeCastOverflowedUintDowncast(32, value);
}
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toUint24(uint256 value) internal pure returns (uint24) {
if (value > type(uint24).max) {
revert SafeCastOverflowedUintDowncast(24, value);
}
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
if (value > type(uint16).max) {
revert SafeCastOverflowedUintDowncast(16, value);
}
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toUint8(uint256 value) internal pure returns (uint8) {
if (value > type(uint8).max) {
revert SafeCastOverflowedUintDowncast(8, value);
}
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
if (value < 0) {
revert SafeCastOverflowedIntToUint(value);
}
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(248, value);
}
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(240, value);
}
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(232, value);
}
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(224, value);
}
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(216, value);
}
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(208, value);
}
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(200, value);
}
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(192, value);
}
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(184, value);
}
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(176, value);
}
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(168, value);
}
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(160, value);
}
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(152, value);
}
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(144, value);
}
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(136, value);
}
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(128, value);
}
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(120, value);
}
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(112, value);
}
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(104, value);
}
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(96, value);
}
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(88, value);
}
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(80, value);
}
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(72, value);
}
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(64, value);
}
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(56, value);
}
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(48, value);
}
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(40, value);
}
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(32, value);
}
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(24, value);
}
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(16, value);
}
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
if (downcasted != value) {
revert SafeCastOverflowedIntDowncast(8, value);
}
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
if (value > uint256(type(int256).max)) {
revert SafeCastOverflowedUintToInt(value);
}
return int256(value);
}
/**
* @dev Cast a boolean (false or true) to a uint256 (0 or 1) with no jump.
*/
function toUint(bool b) internal pure returns (uint256 u) {
assembly ("memory-safe") {
u := iszero(iszero(b))
}
}
}
SecureAccess.sol 101 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {ISecureAccess} from "./ISecureAccess.sol";
import {IAccessManager} from "./IAccessManager.sol";
import {SYSTEM_ADMIN_ROLE, SYSTEM_ROLE} from "./Roles.sol";
import {UnauthorizedAccess, InvalidAddress, AddressRequired} from "../errors/Errors.sol";
import {ERC165Validator} from "../utils/libs/ERC165Validator.sol";
/**
* @title SecureAccess
* @dev Abstract contract that provides role-based access control functionality using an external IAccessManager contract.
* Inherit from this contract to create secure contracts with role-based access control.
*/
abstract contract SecureAccess is ISecureAccess {
using ERC165Validator for address;
// Reference to the access manager contract that manages roles and permissions
IAccessManager public immutable accessManager;
/**
* @dev Modifier to restrict access to functions to only users with the ADMIN_ROLE.
*/
modifier onlyAdmin() {
accessManager.checkRole(SYSTEM_ADMIN_ROLE, msg.sender); // Check if the sender has the ADMIN_ROLE
_;
}
/**
* @dev Modifier to restrict access to functions to only users with a specific role.
*/
modifier onlySystem() {
accessManager.checkRole(SYSTEM_ROLE, msg.sender); // Check if the sender has the specified role
_;
}
/**
* @dev Modifier to restrict access to only the system or a specific role.
* @param _role The role that is allowed to access the function.
* @notice This modifier checks if the caller has the SYSTEM_ROLE or the specified role.
* If the caller has the required role, the function is executed.
* Otherwise, it reverts with an UnauthorizedAccess error, indicating the caller and the required role.
*/
modifier onlySystemOrRole(bytes32 _role) {
if (accessManager.hasRole(SYSTEM_ROLE, msg.sender) || accessManager.hasRole(_role, msg.sender)) {
_;
} else {
revert UnauthorizedAccess(msg.sender, _role);
}
}
/**
* @dev Modifier to restrict access to functions to only users with a specific role.
* @param _role The role required to access the function.
*/
modifier onlyRole(bytes32 _role) {
accessManager.checkRole(_role, msg.sender); // Check if the sender has the specified role
_;
}
/**
* @dev Constructor that initializes the access manager.
* @param _accessManager Address of the IAccessManager contract.
*/
constructor(address _accessManager) {
if (_accessManager == address(0)) {
revert AddressRequired();
} else if (!_accessManager.supportsInterface(type(IAccessManager).interfaceId)) {
revert InvalidAddress();
}
accessManager = IAccessManager(_accessManager);
}
/**
* @dev returns access manager's address.
*/
function getAccessManager() external view returns (address) {
return address(accessManager);
}
/**
* @dev Internal function to check if an account has a specific role.
* @param _role The role to check.
* @param _account The account to check the role for.
* @return bool True if the account has the role, false otherwise.
*/
function _hasRole(bytes32 _role, address _account) internal view virtual returns (bool) {
return accessManager.hasRole(_role, _account); // Use the access manager to check if the account has the role
}
/**
* @dev Internal function to enforce role-based access control.
* Reverts if the account does not have the specified role.
* @param _role The role required.
* @param _account The account to check the role for.
*/
function _checkRole(bytes32 _role, address _account) internal view {
accessManager.checkRole(_role, _account); // Use the access manager to check the role and revert if not met
}
}
DataReader.sol 47 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {IDataReader} from "./IDataReader.sol";
import {IDataStore} from "./IDataStore.sol";
import {ERC165Validator} from "../utils/libs/ERC165Validator.sol";
import {UnauthorizedAccess, InvalidAddress, AddressRequired} from "../errors/Errors.sol";
/**
* @title DataReader
* @dev Abstract contract that provides access to data using an external IDataStore contract.
* Inherit from this contract to create access to datastore.
*/
abstract contract DataReader is IDataReader {
using ERC165Validator for address;
// Reference to the data store contract that manages data
IDataStore public immutable dataStore;
/**
* @dev Constructor that initializes the data store.
* @param _dataStoreAddress Address of the IDataStore contract.
*/
constructor(address _dataStoreAddress) {
_checkAddress(_dataStoreAddress);
dataStore = IDataStore(_dataStoreAddress);
}
/**
* @dev returns datastore's address.
*/
function getDataStore() external view returns (address) {
return address(dataStore);
}
/**
* @dev function to check address validity.
* @param _address Address of the new IDataStore contract need to be verified.
*/
function _checkAddress(address _address) internal view {
if (_address == address(0)) {
revert AddressRequired();
} else if (!_address.supportsInterface(type(IDataStore).interfaceId)) {
revert InvalidAddress();
}
}
}
BeaconWatcher.sol 34 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {IBeacon} from "./IBeacon.sol";
import {IBeaconWatcher} from "./IBeaconWatcher.sol";
import {ERC165Validator} from "../utils/libs/ERC165Validator.sol";
import {UnauthorizedAccess, InvalidAddress, AddressRequired} from "../errors/Errors.sol";
abstract contract BeaconWatcher is IBeaconWatcher {
using ERC165Validator for address;
address internal immutable beacon;
constructor(address _beacon) {
if (_beacon == address(0)) {
revert AddressRequired();
} else if (!_beacon.supportsInterface(type(IBeacon).interfaceId)) {
revert InvalidAddress();
}
beacon = _beacon;
}
function getBeacon() external view override returns (address) {
return beacon;
}
function _getContractAddress(bytes32 _contractName) internal view returns (address) {
return IBeacon(beacon).getContractAddress(_contractName);
}
}
Pausable.sol 40 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {IPauser} from "./IPauser.sol";
import {IPausable} from "./IPausable.sol";
import {Paused, NotPaused, PausedScope, NotPausedScope} from "../errors/Errors.sol";
contract Pausable is IPausable {
IPauser public immutable pauser;
constructor(address _pauser) {
pauser = IPauser(_pauser);
}
modifier whenScopeNotPaused(bytes32 _scope) {
if (pauser.isPausedScope(_scope)) revert PausedScope(_scope);
_;
}
modifier whenScopePaused(bytes32 _scope) {
if (!pauser.isPausedScope(_scope)) revert NotPausedScope(_scope);
_;
}
modifier whenNotPaused() {
if (pauser.isPaused()) revert Paused();
_;
}
modifier whenPaused() {
if (!pauser.isPaused()) revert NotPaused();
_;
}
function getPauser() external view returns (address) {
return address(pauser);
}
}
ReceiptTokens.sol 9 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.29;
struct ReceiptTokens {
address tokenAddress;
uint256 depositRatio;
uint256 withdrawalRatio;
}
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC20.sol)
pragma solidity >=0.4.16;
import {IERC20} from "../token/ERC20/IERC20.sol";
IERC165.sol 6 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (interfaces/IERC165.sol)
pragma solidity >=0.4.16;
import {IERC165} from "../utils/introspection/IERC165.sol";
ISecureAccess.sol 13 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
/**
* @title ISecureAccess
* @dev Interface for Abstract contract that provides role-based access control functionality using an external IAccessManager contract.
*/
interface ISecureAccess {
/**
* @dev returns access manager's address.
*/
function getAccessManager() external view returns (address);
}
IAccessManager.sol 100 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
interface IAccessManager {
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have `role`'s admin role.
*
* May emit a {RoleGranted} event.
*/
function grantRole(bytes32 role, address account) external returns (bool);
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*
* May emit a {RoleRevoked} event.
*/
function revokeRole(bytes32 role, address account) external returns (bool);
/**
* @dev Revokes all roles from `account`.
*
* WARNING: This function should be used only in emergency situations. can be quite expensive.
*/
function revokeAllRoles(address account) external;
/**
* @dev Delete a role.
*
* WARNING: This function should be used only in emergency situations. can be quite expensive.
*/
function deleteRole(bytes32 role) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `callerConfirmation`.
*
* May emit a {RoleRevoked} event.
*/
function renounceRole(bytes32 role, address callerConfirmation) external;
function setRoleAdmin(bytes32 role, bytes32 adminRole) external;
/**
* @dev Returns the roles that an account has.
*/
function getRoles(address account) external view returns (bytes32[] memory);
/**
* @dev Returns the accounts that have been granted `role`.
*/
function getRoleMembers(bytes32 role) external view returns (address[] memory);
/**
* @dev Returns the number of accounts that have been granted `role`.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Reverts with an {UnauthorizedAccess} error if `_sender`
* is missing `role`.
*/
function checkRole(bytes32 role, address _sender) external view;
}
Roles.sol 12 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.21;
/**
* @dev roles for access management
*/
bytes32 constant SYSTEM_ADMIN_ROLE = 0x00;
bytes32 constant SYSTEM_ROLE = keccak256("SYSTEM");
bytes32 constant DATA_STORE_OPERATOR_ROLE = keccak256("DATA_STORE_OPERATOR");
bytes32 constant OPERATOR_ROLE = keccak256("OPERATOR");
bytes32 constant RESCUE_ROLE = keccak256("RESCUE");
Errors.sol 18 lines
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.26; //common errors error UnauthorizedDataAccess(bytes32 tableKey, address account); error UnauthorizedAccess(address account, bytes32 role); error BadConformation(address callerConfirmation); error InvalidInput(string message); error InvalidAddress(); error AddressRequired(); error InvalidAmount(); error InvalidArrayLength(); error MissingContract(bytes32 contractName); error Paused(); error NotPaused(); error PausedScope(bytes32 scope); error NotPausedScope(bytes32 scope);
ERC165Validator.sol 15 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {ERC165} from "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @title ERC165Validator
* @dev Library for validating ERC165 support
*/
library ERC165Validator {
function supportsInterface(address _contract, bytes4 _interfaceId) internal view returns (bool) {
return ERC165(_contract).supportsInterface(_interfaceId);
}
}
IDataReader.sol 15 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
import {IDataStore} from "./IDataStore.sol";
/**
* @title IDataReader
* @dev Interface for Abstract contract that provides access to data using an external IDataStore contract.
*/
interface IDataReader {
/**
* @dev returns datastore's address.
*/
function getDataStore() external view returns (address);
}
IDataStore.sol 559 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
/**
* @title IDataStore
* @dev Interface for accessing data from a data store.
*/
interface IDataStore {
/**
* @dev Retrieves a uint256 value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to retrieve.
* @return The retrieved uint256 value.
*/
function getUint(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Retrieves an int256 value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to retrieve.
* @return The retrieved int256 value.
*/
function getInt(bytes32 _tableKey, bytes32 _key) external view returns (int256);
/**
* @dev Retrieves an address value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to retrieve.
* @return The retrieved address value.
*/
function getAddress(bytes32 _tableKey, bytes32 _key) external view returns (address);
/**
* @dev Retrieves a bool value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to retrieve.
* @return The retrieved bool value.
*/
function getBool(bytes32 _tableKey, bytes32 _key) external view returns (bool);
/**
* @dev Retrieves a string value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to retrieve.
* @return The retrieved string value.
*/
function getString(bytes32 _tableKey, bytes32 _key) external view returns (string memory);
/**
* @dev Retrieves a bytes32 value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to retrieve.
* @return The retrieved bytes32 value.
*/
function getBytes32(bytes32 _tableKey, bytes32 _key) external view returns (bytes32);
/**
* @dev Retrieves a bytes value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to retrieve.
* @return The retrieved bytes value.
*/
function getBytes(bytes32 _tableKey, bytes32 _key) external view returns (bytes memory);
/**
* @dev Sets a uint256 value in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value.
* @param _value The uint256 value to be set.
* @return The updated uint256 value.
*/
function setUint(bytes32 _tableKey, bytes32 _key, uint256 _value) external returns (uint256);
/**
* @dev Sets an int256 value in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value.
* @param _value The int256 value to be set.
* @return The updated int256 value.
*/
function setInt(bytes32 _tableKey, bytes32 _key, int256 _value) external returns (int256);
/**
* @dev Sets an address value in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value.
* @param _value The address value to be set.
* @return The updated address value.
*/
function setAddress(bytes32 _tableKey, bytes32 _key, address _value) external returns (address);
/**
* @dev Sets a bool value in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value.
* @param _value The bool value to be set.
* @return The updated bool value.
*/
function setBool(bytes32 _tableKey, bytes32 _key, bool _value) external returns (bool);
/**
* @dev Sets a string value in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value.
* @param _value The string value to be set.
* @return The updated string value.
*/
function setString(bytes32 _tableKey, bytes32 _key, string memory _value) external returns (string memory);
/**
* @dev Sets a bytes32 value in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value.
* @param _value The bytes32 value to be set.
* @return The updated bytes32 value.
*/
function setBytes32(bytes32 _tableKey, bytes32 _key, bytes32 _value) external returns (bytes32);
/**
* @dev Sets a bytes value in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value.
* @param _value The bytes value to be set.
* @return The updated bytes value.
*/
function setBytes(bytes32 _tableKey, bytes32 _key, bytes calldata _value) external returns (bytes memory);
/**
* @dev Removes a uint value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to be removed.
*/
function removeUint(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes an int value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to be removed.
*/
function removeInt(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes an address value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to be removed.
*/
function removeAddress(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes a bool value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to be removed.
*/
function removeBool(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes a string value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to be removed.
*/
function removeString(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes a bytes32 value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to be removed.
*/
function removeBytes32(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes a bytes value from the data store.
* @param _tableKey The key of the table where the value is stored.
* @param _key The key of the value to be removed.
*/
function removeBytes(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Increments the value associated with the given table key and key by the specified amount.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The amount to increment by.
* @return The new value after incrementing.
*/
function incrementUint(bytes32 _tableKey, bytes32 _key, uint256 _value) external returns (uint256);
/**
* @dev Decrements the value associated with the given table key and key by the specified amount.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The amount to decrement by.
* @return The new value after decrementing.
*/
function decrementUint(bytes32 _tableKey, bytes32 _key, uint256 _value) external returns (uint256);
/**
* @dev Increments the value associated with the given table key and key by the specified amount.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The amount to increment by.
* @return The new value after incrementing.
*/
function incrementInt(bytes32 _tableKey, bytes32 _key, int256 _value) external returns (int256);
/**
* @dev Decrements the value associated with the given table key and key by the specified amount.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The amount to decrement by.
* @return The new value after decrementing.
*/
function decrementInt(bytes32 _tableKey, bytes32 _key, int256 _value) external returns (int256);
/**
* @dev Retrieves an array of uint256 values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @return An array of uint256 values.
*/
function getUintArray(bytes32 _tableKey, bytes32 _key) external view returns (uint256[] memory);
/**
* @dev Retrieves an array of int256 values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @return An array of int256 values.
*/
function getIntArray(bytes32 _tableKey, bytes32 _key) external view returns (int256[] memory);
/**
* @dev Retrieves an array of address values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @return An array of address values.
*/
function getAddressArray(bytes32 _tableKey, bytes32 _key) external view returns (address[] memory);
/**
* @dev Retrieves an array of bool values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @return An array of bool values.
*/
function getBoolArray(bytes32 _tableKey, bytes32 _key) external view returns (bool[] memory);
/**
* @dev Retrieves an array of string values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @return An array of string values.
*/
function getStringArray(bytes32 _tableKey, bytes32 _key) external view returns (string[] memory);
/**
* @dev Retrieves an array of bytes32 values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @return An array of bytes32 values.
*/
function getBytes32Array(bytes32 _tableKey, bytes32 _key) external view returns (bytes32[] memory);
/**
* @dev Sets an array of uint256 values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The array of uint256 values to set.
*/
function setUintArray(bytes32 _tableKey, bytes32 _key, uint256[] memory _value) external;
/**
* @dev Sets an array of int256 values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The array of int256 values to set.
*/
function setIntArray(bytes32 _tableKey, bytes32 _key, int256[] memory _value) external;
/**
* @dev Sets an array of address values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The array of address values to set.
*/
function setAddressArray(bytes32 _tableKey, bytes32 _key, address[] memory _value) external;
/**
* @dev Sets an array of bool values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The array of bool values to set.
*/
function setBoolArray(bytes32 _tableKey, bytes32 _key, bool[] memory _value) external;
/**
* @dev Sets an array of string values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The array of string values to set.
*/
function setStringArray(bytes32 _tableKey, bytes32 _key, string[] memory _value) external;
/**
* @dev Sets an array of bytes32 values associated with the given table key and key.
* @param _tableKey The table key.
* @param _key The key.
* @param _value The array of bytes32 values to set.
*/
function setBytes32Array(bytes32 _tableKey, bytes32 _key, bytes32[] memory _value) external;
/**
* @dev Returns the length of a uint256 array stored in the data store.
* @param _tableKey The key of the table where the array is stored.
* @param _key The key of the array within the table.
* @return The length of the uint256 array.
*/
function getUintArrayLength(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Returns the length of an int256 array stored in the data store.
* @param _tableKey The key of the table where the array is stored.
* @param _key The key of the array within the table.
* @return The length of the int256 array.
*/
function getIntArrayLength(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Returns the length of an address array stored in the data store.
* @param _tableKey The key of the table where the array is stored.
* @param _key The key of the array within the table.
* @return The length of the address array.
*/
function getAddressArrayLength(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Returns the length of a bool array stored in the data store.
* @param _tableKey The key of the table where the array is stored.
* @param _key The key of the array within the table.
* @return The length of the bool array.
*/
function getBoolArrayLength(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Returns the length of a string array stored in the data store.
* @param _tableKey The key of the table where the array is stored.
* @param _key The key of the array within the table.
* @return The length of the string array.
*/
function getStringArrayLength(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Retrieves the length of a bytes32 array stored in the data store.
* @param _tableKey The key of the table where the array is stored.
* @param _key The key of the specific array within the table.
* @return The length of the bytes32 array.
*/
function getBytes32ArrayLength(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Removes an array of uint values associated with a given table key and key.
* @param _tableKey The table key.
* @param _key The key.
*/
function removeUintArray(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes an array of int values associated with a given table key and key.
* @param _tableKey The table key.
* @param _key The key.
*/
function removeIntArray(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes an array of address values associated with a given table key and key.
* @param _tableKey The table key.
* @param _key The key.
*/
function removeAddressArray(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes an array of bool values associated with a given table key and key.
* @param _tableKey The table key.
* @param _key The key.
*/
function removeBoolArray(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes an array of string values associated with a given table key and key.
* @param _tableKey The table key.
* @param _key The key.
*/
function removeStringArray(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Removes an array of bytes32 values associated with a given table key and key.
* @param _tableKey The table key.
* @param _key The key.
*/
function removeBytes32Array(bytes32 _tableKey, bytes32 _key) external;
/**
* @dev Checks if a given value exists in a set of bytes32 values.
* @param _tableKey The key of the table containing the set.
* @param _key The key of the value to remove.
* @param _value The value to check for existence.
* @return A boolean indicating whether the value exists in the set.
*/
function containsBytes32(bytes32 _tableKey, bytes32 _key, bytes32 _value) external view returns (bool);
/**
* @dev Returns the number of values in a set of bytes32 values.
* @param _tableKey The key of the table containing the set.
* @param _key The key of the value to remove.
* @return The number of values in the set.
*/
function getBytes32SetCount(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Returns an array of bytes32 values in a set within a specified range.
* @param _tableKey The key of the table containing the set.
* @param _key The key of the value to remove.
* @param _start The start index of the range.
* @param _end The end index of the range.
* @return An array of bytes32 values within the specified range.
*/
function getBytes32SetValuesAt(bytes32 _tableKey, bytes32 _key, uint256 _start, uint256 _end)
external
view
returns (bytes32[] memory);
/**
* @dev Returns an array of bytes32 values in a set.
* @param _tableKey The key of the table containing the set.
* @param _key The key of the value to remove.
* @return An array of bytes32 values.
*/
function getBytes32SetValues(bytes32 _tableKey, bytes32 _key) external view returns (bytes32[] memory);
/**
* @dev Adds a value to a set of bytes32 values.
* @param _tableKey The key of the table containing the set.
* @param _key The key of the value to remove.
* @param _value The value to add to the set.
*/
function addBytes32Set(bytes32 _tableKey, bytes32 _key, bytes32 _value) external;
/**
* @dev Removes a value from a set of bytes32 values.
* @param _tableKey The key of the table containing the set.
* @param _key The key of the value to remove.
* @param _value The value to remove from the set.
*/
function removeBytes32FromSet(bytes32 _tableKey, bytes32 _key, bytes32 _value) external;
/**
* @dev Checks if the specified address value exists in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @param _value The address value to check.
* @return True if the address value exists, false otherwise.
*/
function containsAddress(bytes32 _tableKey, bytes32 _key, address _value) external view returns (bool);
/**
* @dev Returns the number of address values stored in the data store for the specified key.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @return The number of address values stored.
*/
function getAddressSetCount(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Returns an array of address values stored in the data store for the specified key, within the specified range.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @param _start The start index of the range.
* @param _end The end index of the range.
* @return An array of address values.
*/
function getAddressSetValuesAt(bytes32 _tableKey, bytes32 _key, uint256 _start, uint256 _end)
external
view
returns (address[] memory);
/**
* @dev Returns an array of address values stored in the data store for the specified key.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @return An array of address values.
*/
function getAddressSetValues(bytes32 _tableKey, bytes32 _key) external view returns (address[] memory);
/**
* @dev Adds an address value to the data store for the specified key.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @param _value The address value to add.
*/
function addAddressSet(bytes32 _tableKey, bytes32 _key, address _value) external;
/**
* @dev Removes an address value from the data store for the specified key.
* @param _tableKey The key of the table.
* @param _value The address value to remove.
*/
function removeAddressSet(bytes32 _tableKey, bytes32 _key, address _value) external;
/**
* @dev Checks if a given value exists in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @param _value The value to check for existence.
* @return True if the value exists, false otherwise.
*/
function containsUint(bytes32 _tableKey, bytes32 _key, uint256 _value) external view returns (bool);
/**
* @dev Returns the number of uint256 values associated with a given key in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @return The number of uint256 values associated with the key.
*/
function getUintSetCount(bytes32 _tableKey, bytes32 _key) external view returns (uint256);
/**
* @dev Returns an array of uint256 values associated with a given key in the data store, within a specified range.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @param _start The start index of the range.
* @param _end The end index of the range.
* @return An array of uint256 values within the specified range.
*/
function getUintSetValuesAt(bytes32 _tableKey, bytes32 _key, uint256 _start, uint256 _end)
external
view
returns (uint256[] memory);
/**
* @dev Returns an array of uint256 values associated with a given key in the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @return An array of uint256 values within the specified range.
*/
function getUintSetValues(bytes32 _tableKey, bytes32 _key) external view returns (uint256[] memory);
/**
* @dev Adds a uint256 value to the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @param _value The value to add.
*/
function addUintSet(bytes32 _tableKey, bytes32 _key, uint256 _value) external;
/**
* @dev Removes a uint256 value from the data store.
* @param _tableKey The key of the table.
* @param _key The key of the value to remove.
* @param _value The value to remove.
*/
function removeUintSet(bytes32 _tableKey, bytes32 _key, uint256 _value) external;
}
IBeacon.sol 9 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
interface IBeacon {
function setContractAddress(bytes32 _contractName, address _contractAddress) external;
function getContractAddress(bytes32 _contractName) external view returns (address);
}
IBeaconWatcher.sol 14 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
/**
* @title IBeaconWatcher
* @dev Interface for a contract that watches a beacon.
*/
interface IBeaconWatcher {
/**
* @dev Returns the address of the beacon.
* @return The address of the beacon.
*/
function getBeacon() external view returns (address);
}
IPauser.sol 45 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
/**
* @title Pauser
* @dev Contract module which allows to implement an emergency stop mechanism that can be triggered by an authorized account.
* The contract allows pausing and unpausing of the entire contract as well as specific scopes.
* Inherits from SecureAccess to manage access control.
*/
interface IPauser {
/**
* @dev Triggers stopped state.
* Can only be called by an admin.
*/
function pause() external;
/**
* @dev Returns to normal state.
* Can only be called by an admin.
*/
function unpause() external;
/**
* @dev Triggers stopped state for a specific scope.
* Can only be called by an admin.
* @param _scope The scope to be paused.
*/
function pauseScope(bytes32 _scope) external;
/**
* @dev Returns to normal state for a specific scope.
* Can only be called by an admin.
* @param _scope The scope to be unpaused.
*/
function unpauseScope(bytes32 _scope) external;
/**
* @dev Returns true if the contract is paused, and false otherwise.
* @return True if the contract is paused, false otherwise.
*/
function isPaused() external view returns (bool);
/**
* @dev Returns true if the specific scope is paused or if the general paused state is true, and false otherwise.
* @param _scope The scope to check.
* @return True if the specific scope is paused or if the general paused state is true, false otherwise.
*/
function isPausedScope(bytes32 _scope) external view returns (bool);
}
IPausable.sol 7 lines
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.26;
interface IPausable {
function getPauser() external view returns (address);
}
IERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/IERC165.sol)
pragma solidity >=0.4.16;
/**
* @dev Interface of the ERC-165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[ERC].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[ERC section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
ERC165.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.4.0) (utils/introspection/ERC165.sol)
pragma solidity ^0.8.20;
import {IERC165} from "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC-165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*/
abstract contract ERC165 is IERC165 {
/// @inheritdoc IERC165
function supportsInterface(bytes4 interfaceId) public view virtual returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
Read Contract
accessManager 0xfdcb6068 → address
calculateDeposit 0x4ec508f9 → uint256, uint256, uint256
calculateWithdrawal 0x23df13a7 → uint256, uint256, uint256
dataStore 0x660d0d67 → address
getAccessManager 0x9f4bc3c3 → address
getAllWithdrawalRequests 0xdc929353 → tuple[]
getAvailableBalance 0x809dab6a → uint256
getBeacon 0x2d6b3a6b → address
getClaimableBalance 0x06def802 → uint256
getCustodian 0xc561d4b7 → address
getDataStore 0xfe58265e → address
getExchangeRate 0xe6aa216c → uint256, uint256
getMinimumDepositAmount 0xde4303bc → uint256
getPauser 0x7008b548 → address
getPendingWithdrawalCount 0xaabd4ac1 → uint256
getSPRToken 0x2cdf7d83 → address
getUserWithdrawalRequests 0x6c930228 → tuple[]
isQueuePaused 0x89b87998 → bool
pauser 0x9fd0506d → address
Write Contract 7 functions
These functions modify contract state and require a wallet transaction to execute.
cancelWithdrawalRequest 0x45b05d09
uint256 _requestId
claim 0x4e71d92d
No parameters
deposit 0xb6b55f25
uint256 _amount
emergencyWithdraw 0x6382d9ad
address token
address recipient
processWithdrawalQueue 0x342c00b3
uint256 _maxRequests
setQueuePaused 0x9750730a
bool _paused
withdraw 0x2e1a7d4d
uint256 _shareAmount
Token Balances (1)
View Transfers →Recent Transactions
No transactions found for this address