Address Contract Verified
Address
0x0239182D3DC3973A43e01D8AdFca4893484c7290
Balance
0 ETH
Nonce
1
Code Size
10067 bytes
Creator
0xd9a43224...4312 at tx 0x387f6fcf...6e50c4
Indexed Transactions
0
Contract Bytecode
10067 bytes
0x608060405234801561000f575f80fd5b50600436106102cb575f3560e01c8063866512031161017b578063ba087652116100e4578063dd62ed3e1161009e578063ef8b30f711610079578063ef8b30f7146105f2578063f2fde38b1461068f578063f5a23d8d146106a2578063fd896f9e146106cc575f80fd5b8063dd62ed3e14610633578063e30c39781461066b578063eaed1d071461067c575f80fd5b8063ba087652146105df578063c63d75b6146103bd578063c6e6f592146105f2578063ce96cb7714610605578063d905777e14610618578063dbd5edc71461062b575f80fd5b8063a9059cbb11610135578063a9059cbb14610561578063ae604c4314610574578063b3d7f6b914610587578063b460af941461059a578063b6363cf2146105ad578063b90f5084146105c0575f80fd5b806386651203146104ee5780638da5cb5b1461050157806391ac6a061461051257806394bf804d1461053157806395d89b41146105445780639fe8eecd1461054c575f80fd5b80634cdad506116102375780636e553f65116101f157806372624857116101cc57806372624857146104b857806379ba5097146104cb5780637d41c86e146104d35780638456cb59146104e6575f80fd5b80636e553f651461047557806370a0823114610488578063715018a6146104b0575f80fd5b80634cdad506146102fb57806351f1f5fa146103e4578063558a7297146103f75780635c975abb1461043d578063671e8c8d1461044f5780636c606a6214610462575f80fd5b806323b872dd1161028857806323b872dd1461034c578063313ce5671461035f57806338d52e0f146103795780633f4ba83a146103b3578063402d267d146103bd5780634cdac289146103d1575f80fd5b806301e1d114146102cf57806306fdde03146102e657806307a2d13a146102fb578063095ea7b31461030e5780630a28a4771461033157806318160ddd14610344575b5f80fd5b6008545b6040519081526020015b60405180910390f35b6102ee6106f6565b6040516102dd919061211c565b6102d361030936600461214e565b610786565b61032161031c366004612180565b610797565b60405190151581526020016102dd565b6102d361033f36600461214e565b6107ae565b6002546102d3565b61032161035a3660046121a8565b6107ba565b6103676107d8565b60405160ff90911681526020016102dd565b7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb485b6040516001600160a01b0390911681526020016102dd565b6103bb610808565b005b6102d36103cb3660046121e1565b505f1990565b6103bb6103df3660046121fa565b61081a565b6103bb6103f2366004612233565b610974565b610321610405366004612260565b335f908152600f602090815260408083206001600160a01b03861684529091529020805482151560ff19909116179055600192915050565b600654600160a01b900460ff16610321565b6103bb61045d36600461231c565b610aca565b6103bb610470366004612358565b610c54565b6102d36104833660046123c7565b610e19565b6102d36104963660046121e1565b6001600160a01b03165f9081526020819052604090205490565b6103bb610e4d565b6102d36104c63660046123e8565b610e5e565b6103bb6110eb565b6102d36104e13660046121fa565b61112f565b6103bb6111de565b6103bb6104fc36600461214e565b6111ee565b6005546001600160a01b031661039b565b6102d36105203660046121e1565b600e6020525f908152604090205481565b6102d361053f3660046123c7565b6111fb565b6102ee61125c565b61055461126b565b6040516102dd9190612418565b61032161056f366004612180565b6112fa565b6103bb610582366004612485565b61130d565b6102d361059536600461214e565b611421565b6102d36105a83660046121fa565b61142d565b6103216105bb36600461249f565b611496565b6102d36105ce3660046121e1565b600d6020525f908152604090205481565b6102d36105ed3660046121fa565b6114c3565b6102d361060036600461214e565b61151e565b6102d36106133660046121e1565b611529565b6102d36106263660046121e1565b611546565b6009546102d3565b6102d361064136600461249f565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b6006546001600160a01b031661039b565b6102d361068a3660046123c7565b61154d565b6103bb61069d3660046121e1565b61156e565b6102d36106b03660046123c7565b6001600160a01b03165f908152600d6020526040902054919050565b6102d36106da3660046123c7565b6001600160a01b03165f908152600e6020526040902054919050565b606060038054610705906124c7565b80601f0160208091040260200160405190810160405280929190818152602001828054610731906124c7565b801561077c5780601f106107535761010080835404028352916020019161077c565b820191905f5260205f20905b81548152906001019060200180831161075f57829003601f168201915b5050505050905090565b5f610791825f6115df565b92915050565b5f336107a4818585611618565b5060019392505050565b5f610791826001611625565b5f6107c361164f565b6107ce84848461167a565b90505b9392505050565b5f610803817f0000000000000000000000000000000000000000000000000000000000000006612513565b905090565b61081061169d565b6108186116ca565b565b61082261164f565b336001600160a01b0383161480159061084257506108408233611496565b155b156108865760405162461bcd60e51b815260206004820152600f60248201526e2737ba1030b71037b832b930ba37b960891b60448201526064015b60405180910390fd5b6001600160a01b0382165f908152600d60205260409020548311156108ed5760405162461bcd60e51b815260206004820152601d60248201527f43616e63656c696e67206d6f7265207468656e20726571756573746564000000604482015260640161087d565b6108f830828561171f565b6001600160a01b0382165f908152600d60205260408120805485929061091f90849061252c565b909155505060408051338152602081018590525f916001600160a01b0380851692908616917f9cfcc9b32b1fd2d28f14449db4e7234c5742a8e7a3503c3e6a461749ab77f950910160405180910390a4505050565b61097c61169d565b600c54600a5442916109969163ffffffff9091169061253f565b11156109f05760405162461bcd60e51b8152602060048201526024808201527f4368616e67696e6720746f74616c20617373657473206973206f6e20636f6f6c6044820152633237bbb760e11b606482015260840161087d565b610a07600854600b54670de0b6b3a764000061177c565b610a1382600b0b61183b565b1115610a6d5760405162461bcd60e51b815260206004820152602360248201527f43616e6e6f74206368616e676520746f74616c2061737365747320746f6f206d6044820152620eac6d60eb1b606482015260840161087d565b80600b0b600854610a7e9190612552565b600881905542600a5560408051600b84900b8152602081019290925233917f11043077a0cf71e389c289edb40f672afc73ee30a1b733a3d124f7ce5418e980910160405180910390a250565b610ad261169d565b8163ffffffff165f03610b75577f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486001600160a01b0316815f01516001600160a01b031614610b755760405162461bcd60e51b815260206004820152602960248201527f466972737420696e70757420746f6b656e2073686f756c642062652073616d6560448201526808185cc8185cdcd95d60ba1b606482015260840161087d565b60208101516001600160a01b0316610be3575f81604001516001600160601b031611610be35760405162461bcd60e51b815260206004820152601a60248201527f7065724f6e6541737365742063616e6e6f74206265207a65726f000000000000604482015260640161087d565b8060078363ffffffff1681548110610bfd57610bfd612579565b5f918252602091829020835160029092020180546001600160a01b039283166001600160a01b0319909116178155918301516040909301516001600160601b0316600160a01b029216919091176001909101555050565b610c5c61169d565b5f805b63ffffffff8116831115610ddc575f610c9885858463ffffffff16818110610c8957610c89612579565b90506040020160200135610786565b9050610cc53086868563ffffffff16818110610cb657610cb6612579565b90506040020160200135611850565b8060085f828254610cd6919061252c565b909155508590508463ffffffff8416818110610cf457610cf4612579565b90506040020160200135600d5f87878663ffffffff16818110610d1957610d19612579565b610d2f92602060409092020190810191506121e1565b6001600160a01b03166001600160a01b031681526020019081526020015f205f828254610d5c919061252c565b90915550819050600e5f878763ffffffff8716818110610d7e57610d7e612579565b610d9492602060409092020190810191506121e1565b6001600160a01b03166001600160a01b031681526020019081526020015f205f828254610dc1919061253f565b90915550610dd19050818461253f565b925050600101610c5f565b50610e147f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486005546001600160a01b03163084611888565b505050565b5f610e2261164f565b6107d17f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb488484610e5e565b610e5561169d565b6108185f6118f5565b5f610e6761164f565b6001600160a01b038416610ec95760405162461bcd60e51b8152602060048201526024808201527f746f6b656e20616464726573732063616e6e6f74206265207a65726f206164646044820152637265737360e01b606482015260840161087d565b5f5b60075481101561109857846001600160a01b031660078281548110610ef257610ef2612579565b5f9182526020909120600290910201546001600160a01b031603611090575f806001600160a01b031660078381548110610f2e57610f2e612579565b5f9182526020909120600160029092020101546001600160a01b03161461101a5760078281548110610f6257610f62612579565b5f9182526020909120600290910201600101546001600160a01b031663ac41865a7f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb486040516001600160e01b031960e084901b1681526001600160a01b03918216600482015290891660248201526044016020604051808303815f875af1158015610fef573d5f803e3d5ffd5b505050506040513d601f19601f82011682018060405250810190611013919061258d565b9050611053565b6007828154811061102d5761102d612579565b5f918252602090912060029091020160010154600160a01b90046001600160601b031690505b5f61106786670de0b6b3a76400008461177c565b90505f611075826002611625565b905061108533898989868661190e565b93506107d192505050565b600101610ecb565b5060405162461bcd60e51b815260206004820152602160248201527f5468697320696e70757420746f6b656e206973206e6f7420737570706f7274656044820152601960fa1b606482015260840161087d565b60065433906001600160a01b031681146111235760405163118cdaa760e01b81526001600160a01b038216600482015260240161087d565b61112c816118f5565b50565b5f61113861164f565b336001600160a01b0383161461115357611153823386611a61565b61115e82308661171f565b6001600160a01b0383165f908152600d60205260408120805486929061118590849061253f565b909155505060408051338152602081018690525f916001600160a01b0380861692908716917f1fdc681a13d8c5da54e301c7ce6542dcde4581e4725043fdab2db12ddc574506910160405180910390a4505f9392505050565b6111e661169d565b610818611ad6565b6111f661169d565b600955565b5f61120461164f565b60405162461bcd60e51b815260206004820152602760248201527f4d696e74696e672069732064697361626c65642c20757365206465706f736974604482015266213caa37b5b2b760c91b606482015260840161087d565b606060048054610705906124c7565b60606007805480602002602001604051908101604052809291908181526020015f905b828210156112f1575f848152602090819020604080516060810182526002860290920180546001600160a01b03908116845260019182015490811684860152600160a01b90046001600160601b031691830191909152908352909201910161128e565b50505050905090565b5f61130361164f565b6107d18383611b19565b61131561169d565b60208101516001600160a01b0316611383575f81604001516001600160601b0316116113835760405162461bcd60e51b815260206004820152601a60248201527f7065724f6e6541737365742063616e6e6f74206265207a65726f000000000000604482015260640161087d565b600780546001810182555f91909152815160029091027fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c688810180546001600160a01b039384166001600160a01b031990911617905560208301516040909301516001600160601b0316600160a01b0292909116919091177fa66cc928b5edb82af9bd49922954155ab7b0942694bea4ce44661d9a8736c68990910155565b5f6107918260016115df565b5f8061143883611529565b90508085111561147457604051633fa733bb60e21b81526001600160a01b0384166004820152602481018690526044810182905260640161087d565b5f61147e866107ae565b905061148d3386868985611b26565b95945050505050565b6001600160a01b039182165f908152600f6020908152604080832093909416825291909152205460ff1690565b60405162461bcd60e51b815260206004820152602860248201527f52656465656d2069732064697361626c65642e20557365207769746864726177604482015267081a5b9cdd19585960c21b60648201525f9060840161087d565b5f610791825f611625565b6001600160a01b0381165f908152600e6020526040812054610791565b5f6107915f835b6001600160a01b0381165f908152600e60205260408120546107d19061151e565b61157661169d565b600680546001600160a01b0383166001600160a01b031990911681179091556115a76005546001600160a01b031690565b6001600160a01b03167f38d16b8cac22d99fc7c124b9cd0de2d3fa1faef420bfe791d8c362d765e2270060405160405180910390a350565b5f6107d16115ec60085490565b6115f790600161253f565b6116025f600a612684565b60025461160f919061253f565b85919085611c55565b610e148383836001611ca2565b5f6107d161163482600a612684565b600254611641919061253f565b60085461160f90600161253f565b600654600160a01b900460ff16156108185760405163d93c066560e01b815260040160405180910390fd5b5f33611687858285611a61565b61169285858561171f565b506001949350505050565b6005546001600160a01b031633146108185760405163118cdaa760e01b815233600482015260240161087d565b6116d2611d74565b6006805460ff60a01b191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6001600160a01b03831661174857604051634b637e8f60e11b81525f600482015260240161087d565b6001600160a01b0382166117715760405163ec442f0560e01b81525f600482015260240161087d565b610e14838383611d9e565b5f838302815f1985870982811083820303915050805f036117b0578382816117a6576117a6612692565b04925050506107d1565b8084116117d05760405163227bc15360e01b815260040160405180910390fd5b5f848688095f868103871696879004966002600389028118808a02820302808a02820302808a02820302808a02820302808a02820302808a02909103029181900381900460010186841190950394909402919094039290920491909117919091029150509392505050565b5f8082121561184c57815f03610791565b5090565b6001600160a01b03821661187957604051634b637e8f60e11b81525f600482015260240161087d565b611884825f83611d9e565b5050565b6040516001600160a01b0384811660248301528381166044830152606482018390526118ef9186918216906323b872dd906084015b604051602081830303815290604052915060e01b6020820180516001600160e01b038381831617835250505050611ec4565b50505050565b600680546001600160a01b031916905561112c81611f25565b60095415611973576009548261192360085490565b61192d919061253f565b11156119735760405162461bcd60e51b815260206004820152601560248201527404465706f736974206d6f7265207468656e2043617605c1b604482015260640161087d565b805f036119d35760405162461bcd60e51b815260206004820152602860248201527f4465706f73697420746f6f20736d616c6c20746f2067656e657261746520616e604482015267792073686172657360c01b606482015260840161087d565b6119f085876119ea6005546001600160a01b031690565b87611888565b6119fa8382611f76565b8160085f828254611a0b919061253f565b909155505060408051838152602081018390526001600160a01b0380861692908916917fdcbc1c05240f31ff3ad067ef1ee35ce4997762752e3a095284754544f4c709d7910160405180910390a3505050505050565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f1981146118ef5781811015611ac857604051637dc7a0d960e11b81526001600160a01b0384166004820152602481018290526044810183905260640161087d565b6118ef84848484035f611ca2565b611ade61164f565b6006805460ff60a01b1916600160a01b1790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a2586117023390565b5f336107a481858561171f565b611b2e61164f565b826001600160a01b0316856001600160a01b031614158015611b575750611b558386611496565b155b15611b965760405162461bcd60e51b815260206004820152600f60248201526e2737ba1030b71037b832b930ba37b960891b604482015260640161087d565b6001600160a01b0383165f908152600e602052604081208054849290611bbd90849061252c565b90915550611bee90507f000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb488584611faa565b826001600160a01b0316846001600160a01b0316866001600160a01b03167ffbde797d201c681b91056529119e0b02407c7bb96a4a2c75c01fc9667232c8db8585604051611c46929190918252602082015260400190565b60405180910390a45050505050565b5f80611c6286868661177c565b9050611c6d83611fdb565b8015611c8857505f8480611c8357611c83612692565b868809115b1561148d57611c9860018261253f565b9695505050505050565b6001600160a01b038416611ccb5760405163e602df0560e01b81525f600482015260240161087d565b6001600160a01b038316611cf457604051634a1406b160e11b81525f600482015260240161087d565b6001600160a01b038085165f90815260016020908152604080832093871683529290522082905580156118ef57826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92584604051611d6691815260200190565b60405180910390a350505050565b600654600160a01b900460ff1661081857604051638dfc202b60e01b815260040160405180910390fd5b6001600160a01b038316611dc8578060025f828254611dbd919061253f565b90915550611e389050565b6001600160a01b0383165f9081526020819052604090205481811015611e1a5760405163391434e360e21b81526001600160a01b0385166004820152602481018290526044810183905260640161087d565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b038216611e5457600280548290039055611e72565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef83604051611eb791815260200190565b60405180910390a3505050565b5f611ed86001600160a01b03841683612007565b905080515f14158015611efc575080806020019051810190611efa91906126a6565b155b15610e1457604051635274afe760e01b81526001600160a01b038416600482015260240161087d565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6001600160a01b038216611f9f5760405163ec442f0560e01b81525f600482015260240161087d565b6118845f8383611d9e565b6040516001600160a01b03838116602483015260448201839052610e1491859182169063a9059cbb906064016118bd565b5f6002826003811115611ff057611ff06126c1565b611ffa91906126d5565b60ff166001149050919050565b60606107d183835f845f80856001600160a01b0316848660405161202b9190612702565b5f6040518083038185875af1925050503d805f8114612065576040519150601f19603f3d011682016040523d82523d5f602084013e61206a565b606091505b5091509150611c9886838360608261208a57612085826120d1565b6107d1565b81511580156120a157506001600160a01b0384163b155b156120ca57604051639996b31560e01b81526001600160a01b038516600482015260240161087d565b50806107d1565b8051156120e15780518082602001fd5b604051630a12f52160e11b815260040160405180910390fd5b5f5b838110156121145781810151838201526020016120fc565b50505f910152565b602081525f825180602084015261213a8160408501602087016120fa565b601f01601f19169190910160400192915050565b5f6020828403121561215e575f80fd5b5035919050565b80356001600160a01b038116811461217b575f80fd5b919050565b5f8060408385031215612191575f80fd5b61219a83612165565b946020939093013593505050565b5f805f606084860312156121ba575f80fd5b6121c384612165565b92506121d160208501612165565b9150604084013590509250925092565b5f602082840312156121f1575f80fd5b6107d182612165565b5f805f6060848603121561220c575f80fd5b8335925061221c60208501612165565b915061222a60408501612165565b90509250925092565b5f60208284031215612243575f80fd5b813580600b0b81146107d1575f80fd5b801515811461112c575f80fd5b5f8060408385031215612271575f80fd5b61227a83612165565b9150602083013561228a81612253565b809150509250929050565b5f606082840312156122a5575f80fd5b6040516060810181811067ffffffffffffffff821117156122d457634e487b7160e01b5f52604160045260245ffd5b6040529050806122e383612165565b81526122f160208401612165565b602082015260408301356001600160601b038116811461230f575f80fd5b6040919091015292915050565b5f806080838503121561232d575f80fd5b823563ffffffff81168114612340575f80fd5b915061234f8460208501612295565b90509250929050565b5f8060208385031215612369575f80fd5b823567ffffffffffffffff80821115612380575f80fd5b818501915085601f830112612393575f80fd5b8135818111156123a1575f80fd5b8660208260061b85010111156123b5575f80fd5b60209290920196919550909350505050565b5f80604083850312156123d8575f80fd5b8235915061234f60208401612165565b5f805f606084860312156123fa575f80fd5b61240384612165565b92506020840135915061222a60408501612165565b602080825282518282018190525f919060409081850190868401855b8281101561247857815180516001600160a01b0390811686528782015116878601528501516001600160601b03168585015260609093019290850190600101612434565b5091979650505050505050565b5f60608284031215612495575f80fd5b6107d18383612295565b5f80604083850312156124b0575f80fd5b6124b983612165565b915061234f60208401612165565b600181811c908216806124db57607f821691505b6020821081036124f957634e487b7160e01b5f52602260045260245ffd5b50919050565b634e487b7160e01b5f52601160045260245ffd5b60ff8181168382160190811115610791576107916124ff565b81810381811115610791576107916124ff565b80820180821115610791576107916124ff565b8082018281125f831280158216821582161715612571576125716124ff565b505092915050565b634e487b7160e01b5f52603260045260245ffd5b5f6020828403121561259d575f80fd5b5051919050565b600181815b808511156125de57815f19048211156125c4576125c46124ff565b808516156125d157918102915b93841c93908002906125a9565b509250929050565b5f826125f457506001610791565b8161260057505f610791565b816001811461261657600281146126205761263c565b6001915050610791565b60ff841115612631576126316124ff565b50506001821b610791565b5060208310610133831016604e8410600b841016171561265f575081810a610791565b61266983836125a4565b805f190482111561267c5761267c6124ff565b029392505050565b5f6107d160ff8416836125e6565b634e487b7160e01b5f52601260045260245ffd5b5f602082840312156126b6575f80fd5b81516107d181612253565b634e487b7160e01b5f52602160045260245ffd5b5f60ff8316806126f357634e487b7160e01b5f52601260045260245ffd5b8060ff84160691505092915050565b5f82516127138184602087016120fa565b919091019291505056fea2646970667358221220308c1c684a7902763de7633e01638ec78dca12f912b11fa2c58859ed6c28b4ca64736f6c63430008140033
Verified Source Code Full Match
Compiler: v0.8.20+commit.a1b79de6
EVM: shanghai
Optimization: Yes (200 runs)
WallchainVault.sol 542 lines
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.8.20;
import {ERC20, IERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC4626} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {Math} from "@openzeppelin/contracts/utils/math/Math.sol";
import {SignedMath} from "@openzeppelin/contracts/utils/math/SignedMath.sol";
import {Pausable} from "@openzeppelin/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import {Ownable2Step} from "@openzeppelin/contracts/access/Ownable2Step.sol";
uint256 constant DENOMINATOR = 10 ** 18;
/**
* @title A price oracle interface
*
* @dev This abstracts details on about exact API oracle provider uses. Adapter contract
* should developed per provider and deployed separately.
*/
interface PricingOracle {
/**
* @dev Get amount of tokenOut per one tokenIn, multiplied by DENOMINATOR;
*
* @param tokenIn token to be priced
* @param tokenOut token use as a currency of the price of the tokenIn
*/
function getPrice(address tokenIn, address tokenOut) external returns (uint256);
}
/**
* @title A main vault contract.
*
* @dev The vault is ERC4626 vault, and doesnt hold any funds - any deposit is directly
* transferred to owner address. This address supposed to be something like Gnosis Safe,
* e.g. safe contract that allows to control funds without risks.
*/
contract WallchainVault is ERC4626, Ownable2Step, Pausable {
using Math for uint256;
struct InputToken {
address token;
address priceOracle; // If address is non-zero, contract will use oracle for pricing,
// otherwise it will use perOneAsset
uint96 perOneAsset; // What amount of this token corresponds to 1 asset token,
// multiplied by DENOMINATOR to allow integer calculations.
// Sets how to convert this token into main assets
// This includes external fees, decimal conversion,
// and base price difference
}
InputToken[] _inputTokens;
uint256 _totalAssets = 0;
uint256 _depositCap = 0;
uint256 _totalAssetsLastChange = 0;
uint256 _totalAssetsMaxSingleChangeFraction;
uint32 _totalAssetsChangeCooldown;
mapping(address => uint256) public pendingRedeemSharesRequest;
mapping(address => uint256) public claimableRedeemAssetsRequest;
/**
* @dev Emitted when user requests a withdrawal
*
* @param controller an address that will control this withdrawal
* @param owner an owner of the shares that requests this withdrawal
* @param requestId not used by this implementation of ERC-7540
* @param sender msg.sender that initiated this withdrawal
* @param shares amount of the shares requested to be withdrawn
*/
event RedeemRequest(
address indexed controller, address indexed owner, uint256 indexed requestId, address sender, uint256 shares
);
/**
* @dev Emitted when user cancels a withdrawal
*
* @param controller an address that will control this withdrawal
* @param receiver an address that receives shares back
* @param requestId not used by this implementation of ERC-7540
* @param sender msg.sender that initiated cancellation of the withdrawal
* @param shares amount of the shares canceled from the withdrawal
*/
event RedeemCanceled(
address indexed controller, address indexed receiver, uint256 indexed requestId, address sender, uint256 shares
);
/**
* @dev Emitted when owner updates total assets
*
* @param owner an address that executed this change
* @param delta update change amount
* @param totalAssets new total assets amount
*/
event TotalAssetsUpdated(address indexed owner, int256 delta, uint256 totalAssets);
/**
* @dev Construct of the contract
*
* @param owner the contact owner (administrator). Can execute all privileged methods,
* and also collects all deposits.
* @param name_ a name for ERC20 vault share token
* @param symbol_ a symbol for ERC20 vault share token
* @param asset_ an address of ERC20 asset token, e.g. token used for deposits/withdraws
* @param depositCap_ a limit on how much all users can deposit in total into this vault
* @param inputTokens_ a list of tokens that can be used to deposit into vault
* @param totalAssetsUpdateCooldown a timeout (in seconds) between sequential calls to updateTotalAssets by owner
* this prevents owner from being able to change totalAssets too often
* @param totalAssetsMaxSingleChangeFraction a fraction that limits delta absolute value used to update
* totalAssets (e.g. 0.1 - only 10% change is allowed, 0.01 - only
* 1% changes) multiplied by DENOMINATOR to allow integer calculations.
*/
constructor(
address owner,
string memory name_,
string memory symbol_,
IERC20 asset_,
uint256 depositCap_,
InputToken[] memory inputTokens_,
uint32 totalAssetsUpdateCooldown,
uint256 totalAssetsMaxSingleChangeFraction
) Ownable(owner) ERC20(name_, symbol_) ERC4626(asset_) {
_depositCap = depositCap_;
_totalAssetsLastChange = block.timestamp;
_totalAssetsChangeCooldown = totalAssetsUpdateCooldown;
_totalAssetsMaxSingleChangeFraction = totalAssetsMaxSingleChangeFraction;
require(inputTokens_.length > 0, "Input tokens should be set");
// Next requirement is needed to support ERC4626 deposit()
require(inputTokens_[0].token == address(asset_), "First input token should be same as asset");
for (uint256 index = 0; index < inputTokens_.length; ++index) {
if (inputTokens_[index].priceOracle == address(0)) {
require(inputTokens_[index].perOneAsset > 0, "perOneAsset cannot be zero");
}
_inputTokens.push(inputTokens_[index]);
}
}
// Controlling contract
/**
* @dev Pause a contract, disabling deposit/withdraw/transfer functionality
*/
function pause() external onlyOwner {
_pause();
}
/**
* @dev Unpause a contract, re-enabling deposit/withdraw/transfer functionality
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @dev a limit on how much all users can deposit in total into this vault
*/
function depositCap() external view returns (uint256) {
return _depositCap;
}
/**
* @dev Update the limit on how much all users can deposit in total into this vault
*
* @param assetsCap new limit amount
*/
function setDepositCap(uint256 assetsCap) external onlyOwner {
_depositCap = assetsCap;
}
/**
* @dev Vaults total assets using asset as currency
*/
function totalAssets() public view override returns (uint256) {
return _totalAssets;
}
/**
* @dev Update vaults total assets
*
* Allows admin to increase total assets in case it generated some yield
*
* and there is no more 1-1 ratio between asset and share.
*
*
* @param assetsDelta incremental update amount of total assets
*/
function updateTotalAssets(int96 assetsDelta) external onlyOwner {
require(
_totalAssetsLastChange + _totalAssetsChangeCooldown <= block.timestamp,
"Changing total assets is on cooldown"
);
require(
SignedMath.abs(assetsDelta) <= Math.mulDiv(_totalAssets, _totalAssetsMaxSingleChangeFraction, DENOMINATOR),
"Cannot change total assets too much"
);
_totalAssets = uint256(int256(_totalAssets) + assetsDelta);
_totalAssetsLastChange = block.timestamp;
emit TotalAssetsUpdated(msg.sender, assetsDelta, _totalAssets);
}
/**
* @dev List tokens that vault accepts as input
*/
function inputTokens() public view returns (InputToken[] memory) {
return _inputTokens;
}
/**
* @dev Add new input token
*
* Allows admin to enable new token as input token, e.g. as token used to deposit
*
* @param inputToken new token description
*/
function addInputToken(InputToken memory inputToken) external onlyOwner {
if (inputToken.priceOracle == address(0)) {
require(inputToken.perOneAsset > 0, "perOneAsset cannot be zero");
}
_inputTokens.push(inputToken);
}
/**
* @dev Set input token
*
* Allows admin to update input token, for example changing its perOneAsset factor.
* Can be also used to disable token by settings its address to address(0).
*
* @param index position of token in _inputToken array to update
* @param inputToken updated token description
*/
function setInputToken(uint32 index, InputToken memory inputToken) external onlyOwner {
if (index == 0) {
require(inputToken.token == asset(), "First input token should be same as asset");
}
if (inputToken.priceOracle == address(0)) {
require(inputToken.perOneAsset > 0, "perOneAsset cannot be zero");
}
_inputTokens[index] = inputToken;
}
// Transfer
/**
* @dev See {IERC20-transferFrom}.
*
* Ovveriden here to add `whenNotPaused` modifier.
*/
function transferFrom(address from, address to, uint256 value)
public
override(ERC20, IERC20)
whenNotPaused
returns (bool)
{
return super.transferFrom(from, to, value);
}
/**
* @dev See {IERC20-transfer}.
*
* Ovveriden here to add `whenNotPaused` modifier.
*/
function transfer(address to, uint256 value) public override(ERC20, IERC20) whenNotPaused returns (bool) {
return super.transfer(to, value);
}
// Deposit
function depositByToken(address token, uint256 amount, address receiver) public whenNotPaused returns (uint256) {
require(address(token) != address(0), "token address cannot be zero address");
for (uint256 index = 0; index < _inputTokens.length;) {
if (_inputTokens[index].token == token) {
uint256 perOneAsset;
if (_inputTokens[index].priceOracle != address(0)) {
perOneAsset = PricingOracle(_inputTokens[index].priceOracle).getPrice(asset(), token);
} else {
perOneAsset = _inputTokens[index].perOneAsset;
}
uint256 assets = Math.mulDiv(amount, DENOMINATOR, perOneAsset);
uint256 shares = _convertToShares(assets, Math.Rounding.Trunc);
_depositByToken(_msgSender(), token, amount, receiver, assets, shares);
return shares;
}
unchecked {
++index;
}
}
revert("This input token is not supported");
}
/**
* @dev See {IERC4626-deposit}.
*
* Overridden here to disable
*/
function deposit(uint256 assets, address receiver) public override whenNotPaused returns (uint256) {
return depositByToken(asset(), assets, receiver);
}
/**
* @dev See {IERC4626-mint}.
*
* Overridden here to disable
*/
function mint(uint256, address) public view override whenNotPaused returns (uint256) {
revert("Minting is disabled, use depositByToken");
}
/**
* @dev Deposit/mint common workflow.
*
* Almost same as base ER4626 version, but transfers funds directly to owner and updates
* total assets.
*/
function _depositByToken(
address caller,
address token,
uint256 tokenAmount,
address receiver,
uint256 assets,
uint256 shares
) internal {
// If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
if (_depositCap != 0) {
require(totalAssets() + assets <= _depositCap, "Deposit more then Cap");
}
require(shares != 0, "Deposit too small to generate any shares");
SafeERC20.safeTransferFrom(IERC20(token), caller, owner(), tokenAmount);
_mint(receiver, shares);
_totalAssets += assets;
emit Deposit(caller, receiver, assets, shares);
}
// Withdraw
/**
* @dev Request a redeem (withdrawal) from the vault
*
* This function is accept amount in term of shares as asset amount is fixed
* when request is confirmed by admin. This allows user to collect yield (but not time-shares)
* during withdrawal.
*
* @param shares amount of the shares to withdraw
* @param controller an address that will control the withdrawal (e.g. claim the withdrawal)
* @param owner owner of the shares
*/
function requestRedeem(uint256 shares, address controller, address owner)
external
whenNotPaused
returns (uint256 requestId)
{
if (msg.sender != owner) {
_spendAllowance(owner, msg.sender, shares);
}
_transfer(owner, address(this), shares);
pendingRedeemSharesRequest[controller] += shares;
emit RedeemRequest(controller, owner, 0, msg.sender, shares);
return 0;
}
struct ClaimableAmounts {
address controller;
uint256 shares;
}
/**
* @dev Mark a redeem withdrawal as claimable by admin.
*
* This call marks request as ready and locks funds for the withdrawal.
*
* @param amounts list of share amounts per controller to confirm to be withdrawen.
*/
function makeRequestsClaimable(ClaimableAmounts[] calldata amounts) external onlyOwner {
uint256 totalAssetsForWithdrawal = 0;
for (uint32 index = 0; index < amounts.length;) {
uint256 assets = convertToAssets(amounts[index].shares);
_burn(address(this), amounts[index].shares);
_totalAssets -= assets;
pendingRedeemSharesRequest[amounts[index].controller] -= amounts[index].shares;
claimableRedeemAssetsRequest[amounts[index].controller] += assets;
totalAssetsForWithdrawal += assets;
unchecked {
++index;
}
}
// Call third-party contract after all changes is done
// See https://fravoll.github.io/solidity-patterns/checks_effects_interactions.html
SafeERC20.safeTransferFrom(IERC20(asset()), owner(), address(this), totalAssetsForWithdrawal);
}
/**
* @dev Get amount of shares user request to withdraw that still not approved by owner
*
* For example, If user requested to withdraw 3 vault-ETH, and owner approved 1 vault-ETH to be claimed,
* this will return 2 vault-ETH as it is 3 - 1.
*
* @notice As this implmenetation of ERC-7540 doesnt use requestIds, first argument is unused.
*
* @param controller the controller of withdrawal request. Most of the time this is just user address
*/
function pendingRedeemRequest(uint256, address controller) external view returns (uint256 shares) {
return pendingRedeemSharesRequest[controller];
}
/**
* @dev Get amount of shares user can withdraw that is approved by admin
*
* For example, If user requested to withdraw 3 vault-ETH, and admin approved 1 vault-ETH to be claimed,
* this will return 1 vault-ETH.
*
* Note that amount is fixed in assets, so this value can change if shares to asset rate changes.
* Please use claimableRedeemRequestAsAssets() to receive fixed value.
*
* @notice As this implmenetation of ERC-7540 doesnt use requestIds, first argument is unused.
*
* @param controller the controller of withdrawal request. Most of the time this is just user address
*/
function claimableRedeemRequest(uint256, address controller) public view returns (uint256 shares) {
return convertToShares(claimableRedeemAssetsRequest[controller]);
}
/**
* @dev Get amount of assets user can withdraw that is approved by admin
*
* For example, If user requested to withdraw 3 vault-ETH, and admin approved 1 vault-ETH to be claimed,
* this will return 1 ETH.
*
* @notice As this implmenetation of ERC-7540 doesnt use requestIds, first argument is unused.
*
* @param controller the controller of withdrawal request. Most of the time this is just user address
*/
function claimableRedeemRequestAsAssets(uint256, address controller) public view returns (uint256 shares) {
return claimableRedeemAssetsRequest[controller];
}
mapping(address => mapping(address => bool)) operators;
/**
* @dev Check if given address is registered as operator for given controller
*
* This functionality is part of ERC-7540, allowing to give permissions on withdrawal to different addresses.
*
* @param controller the controller of withdrawal request.
* @param operator the operator of withdrawal request, e.g. address that will execure claim txn.
*/
function isOperator(address controller, address operator) public view returns (bool) {
return operators[controller][operator];
}
/**
* @dev (Un)register an address as operator for controller
*
* This functionality is part of ERC-7540, allowing to give permissions on withdrawal to different addresses.
*
* @param operator the operator of withdrawal request, e.g. address that will execure claim txn.
* @param approved boolean flag, should be address registered or unregistered.
*/
function setOperator(address operator, bool approved) external returns (bool) {
operators[msg.sender][operator] = approved;
return true;
}
/**
* @dev Max amount given address can withdraw in asset as currency
*
* @param owner the controller of withdrawal request. Called owner here as it is part of ERC-4626
*/
function maxWithdraw(address owner) public view override returns (uint256) {
return claimableRedeemRequestAsAssets(0, owner);
}
/**
* @dev Max amount given address can withdraw in shares as currency
*
* @param owner the controller of withdrawal request. Called owner here as it is part of ERC-4626
*/
function maxRedeem(address owner) public view override returns (uint256) {
return claimableRedeemRequest(0, owner);
}
/**
* @dev Redeem is disabled as shares depends on totalAssets, and also can only be calculated
* from fixed assets amount approved by admin. To avoid bad UX we force user to use
* withdraw() instead
*/
function redeem(uint256, address, address) public pure override returns (uint256) {
revert("Redeem is disabled. Use withdraw instead");
}
/**
* @dev Execute (claim) a withdraw
*
* This function transfers locked claimable withdraw to user who request withdrawal
*
* @param caller a caller of this transaction
* @param receiver an address to received withdrawed funds
* @param owner he controller of withdrawal request. Called owner here as it is part of ERC-4626
* @param assets amount of assets to withdraw. Corresponds to shares using current exchange rate
* @param shares amount of shares to withdraw. Corresponds to assets using current exchange rate
*/
function _withdraw(address caller, address receiver, address owner, uint256 assets, uint256 shares)
internal
override
whenNotPaused
{
if (caller != owner && !isOperator(owner, caller)) {
revert("Not an operator");
}
claimableRedeemAssetsRequest[owner] -= assets;
SafeERC20.safeTransfer(IERC20(asset()), receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
/**
* @dev Cancel a redeem (withdrawal) from the vault
*
* @param shares amount of the shares to withdraw
* @param controller an address that controls the withdrawal
* @param receiver an address to receive shares back
*/
function cancelRedeem(uint256 shares, address controller, address receiver) external whenNotPaused {
if (msg.sender != controller && !isOperator(controller, msg.sender)) {
revert("Not an operator");
}
require(shares <= pendingRedeemSharesRequest[controller], "Canceling more then requested");
_transfer(address(this), receiver, shares);
pendingRedeemSharesRequest[controller] -= shares;
emit RedeemCanceled(controller, receiver, 0, msg.sender, shares);
}
}
ERC20.sol 316 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.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 ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*/
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}.
*
* All two of these 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;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
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;
}
/**
* @dev See {IERC20-allowance}.
*/
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}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* 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:
* ```
* 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);
}
}
}
}
ERC4626.sol 286 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/ERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20, IERC20Metadata, ERC20} from "../ERC20.sol";
import {SafeERC20} from "../utils/SafeERC20.sol";
import {IERC4626} from "../../../interfaces/IERC4626.sol";
import {Math} from "../../../utils/math/Math.sol";
/**
* @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in
* https://eips.ethereum.org/EIPS/eip-4626[EIP-4626].
*
* This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for
* underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends
* the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this
* contract and not the "assets" token which is an independent contract.
*
* [CAUTION]
* ====
* In empty (or nearly empty) ERC-4626 vaults, deposits are at high risk of being stolen through frontrunning
* with a "donation" to the vault that inflates the price of a share. This is variously known as a donation or inflation
* attack and is essentially a problem of slippage. Vault deployers can protect against this attack by making an initial
* deposit of a non-trivial amount of the asset, such that price manipulation becomes infeasible. Withdrawals may
* similarly be affected by slippage. Users can protect against this attack as well as unexpected slippage in general by
* verifying the amount received is as expected, using a wrapper that performs these checks such as
* https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router].
*
* Since v4.9, this implementation uses virtual assets and shares to mitigate that risk. The `_decimalsOffset()`
* corresponds to an offset in the decimal representation between the underlying asset's decimals and the vault
* decimals. This offset also determines the rate of virtual shares to virtual assets in the vault, which itself
* determines the initial exchange rate. While not fully preventing the attack, analysis shows that the default offset
* (0) makes it non-profitable, as a result of the value being captured by the virtual shares (out of the attacker's
* donation) matching the attacker's expected gains. With a larger offset, the attack becomes orders of magnitude more
* expensive than it is profitable. More details about the underlying math can be found
* xref:erc4626.adoc#inflation-attack[here].
*
* The drawback of this approach is that the virtual shares do capture (a very small) part of the value being accrued
* to the vault. Also, if the vault experiences losses, the users try to exit the vault, the virtual shares and assets
* will cause the first user to exit to experience reduced losses in detriment to the last users that will experience
* bigger losses. Developers willing to revert back to the pre-v4.9 behavior just need to override the
* `_convertToShares` and `_convertToAssets` functions.
*
* To learn more, check out our xref:ROOT:erc4626.adoc[ERC-4626 guide].
* ====
*/
abstract contract ERC4626 is ERC20, IERC4626 {
using Math for uint256;
IERC20 private immutable _asset;
uint8 private immutable _underlyingDecimals;
/**
* @dev Attempted to deposit more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxDeposit(address receiver, uint256 assets, uint256 max);
/**
* @dev Attempted to mint more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxMint(address receiver, uint256 shares, uint256 max);
/**
* @dev Attempted to withdraw more assets than the max amount for `receiver`.
*/
error ERC4626ExceededMaxWithdraw(address owner, uint256 assets, uint256 max);
/**
* @dev Attempted to redeem more shares than the max amount for `receiver`.
*/
error ERC4626ExceededMaxRedeem(address owner, uint256 shares, uint256 max);
/**
* @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777).
*/
constructor(IERC20 asset_) {
(bool success, uint8 assetDecimals) = _tryGetAssetDecimals(asset_);
_underlyingDecimals = success ? assetDecimals : 18;
_asset = asset_;
}
/**
* @dev Attempts to fetch the asset decimals. A return value of false indicates that the attempt failed in some way.
*/
function _tryGetAssetDecimals(IERC20 asset_) private view returns (bool, uint8) {
(bool success, bytes memory encodedDecimals) = address(asset_).staticcall(
abi.encodeCall(IERC20Metadata.decimals, ())
);
if (success && encodedDecimals.length >= 32) {
uint256 returnedDecimals = abi.decode(encodedDecimals, (uint256));
if (returnedDecimals <= type(uint8).max) {
return (true, uint8(returnedDecimals));
}
}
return (false, 0);
}
/**
* @dev Decimals are computed by adding the decimal offset on top of the underlying asset's decimals. This
* "original" value is cached during construction of the vault contract. If this read operation fails (e.g., the
* asset has not been created yet), a default of 18 is used to represent the underlying asset's decimals.
*
* See {IERC20Metadata-decimals}.
*/
function decimals() public view virtual override(IERC20Metadata, ERC20) returns (uint8) {
return _underlyingDecimals + _decimalsOffset();
}
/** @dev See {IERC4626-asset}. */
function asset() public view virtual returns (address) {
return address(_asset);
}
/** @dev See {IERC4626-totalAssets}. */
function totalAssets() public view virtual returns (uint256) {
return _asset.balanceOf(address(this));
}
/** @dev See {IERC4626-convertToShares}. */
function convertToShares(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-convertToAssets}. */
function convertToAssets(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxDeposit}. */
function maxDeposit(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxMint}. */
function maxMint(address) public view virtual returns (uint256) {
return type(uint256).max;
}
/** @dev See {IERC4626-maxWithdraw}. */
function maxWithdraw(address owner) public view virtual returns (uint256) {
return _convertToAssets(balanceOf(owner), Math.Rounding.Floor);
}
/** @dev See {IERC4626-maxRedeem}. */
function maxRedeem(address owner) public view virtual returns (uint256) {
return balanceOf(owner);
}
/** @dev See {IERC4626-previewDeposit}. */
function previewDeposit(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Floor);
}
/** @dev See {IERC4626-previewMint}. */
function previewMint(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewWithdraw}. */
function previewWithdraw(uint256 assets) public view virtual returns (uint256) {
return _convertToShares(assets, Math.Rounding.Ceil);
}
/** @dev See {IERC4626-previewRedeem}. */
function previewRedeem(uint256 shares) public view virtual returns (uint256) {
return _convertToAssets(shares, Math.Rounding.Floor);
}
/** @dev See {IERC4626-deposit}. */
function deposit(uint256 assets, address receiver) public virtual returns (uint256) {
uint256 maxAssets = maxDeposit(receiver);
if (assets > maxAssets) {
revert ERC4626ExceededMaxDeposit(receiver, assets, maxAssets);
}
uint256 shares = previewDeposit(assets);
_deposit(_msgSender(), receiver, assets, shares);
return shares;
}
/** @dev See {IERC4626-mint}.
*
* As opposed to {deposit}, minting is allowed even if the vault is in a state where the price of a share is zero.
* In this case, the shares will be minted without requiring any assets to be deposited.
*/
function mint(uint256 shares, address receiver) public virtual returns (uint256) {
uint256 maxShares = maxMint(receiver);
if (shares > maxShares) {
revert ERC4626ExceededMaxMint(receiver, shares, maxShares);
}
uint256 assets = previewMint(shares);
_deposit(_msgSender(), receiver, assets, shares);
return assets;
}
/** @dev See {IERC4626-withdraw}. */
function withdraw(uint256 assets, address receiver, address owner) public virtual returns (uint256) {
uint256 maxAssets = maxWithdraw(owner);
if (assets > maxAssets) {
revert ERC4626ExceededMaxWithdraw(owner, assets, maxAssets);
}
uint256 shares = previewWithdraw(assets);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return shares;
}
/** @dev See {IERC4626-redeem}. */
function redeem(uint256 shares, address receiver, address owner) public virtual returns (uint256) {
uint256 maxShares = maxRedeem(owner);
if (shares > maxShares) {
revert ERC4626ExceededMaxRedeem(owner, shares, maxShares);
}
uint256 assets = previewRedeem(shares);
_withdraw(_msgSender(), receiver, owner, assets, shares);
return assets;
}
/**
* @dev Internal conversion function (from assets to shares) with support for rounding direction.
*/
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256) {
return assets.mulDiv(totalSupply() + 10 ** _decimalsOffset(), totalAssets() + 1, rounding);
}
/**
* @dev Internal conversion function (from shares to assets) with support for rounding direction.
*/
function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256) {
return shares.mulDiv(totalAssets() + 1, totalSupply() + 10 ** _decimalsOffset(), rounding);
}
/**
* @dev Deposit/mint common workflow.
*/
function _deposit(address caller, address receiver, uint256 assets, uint256 shares) internal virtual {
// If _asset is ERC777, `transferFrom` can trigger a reentrancy BEFORE the transfer happens through the
// `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the
// assets are transferred and before the shares are minted, which is a valid state.
// slither-disable-next-line reentrancy-no-eth
SafeERC20.safeTransferFrom(_asset, caller, address(this), assets);
_mint(receiver, shares);
emit Deposit(caller, receiver, assets, shares);
}
/**
* @dev Withdraw/redeem common workflow.
*/
function _withdraw(
address caller,
address receiver,
address owner,
uint256 assets,
uint256 shares
) internal virtual {
if (caller != owner) {
_spendAllowance(owner, caller, shares);
}
// If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the
// `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer,
// calls the vault, which is assumed not malicious.
//
// Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the
// shares are burned and after the assets are transferred, which is a valid state.
_burn(owner, shares);
SafeERC20.safeTransfer(_asset, receiver, assets);
emit Withdraw(caller, receiver, owner, assets, shares);
}
function _decimalsOffset() internal view virtual returns (uint8) {
return 0;
}
}
Ownable.sol 100 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is set to the address provided by the deployer. This can
* later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
/**
* @dev The caller account is not authorized to perform an operation.
*/
error OwnableUnauthorizedAccount(address account);
/**
* @dev The owner is not a valid owner account. (eg. `address(0)`)
*/
error OwnableInvalidOwner(address owner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the address provided by the deployer as the initial owner.
*/
constructor(address initialOwner) {
if (initialOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(initialOwner);
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
if (owner() != _msgSender()) {
revert OwnableUnauthorizedAccount(_msgSender());
}
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
if (newOwner == address(0)) {
revert OwnableInvalidOwner(address(0));
}
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
SafeERC20.sol 118 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
import {IERC20Permit} from "../extensions/IERC20Permit.sol";
import {Address} from "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
/**
* @dev An operation with an ERC20 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 Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(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.
*/
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.
*/
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 Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data);
if (returndata.length != 0 && !abi.decode(returndata, (bool))) {
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 silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && address(token).code.length > 0;
}
}
Math.sol 415 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/Math.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Muldiv operation overflow.
*/
error MathOverflowedMulDiv();
enum Rounding {
Floor, // Toward negative infinity
Ceil, // Toward positive infinity
Trunc, // Toward zero
Expand // Away from zero
}
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the subtraction of two unsigned integers, with an overflow flag.
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return 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.
return a / b;
}
// (a + b - 1) / b can overflow on addition, so we distribute.
return a == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or
* denominator == 0.
* @dev 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 {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0 = x * y; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 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 prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (denominator <= prod1) {
revert MathOverflowedMulDiv();
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, 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 {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
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^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// 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^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice 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) {
uint256 result = mulDiv(x, y, denominator);
if (unsignedRoundsUp(rounding) && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded
* towards zero.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice 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 + (unsignedRoundsUp(rounding) && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2 of a positive value rounded towards zero.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (unsignedRoundsUp(rounding) && 1 << result < value ? 1 : 0);
}
}
/**
* @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 + (unsignedRoundsUp(rounding) && 10 ** result < value ? 1 : 0);
}
}
/**
* @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 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @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 + (unsignedRoundsUp(rounding) && 1 << (result << 3) < value ? 1 : 0);
}
}
/**
* @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;
}
}
SignedMath.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
Pausable.sol 119 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Pausable.sol)
pragma solidity ^0.8.20;
import {Context} from "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
bool private _paused;
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
/**
* @dev The operation failed because the contract is paused.
*/
error EnforcedPause();
/**
* @dev The operation failed because the contract is not paused.
*/
error ExpectedPause();
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
if (paused()) {
revert EnforcedPause();
}
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
if (!paused()) {
revert ExpectedPause();
}
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
Strings.sol 94 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Strings.sol)
pragma solidity ^0.8.20;
import {Math} from "./math/Math.sol";
import {SignedMath} from "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant HEX_DIGITS = "0123456789abcdef";
uint8 private constant ADDRESS_LENGTH = 20;
/**
* @dev The `value` string doesn't fit in the specified `length`.
*/
error StringsInsufficientHexLength(uint256 value, uint256 length);
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), HEX_DIGITS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toStringSigned(int256 value) internal pure returns (string memory) {
return string.concat(value < 0 ? "-" : "", toString(SignedMath.abs(value)));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
uint256 localValue = value;
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = HEX_DIGITS[localValue & 0xf];
localValue >>= 4;
}
if (localValue != 0) {
revert StringsInsufficientHexLength(value, length);
}
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal
* representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return bytes(a).length == bytes(b).length && keccak256(bytes(a)) == keccak256(bytes(b));
}
}
Ownable2Step.sol 59 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable2Step.sol)
pragma solidity ^0.8.20;
import {Ownable} from "./Ownable.sol";
/**
* @dev Contract module which provides access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* The initial owner is specified at deployment time in the constructor for `Ownable`. This
* can later be changed with {transferOwnership} and {acceptOwnership}.
*
* This module is used through inheritance. It will make available all functions
* from parent (Ownable).
*/
abstract contract Ownable2Step is Ownable {
address private _pendingOwner;
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Returns the address of the pending owner.
*/
function pendingOwner() public view virtual returns (address) {
return _pendingOwner;
}
/**
* @dev Starts the ownership transfer of the contract to a new account. Replaces the pending transfer if there is one.
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual override onlyOwner {
_pendingOwner = newOwner;
emit OwnershipTransferStarted(owner(), newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`) and deletes any pending owner.
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual override {
delete _pendingOwner;
super._transferOwnership(newOwner);
}
/**
* @dev The new owner accepts the ownership transfer.
*/
function acceptOwnership() public virtual {
address sender = _msgSender();
if (pendingOwner() != sender) {
revert OwnableUnauthorizedAccount(sender);
}
_transferOwnership(sender);
}
}
IERC20.sol 79 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the 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.0.0) (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 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.0.0) (interfaces/draft-IERC6093.sol)
pragma solidity ^0.8.20;
/**
* @dev Standard ERC20 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC20 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 ERC721 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC721 tokens.
*/
interface IERC721Errors {
/**
* @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in EIP-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 ERC1155 Errors
* Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC1155 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);
}
IERC4626.sol 230 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (interfaces/IERC4626.sol)
pragma solidity ^0.8.20;
import {IERC20} from "../token/ERC20/IERC20.sol";
import {IERC20Metadata} from "../token/ERC20/extensions/IERC20Metadata.sol";
/**
* @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in
* https://eips.ethereum.org/EIPS/eip-4626[ERC-4626].
*/
interface IERC4626 is IERC20, IERC20Metadata {
event Deposit(address indexed sender, address indexed owner, uint256 assets, uint256 shares);
event Withdraw(
address indexed sender,
address indexed receiver,
address indexed owner,
uint256 assets,
uint256 shares
);
/**
* @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing.
*
* - MUST be an ERC-20 token contract.
* - MUST NOT revert.
*/
function asset() external view returns (address assetTokenAddress);
/**
* @dev Returns the total amount of the underlying asset that is “managed” by Vault.
*
* - SHOULD include any compounding that occurs from yield.
* - MUST be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT revert.
*/
function totalAssets() external view returns (uint256 totalManagedAssets);
/**
* @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToShares(uint256 assets) external view returns (uint256 shares);
/**
* @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal
* scenario where all the conditions are met.
*
* - MUST NOT be inclusive of any fees that are charged against assets in the Vault.
* - MUST NOT show any variations depending on the caller.
* - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange.
* - MUST NOT revert.
*
* NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the
* “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and
* from.
*/
function convertToAssets(uint256 shares) external view returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver,
* through a deposit call.
*
* - MUST return a limited value if receiver is subject to some deposit limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited.
* - MUST NOT revert.
*/
function maxDeposit(address receiver) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit
* call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called
* in the same transaction.
* - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the
* deposit would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewDeposit(uint256 assets) external view returns (uint256 shares);
/**
* @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* deposit execution, and are accounted for during deposit.
* - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function deposit(uint256 assets, address receiver) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call.
* - MUST return a limited value if receiver is subject to some mint limit.
* - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted.
* - MUST NOT revert.
*/
function maxMint(address receiver) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given
* current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call
* in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the
* same transaction.
* - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint
* would be accepted, regardless if the user has enough tokens approved, etc.
* - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by minting.
*/
function previewMint(uint256 shares) external view returns (uint256 assets);
/**
* @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens.
*
* - MUST emit the Deposit event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint
* execution, and are accounted for during mint.
* - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not
* approving enough underlying tokens to the Vault contract, etc).
*
* NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token.
*/
function mint(uint256 shares, address receiver) external returns (uint256 assets);
/**
* @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the
* Vault, through a withdraw call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxWithdraw(address owner) external view returns (uint256 maxAssets);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw
* call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if
* called
* in the same transaction.
* - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though
* the withdrawal would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by depositing.
*/
function previewWithdraw(uint256 assets) external view returns (uint256 shares);
/**
* @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* withdraw execution, and are accounted for during withdraw.
* - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function withdraw(uint256 assets, address receiver, address owner) external returns (uint256 shares);
/**
* @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault,
* through a redeem call.
*
* - MUST return a limited value if owner is subject to some withdrawal limit or timelock.
* - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock.
* - MUST NOT revert.
*/
function maxRedeem(address owner) external view returns (uint256 maxShares);
/**
* @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block,
* given current on-chain conditions.
*
* - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call
* in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the
* same transaction.
* - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the
* redemption would be accepted, regardless if the user has enough shares, etc.
* - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees.
* - MUST NOT revert.
*
* NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in
* share price or some other type of condition, meaning the depositor will lose assets by redeeming.
*/
function previewRedeem(uint256 shares) external view returns (uint256 assets);
/**
* @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver.
*
* - MUST emit the Withdraw event.
* - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the
* redeem execution, and are accounted for during redeem.
* - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner
* not having enough shares, etc).
*
* NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed.
* Those methods should be performed separately.
*/
function redeem(uint256 shares, address receiver, address owner) external returns (uint256 assets);
}
IERC20Permit.sol 90 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.20;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* ==== Security Considerations
*
* There are two important considerations concerning the use of `permit`. The first is that a valid permit signature
* expresses an allowance, and it should not be assumed to convey additional meaning. In particular, it should not be
* considered as an intention to spend the allowance in any specific way. The second is that because permits have
* built-in replay protection and can be submitted by anyone, they can be frontrun. A protocol that uses permits should
* take this into consideration and allow a `permit` call to fail. Combining these two aspects, a pattern that may be
* generally recommended is:
*
* ```solidity
* function doThingWithPermit(..., uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public {
* try token.permit(msg.sender, address(this), value, deadline, v, r, s) {} catch {}
* doThing(..., value);
* }
*
* function doThing(..., uint256 value) public {
* token.safeTransferFrom(msg.sender, address(this), value);
* ...
* }
* ```
*
* Observe that: 1) `msg.sender` is used as the owner, leaving no ambiguity as to the signer intent, and 2) the use of
* `try/catch` allows the permit to fail and makes the code tolerant to frontrunning. (See also
* {SafeERC20-safeTransferFrom}).
*
* Additionally, note that smart contract wallets (such as Argent or Safe) are not able to produce permit signatures, so
* contracts should have entry points that don't rely on permit.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*
* CAUTION: See Security Considerations above.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
Address.sol 159 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v5.0.0) (utils/Address.sol)
pragma solidity ^0.8.20;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev The ETH balance of the account is not enough to perform the operation.
*/
error AddressInsufficientBalance(address account);
/**
* @dev There's no code at `target` (it is not a contract).
*/
error AddressEmptyCode(address target);
/**
* @dev A call to an address target failed. The target may have reverted.
*/
error FailedInnerCall();
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.20/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
if (address(this).balance < amount) {
revert AddressInsufficientBalance(address(this));
}
(bool success, ) = recipient.call{value: amount}("");
if (!success) {
revert FailedInnerCall();
}
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason or custom error, it is bubbled
* up by this function (like regular Solidity function calls). However, if
* the call reverted with no returned reason, this function reverts with a
* {FailedInnerCall} error.
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
if (address(this).balance < value) {
revert AddressInsufficientBalance(address(this));
}
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and reverts if the target
* was not a contract or bubbling up the revert reason (falling back to {FailedInnerCall}) in case of an
* unsuccessful call.
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata
) internal view returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
// only check if target is a contract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
if (returndata.length == 0 && target.code.length == 0) {
revert AddressEmptyCode(target);
}
return returndata;
}
}
/**
* @dev Tool to verify that a low level call was successful, and reverts if it wasn't, either by bubbling the
* revert reason or with a default {FailedInnerCall} error.
*/
function verifyCallResult(bool success, bytes memory returndata) internal pure returns (bytes memory) {
if (!success) {
_revert(returndata);
} else {
return returndata;
}
}
/**
* @dev Reverts with returndata if present. Otherwise reverts with {FailedInnerCall}.
*/
function _revert(bytes memory returndata) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert FailedInnerCall();
}
}
}
Read Contract
allowance 0xdd62ed3e → uint256
asset 0x38d52e0f → address
balanceOf 0x70a08231 → uint256
claimableRedeemAssetsRequest 0x91ac6a06 → uint256
claimableRedeemRequest 0xeaed1d07 → uint256
claimableRedeemRequestAsAssets 0xfd896f9e → uint256
convertToAssets 0x07a2d13a → uint256
convertToShares 0xc6e6f592 → uint256
decimals 0x313ce567 → uint8
depositCap 0xdbd5edc7 → uint256
inputTokens 0x9fe8eecd → tuple[]
isOperator 0xb6363cf2 → bool
maxDeposit 0x402d267d → uint256
maxMint 0xc63d75b6 → uint256
maxRedeem 0xd905777e → uint256
maxWithdraw 0xce96cb77 → uint256
mint 0x94bf804d → uint256
name 0x06fdde03 → string
owner 0x8da5cb5b → address
paused 0x5c975abb → bool
pendingOwner 0xe30c3978 → address
pendingRedeemRequest 0xf5a23d8d → uint256
pendingRedeemSharesRequest 0xb90f5084 → uint256
previewDeposit 0xef8b30f7 → uint256
previewMint 0xb3d7f6b9 → uint256
previewRedeem 0x4cdad506 → uint256
previewWithdraw 0x0a28a477 → uint256
redeem 0xba087652 → uint256
symbol 0x95d89b41 → string
totalAssets 0x01e1d114 → uint256
totalSupply 0x18160ddd → uint256
Write Contract 19 functions
These functions modify contract state and require a wallet transaction to execute.
acceptOwnership 0x79ba5097
No parameters
addInputToken 0x571241d0
tuple inputToken
approve 0x095ea7b3
address spender
uint256 value
returns: bool
cancelRedeem 0x4cdac289
uint256 shares
address controller
address receiver
deposit 0x6e553f65
uint256 assets
address receiver
returns: uint256
depositByToken 0x72624857
address token
uint256 amount
address receiver
returns: uint256
makeRequestsClaimable 0x803dcac8
tuple[] amounts
pause 0x8456cb59
No parameters
renounceOwnership 0x715018a6
No parameters
requestRedeem 0x7d41c86e
uint256 shares
address controller
address owner
returns: uint256
setDepositCap 0x86651203
uint256 assetsCap
setInputToken 0xde78a5d4
uint32 index
tuple inputToken
setOperator 0x558a7297
address operator
bool approved
returns: bool
transfer 0xa9059cbb
address to
uint256 value
returns: bool
transferFrom 0x23b872dd
address from
address to
uint256 value
returns: bool
transferOwnership 0xf2fde38b
address newOwner
unpause 0x3f4ba83a
No parameters
updateTotalAssets 0x51f1f5fa
int96 assetsDelta
withdraw 0xb460af94
uint256 assets
address receiver
address owner
returns: uint256
Token Balances (1)
View Transfers →Recent Transactions
No transactions found for this address