Cryo Explorer Ethereum Mainnet

Address Contract Verified

Address 0xD6c68aAc3C46E754cA54a551560ce07cB89dc20b
Balance 0 ETH
Nonce 1
Code Size 13053 bytes
Indexed Transactions 0
External Etherscan · Sourcify

Contract Bytecode

13053 bytes
0x608060405234801561001057600080fd5b50600436106101b95760003560e01c80637e1ac748116100f9578063a67a684311610097578063cd28308511610071578063cd283085146103bb578063d74385d9146103db578063f2fde38b146103ee578063fd47f60f1461040157600080fd5b8063a67a684314610382578063c02486d014610395578063cbf4f651146103a857600080fd5b806384ba3f69116100d357806384ba3f69146103245780638da5cb5b1461033757806391b694fc1461035c5780639a59b9bd1461036f57600080fd5b80637e1ac748146102e95780637eb11c63146102fe578063843a3b501461031157600080fd5b8063313ce5671161016657806365b4c6e11161014057806365b4c6e1146102a8578063695ee9ae146102bb578063715018a6146102ce5780637b160cf5146102d657600080fd5b8063313ce56714610254578063329aac801461028d57806356cdeb0b1461029557600080fd5b80630983b122116101975780630983b1221461021b5780631f96b34e1461022c5780632b6173b51461024157600080fd5b806304330676146101be578063047d3ee7146101e757806304b3953414610208575b600080fd5b6101d16101cc3660046123a5565b610414565b6040516101de91906123e7565b60405180910390f35b6101fa6101f536600461246d565b61056e565b6040519081526020016101de565b6101fa6102163660046124fb565b610638565b6101fa610229366004612546565b90565b61023f61023a36600461255f565b61071d565b005b6101fa61024f3660046125b4565b61079d565b61027b7f000000000000000000000000000000000000000000000000000000000000001e81565b60405160ff90911681526020016101de565b6101fa6107ae565b6101fa6102a336600461246d565b6107bf565b6101fa6102b63660046125df565b61082b565b6101fa6102c93660046125b4565b610966565b61023f610a01565b61023f6102e43660046123a5565b610a15565b6102f1610b0e565b6040516101de919061265d565b6101fa61030c3660046125b4565b610b1a565b6101fa61031f366004612670565b610c72565b6101fa6103323660046125b4565b610de4565b6000546001600160a01b03165b6040516001600160a01b0390911681526020016101de565b6101fa61036a3660046125b4565b610e0c565b6101fa61037d3660046125df565b6110f9565b6101fa61039036600461269c565b61115e565b6101fa6103a33660046125b4565b611429565b6101fa6103b63660046126dc565b61164e565b6103ce6103c93660046125b4565b6118aa565b6040516101de919061272e565b6103446103e9366004612546565b611944565b61023f6103fc3660046125b4565b611951565b6101fa61040f3660046125b4565b6119fb565b60608167ffffffffffffffff81111561042f5761042f612761565b604051908082528060200260200182016040528015610458578160200160208202803683370190505b50905060005b82811015610567576105426001600086868581811061047f5761047f612790565b905060200201602081019061049491906125b4565b6001600160a01b03166001600160a01b0316815260200190815260200160002080546104bf906127bf565b80601f01602080910402602001604051908101604052809291908181526020018280546104eb906127bf565b80156105385780601f1061050d57610100808354040283529160200191610538565b820191906000526020600020905b81548152906001019060200180831161051b57829003601f168201915b5050505050611bc3565b82828151811061055457610554612790565b602090810291909101015260010161045e565b5092915050565b60006105af83838080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611bc392505050565b6105da7f000000000000000000000000000000000000000000000000000000000000001e600a612925565b61061987878080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611bc392505050565b6106239190612934565b61062d919061297a565b90505b949350505050565b6000610713846001600160a01b031663c6845a0985856040518363ffffffff1660e01b815260040161066b929190612a1b565b602060405180830381865afa158015610688573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106ac9190612a41565b856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106ea573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061070e9190612a70565b611c73565b90505b9392505050565b610725611d13565b826001600160a01b03167f93fa1ce7e48dfdc05f1ed4d25b05cf97a746916f5b7db908adee4d56082d8fcd8383604051610760929190612a8b565b60405180910390a26001600160a01b038316600090815260016020526040902061078b828483612b0b565b50610797600284611d87565b50505050565b60006107a882610de4565b92915050565b60006107ba6002611d9c565b905090565b60006107ec7f000000000000000000000000000000000000000000000000000000000000001e600a612925565b6105da84848080601f016020809104026020016040519081016040528093929190818152602001838380828437600092019190915250611bc392505050565b600080836001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa15801561086c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108909190612bf0565b50505050505090506106308184866001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa1580156108db573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108ff9190612c88565b876001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa15801561093d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906109619190612c88565b611da6565b60006001600160a01b038216637a28fb886109a27f000000000000000000000000000000000000000000000000000000000000001e600a612925565b6040518263ffffffff1660e01b81526004016109c091815260200190565b602060405180830381865afa1580156109dd573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906107a89190612a41565b610a09611d13565b610a136000612036565b565b610a1d611d13565b3660005b8281101561079757838382818110610a3b57610a3b612790565b9050602002810190610a4d9190612ca5565b9150610a5c60208301836125b4565b6001600160a01b03167f93fa1ce7e48dfdc05f1ed4d25b05cf97a746916f5b7db908adee4d56082d8fcd610a936020850185612ce3565b604051610aa1929190612a8b565b60405180910390a2610ab66020830183612ce3565b60016000610ac760208701876125b4565b6001600160a01b03168152602081019190915260400160002091610aec919083612b0b565b50610b05610afd60208401846125b4565b600290611d87565b50600101610a21565b60606107ba600261209e565b6000808290506000816001600160a01b031663f4325d676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610b60573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b849190612c88565b9050806001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610bc4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610be89190612a70565b610bf390600a612925565b826001600160a01b0316631902848a6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610c31573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c559190612a41565b610c5e83610de4565b610c689190612934565b610630919061297a565b600080839050600080600080846001600160a01b031663feaf968c6040518163ffffffff1660e01b815260040160a060405180830381865afa158015610cbc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ce09190612d62565b9450945050935093508369ffffffffffffffffffff168169ffffffffffffffffffff1611158015610d19575086610d178342612db2565b115b15610d58576040517f38ee04a7000000000000000000000000000000000000000000000000000000008152600481018490526024015b60405180910390fd5b6000831215610d96576040517f38ee04a700000000000000000000000000000000000000000000000000000000815260048101849052602401610d4f565b610dd883866001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa1580156106ea573d6000803e3d6000fd5b98975050505050505050565b6001600160a01b038116600090815260016020526040812080546107a891906104bf906127bf565b600080826001600160a01b0316630dfe16816040518163ffffffff1660e01b8152600401602060405180830381865afa158015610e4d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610e719190612c88565b90506000836001600160a01b031663d21220a76040518163ffffffff1660e01b8152600401602060405180830381865afa158015610eb3573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ed79190612c88565b9050600080856001600160a01b0316631322d9546040518163ffffffff1660e01b81526004016040805180830381865afa158015610f19573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f3d9190612dc5565b915091506000610fc482610f5086610de4565b866001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f8e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fb29190612a70565b610fbd90600a612925565b60006120ab565b61100f84610fd188610de4565b886001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f8e573d6000803e3d6000fd5b6110199190612de9565b90506110ee81886001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561105d573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110819190612a70565b61108c90600a612925565b896001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156110ca573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610fbd9190612a41565b979650505050505050565b600080836001600160a01b0316633850c7bd6040518163ffffffff1660e01b815260040160e060405180830381865afa15801561113a573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906108909190612dfc565b60408051600280825260608201835260009283929190602083019080368337019050509050838160008151811061119757611197612790565b60200260200101906001600160a01b031690816001600160a01b03168152505082816001815181106111cb576111cb612790565b60200260200101906001600160a01b031690816001600160a01b0316815250506000836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561122b573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061124f9190612a70565b90506000856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611291573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906112b59190612a70565b905060006001600160a01b03881663c1b7687b856112d485600a612925565b6040518363ffffffff1660e01b81526004016112f1929190612e78565b600060405180830381865afa15801561130e573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526113369190810190612fef565b90506000611362826080015160008151811061135457611354612790565b602002602001015184611c73565b90506000670de0b6b3a76400008360a0015160008151811061138657611386612790565b6020026020010151836113999190612934565b6113a3919061297a565b905060006113cf84608001516001815181106113c1576113c1612790565b602002602001015187611c73565b90506113db8284612db2565b6114067f000000000000000000000000000000000000000000000000000000000000001e600a612925565b6114109083612934565b61141a919061297a565b9b9a5050505050505050505050565b600080826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa15801561146a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061148e9190612a70565b9050826000806001600160a01b038316638f39a80b6114ae86600a612925565b6040518263ffffffff1660e01b81526004016114cc91815260200190565b600060405180830381865afa1580156114e9573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526115119190810190613110565b91509150600080846001600160a01b0316639d63848a6040518163ffffffff1660e01b8152600401600060405180830381865afa158015611556573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f1916820160405261157e9190810190613174565b915091506000805b83518110156115df576115cb8482815181106115a4576115a4612790565b60200260200101518783815181106115be576115be612790565b602002602001015161213e565b6115d590836131ce565b9150600101611586565b5060005b825181101561162f5761161b83828151811061160157611601612790565b60200260200101518683815181106115be576115be612790565b61162590836131f6565b91506001016115e3565b506000811361163f576000611641565b805b9998505050505050505050565b6000806000846001600160a01b031663f94d4668856001600160a01b03166338fff2d06040518163ffffffff1660e01b8152600401602060405180830381865afa1580156116a0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116c49190612a41565b6040518263ffffffff1660e01b81526004016116e291815260200190565b600060405180830381865afa1580156116ff573d6000803e3d6000fd5b505050506040513d6000823e601f3d908101601f191682016040526117279190810190613216565b50915091506000805b83518110156117f057600084828151811061174d5761174d612790565b60200260200101519050866001600160a01b0316816001600160a01b03160361177657506117e8565b6117da84838151811061178b5761178b612790565b602002602001015161179c83610de4565b836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f8e573d6000803e3d6000fd5b6117e49084612de9565b9250505b600101611730565b506118a081866001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611833573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906118579190612a70565b61186290600a612925565b876001600160a01b031663876f303b6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156110ca573d6000803e3d6000fd5b9695505050505050565b600160205260009081526040902080546118c3906127bf565b80601f01602080910402602001604051908101604052809291908181526020018280546118ef906127bf565b801561193c5780601f106119115761010080835404028352916020019161193c565b820191906000526020600020905b81548152906001019060200180831161191f57829003601f168201915b505050505081565b60006107a860028361218b565b611959611d13565b6001600160a01b0381166119ef576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f64647265737300000000000000000000000000000000000000000000000000006064820152608401610d4f565b6119f881612036565b50565b600080826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611a3c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a609190612a70565b905060008390506000816001600160a01b03166338d52e0f6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611aa7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611acb9190612c88565b90506000816001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b0d573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b319190612a70565b90506118a0611b3f83610de4565b6001600160a01b0385166307a2d13a611b5988600a612925565b6040518263ffffffff1660e01b8152600401611b7791815260200190565b602060405180830381865afa158015611b94573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bb89190612a41565b610fbd84600a612925565b6000806000306001600160a01b031684604051611be09190613283565b600060405180830381855afa9150503d8060008114611c1b576040519150601f19603f3d011682016040523d82523d6000602084013e611c20565b606091505b50915091508115611c3f57808060200190518101906106309190612a41565b836040517f1d07c994000000000000000000000000000000000000000000000000000000008152600401610d4f919061272e565b60007f000000000000000000000000000000000000000000000000000000000000001e60ff168260ff1611611cd457817f000000000000000000000000000000000000000000000000000000000000001e0360ff16600a0a830290506107a8565b7f000000000000000000000000000000000000000000000000000000000000001e820360ff16600a0a8381611d0b57611d0b61294b565b0490506107a8565b6000546001600160a01b03163314610a13576040517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152606401610d4f565b6000610716836001600160a01b038416612197565b60006107a8825490565b60008315611ef5576000826001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611dee573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e129190612a70565b846001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611e50573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611e749190612a70565b611e9e907f000000000000000000000000000000000000000000000000000000000000001e613295565b611ea891906132ae565b611eb390600a612925565b9050611eed611ecb6001600160a01b03881680612934565b82780100000000000000000000000000000000000000000000000060006120ab565b915050610630565b6000836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f35573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f599190612a70565b836001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015611f97573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fbb9190612a70565b611fe5907f000000000000000000000000000000000000000000000000000000000000001e613295565b611fef91906132ae565b611ffa90600a612925565b90506001600160a01b03861661202c7801000000000000000000000000000000000000000000000000838360006120ab565b611eed919061297a565b600080546001600160a01b038381167fffffffffffffffffffffffff0000000000000000000000000000000000000000831681178455604051919092169283917f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e09190a35050565b60606000610716836121e6565b60006120b8858585612242565b905060018260018111156120ce576120ce6129b5565b036106305782806120e1576120e161294b565b84860915610630576000198110156120fb57600101610630565b6040517f63a05778000000000000000000000000000000000000000000000000000000008152600481018690526024810185905260448101849052606401610d4f565b600061071661214c84610de4565b83856001600160a01b031663313ce5676040518163ffffffff1660e01b8152600401602060405180830381865afa158015610f8e573d6000803e3d6000fd5b6000610716838361232f565b60008181526001830160205260408120546121de575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556107a8565b5060006107a8565b60608160000180548060200260200160405190810160405280929190818152602001828054801561223657602002820191906000526020600020905b815481526020019060010190808311612222575b50505050509050919050565b600080806000198587098587029250828110838203039150508060000361227c578382816122725761227261294b565b0492505050610716565b8381106122c6576040517f63a05778000000000000000000000000000000000000000000000000000000008152600481018790526024810186905260448101859052606401610d4f565b60008486880960026001871981018816978890046003810283188082028403028082028403028082028403028082028403028082028403029081029092039091026000889003889004909101858311909403939093029303949094049190911702949350505050565b600082600001828154811061234657612346612790565b9060005260206000200154905092915050565b60008083601f84011261236b57600080fd5b50813567ffffffffffffffff81111561238357600080fd5b6020830191508360208260051b850101111561239e57600080fd5b9250929050565b600080602083850312156123b857600080fd5b823567ffffffffffffffff8111156123cf57600080fd5b6123db85828601612359565b90969095509350505050565b6020808252825182820181905260009190848201906040850190845b8181101561241f57835183529284019291840191600101612403565b50909695505050505050565b60008083601f84011261243d57600080fd5b50813567ffffffffffffffff81111561245557600080fd5b60208301915083602082850101111561239e57600080fd5b6000806000806040858703121561248357600080fd5b843567ffffffffffffffff8082111561249b57600080fd5b6124a78883890161242b565b909650945060208701359150808211156124c057600080fd5b506124cd8782880161242b565b95989497509550505050565b6001600160a01b03811681146119f857600080fd5b600281106119f857600080fd5b60008060006060848603121561251057600080fd5b833561251b816124d9565b9250602084013561252b816124ee565b9150604084013561253b816124ee565b809150509250925092565b60006020828403121561255857600080fd5b5035919050565b60008060006040848603121561257457600080fd5b833561257f816124d9565b9250602084013567ffffffffffffffff81111561259b57600080fd5b6125a78682870161242b565b9497909650939450505050565b6000602082840312156125c657600080fd5b8135610716816124d9565b80151581146119f857600080fd5b600080604083850312156125f257600080fd5b82356125fd816124d9565b9150602083013561260d816125d1565b809150509250929050565b60008151808452602080850194506020840160005b838110156126525781516001600160a01b03168752958201959082019060010161262d565b509495945050505050565b6020815260006107166020830184612618565b6000806040838503121561268357600080fd5b823561268e816124d9565b946020939093013593505050565b6000806000606084860312156126b157600080fd5b83356126bc816124d9565b925060208401356126cc816124d9565b9150604084013561253b816124d9565b600080604083850312156126ef57600080fd5b82356126fa816124d9565b9150602083013561260d816124d9565b60005b8381101561272557818101518382015260200161270d565b50506000910152565b602081526000825180602084015261274d81604085016020870161270a565b601f01601f19169190910160400192915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600181811c908216806127d357607f821691505b60208210810361280c577f4e487b7100000000000000000000000000000000000000000000000000000000600052602260045260246000fd5b50919050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601160045260246000fd5b600181815b8085111561287c57816000190482111561286257612862612812565b8085161561286f57918102915b93841c9390800290612846565b509250929050565b600082612893575060016107a8565b816128a0575060006107a8565b81600181146128b657600281146128c0576128dc565b60019150506107a8565b60ff8411156128d1576128d1612812565b50506001821b6107a8565b5060208310610133831016604e8410600b84101617156128ff575081810a6107a8565b6129098383612841565b806000190482111561291d5761291d612812565b029392505050565b600061071660ff841683612884565b80820281158282048414176107a8576107a8612812565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b6000826129b0577f4e487b7100000000000000000000000000000000000000000000000000000000600052601260045260246000fd5b500490565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b600281106119f8577f4e487b7100000000000000000000000000000000000000000000000000000000600052602160045260246000fd5b60408101612a28846129e4565b838252612a34836129e4565b8260208301529392505050565b600060208284031215612a5357600080fd5b5051919050565b805160ff81168114612a6b57600080fd5b919050565b600060208284031215612a8257600080fd5b61071682612a5a565b60208152816020820152818360408301376000818301604090810191909152601f909201601f19160101919050565b601f821115612b06576000816000526020600020601f850160051c81016020861015612ae35750805b601f850160051c820191505b81811015612b0257828155600101612aef565b5050505b505050565b67ffffffffffffffff831115612b2357612b23612761565b612b3783612b3183546127bf565b83612aba565b6000601f841160018114612b6b5760008515612b535750838201355b600019600387901b1c1916600186901b178355612bc5565b600083815260209020601f19861690835b82811015612b9c5786850135825560209485019460019092019101612b7c565b5086821015612bb95760001960f88860031b161c19848701351681555b505060018560011b0183555b5050505050565b8051600281900b8114612a6b57600080fd5b805161ffff81168114612a6b57600080fd5b600080600080600080600060e0888a031215612c0b57600080fd5b8751612c16816124d9565b9650612c2460208901612bcc565b9550612c3260408901612bde565b9450612c4060608901612bde565b9350612c4e60808901612bde565b925060a088015163ffffffff81168114612c6757600080fd5b60c0890151909250612c78816125d1565b8091505092959891949750929550565b600060208284031215612c9a57600080fd5b8151610716816124d9565b600082357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc1833603018112612cd957600080fd5b9190910192915050565b60008083357fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe1843603018112612d1857600080fd5b83018035915067ffffffffffffffff821115612d3357600080fd5b60200191503681900382131561239e57600080fd5b805169ffffffffffffffffffff81168114612a6b57600080fd5b600080600080600060a08688031215612d7a57600080fd5b612d8386612d48565b9450602086015193506040860151925060608601519150612da660808701612d48565b90509295509295909350565b818103818111156107a8576107a8612812565b60008060408385031215612dd857600080fd5b505080516020909101519092909150565b808201808211156107a8576107a8612812565b600080600080600080600060e0888a031215612e1757600080fd5b8751612e22816124d9565b9650612e3060208901612bcc565b9550612e3e60408901612bde565b9450612e4c60608901612bde565b9350612e5a60808901612bde565b9250612e6860a08901612a5a565b915060c0880151612c78816125d1565b604081526000612e8b6040830185612618565b90508260208301529392505050565b60405160c0810167ffffffffffffffff81118282101715612ebd57612ebd612761565b60405290565b604051601f8201601f1916810167ffffffffffffffff81118282101715612eec57612eec612761565b604052919050565b600067ffffffffffffffff821115612f0e57612f0e612761565b5060051b60200190565b600082601f830112612f2957600080fd5b81516020612f3e612f3983612ef4565b612ec3565b8083825260208201915060208460051b870101935086841115612f6057600080fd5b602086015b84811015612f85578051612f78816124d9565b8352918301918301612f65565b509695505050505050565b600082601f830112612fa157600080fd5b81516020612fb1612f3983612ef4565b8083825260208201915060208460051b870101935086841115612fd357600080fd5b602086015b84811015612f855780518352918301918301612fd8565b60006020828403121561300157600080fd5b815167ffffffffffffffff8082111561301957600080fd5b9083019060c0828603121561302d57600080fd5b613035612e9a565b82518281111561304457600080fd5b61305087828601612f18565b82525060208301518281111561306557600080fd5b61307187828601612f18565b60208301525060408301518281111561308957600080fd5b61309587828601612f90565b6040830152506060830151828111156130ad57600080fd5b6130b987828601612f90565b6060830152506080830151828111156130d157600080fd5b6130dd87828601612f90565b60808301525060a0830151828111156130f557600080fd5b61310187828601612f90565b60a08301525095945050505050565b6000806040838503121561312357600080fd5b825167ffffffffffffffff8082111561313b57600080fd5b61314786838701612f90565b9350602085015191508082111561315d57600080fd5b5061316a85828601612f90565b9150509250929050565b6000806040838503121561318757600080fd5b825167ffffffffffffffff8082111561319f57600080fd5b6131ab86838701612f18565b935060208501519150808211156131c157600080fd5b5061316a85828601612f18565b80820182811260008312801582168215821617156131ee576131ee612812565b505092915050565b818103600083128015838313168383128216171561056757610567612812565b60008060006060848603121561322b57600080fd5b835167ffffffffffffffff8082111561324357600080fd5b61324f87838801612f18565b9450602086015191508082111561326557600080fd5b5061327286828701612f90565b925050604084015190509250925092565b60008251612cd981846020870161270a565b60ff81811683821601908111156107a8576107a8612812565b60ff82811682821603908111156107a8576107a861281256fea26469706673582212208ca78b730cb62aeaf41f85f825769b0ffdbf0424198358a963202fe1f636aac164736f6c63430008160033

Verified Source Code Full Match

Compiler: v0.8.22+commit.4fc1097e EVM: paris Optimization: Yes (9999 runs)
Ownable.sol 83 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../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.
 *
 * By default, the owner account will be the one that deploys the contract. 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;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @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 {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
    }

    /**
     * @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 {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _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);
    }
}
IERC4626.sol 232 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC4626.sol)

pragma solidity ^0.8.0;

import "../token/ERC20/IERC20.sol";
import "../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].
 *
 * _Available since v4.7._
 */
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);
}
ERC20.sol 365 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.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}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * 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.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => 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 override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override 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 override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override 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 `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * NOTE: If `amount` 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 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, amount);
        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 `amount`.
     * - the caller must have allowance for ``from``'s tokens of at least
     * `amount`.
     */
    function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
        address spender = _msgSender();
        _spendAllowance(from, spender, amount);
        _transfer(from, to, amount);
        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        address owner = _msgSender();
        _approve(owner, spender, allowance(owner, spender) + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        address owner = _msgSender();
        uint256 currentAllowance = allowance(owner, spender);
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `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.
     *
     * Requirements:
     *
     * - `from` cannot be the zero address.
     * - `to` cannot be the zero address.
     * - `from` must have a balance of at least `amount`.
     */
    function _transfer(address from, address to, uint256 amount) internal virtual {
        require(from != address(0), "ERC20: transfer from the zero address");
        require(to != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(from, to, amount);

        uint256 fromBalance = _balances[from];
        require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[from] = fromBalance - amount;
            // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
            // decrementing then incrementing.
            _balances[to] += amount;
        }

        emit Transfer(from, to, amount);

        _afterTokenTransfer(from, to, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        unchecked {
            // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
            _balances[account] += amount;
        }
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
            // Overflow not possible: amount <= accountBalance <= totalSupply.
            _totalSupply -= amount;
        }

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` 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.
     */
    function _approve(address owner, address spender, uint256 amount) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Updates `owner` s allowance for `spender` based on spent `amount`.
     *
     * Does not update the allowance amount in case of infinite allowance.
     * Revert if not enough allowance is available.
     *
     * Might emit an {Approval} event.
     */
    function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
        uint256 currentAllowance = allowance(owner, spender);
        if (currentAllowance != type(uint256).max) {
            require(currentAllowance >= amount, "ERC20: insufficient allowance");
            unchecked {
                _approve(owner, spender, currentAllowance - amount);
            }
        }
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
IERC20Metadata.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

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

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

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

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
 * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
 *
 * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
 * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
 * need to send a transaction, and thus is not required to hold Ether at all.
 */
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].
     */
    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);
}
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

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

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

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

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

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

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

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

    /**
     * @dev Moves `amount` tokens from `from` to `to` using the
     * allowance mechanism. `amount` is then deducted from the caller's
     * allowance.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
Context.sol 24 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;

/**
 * @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;
    }
}
EnumerableSet.sol 378 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)
// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.

pragma solidity ^0.8.0;

/**
 * @dev Library for managing
 * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
 * types.
 *
 * Sets have the following properties:
 *
 * - Elements are added, removed, and checked for existence in constant time
 * (O(1)).
 * - Elements are enumerated in O(n). No guarantees are made on the ordering.
 *
 * ```solidity
 * contract Example {
 *     // Add the library methods
 *     using EnumerableSet for EnumerableSet.AddressSet;
 *
 *     // Declare a set state variable
 *     EnumerableSet.AddressSet private mySet;
 * }
 * ```
 *
 * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
 * and `uint256` (`UintSet`) are supported.
 *
 * [WARNING]
 * ====
 * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure
 * unusable.
 * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.
 *
 * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an
 * array of EnumerableSet.
 * ====
 */
library EnumerableSet {
    // To implement this library for multiple types with as little code
    // repetition as possible, we write it in terms of a generic Set type with
    // bytes32 values.
    // The Set implementation uses private functions, and user-facing
    // implementations (such as AddressSet) are just wrappers around the
    // underlying Set.
    // This means that we can only create new EnumerableSets for types that fit
    // in bytes32.

    struct Set {
        // Storage of set values
        bytes32[] _values;
        // Position of the value in the `values` array, plus 1 because index 0
        // means a value is not in the set.
        mapping(bytes32 => uint256) _indexes;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function _add(Set storage set, bytes32 value) private returns (bool) {
        if (!_contains(set, value)) {
            set._values.push(value);
            // The value is stored at length-1, but we add 1 to all indexes
            // and use 0 as a sentinel value
            set._indexes[value] = set._values.length;
            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function _remove(Set storage set, bytes32 value) private returns (bool) {
        // We read and store the value's index to prevent multiple reads from the same storage slot
        uint256 valueIndex = set._indexes[value];

        if (valueIndex != 0) {
            // Equivalent to contains(set, value)
            // To delete an element from the _values array in O(1), we swap the element to delete with the last one in
            // the array, and then remove the last element (sometimes called as 'swap and pop').
            // This modifies the order of the array, as noted in {at}.

            uint256 toDeleteIndex = valueIndex - 1;
            uint256 lastIndex = set._values.length - 1;

            if (lastIndex != toDeleteIndex) {
                bytes32 lastValue = set._values[lastIndex];

                // Move the last value to the index where the value to delete is
                set._values[toDeleteIndex] = lastValue;
                // Update the index for the moved value
                set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex
            }

            // Delete the slot where the moved value was stored
            set._values.pop();

            // Delete the index for the deleted slot
            delete set._indexes[value];

            return true;
        } else {
            return false;
        }
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function _contains(Set storage set, bytes32 value) private view returns (bool) {
        return set._indexes[value] != 0;
    }

    /**
     * @dev Returns the number of values on the set. O(1).
     */
    function _length(Set storage set) private view returns (uint256) {
        return set._values.length;
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function _at(Set storage set, uint256 index) private view returns (bytes32) {
        return set._values[index];
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function _values(Set storage set) private view returns (bytes32[] memory) {
        return set._values;
    }

    // Bytes32Set

    struct Bytes32Set {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _add(set._inner, value);
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
        return _remove(set._inner, value);
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
        return _contains(set._inner, value);
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(Bytes32Set storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
        return _at(set._inner, index);
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
        bytes32[] memory store = _values(set._inner);
        bytes32[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // AddressSet

    struct AddressSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(AddressSet storage set, address value) internal returns (bool) {
        return _add(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(AddressSet storage set, address value) internal returns (bool) {
        return _remove(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(AddressSet storage set, address value) internal view returns (bool) {
        return _contains(set._inner, bytes32(uint256(uint160(value))));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(AddressSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(AddressSet storage set, uint256 index) internal view returns (address) {
        return address(uint160(uint256(_at(set._inner, index))));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(AddressSet storage set) internal view returns (address[] memory) {
        bytes32[] memory store = _values(set._inner);
        address[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }

    // UintSet

    struct UintSet {
        Set _inner;
    }

    /**
     * @dev Add a value to a set. O(1).
     *
     * Returns true if the value was added to the set, that is if it was not
     * already present.
     */
    function add(UintSet storage set, uint256 value) internal returns (bool) {
        return _add(set._inner, bytes32(value));
    }

    /**
     * @dev Removes a value from a set. O(1).
     *
     * Returns true if the value was removed from the set, that is if it was
     * present.
     */
    function remove(UintSet storage set, uint256 value) internal returns (bool) {
        return _remove(set._inner, bytes32(value));
    }

    /**
     * @dev Returns true if the value is in the set. O(1).
     */
    function contains(UintSet storage set, uint256 value) internal view returns (bool) {
        return _contains(set._inner, bytes32(value));
    }

    /**
     * @dev Returns the number of values in the set. O(1).
     */
    function length(UintSet storage set) internal view returns (uint256) {
        return _length(set._inner);
    }

    /**
     * @dev Returns the value stored at position `index` in the set. O(1).
     *
     * Note that there are no guarantees on the ordering of values inside the
     * array, and it may change when more values are added or removed.
     *
     * Requirements:
     *
     * - `index` must be strictly less than {length}.
     */
    function at(UintSet storage set, uint256 index) internal view returns (uint256) {
        return uint256(_at(set._inner, index));
    }

    /**
     * @dev Return the entire set in an array
     *
     * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
     * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
     * this function has an unbounded cost, and using it as part of a state-changing function may render the function
     * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
     */
    function values(UintSet storage set) internal view returns (uint256[] memory) {
        bytes32[] memory store = _values(set._inner);
        uint256[] memory result;

        /// @solidity memory-safe-assembly
        assembly {
            result := store
        }

        return result;
    }
}
Common.sol 672 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.19;

// Common.sol
//
// Common mathematical functions needed by both SD59x18 and UD60x18. Note that these global functions do not
// always operate with SD59x18 and UD60x18 numbers.

/*//////////////////////////////////////////////////////////////////////////
                                CUSTOM ERRORS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Thrown when the resultant value in {mulDiv} overflows uint256.
error PRBMath_MulDiv_Overflow(uint256 x, uint256 y, uint256 denominator);

/// @notice Thrown when the resultant value in {mulDiv18} overflows uint256.
error PRBMath_MulDiv18_Overflow(uint256 x, uint256 y);

/// @notice Thrown when one of the inputs passed to {mulDivSigned} is `type(int256).min`.
error PRBMath_MulDivSigned_InputTooSmall();

/// @notice Thrown when the resultant value in {mulDivSigned} overflows int256.
error PRBMath_MulDivSigned_Overflow(int256 x, int256 y);

/*//////////////////////////////////////////////////////////////////////////
                                    CONSTANTS
//////////////////////////////////////////////////////////////////////////*/

/// @dev The maximum value a uint128 number can have.
uint128 constant MAX_UINT128 = type(uint128).max;

/// @dev The maximum value a uint40 number can have.
uint40 constant MAX_UINT40 = type(uint40).max;

/// @dev The unit number, which the decimal precision of the fixed-point types.
uint256 constant UNIT = 1e18;

/// @dev The unit number inverted mod 2^256.
uint256 constant UNIT_INVERSE = 78156646155174841979727994598816262306175212592076161876661_508869554232690281;

/// @dev The the largest power of two that divides the decimal value of `UNIT`. The logarithm of this value is the least significant
/// bit in the binary representation of `UNIT`.
uint256 constant UNIT_LPOTD = 262144;

/*//////////////////////////////////////////////////////////////////////////
                                    FUNCTIONS
//////////////////////////////////////////////////////////////////////////*/

/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers. See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function exp2(uint256 x) pure returns (uint256 result) {
    unchecked {
        // Start from 0.5 in the 192.64-bit fixed-point format.
        result = 0x800000000000000000000000000000000000000000000000;

        // The following logic multiplies the result by $\sqrt{2^{-i}}$ when the bit at position i is 1. Key points:
        //
        // 1. Intermediate results will not overflow, as the starting point is 2^191 and all magic factors are under 2^65.
        // 2. The rationale for organizing the if statements into groups of 8 is gas savings. If the result of performing
        // a bitwise AND operation between x and any value in the array [0x80; 0x40; 0x20; 0x10; 0x08; 0x04; 0x02; 0x01] is 1,
        // we know that `x & 0xFF` is also 1.
        if (x & 0xFF00000000000000 > 0) {
            if (x & 0x8000000000000000 > 0) {
                result = (result * 0x16A09E667F3BCC909) >> 64;
            }
            if (x & 0x4000000000000000 > 0) {
                result = (result * 0x1306FE0A31B7152DF) >> 64;
            }
            if (x & 0x2000000000000000 > 0) {
                result = (result * 0x1172B83C7D517ADCE) >> 64;
            }
            if (x & 0x1000000000000000 > 0) {
                result = (result * 0x10B5586CF9890F62A) >> 64;
            }
            if (x & 0x800000000000000 > 0) {
                result = (result * 0x1059B0D31585743AE) >> 64;
            }
            if (x & 0x400000000000000 > 0) {
                result = (result * 0x102C9A3E778060EE7) >> 64;
            }
            if (x & 0x200000000000000 > 0) {
                result = (result * 0x10163DA9FB33356D8) >> 64;
            }
            if (x & 0x100000000000000 > 0) {
                result = (result * 0x100B1AFA5ABCBED61) >> 64;
            }
        }

        if (x & 0xFF000000000000 > 0) {
            if (x & 0x80000000000000 > 0) {
                result = (result * 0x10058C86DA1C09EA2) >> 64;
            }
            if (x & 0x40000000000000 > 0) {
                result = (result * 0x1002C605E2E8CEC50) >> 64;
            }
            if (x & 0x20000000000000 > 0) {
                result = (result * 0x100162F3904051FA1) >> 64;
            }
            if (x & 0x10000000000000 > 0) {
                result = (result * 0x1000B175EFFDC76BA) >> 64;
            }
            if (x & 0x8000000000000 > 0) {
                result = (result * 0x100058BA01FB9F96D) >> 64;
            }
            if (x & 0x4000000000000 > 0) {
                result = (result * 0x10002C5CC37DA9492) >> 64;
            }
            if (x & 0x2000000000000 > 0) {
                result = (result * 0x1000162E525EE0547) >> 64;
            }
            if (x & 0x1000000000000 > 0) {
                result = (result * 0x10000B17255775C04) >> 64;
            }
        }

        if (x & 0xFF0000000000 > 0) {
            if (x & 0x800000000000 > 0) {
                result = (result * 0x1000058B91B5BC9AE) >> 64;
            }
            if (x & 0x400000000000 > 0) {
                result = (result * 0x100002C5C89D5EC6D) >> 64;
            }
            if (x & 0x200000000000 > 0) {
                result = (result * 0x10000162E43F4F831) >> 64;
            }
            if (x & 0x100000000000 > 0) {
                result = (result * 0x100000B1721BCFC9A) >> 64;
            }
            if (x & 0x80000000000 > 0) {
                result = (result * 0x10000058B90CF1E6E) >> 64;
            }
            if (x & 0x40000000000 > 0) {
                result = (result * 0x1000002C5C863B73F) >> 64;
            }
            if (x & 0x20000000000 > 0) {
                result = (result * 0x100000162E430E5A2) >> 64;
            }
            if (x & 0x10000000000 > 0) {
                result = (result * 0x1000000B172183551) >> 64;
            }
        }

        if (x & 0xFF00000000 > 0) {
            if (x & 0x8000000000 > 0) {
                result = (result * 0x100000058B90C0B49) >> 64;
            }
            if (x & 0x4000000000 > 0) {
                result = (result * 0x10000002C5C8601CC) >> 64;
            }
            if (x & 0x2000000000 > 0) {
                result = (result * 0x1000000162E42FFF0) >> 64;
            }
            if (x & 0x1000000000 > 0) {
                result = (result * 0x10000000B17217FBB) >> 64;
            }
            if (x & 0x800000000 > 0) {
                result = (result * 0x1000000058B90BFCE) >> 64;
            }
            if (x & 0x400000000 > 0) {
                result = (result * 0x100000002C5C85FE3) >> 64;
            }
            if (x & 0x200000000 > 0) {
                result = (result * 0x10000000162E42FF1) >> 64;
            }
            if (x & 0x100000000 > 0) {
                result = (result * 0x100000000B17217F8) >> 64;
            }
        }

        if (x & 0xFF000000 > 0) {
            if (x & 0x80000000 > 0) {
                result = (result * 0x10000000058B90BFC) >> 64;
            }
            if (x & 0x40000000 > 0) {
                result = (result * 0x1000000002C5C85FE) >> 64;
            }
            if (x & 0x20000000 > 0) {
                result = (result * 0x100000000162E42FF) >> 64;
            }
            if (x & 0x10000000 > 0) {
                result = (result * 0x1000000000B17217F) >> 64;
            }
            if (x & 0x8000000 > 0) {
                result = (result * 0x100000000058B90C0) >> 64;
            }
            if (x & 0x4000000 > 0) {
                result = (result * 0x10000000002C5C860) >> 64;
            }
            if (x & 0x2000000 > 0) {
                result = (result * 0x1000000000162E430) >> 64;
            }
            if (x & 0x1000000 > 0) {
                result = (result * 0x10000000000B17218) >> 64;
            }
        }

        if (x & 0xFF0000 > 0) {
            if (x & 0x800000 > 0) {
                result = (result * 0x1000000000058B90C) >> 64;
            }
            if (x & 0x400000 > 0) {
                result = (result * 0x100000000002C5C86) >> 64;
            }
            if (x & 0x200000 > 0) {
                result = (result * 0x10000000000162E43) >> 64;
            }
            if (x & 0x100000 > 0) {
                result = (result * 0x100000000000B1721) >> 64;
            }
            if (x & 0x80000 > 0) {
                result = (result * 0x10000000000058B91) >> 64;
            }
            if (x & 0x40000 > 0) {
                result = (result * 0x1000000000002C5C8) >> 64;
            }
            if (x & 0x20000 > 0) {
                result = (result * 0x100000000000162E4) >> 64;
            }
            if (x & 0x10000 > 0) {
                result = (result * 0x1000000000000B172) >> 64;
            }
        }

        if (x & 0xFF00 > 0) {
            if (x & 0x8000 > 0) {
                result = (result * 0x100000000000058B9) >> 64;
            }
            if (x & 0x4000 > 0) {
                result = (result * 0x10000000000002C5D) >> 64;
            }
            if (x & 0x2000 > 0) {
                result = (result * 0x1000000000000162E) >> 64;
            }
            if (x & 0x1000 > 0) {
                result = (result * 0x10000000000000B17) >> 64;
            }
            if (x & 0x800 > 0) {
                result = (result * 0x1000000000000058C) >> 64;
            }
            if (x & 0x400 > 0) {
                result = (result * 0x100000000000002C6) >> 64;
            }
            if (x & 0x200 > 0) {
                result = (result * 0x10000000000000163) >> 64;
            }
            if (x & 0x100 > 0) {
                result = (result * 0x100000000000000B1) >> 64;
            }
        }

        if (x & 0xFF > 0) {
            if (x & 0x80 > 0) {
                result = (result * 0x10000000000000059) >> 64;
            }
            if (x & 0x40 > 0) {
                result = (result * 0x1000000000000002C) >> 64;
            }
            if (x & 0x20 > 0) {
                result = (result * 0x10000000000000016) >> 64;
            }
            if (x & 0x10 > 0) {
                result = (result * 0x1000000000000000B) >> 64;
            }
            if (x & 0x8 > 0) {
                result = (result * 0x10000000000000006) >> 64;
            }
            if (x & 0x4 > 0) {
                result = (result * 0x10000000000000003) >> 64;
            }
            if (x & 0x2 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
            if (x & 0x1 > 0) {
                result = (result * 0x10000000000000001) >> 64;
            }
        }

        // In the code snippet below, two operations are executed simultaneously:
        //
        // 1. The result is multiplied by $(2^n + 1)$, where $2^n$ represents the integer part, and the additional 1
        // accounts for the initial guess of 0.5. This is achieved by subtracting from 191 instead of 192.
        // 2. The result is then converted to an unsigned 60.18-decimal fixed-point format.
        //
        // The underlying logic is based on the relationship $2^{191-ip} = 2^{ip} / 2^{191}$, where $ip$ denotes the,
        // integer part, $2^n$.
        result *= UNIT;
        result >>= (191 - (x >> 64));
    }
}

/// @notice Finds the zero-based index of the first 1 in the binary representation of x.
///
/// @dev See the note on "msb" in this Wikipedia article: https://en.wikipedia.org/wiki/Find_first_set
///
/// Each step in this implementation is equivalent to this high-level code:
///
/// ```solidity
/// if (x >= 2 ** 128) {
///     x >>= 128;
///     result += 128;
/// }
/// ```
///
/// Where 128 is replaced with each respective power of two factor. See the full high-level implementation here:
/// https://gist.github.com/PaulRBerg/f932f8693f2733e30c4d479e8e980948
///
/// The Yul instructions used below are:
///
/// - "gt" is "greater than"
/// - "or" is the OR bitwise operator
/// - "shl" is "shift left"
/// - "shr" is "shift right"
///
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return result The index of the most significant bit as a uint256.
/// @custom:smtchecker abstract-function-nondet
function msb(uint256 x) pure returns (uint256 result) {
    // 2^128
    assembly ("memory-safe") {
        let factor := shl(7, gt(x, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^64
    assembly ("memory-safe") {
        let factor := shl(6, gt(x, 0xFFFFFFFFFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^32
    assembly ("memory-safe") {
        let factor := shl(5, gt(x, 0xFFFFFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^16
    assembly ("memory-safe") {
        let factor := shl(4, gt(x, 0xFFFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^8
    assembly ("memory-safe") {
        let factor := shl(3, gt(x, 0xFF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^4
    assembly ("memory-safe") {
        let factor := shl(2, gt(x, 0xF))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^2
    assembly ("memory-safe") {
        let factor := shl(1, gt(x, 0x3))
        x := shr(factor, x)
        result := or(result, factor)
    }
    // 2^1
    // No need to shift x any more.
    assembly ("memory-safe") {
        let factor := gt(x, 0x1)
        result := or(result, factor)
    }
}

/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev Credits to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - The denominator must not be zero.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as a uint256.
/// @param y The multiplier as a uint256.
/// @param denominator The divisor as a uint256.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function mulDiv(uint256 x, uint256 y, uint256 denominator) pure returns (uint256 result) {
    // 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; // Least significant 256 bits of the product
    uint256 prod1; // Most significant 256 bits of the product
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    // Handle non-overflow cases, 256 by 256 division.
    if (prod1 == 0) {
        unchecked {
            return prod0 / denominator;
        }
    }

    // Make sure the result is less than 2^256. Also prevents denominator == 0.
    if (prod1 >= denominator) {
        revert PRBMath_MulDiv_Overflow(x, y, denominator);
    }

    ////////////////////////////////////////////////////////////////////////////
    // 512 by 256 division
    ////////////////////////////////////////////////////////////////////////////

    // Make division exact by subtracting the remainder from [prod1 prod0].
    uint256 remainder;
    assembly ("memory-safe") {
        // Compute remainder using the mulmod Yul instruction.
        remainder := mulmod(x, y, denominator)

        // Subtract 256 bit number from 512-bit number.
        prod1 := sub(prod1, gt(remainder, prod0))
        prod0 := sub(prod0, remainder)
    }

    unchecked {
        // Calculate the largest power of two divisor of the denominator using the unary operator ~. This operation cannot overflow
        // because the denominator cannot be zero at this point in the function execution. The result is always >= 1.
        // For more detail, see https://cs.stackexchange.com/q/138556/92363.
        uint256 lpotdod = denominator & (~denominator + 1);
        uint256 flippedLpotdod;

        assembly ("memory-safe") {
            // Factor powers of two out of denominator.
            denominator := div(denominator, lpotdod)

            // Divide [prod1 prod0] by lpotdod.
            prod0 := div(prod0, lpotdod)

            // Get the flipped value `2^256 / lpotdod`. If the `lpotdod` is zero, the flipped value is one.
            // `sub(0, lpotdod)` produces the two's complement version of `lpotdod`, which is equivalent to flipping all the bits.
            // However, `div` interprets this value as an unsigned value: https://ethereum.stackexchange.com/q/147168/24693
            flippedLpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
        }

        // Shift in bits from prod1 into prod0.
        prod0 |= prod1 * flippedLpotdod;

        // 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;
    }
}

/// @notice Calculates x*y÷1e18 with 512-bit precision.
///
/// @dev A variant of {mulDiv} with constant folding, i.e. in which the denominator is hard coded to 1e18.
///
/// Notes:
/// - The body is purposely left uncommented; to understand how this works, see the documentation in {mulDiv}.
/// - The result is rounded toward zero.
/// - We take as an axiom that the result cannot be `MAX_UINT256` when x and y solve the following system of equations:
///
/// $$
/// \begin{cases}
///     x * y = MAX\_UINT256 * UNIT \\
///     (x * y) \% UNIT \geq \frac{UNIT}{2}
/// \end{cases}
/// $$
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - The result must fit in uint256.
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
/// @custom:smtchecker abstract-function-nondet
function mulDiv18(uint256 x, uint256 y) pure returns (uint256 result) {
    uint256 prod0;
    uint256 prod1;
    assembly ("memory-safe") {
        let mm := mulmod(x, y, not(0))
        prod0 := mul(x, y)
        prod1 := sub(sub(mm, prod0), lt(mm, prod0))
    }

    if (prod1 == 0) {
        unchecked {
            return prod0 / UNIT;
        }
    }

    if (prod1 >= UNIT) {
        revert PRBMath_MulDiv18_Overflow(x, y);
    }

    uint256 remainder;
    assembly ("memory-safe") {
        remainder := mulmod(x, y, UNIT)
        result :=
            mul(
                or(
                    div(sub(prod0, remainder), UNIT_LPOTD),
                    mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, UNIT_LPOTD), UNIT_LPOTD), 1))
                ),
                UNIT_INVERSE
            )
    }
}

/// @notice Calculates x*y÷denominator with 512-bit precision.
///
/// @dev This is an extension of {mulDiv} for signed numbers, which works by computing the signs and the absolute values separately.
///
/// Notes:
/// - The result is rounded toward zero.
///
/// Requirements:
/// - Refer to the requirements in {mulDiv}.
/// - None of the inputs can be `type(int256).min`.
/// - The result must fit in int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
/// @custom:smtchecker abstract-function-nondet
function mulDivSigned(int256 x, int256 y, int256 denominator) pure returns (int256 result) {
    if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
        revert PRBMath_MulDivSigned_InputTooSmall();
    }

    // Get hold of the absolute values of x, y and the denominator.
    uint256 xAbs;
    uint256 yAbs;
    uint256 dAbs;
    unchecked {
        xAbs = x < 0 ? uint256(-x) : uint256(x);
        yAbs = y < 0 ? uint256(-y) : uint256(y);
        dAbs = denominator < 0 ? uint256(-denominator) : uint256(denominator);
    }

    // Compute the absolute value of x*y÷denominator. The result must fit in int256.
    uint256 resultAbs = mulDiv(xAbs, yAbs, dAbs);
    if (resultAbs > uint256(type(int256).max)) {
        revert PRBMath_MulDivSigned_Overflow(x, y);
    }

    // Get the signs of x, y and the denominator.
    uint256 sx;
    uint256 sy;
    uint256 sd;
    assembly ("memory-safe") {
        // "sgt" is the "signed greater than" assembly instruction and "sub(0,1)" is -1 in two's complement.
        sx := sgt(x, sub(0, 1))
        sy := sgt(y, sub(0, 1))
        sd := sgt(denominator, sub(0, 1))
    }

    // XOR over sx, sy and sd. What this does is to check whether there are 1 or 3 negative signs in the inputs.
    // If there are, the result should be negative. Otherwise, it should be positive.
    unchecked {
        result = sx ^ sy ^ sd == 0 ? -int256(resultAbs) : int256(resultAbs);
    }
}

/// @notice Calculates the square root of x using the Babylonian method.
///
/// @dev See https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Notes:
/// - If x is not a perfect square, the result is rounded down.
/// - Credits to OpenZeppelin for the explanations in comments below.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as a uint256.
/// @custom:smtchecker abstract-function-nondet
function sqrt(uint256 x) pure returns (uint256 result) {
    if (x == 0) {
        return 0;
    }

    // For our first guess, we calculate the biggest power of 2 which is smaller than the square root of x.
    //
    // We know that the "msb" (most significant bit) of x is a power of 2 such that we have:
    //
    // $$
    // msb(x) <= x <= 2*msb(x)$
    // $$
    //
    // We write $msb(x)$ as $2^k$, and we get:
    //
    // $$
    // k = log_2(x)
    // $$
    //
    // Thus, we can write the initial inequality as:
    //
    // $$
    // 2^{log_2(x)} <= x <= 2*2^{log_2(x)+1} \\
    // sqrt(2^k) <= sqrt(x) < sqrt(2^{k+1}) \\
    // 2^{k/2} <= sqrt(x) < 2^{(k+1)/2} <= 2^{(k/2)+1}
    // $$
    //
    // Consequently, $2^{log_2(x) /2} is a good first approximation of sqrt(x) with at least one correct bit.
    uint256 xAux = uint256(x);
    result = 1;
    if (xAux >= 2 ** 128) {
        xAux >>= 128;
        result <<= 64;
    }
    if (xAux >= 2 ** 64) {
        xAux >>= 64;
        result <<= 32;
    }
    if (xAux >= 2 ** 32) {
        xAux >>= 32;
        result <<= 16;
    }
    if (xAux >= 2 ** 16) {
        xAux >>= 16;
        result <<= 8;
    }
    if (xAux >= 2 ** 8) {
        xAux >>= 8;
        result <<= 4;
    }
    if (xAux >= 2 ** 4) {
        xAux >>= 4;
        result <<= 2;
    }
    if (xAux >= 2 ** 2) {
        result <<= 1;
    }

    // At this point, `result` is an estimation with at least one bit of precision. We know the true value has at
    // most 128 bits, 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 + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;
        result = (result + x / result) >> 1;

        // If x is not a perfect square, round the result toward zero.
        uint256 roundedResult = x / result;
        if (result >= roundedResult) {
            result = roundedResult;
        }
    }
}
TokenPrices.sol 361 lines
pragma solidity ^0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (common/TokenPrices.sol)

import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import { ERC20 } from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import { IERC4626 } from "@openzeppelin/contracts/interfaces/IERC4626.sol";
import { EnumerableSet } from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";

import { IAggregatorV3Interface } from "contracts/interfaces/external/chainlink/IAggregatorV3Interface.sol";
import { IUniswapV3Pool } from "contracts/interfaces/external/uniswap/IUniswapV3Pool.sol";
import { IKodiakV3Pool } from "contracts/interfaces/external/kodiak/IKodiakV3Pool.sol";
import { IKodiakIsland } from "contracts/interfaces/external/kodiak/IKodiakIsland.sol";
import { IBalancerVault } from "contracts/interfaces/external/balancer/IBalancerVault.sol";
import { IBalancerBptToken } from "contracts/interfaces/external/balancer/IBalancerBptToken.sol";
import { IJoeLBQuoter } from "contracts/interfaces/external/traderJoe/IJoeLBQuoter.sol";
import { IStETH } from "contracts/interfaces/external/lido/IStETH.sol";

import { ITokenPrices } from "contracts/interfaces/common/ITokenPrices.sol";
import { IRepricingToken } from "contracts/interfaces/common/IRepricingToken.sol";
import { OrigamiMath } from "contracts/libraries/OrigamiMath.sol";
import { IOrigamiOracle } from "contracts/interfaces/common/oracle/IOrigamiOracle.sol";
import { ITokenizedBalanceSheetVault } from "contracts/interfaces/external/tokenizedBalanceSheetVault/ITokenizedBalanceSheetVault.sol";

/// @title Token Prices
/// @notice A utility contract to pull token prices on-chain.
/// @dev Composable functions (using encoded function calldata) to build up price formulas
/// Do NOT use these prices for direct on-chain purposes, as they can generally be abused.
/// eg single block sandwich attacks, multi-block attacks by block producers, etc.
/// They are only to be used for utilities such as showing estimated $USD equiv. prices in a dapp, etc
contract TokenPrices is ITokenPrices, Ownable {
    using EnumerableSet for EnumerableSet.AddressSet;

    uint8 public immutable override decimals;
    
    /// @notice Token address to function calldata for how to lookup the price for this token
    mapping(address token => bytes fnCalldata) public override priceFnCalldata;

    /// @dev The list of token addresses which have been mapped.
    EnumerableSet.AddressSet internal _mappedTokens;

    error InvalidPrice(int256);
    error FailedPriceLookup(bytes fnCalldata);
    event TokenPriceFunctionSet(address indexed token, bytes fnCalldata);
    
    struct PriceMapping {
        address token;
        bytes fnCalldata;
    }

    constructor(uint8 _decimals) {
        decimals = _decimals;
    }

    /// @notice Map a token address to a function calldata defining how to retrieve the price
    function setTokenPriceFunction(address token, bytes calldata fnCalldata) external onlyOwner {
        emit TokenPriceFunctionSet(token, fnCalldata);
        priceFnCalldata[token] = fnCalldata;
        _mappedTokens.add(token);
    }

    /// @notice Map a token address to a function calldata defining how to retrieve the price
    function setTokenPriceFunctions(PriceMapping[] calldata mappings) external onlyOwner {
        PriceMapping calldata m;
        for (uint256 i; i < mappings.length; ++i) {
            m = mappings[i];
            emit TokenPriceFunctionSet(m.token, m.fnCalldata);
            priceFnCalldata[m.token] = m.fnCalldata;
            _mappedTokens.add(m.token);
        }
    }

    /** TOKEN->PRICE LOOKUP FUNCTIONS */

    /// @notice Retrieve the price for a given token.
    /// @dev If not mapped, or an underlying error occurs, FailedPriceLookup will be thrown.
    function tokenPrice(address token) public override view returns (uint256 price) {
        return runPriceFunction(priceFnCalldata[token]);
    }

    /// @notice Retrieve the price for a list of tokens.
    /// @dev If any aren't mapped, or an underlying error occurs, FailedPriceLookup will be thrown.
    /// Not particularly gas efficient - wouldn't recommend to use on-chain
    function tokenPrices(address[] calldata tokens) external override view returns (uint256[] memory prices) {
        prices = new uint256[](tokens.length);
        for (uint256 i; i < tokens.length; ++i) {
            prices[i] = runPriceFunction(priceFnCalldata[tokens[i]]);
        }
    }

    /// @notice The set of all mapped tokens
    function mappedTokenAt(uint256 i) external override view returns (address token) {
        return _mappedTokens.at(i);
    }

    /// @notice The set of all mapped tokens
    function allMappedTokens() external override view returns (address[] memory) {
        return _mappedTokens.values();
    }

    /// @notice The number of mapped tokens
    function numMappedTokens() external override view returns (uint256) {
        return _mappedTokens.length();
    }

    /** EXTERNAL PRICE LOOKUPS */

    /// @notice Lookup the price of an oracle, scaled to `pricePrecision`
    function oraclePrice(address _oracle, uint256 _stalenessThreshold) external view returns (uint256 price) {
        IAggregatorV3Interface oracle = IAggregatorV3Interface(_oracle);
        (uint80 roundId, int256 feedValue, , uint256 updatedAt, uint80 answeredInRound) = oracle.latestRoundData();
		if (answeredInRound <= roundId && block.timestamp - updatedAt > _stalenessThreshold) revert InvalidPrice(feedValue);

        if (feedValue < 0) revert InvalidPrice(feedValue);
        price = scaleToPrecision(uint256(feedValue), oracle.decimals());
    }

    /// @notice The wstEth -> stETH conversion ratio
    function wstEthRatio(address _stEthToken) external view returns (uint256 ratio) {
        return IStETH(_stEthToken).getPooledEthByShares(10 ** decimals);
    }

    /// @notice Fetch the Trader Joe pair price, not inclusive of swap fees or price impact.
    /// @dev Do not use this for on-chain calculations, as it can be exploited 
    /// with a single block sandwhich attack. Only use for off-chain utilities (eg informational purposes only)
    function traderJoeBestPrice(IJoeLBQuoter joeQuoter, address sellToken, address buyToken) external view returns (uint256) {
        address[] memory route = new address[](2);
        route[0] = sellToken;
        route[1] = buyToken;
        uint8 buyTokenDecimals = ERC20(buyToken).decimals();
        uint8 sellTokenDecimals = ERC20(sellToken).decimals();

        // Get the quote details to sell 1 token, across all v1 and v2 pools
        IJoeLBQuoter.Quote memory quote = joeQuoter.findBestPathFromAmountIn(route, 10 ** sellTokenDecimals);

        // Scale to 1e30.
        uint256 sellTokenAmount = scaleToPrecision(quote.virtualAmountsWithoutSlippage[0], sellTokenDecimals);
        uint256 sellTokenFeeAmount = sellTokenAmount * quote.fees[0] / 1e18; // fees are a percentage of the sell token amount
        uint256 buyTokenAmount = scaleToPrecision(quote.virtualAmountsWithoutSlippage[1], buyTokenDecimals);

        return buyTokenAmount * 10 ** decimals / (sellTokenAmount - sellTokenFeeAmount);
    }

    /// @notice Fetch the price from a univ3 pool, in quoted order (token0Price), to `pricePrecision`
    /// @dev https://web.archive.org/web/20210918154903/https://docs.uniswap.org/sdk/guides/fetching-prices
    /// @dev Do not use this for on-chain calculations, as it can be exploited 
    /// with a multi block attacks by block producers. Only use for off-chain utilities (eg informational purposes only)
    function univ3Price(IUniswapV3Pool pool, bool inQuotedOrder) external view returns (uint256) {
        // Pull the current price from the pool
        (uint160 sqrtPriceX96,,,,,,) = pool.slot0();
        return _priceFromSqrtX96(
            sqrtPriceX96,
            inQuotedOrder,
            IERC20Metadata(pool.token0()),
            IERC20Metadata(pool.token1())
        );
    }

    /// @notice Fetch the price from a kodiak v3 pool, in quoted order (token0Price), to `pricePrecision`
    /// @dev The same as `univ3Price()` above, except the Kodiak fork has a minor interface change.
    /// @dev Do not use this for on-chain calculations, as it can be exploited 
    /// with a multi block attacks by block producers. Only use for off-chain utilities (eg informational purposes only)
    function kodiakV3Price(IKodiakV3Pool pool, bool inQuotedOrder) external view returns (uint256) {
        (uint160 sqrtPriceX96,,,,,,) = pool.slot0();
        return _priceFromSqrtX96(
            sqrtPriceX96,
            inQuotedOrder,
            IERC20Metadata(pool.token0()),
            IERC20Metadata(pool.token1())
        );
    }

    /// @notice Calculate the price of a Kodiak Island ERC20 token
    /// @dev Based on the total token value of the island v3 position divided by the total supply
    function kodiakIslandPrice(IKodiakIsland island) external view returns (uint256) {
        IERC20Metadata token0 = IERC20Metadata(address(island.token0()));
        IERC20Metadata token1 = IERC20Metadata(address(island.token1()));
        (uint256 amount0Current, uint256 amount1Current) = island.getUnderlyingBalances();

        uint256 totalIslandUsd = (
            OrigamiMath.mulDiv(
                amount0Current,
                tokenPrice(address(token0)),
                10 ** token0.decimals(),
                OrigamiMath.Rounding.ROUND_DOWN
            ) +
            OrigamiMath.mulDiv(
                amount1Current,
                tokenPrice(address(token1)),
                10 ** token1.decimals(),
                OrigamiMath.Rounding.ROUND_DOWN
            )
        );

        return OrigamiMath.mulDiv(
            totalIslandUsd,
            10 ** IERC20Metadata(address(island)).decimals(),
            island.totalSupply(),
            OrigamiMath.Rounding.ROUND_DOWN
        );
    }

    /// @notice Calculate the price of a Balancer BPT token
    /// @dev Based on the total token value in the BPT divided by the total supply
    function balancerV2BptPrice(IBalancerVault balancerVault, IBalancerBptToken bptToken) external view returns (uint256) {
        (address[] memory tokens, uint256[] memory balances,) = balancerVault.getPoolTokens(
            bptToken.getPoolId()
        );

        uint256 totalPoolUsd;
        for (uint256 i; i < tokens.length; ++i) {
            address token = tokens[i];
            if (token == address(bptToken)) continue;

            totalPoolUsd += OrigamiMath.mulDiv(
                balances[i],
                tokenPrice(token),
                10 ** IERC20Metadata(token).decimals(),
                OrigamiMath.Rounding.ROUND_DOWN
            );
        }

        return OrigamiMath.mulDiv(
            totalPoolUsd,
            10 ** IERC20Metadata(address(bptToken)).decimals(),
            bptToken.getActualSupply(),
            OrigamiMath.Rounding.ROUND_DOWN
        );
    }

    /// @notice Use the origami defined oracle price
    function origamiOraclePrice(
        IOrigamiOracle origamiOracle, 
        IOrigamiOracle.PriceType priceType, 
        OrigamiMath.Rounding roundingMode
    ) external view returns (uint256) {
        return scaleToPrecision(origamiOracle.latestPrice(priceType, roundingMode), origamiOracle.decimals());
    }

    /// @notice Calculate the Repricing Token price based
    /// on the [reserveToken price] * [reservesPerShare()]
    function repricingTokenPrice(address _repricingToken) external view returns (uint256) {
        IRepricingToken repricingToken = IRepricingToken(_repricingToken);

        // reservesPerShare is quoted in the reserve token decimals. The final result should be in `decimals` precision
        address reserveToken = repricingToken.reserveToken();
        return tokenPrice(reserveToken) * repricingToken.reservesPerShare() / (10 ** IERC20Metadata(reserveToken).decimals());
    }

    /// @notice Calculate the price of an ERC-4626 token vault
    /// [asset price] * [assets per share]
    function erc4626TokenPrice(address vault) external view returns (uint256) {
        uint8 _vaultDecimals = IERC20Metadata(vault).decimals();
        IERC4626 _vault = IERC4626(vault);
        address _underlyingAsset = _vault.asset();
        uint8 _underlyingAssetDecimals = IERC20Metadata(_underlyingAsset).decimals();

        // Return the price to this contract's `decimals` precision
        return OrigamiMath.mulDiv(
            tokenPrice(_underlyingAsset),                 // 30 decimals
            _vault.convertToAssets(10 ** _vaultDecimals), // 1 share in underlying asset decimals
            10 ** _underlyingAssetDecimals,               // 1 underlying asset
            OrigamiMath.Rounding.ROUND_DOWN
        );
    }

    /// @notice Calculate the price of a Tokenized Balance Sheet token vault
    /// @dev Each of the underlying tokens in the vault needs to be mapped
    /// price is floored at zero
    function tokenizedBalanceSheetTokenPrice(address vault) external view returns (uint256) {
        uint8 _vaultDecimals = IERC20Metadata(vault).decimals();
        ITokenizedBalanceSheetVault _vault = ITokenizedBalanceSheetVault(vault);

        (uint256[] memory _assetPerShare, uint256[] memory _liabilitiesPerShare) = _vault.convertFromShares(10 ** _vaultDecimals);
        (address[] memory _assetTokens, address[] memory _liabilityTokens) = _vault.tokens();

        int256 _totalPrice;
        for (uint256 i; i < _assetTokens.length; ++i) {
            _totalPrice += int256(_underlyingAssetPrice(_assetTokens[i], _assetPerShare[i]));
        }
        for (uint256 i; i < _liabilityTokens.length; ++i) {
            _totalPrice -= int256(_underlyingAssetPrice(_liabilityTokens[i], _liabilitiesPerShare[i]));
        }

        return _totalPrice > 0 ? uint256(_totalPrice) : 0;
    }

    function _underlyingAssetPrice(address token, uint256 assetPerShare) private view returns (uint256) {
        return OrigamiMath.mulDiv(
            tokenPrice(token),                      // 30 decimals
            assetPerShare,                          // 1 share in underlying asset decimals
            10 ** IERC20Metadata(token).decimals(), // 1 underlying asset
            OrigamiMath.Rounding.ROUND_DOWN
        );
    }

    /** INTERNAL PRIMATIVES AND COMPOSITION FUNCTIONS */

    /// @notice A fixed scalar amount, which can be used in mul/div operations
    function scalar(uint256 _amount) external pure returns (uint256) {
        return _amount;
    }

    /// @notice Use the price function from another source token.
    function aliasFor(address sourceToken) external view returns (uint256) {
        return tokenPrice(sourceToken);
    }

    /// @notice Multiply the result of two separate price lookup functions
    function mul(bytes calldata v1, bytes calldata v2) external view returns (uint256) {
        return runPriceFunction(v1) * runPriceFunction(v2) / 10 ** decimals;
    }

    /// @notice Divide the result of two separate price lookup functions
    function div(bytes calldata numerator, bytes calldata denominator) external view returns (uint256) {
        return runPriceFunction(numerator) * 10 ** decimals / runPriceFunction(denominator);
    }

    function runPriceFunction(bytes memory fnCalldata) internal view returns (uint256 price) {
        (bool success, bytes memory returndata) = address(this).staticcall(fnCalldata);

        if (success) {
            return abi.decode(returndata, (uint256));
        } else {
            revert FailedPriceLookup(fnCalldata);
        }
    }

    /// @notice Scale the price precision of the source to the target `pricePrecision`
    function scaleToPrecision(uint256 price, uint8 sourcePrecision) internal view returns (uint256) {
        unchecked {
            if (sourcePrecision <= decimals) {
                // Scale up (no-op if sourcePrecision == pricePrecision)
                return price * 10 ** (decimals - sourcePrecision);
            } else {
                // scale down
                return price / 10 ** (sourcePrecision - decimals);
            }
        }
    }

    function _priceFromSqrtX96(
        uint160 sqrtPriceX96,
        bool inQuotedOrder,
        IERC20Metadata token0,
        IERC20Metadata token1
    ) private view returns (uint256) {
        // Use mulDiv as otherwise the calc would overflow.        
        // https://xn--2-umb.com/21/muldiv/index.html
        if (inQuotedOrder) {
            // price = sqrtPriceX96^2 / 2^192
            uint256 decimalsScalar = 10 ** (decimals + token0.decimals() - token1.decimals());
            return OrigamiMath.mulDiv(uint256(sqrtPriceX96) * sqrtPriceX96, decimalsScalar, 1 << 192, OrigamiMath.Rounding.ROUND_DOWN);
        } else {
            // price = 2^192 / sqrtPriceX96^2
            uint256 decimalsScalar = 10 ** (decimals + token1.decimals() - token0.decimals());
            return OrigamiMath.mulDiv(1 << 192, decimalsScalar, sqrtPriceX96, OrigamiMath.Rounding.ROUND_DOWN) / sqrtPriceX96;
        }
    }
}
IRepricingToken.sol 74 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/common/IRepricingToken.sol)

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Permit } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Permit.sol";

/// @notice A re-pricing token which implements the ERC20 interface.
/// Each minted RepricingToken represents 1 share.
/// 
///  pricePerShare = numShares * totalReserves / totalSupply
/// Elevated access can increase the totalReserves in order to increase the pricePerShare
interface IRepricingToken is IERC20, IERC20Permit {
    event IssueSharesFromReserves(address indexed user, address indexed recipient, uint256 reserveTokenAmount, uint256 sharesAmount);
    event RedeemReservesFromShares(address indexed user, address indexed recipient, uint256 sharesAmount, uint256 reserveTokenAmount);
    event ReservesVestingDurationSet(uint48 duration);
    event PendingReservesAdded(uint256 amount);
    event VestedReservesAdded(uint256 amount);
    event VestedReservesRemoved(uint256 amount);
    event ReservesCheckpoint(uint256 fullyVestedReserves, uint256 newVestedReserves, uint256 carriedOverPendingReserves, uint256 newPendingReserves);

    error CannotCheckpointReserves(uint256 secsSinceLastCheckpoint, uint256 vestingDuration);

    /// @notice The token used to track reserves for this investment
    function reserveToken() external view returns (address);

    /// @notice The fully vested reserve tokens
    /// @dev Comprised of both user deposited reserves (when new shares are issued)
    /// And also when new reserves are deposited by the protocol to increase the reservesPerShare
    /// (which vest in over time)
    function vestedReserves() external returns (uint128);

    /// @notice Extra reserve tokens deposited by the protocol to increase the reservesPerShare
    /// @dev These vest in per second over `vestingDuration`
    function pendingReserves() external returns (uint128);

    /// @notice When new reserves are added to increase the reservesPerShare, 
    /// they will vest over this duration (in seconds)
    function reservesVestingDuration() external returns (uint48);

    /// @notice The time at which any accrued pendingReserves were last moved from `pendingReserves` -> `vestedReserves`
    function lastVestingCheckpoint() external returns (uint48);

    /// @notice The current amount of fully vested reserves plus any accrued pending reserves
    function totalReserves() external view returns (uint256);

    /// @notice How many reserve tokens would one get given a single share, as of now
    function reservesPerShare() external view returns (uint256);

    /// @notice How many reserve tokens would one get given a number of shares, as of now
    function sharesToReserves(uint256 shares) external view returns (uint256);

    /// @notice How many shares would one get given a number of reserve tokens, as of now
    function reservesToShares(uint256 reserves) external view returns (uint256);

    /// @notice The accrued vs outstanding amount of pending reserve tokens which have
    /// not yet been fully vested.
    function unvestedReserves() external view returns (uint256 accrued, uint256 outstanding);

    /// @notice Add pull in and add reserve tokens, which slowly increases the pricePerShare()
    /// @dev The new amount is vested in continuously per second over an `reservesVestingDuration`
    /// starting from now.
    /// If any amount was still pending and unvested since the previous `addReserves()`, it will be carried over.
    function addPendingReserves(uint256 amount) external;

    /// @notice Checkpoint any pending reserves as long as the `reservesVestingDuration` period has completely passed.
    /// @dev No economic benefit, but may be useful for book keeping purposes.
    function checkpointReserves() external;

    /// @notice Return the current estimated APR based on the pending reserves which are vesting per second
    /// into the totalReserves.
    /// @dev APR = annual reserve token rewards / total reserves
    function apr() external view returns (uint256 aprBps);
}
ITokenPrices.sol 33 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/common/ITokenPrices.sol)

/// @title Token Prices
/// @notice A utility contract to pull token prices from on-chain.
/// @dev composable functions (uisng encoded function calldata) to build up price formulas
interface ITokenPrices {
    /// @notice How many decimals places are the token prices reported in
    function decimals() external view returns (uint8);

    /// @notice Retrieve the price for a given token.
    /// @dev If not mapped, or an underlying error occurs, FailedPriceLookup will be thrown.
    /// @dev 0x000...0 is the native chain token (ETH/AVAX/etc)
    function tokenPrice(address token) external view returns (uint256 price);

    /// @notice Token address to function calldata for how to lookup the price for this token
    function priceFnCalldata(address token) external view returns (bytes memory fnCalldata);

    /// @notice Retrieve the price for a list of tokens.
    /// @dev If any aren't mapped, or an underlying error occurs, FailedPriceLookup will be thrown.
    /// @dev Not particularly gas efficient - wouldn't recommend to use on-chain
    function tokenPrices(address[] memory tokens) external view returns (uint256[] memory prices);

    /// @notice The set of all mapped tokens
    function mappedTokenAt(uint256 i) external view returns (address token);

    /// @notice The set of all mapped tokens
    function allMappedTokens() external view returns (address[] memory);

    /// @notice The number of mapped tokens
    function numMappedTokens() external view returns (uint256);
}
IOrigamiOracle.sol 126 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/common/oracle/IOrigamiOracle.sol)

import { OrigamiMath } from "contracts/libraries/OrigamiMath.sol";

/**
 * @notice An oracle which returns prices for pairs of assets, where an asset
 * could refer to a token (eg DAI) or a currency (eg USD)
 * Convention is the same as the FX market. Given the DAI/USD pair:
 *   - DAI = Base Asset (LHS of pair)
 *   - USD = Quote Asset (RHS of pair)
 * This price defines how many USD you get if selling 1 DAI
 *
 * Further, an oracle can define two PriceType's:
 *   - SPOT_PRICE: The latest spot price, for example from a chainlink oracle
 *   - HISTORIC_PRICE: An expected (eg 1:1 peg) or calculated historic price (eg TWAP)
 *
 * For assets which do are not tokens (eg USD), an internal address reference will be used
 * since this is for internal purposes only
 */
interface IOrigamiOracle {
    error InvalidPrice(address oracle, int256 price);
    error InvalidOracleData(address oracle);
    error StalePrice(address oracle, uint256 lastUpdatedAt, int256 price);
    error UnknownPriceType(uint8 priceType);
    error BelowMinValidRange(address oracle, uint256 price, uint128 floor);
    error AboveMaxValidRange(address oracle, uint256 price, uint128 ceiling);

    event ValidPriceRangeSet(uint128 validFloor, uint128 validCeiling);

    enum PriceType {
        /// @notice The current spot price of this Oracle
        SPOT_PRICE,

        /// @notice The historic price of this Oracle. 
        /// It may be a fixed expectation (eg DAI/USD would be fixed to 1)
        /// or use a TWAP or some other moving average, etc.
        HISTORIC_PRICE
    }

    /**
     * @dev Wrapped in a struct to remove stack-too-deep constraints
     */
    struct BaseOracleParams {
        string description;
        address baseAssetAddress;
        uint8 baseAssetDecimals;
        address quoteAssetAddress;
        uint8 quoteAssetDecimals;
    }

    /**
     * @notice The address used to reference the baseAsset for amount conversions
     */
    function baseAsset() external view returns (address);

    /**
     * @notice The address used to reference the quoteAsset for amount conversions
     */
    function quoteAsset() external view returns (address);

    /**
     * @notice The number of decimals of precision the price is returned as
     */
    function decimals() external view returns (uint8);

    /**
     * @notice The precision that the cross rate oracle price is returned as: `10^decimals`
     */
    function precision() external view returns (uint256);

    /**
     * @notice When converting from baseAsset<->quoteAsset, the fixed point amounts
     * need to be scaled by this amount.
     */
    function assetScalingFactor() external view returns (uint256);

    /**
     * @notice A human readable description for this oracle
     */
    function description() external view returns (string memory);

    /**
     * @notice Return the latest oracle price, to `decimals` precision
     * @dev This may still revert - eg if deemed stale, div by 0, negative price
     * @param priceType What kind of price - Spot or Historic
     * @param roundingMode Round the price at each intermediate step such that the final price rounds in the specified direction.
     */
    function latestPrice(
        PriceType priceType, 
        OrigamiMath.Rounding roundingMode
    ) external view returns (uint256 price);

    /**
     * @notice Same as `latestPrice()` but for two separate prices from this oracle	
     */
    function latestPrices(
        PriceType priceType1, 
        OrigamiMath.Rounding roundingMode1,
        PriceType priceType2, 
        OrigamiMath.Rounding roundingMode2
    ) external view returns (
        uint256 price1, 
        uint256 price2, 
        address oracleBaseAsset,
        address oracleQuoteAsset
    );

    /**
     * @notice Convert either the baseAsset->quoteAsset or quoteAsset->baseAsset
     * @dev The `fromAssetAmount` needs to be in it's natural fixed point precision (eg USDC=6dp)
     * The `toAssetAmount` will also be returned in it's natural fixed point precision
     */
    function convertAmount(
        address fromAsset,
        uint256 fromAssetAmount,
        PriceType priceType,
        OrigamiMath.Rounding roundingMode
    ) external view returns (uint256 toAssetAmount);

    /**
     * @notice Match whether a pair of assets match the base and quote asset on this oracle, in either order
     */
    function matchAssets(address asset1, address asset2) external view returns (bool);
}
IBalancerBptToken.sol 35 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/external/balancer/IBalancerBptToken.sol)

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";

interface IBalancerBptToken is IERC20 {
    /**
     * @notice Returns the effective BPT supply.
     *
     * @dev The Pool owes debt to the Protocol and the Pool's owner in the form of unminted BPT, which will be minted
     * immediately before the next join or exit. We need to take these into account since, even if they don't yet exist,
     * they will effectively be included in any Pool operation that involves BPT.
     *
     * In the vast majority of cases, this function should be used instead of `totalSupply()`.
     *
     * WARNING: since this function reads balances directly from the Vault, it is potentially subject to manipulation
     * via reentrancy. See https://forum.balancer.fi/t/reentrancy-vulnerability-scope-expanded/4345 for reference.
     *
     * To call this function safely, attempt to trigger the reentrancy guard in the Vault by calling a non-reentrant
     * function before calling `getActualSupply`. That will make the transaction revert in an unsafe context.
     * (See `whenNotInVaultContext` in `ManagedPoolSettings`).
    */
    function getActualSupply() external view returns (uint256);

    /**
     * @dev Returns the index of the Pool's BPT in the Pool tokens array (as returned by IVault.getPoolTokens).
    */
    function getBptIndex() external view returns (uint256);

    /**
     * @dev Returns this Pool's ID, used when interacting with the Vault (to e.g. join the Pool or swap with it).
    */
    function getPoolId() external view returns (bytes32);
}
IBalancerVault.sol 213 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/external/balancer/IBalancerVault.sol)

interface IAsset {
    // solhint-disable-previous-line no-empty-blocks
}

interface IBalancerVault {
    /**
     * @dev Called by users to join a Pool, which transfers tokens from `sender` into the Pool's balance. This will
     * trigger custom Pool behavior, which will typically grant something in return to `recipient` - often tokenized
     * Pool shares.
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * The `assets` and `maxAmountsIn` arrays must have the same length, and each entry indicates the maximum amount
     * to send for each asset. The amounts to send are decided by the Pool and not the Vault: it just enforces
     * these maximums.
     *
     * If joining a Pool that holds WETH, it is possible to send ETH directly: the Vault will do the wrapping. To enable
     * this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead of the
     * WETH address. Note that it is not possible to combine ETH and WETH in the same join. Any excess ETH will be sent
     * back to the caller (not the sender, which is important for relayers).
     *
     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
     * interacting with Pools that register and deregister tokens frequently. If sending ETH however, the array must be
     * sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the final
     * `assets` array might not be sorted. Pools with no registered tokens cannot be joined.
     *
     * If `fromInternalBalance` is true, the caller's Internal Balance will be preferred: ERC20 transfers will only
     * be made for the difference between the requested amount and Internal Balance (if any). Note that ETH cannot be
     * withdrawn from Internal Balance: attempting to do so will trigger a revert.
     *
     * This causes the Vault to call the `IBasePool.onJoinPool` hook on the Pool's contract, where Pools implement
     * their own custom logic. This typically requires additional information from the user (such as the expected number
     * of Pool shares). This can be encoded in the `userData` argument, which is ignored by the Vault and passed
     * directly to the Pool's contract, as is `recipient`.
     *
     * Emits a `PoolBalanceChanged` event.
     */
    function joinPool(
        bytes32 poolId,
        address sender,
        address recipient,
        JoinPoolRequest memory request
    ) external payable;

    struct JoinPoolRequest {
        address[] assets;
        uint256[] maxAmountsIn;
        bytes userData;
        bool fromInternalBalance;
    }

    /**
     * @dev Called by users to exit a Pool, which transfers tokens from the Pool's balance to `recipient`. This will
     * trigger custom Pool behavior, which will typically ask for something in return from `sender` - often tokenized
     * Pool shares. The amount of tokens that can be withdrawn is limited by the Pool's `cash` balance (see
     * `getPoolTokenInfo`).
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * The `tokens` and `minAmountsOut` arrays must have the same length, and each entry in these indicates the minimum
     * token amount to receive for each token contract. The amounts to send are decided by the Pool and not the Vault:
     * it just enforces these minimums.
     *
     * If exiting a Pool that holds WETH, it is possible to receive ETH directly: the Vault will do the unwrapping. To
     * enable this mechanism, the IAsset sentinel value (the zero address) must be passed in the `assets` array instead
     * of the WETH address. Note that it is not possible to combine ETH and WETH in the same exit.
     *
     * `assets` must have the same length and order as the array returned by `getPoolTokens`. This prevents issues when
     * interacting with Pools that register and deregister tokens frequently. If receiving ETH however, the array must
     * be sorted *before* replacing the WETH address with the ETH sentinel value (the zero address), which means the
     * final `assets` array might not be sorted. Pools with no registered tokens cannot be exited.
     *
     * If `toInternalBalance` is true, the tokens will be deposited to `recipient`'s Internal Balance. Otherwise,
     * an ERC20 transfer will be performed. Note that ETH cannot be deposited to Internal Balance: attempting to
     * do so will trigger a revert.
     *
     * `minAmountsOut` is the minimum amount of tokens the user expects to get out of the Pool, for each token in the
     * `tokens` array. This array must match the Pool's registered tokens.
     *
     * This causes the Vault to call the `IBasePool.onExitPool` hook on the Pool's contract, where Pools implement
     * their own custom logic. This typically requires additional information from the user (such as the expected number
     * of Pool shares to return). This can be encoded in the `userData` argument, which is ignored by the Vault and
     * passed directly to the Pool's contract.
     *
     * Emits a `PoolBalanceChanged` event.
     */
    function exitPool( 
        bytes32 poolId, 
        address sender, 
        address recipient, 
        ExitPoolRequest memory request 
    ) external;

    struct ExitPoolRequest {
        address[] assets;
        uint256[] minAmountsOut;
        bytes userData;
        bool toInternalBalance;
    }

    /**
      * @dev Returns a Pool's registered tokens, the total balance for each, and the latest block when *any* of
      * the tokens' `balances` changed.
      *
      * The order of the `tokens` array is the same order that will be used in `joinPool`, `exitPool`, as well as in all
      * Pool hooks (where applicable). Calls to `registerTokens` and `deregisterTokens` may change this order.
      *
      * If a Pool only registers tokens once, and these are sorted in ascending order, they will be stored in the same
      * order as passed to `registerTokens`.
      *
      * Total balances include both tokens held by the Vault and those withdrawn by the Pool's Asset Managers. These are
      * the amounts used by joins, exits and swaps. For a detailed breakdown of token balances, use `getPoolTokenInfo`
      * instead.
      */
    function getPoolTokens(bytes32 poolId) external view returns (
        address[] memory tokens,
        uint256[] memory balances,
        uint256 lastChangeBlock
    );

    /**
     * @dev Returns a Pool's contract address and specialization setting.
     */
    function getPool(bytes32 poolId) external view returns (address, PoolSpecialization);

    // Pools
    //
    // There are three specialization settings for Pools, which allow for cheaper swaps at the cost of reduced
    // functionality:
    //
    //  - General: no specialization, suited for all Pools. IGeneralPool is used for swap request callbacks, passing the
    // balance of all tokens in the Pool. These Pools have the largest swap costs (because of the extra storage reads),
    // which increase with the number of registered tokens.
    //
    //  - Minimal Swap Info: IMinimalSwapInfoPool is used instead of IGeneralPool, which saves gas by only passing the
    // balance of the two tokens involved in the swap. This is suitable for some pricing algorithms, like the weighted
    // constant product one popularized by Balancer V1. Swap costs are smaller compared to general Pools, and are
    // independent of the number of registered tokens.
    //
    //  - Two Token: only allows two tokens to be registered. This achieves the lowest possible swap gas cost. Like
    // minimal swap info Pools, these are called via IMinimalSwapInfoPool.

    enum PoolSpecialization { GENERAL, MINIMAL_SWAP_INFO, TWO_TOKEN }

    enum SwapKind { GIVEN_IN, GIVEN_OUT }

    /**
     * @dev Performs a swap with a single Pool.
     *
     * If the swap is 'given in' (the number of tokens to send to the Pool is known), it returns the amount of tokens
     * taken from the Pool, which must be greater than or equal to `limit`.
     *
     * If the swap is 'given out' (the number of tokens to take from the Pool is known), it returns the amount of tokens
     * sent to the Pool, which must be less than or equal to `limit`.
     *
     * Internal Balance usage and the recipient are determined by the `funds` struct.
     *
     * Emits a `Swap` event.
     */
    function swap(
        SingleSwap memory singleSwap,
        FundManagement memory funds,
        uint256 limit,
        uint256 deadline
    ) external payable returns (uint256);

    /**
     * @dev Data for a single swap executed by `swap`. `amount` is either `amountIn` or `amountOut` depending on
     * the `kind` value.
     *
     * `assetIn` and `assetOut` are either token addresses, or the IAsset sentinel value for ETH (the zero address).
     * Note that Pools never interact with ETH directly: it will be wrapped to or unwrapped from WETH by the Vault.
     *
     * The `userData` field is ignored by the Vault, but forwarded to the Pool in the `onSwap` hook, and may be
     * used to extend swap behavior.
     */
    struct SingleSwap {
        bytes32 poolId;
        SwapKind kind;
        IAsset assetIn;
        IAsset assetOut;
        uint256 amount;
        bytes userData;
    }

    /**
     * @dev All tokens in a swap are either sent from the `sender` account to the Vault, or from the Vault to the
     * `recipient` account.
     *
     * If the caller is not `sender`, it must be an authorized relayer for them.
     *
     * If `fromInternalBalance` is true, the `sender`'s Internal Balance will be preferred, performing an ERC20
     * transfer for the difference between the requested amount and the User's Internal Balance (if any). The `sender`
     * must have allowed the Vault to use their tokens via `IERC20.approve()`. This matches the behavior of
     * `joinPool`.
     *
     * If `toInternalBalance` is true, tokens will be deposited to `recipient`'s internal balance instead of
     * transferred. This matches the behavior of `exitPool`.
     *
     * Note that ETH cannot be deposited to or withdrawn from Internal Balance: attempting to do so will trigger a
     * revert.
     */
    struct FundManagement {
        address sender;
        bool fromInternalBalance;
        address payable recipient;
        bool toInternalBalance;
    }
}
IAggregatorV3Interface.sol 15 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/external/chainlink/IAggregatorV3Interface.sol)

interface IAggregatorV3Interface {
    function latestRoundData() external view
        returns (
            uint80 roundId,
            int256 answer,
            uint256 startedAt,
            uint256 updatedAt,
            uint80 answeredInRound
        );
    function decimals() external view returns (uint8);
}
IKodiakIsland.sol 16 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/external/kodiak/IKodiakIsland.sol)

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IKodiakV3Pool } from "contracts/interfaces/external/kodiak/IKodiakV3Pool.sol";

interface IKodiakIsland is IERC20 {
    function getUnderlyingBalances() external view returns (uint256 amount0Current, uint256 amount1Current);
    function token0() external view returns (IERC20);
    function token1() external view returns (IERC20);
    function pool() external view returns (IKodiakV3Pool);
    function lowerTick() external view returns (int24);
    function upperTick() external view returns (int24);
    function getMintAmounts(uint256 amount0Max, uint256 amount1Max) external view returns (uint256 amount0, uint256 amount1, uint256 mintAmount);
}
IKodiakV3Pool.sol 19 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/external/kodiak/IKodiakV3Pool.sol)

/// @dev Kodiak is a uniswap v3 fork -- however they changed the feeProtocol from uint8 => uint32
interface IKodiakV3Pool {
    function slot0() external view returns (
        uint160 sqrtPriceX96,
        int24 tick,
        uint16 observationIndex,
        uint16 observationCardinality,
        uint16 observationCardinalityNext,
        uint32 feeProtocol,
        bool unlocked
    );
        
    function token0() external view returns (address);
    function token1() external view returns (address);
}
IStETH.sol 17 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (external/lido/IStETH.sol)

import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

interface IStETH is IERC20Metadata {
    /**
     * @return the amount of shares that corresponds to `_ethAmount` protocol-controlled Ether.
     */
    function getSharesByPooledEth(uint256 _ethAmount) external view returns (uint256);

    /**
     * @return the amount of Ether that corresponds to `_sharesAmount` token shares.
     */
    function getPooledEthByShares(uint256 _sharesAmount) external view returns (uint256);
}
ITokenizedBalanceSheetVault.sol 406 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later

import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { IERC20Metadata } from "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";

/**
 * @title Tokenized 'Balance Sheet' Vault
 * @notice
 *  Shares in this vault represent a proportional slice of the balance sheet of this vault. The balance sheet adheres to the
 *  fundamental accounting equation: equity = assets - liabilities
 *    - ASSETS represent positive value of the vault, and may be composed of zero or more ERC20 tokens.
 *      The balance of each asset token in the balance sheet may be of different amounts.
 *    - LIABILITIES represent debt that this vault owes, and may be composed of zero or more ERC20 tokens.
 *      The balance of each liability token in the balance sheet may be of different amounts.
 *
 *  When a user mints new shares (aka equity):
 *    - They PROVIDE a proportional amount of each ASSET in the balance sheet as of that moment, for that number of shares.
 *    - They RECEIVE a proportional amount of each LIABILITY in the balance sheet as of that moment, for that number of shares.
 *    - The shares representing that proportional slice of the balance sheet equity are minted.
 *
 *  When a user redeems shares:
 *    - They PROVIDE a proportional amount of each LIABILITY in the balance sheet as of that moment, for that number of shares.
 *    - They RECEIVE a proportional amount of each ASSET in the balance sheet as of that moment, for that number of shares.
 *    - Those shares are burned.
 *
 *  The ASSET or LIABILITY amounts on the balance sheet can change over time:
 *    - The balances of the ASSETS may grow or shrink over time (eg yield, rebalancing the weights of the assets)
 *    - The balances of the LIABILITIES may grow or shrink over time (eg borrow cost increasing the debt over time)
 *
 *  The ASSET or LIABILITY token addresses can change over time:
 *    - A new asset may be added to the balance sheet (rolling Pendle PT expiries)
 *    - An asset can be removed from the balance sheet (effectively zero balance - removed for efficiency)
 *
 * The interface is inspired by ERC-4626. The intended high level UX is:
 *    - joinWithShares(shares):
 *        Caller specifies the number of shares to mint and the amount of each ASSET (pulled from user) and LIABILITY (sent to user)
 *        token is derived from the existing balance weights of the vault's balance sheet.
 *    - joinWithToken(tokenAddress, amount):
 *        Caller specifies either one of the ASSET addresses (pulled from user) or one of the LIABILITY addresses (sent to user),
 *        and the amount of that token. The number of shares to mint, and the required number of the remaining ASSET (pulled from user) and
 *        LIABILITY (sent to user) tokens are derived from the existing balance weights of the vault's balance sheet.
 *    - exitWithShares(shares):
 *        Caller specifies the number of shares to burn and the amount of each ASSET (sent to user) and LIABILITY (pulled from user)
 *        token is derived from the existing balance weights of the vault's balance sheet.
 *    - exitWithToken(tokenAddress, amount):
 *        Caller specifies either one of the ASSET addresses (sent to user) or one of the LIABILITY addresses (pulled from user),
 *        and the amount of that token. The number of shares to burn, and the required number of the remaining ASSET (sent to user) and
 *        LIABILITY (pulled from user) tokens are derived from the existing balance weights of the vault's balance sheet.
 *
 * The benefits of representing the Balance Sheet tokens 'in kind' include
 *    - No oracles required to convert into a single vault asset (like ERC-4626 would require)
 *    - There is no realisation of exposure (from a vault perspective) from one asset/liability into a single vault asset at a certain point in time.
 *    - The vault is not affected if there is a lack of liquidity to convert the other assets/liabilities into a single vault asset.
 *
 * A drawback is that the UX and integration is obviously tricker.
 *    - In most cases, it's likely that there will be AMM liquidity in order for users to easily buy/sell the vault token, rather than minting redeeming
 *    - More sophisticated can mint/redeem directly providing and receiving all required balance sheet tokens.
 *      This could include arbitrage bots which can ensure the AMM liquidity is pegged to the 'real' vault price.
 *    - 'zaps' can be added where possible for dapps to allocate in to the right assets - eg to provide the best price to users (AMM buy vs direct mint)
 *    - The asset and liability tokens can change over time depending on the specific implementation. Integrators need to be aware of this.
 *
 * As with ERC-4626, there is no slippage/deadline guarantees within this interface enforcing bounds on the sent/received. If required for a particular integration,
 * it can be handled via an intermediate 'router' contract enforcing bounds on the assets/liabilities/shares which are transferred.
 */
interface ITokenizedBalanceSheetVault is IERC20, IERC20Metadata {
    
    /// @dev Emitted during a joinWithToken or joinWithShares
    event Join(
        address indexed sender,
        address indexed owner,
        uint256[] assets,
        uint256[] liabilities,
        uint256 shares
    );

    /// @dev Emitted during a exitWithToken or exitWithShares
    event Exit(
        address indexed sender,
        address indexed receiver,
        address indexed owner,
        uint256[] assets,
        uint256[] liabilities,
        uint256 shares
    );

    /**
     * @notice Returns the addresses of the underlying tokens which represent the ASSETS and LIABILITIES in the Vault's balance sheet
     * @dev
     * - MUST be ERC-20 token contracts.
     * - MUST NOT revert.
     *
     * NOTE: tokens MAY be added or removed over time.
     */
    function tokens() external view returns (address[] memory assetTokens, address[] memory liabilityTokens);

    /**
     * @notice Returns the addresses of the underlying tokens which represent the ASSETS in the Vault's balance sheet
     * @dev
     * - MUST be ERC-20 token contracts.
     * - MUST NOT revert.
     *
     * NOTE: tokens MAY be added or removed over time.
     */
    function assetTokens() external view returns (address[] memory tokens);

    /**
     * @notice Returns the addresses of the underlying tokens which represent the LIABILITIES in the Vault's balance sheet
     * @dev
     * - MUST be ERC-20 token contracts.
     * - MUST NOT revert.
     *
     * NOTE: tokens MAY be added or removed over time.
     */
    function liabilityTokens() external view returns (address[] memory tokens);

    /**
     * @notice Validates if a given token is either an asset or a liability
     */
    function isBalanceSheetToken(address tokenAddress) external view returns (bool isAsset, bool isLiability);

    /**
     * @notice Returns the total amount of the ASSETS and LIABILITIES managed by this vault.
     * @dev
     * - `totalAssets` MUST return a list which is the same size and order as `assetTokens()`
     * - `totalLiabilities` MUST return a list which is the same size and order as `liabilityTokens()`
     * - 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 balanceSheet() external view returns (uint256[] memory totalAssets, uint256[] memory totalLiabilities);

    /**
     * @notice Returns the amount of shares that the Vault would exchange for the amount of `tokenAddress` provided, in an ideal
     * scenario where all the conditions are met.
     * The address and exact number of tokens of one of the `balanceSheetTokens()` is specified.
     * The remaining assets and liabilities are derived from the current balance sheet, along with the number of shares that would represent.
     *  @dev
     * - 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.
     * - If `tokenAddress` is not one of the `balanceSheetTokens()` then shares, assets and libilities MUST have zero amounts.
     *
     * 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 convertFromToken(
        address tokenAddress,
        uint256 tokenAmount
    ) external view returns (
        uint256 shares,
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
     * @notice Returns the amount of assets and liabilities that the Vault would exchange for the amount of shares provided, in an ideal
     * scenario where all the conditions are met.
     * The assets and liabilities are derived from the current balance sheet.
     * @dev
     * - 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 convertFromShares(
        uint256 shares
    ) external view returns (
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
     * @notice Returns the maximum amount of `tokenAddress` that can be joined into the vault for the `receiver`,
     * through a joinWithToken call
     * `tokenAddress` must represent one of the assetTokens or liabilityTokens within `balanceSheetTokens()`
     * @dev
     * - MUST return a limited value if receiver is subject to some limit.
     * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of `tokenAddress` that may be joined.
     * - MUST NOT revert.
     * - If `tokenAddress` is not one of the `balanceSheetTokens()` then this MUST return 0.
     */
    function maxJoinWithToken(
        address tokenAddress,
        address receiver
    ) external view returns (uint256 maxTokens);

    /**
     * @notice Allows an on-chain or off-chain user to simulate the effects of their joined at the current block, given
     * current on-chain conditions.
     * The address and exact number of tokens of one of the `balanceSheetTokens()` is specified.
     * The remaining assets and liabilities are derived from the current balance sheet, along with the number of shares that would represent.
     * @dev
     * - MUST return the `shares` as close to and NO MORE than the exact amount of Vault shares
     *    that would be minted in a joinWithToken call in the same transaction (ie round down).
     * - MUST return the `assets` as close to and NO LESS than the exact amount of tokens
     *    transferred FROM the sender for a joinWithToken call in the same transaction (ie round up).
     * - MUST return the `liabilities` as close to and NO MORE than the exact amount of tokens
     *    transferred TO the receiver for a joinWithToken call in the same transaction (ie round down).
     * - MUST NOT account for join limits like those returned from maxJoinWithToken and should always act as though the
     *    join would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of join fees. Integrators should be aware of the existence of join fees.
     * - MUST NOT revert.
     * - If `tokenAddress` is not one of the `balanceSheetTokens()` then shares, assets and libilities MUST have zero amounts.
     */
    function previewJoinWithToken(
        address tokenAddress,
        uint256 tokenAmount
    ) external view returns (
        uint256 shares,
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
      * @notice Mints Vault shares to receiver by transferring an exact amount of underlying tokens proportional to the current balance sheet.
      * The address and exact number of tokens of one of the `balanceSheetTokens()` is specified.
      * The remaining assets and liabilities are derived from the current balance sheet, along with the number of shares that would represent.
      * @dev
      * - MUST emit the JoinWithToken event
      * - MUST revert if all of assets cannot be joined (due to join 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 all of the asset tokens
      */
    function joinWithToken(
        address tokenAddress,
        uint256 tokenAmount,
        address receiver
    ) external returns (
        uint256 shares,
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
     * @notice Returns the maximum amount of the Vault shares that can be minted for the `receiver`, through a joinWithShares call.
     * @dev
     * - 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 maxJoinWithShares(
        address receiver
    ) external view returns (uint256 maxShares);

    /**
     * @notice Allows an on-chain or off-chain user to simulate the effects of their joinWithShares at the current block, given
     * current on-chain conditions.
     * The assets and liabilities are derived from the current balance sheet for that number of shares.
     * @dev
     * - MUST return the `assets` as close to and NO LESS than the exact amount of tokens
     *    transferred FROM the sender for a joinWithShares call in the same transaction (ie round up).
     * - MUST return the `liabilities` as close to and NO MORE than the exact amount of tokens
     *    transferred TO the receiver for a joinWithShares call in the same transaction (ie round down).
     * - MUST NOT account for mint limits like those returned from maxJoinWithShares and should always act as though the
     *    joinWithShares would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of join fees. Integrators should be aware of the existence of join fees.
     * - MUST NOT revert.
     */
    function previewJoinWithShares(
        uint256 shares
    ) external view returns (
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
      * @notice Mints exactly `shares` Vault shares to receiver by joining amount of underlying tokens.
      * The assets and liabilities are derived from the current balance sheet for that number of shares.
      * @dev
      * - MUST emit the Join event
      * - MUST revert if all of shares cannot be minted (due to join 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 all of the asset tokens
      */
    function joinWithShares(
        uint256 shares,
        address receiver
    ) external returns (
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
     * @notice Returns the maximum amount of `tokenAddress` that can be withdrawn from the vault given the owner balance in the vault,
     * through a exitWithToken call
     * `tokenAddress` must represent one of the assetTokens or liabilityTokens within `balanceSheetTokens()`
     * @dev
     * - MUST return a limited value if owner is subject to some exit limit or timelock.
     * - MUST NOT revert.
     * - If `tokenAddress` is not one of the `balanceSheetTokens()` then this MUST return 0.
     */
    function maxExitWithToken(
        address tokenAddress,
        address owner
    ) external view returns (uint256 maxTokens);

    /**
     * @notice Allows an on-chain or off-chain user to simulate the effects of their exit at the current block,
     * given current on-chain conditions.
     * The address and exact number of tokens of one of the `balanceSheetTokens()` is specified.
     * The remaining assets and liabilities are derived from the current balance sheet, along with the number of shares that would represent.
     * @dev
     * - MUST return the `shares` as close to and NO LESS than the exact amount of Vault shares
     *    that would be burned in a exitWithToken call in the same transaction. (ie round up)
     * - MUST return the `assets` as close to and NO MORE than the exact amount of tokens
     *    transferred TO the sender for a exitWithToken call in the same transaction (ie round down).
     * - MUST return the `liabilities` as close to and NO LESS than the exact amount of tokens
     *    transferred FROM the receiver for a exitWithToken call in the same transaction (ie round up).
     * - MUST NOT account for exit limits like those returned from maxExitWithToken and should always act as though the
     *    exit would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of exit fees. Integrators should be aware of the existence of exit fees.
     * - MUST NOT revert.
     * - If `tokenAddress` is not one of the `balanceSheetTokens()` then shares, assets and libilities MUST have zero amounts.
     */
    function previewExitWithToken(
        address tokenAddress,
        uint256 tokenAmount
    ) external view returns (
        uint256 shares,
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
      * @notice Burns shares from owner, sends exactly `tokenAddress` of underlying tokens to receiver.
      * The address and exact number of tokens of one of the `balanceSheetTokens()` is specified.
      * The remaining assets and liabilities are derived from the current balance sheet, along with the number of shares that would represent.
      * @dev
      * - MUST emit the Exit event.
      * - MUST revert if all of assets cannot be withdrawn (due to exit limit being reached, slippage, the owner
      *    not having enough shares, etc).
      *
      * NOTE: most implementations will require pre-approval of the Vault with all of the liability tokens.
      */
    function exitWithToken(
        address tokenAddress,
        uint256 tokenAmount,
        address receiver,
        address owner
    ) external returns (
        uint256 shares,
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
     * @notice Returns the maximum amount of Vault shares that can be redeemed from the vault given the owner balance in the vault,
     * through a exitWithShares call.
     * @dev
     * - MUST return a limited value if owner is subject to some exit limit or timelock.
     * - MUST return balanceOf(owner) if owner is not subject to any exit limit or timelock.
     * - MUST NOT revert.
     */
    function maxExitWithShares(
        address owner
    ) external view returns (uint256 maxShares);

    /**
     * @notice Allows an on-chain or off-chain user to simulate the effects of their redemption at the current block,
     * given current on-chain conditions.
     * The assets and liabilities are derived from the current balance sheet for that number of shares.
     * @dev
     * - MUST return the `assets` as close to and NO MORE than the exact amount of tokens
     *    transferred TO the sender for a exitWithShares call in the same transaction (ie round down).
     * - MUST return the `liabilities` as close to and NO LESS than the exact amount of tokens
     *    transferred FROM the receiver for a exitWithShares call in the same transaction (ie round up).
     * - MUST NOT account for redemption limits like those returned from maxExitWithShares and should always act as though the
     *    redemption would be accepted, regardless if the user has enough tokens approved, etc.
     * - MUST be inclusive of exit fees. Integrators should be aware of the existence of exit fees.
     * - MUST NOT revert.
     */
    function previewExitWithShares(
        uint256 shares
    ) external view returns (
        uint256[] memory assets,
        uint256[] memory liabilities
    );

    /**
      * @notice Burns shares from owner.
      * The assets and liabilities are derived from the current balance sheet for that number of shares.
      * @dev
      * - MUST emit the Exit event.
      * - MUST revert if all of assets cannot be redeemed (due to exit limit being reached, slippage, the owner
      *    not having enough shares, etc).
      *
      * NOTE: most implementations will require pre-approval of the Vault with all of the liability tokens.
      */
    function exitWithShares(
        uint256 shares,
        address receiver,
        address owner
    ) external returns (
        uint256[] memory assets,
        uint256[] memory liabilities
    );
}
IJoeLBQuoter.sol 33 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/external/traderJoe/IJoeLBQuoter.sol)

interface IJoeLBQuoter {
    struct Quote {
        address[] route;
        address[] pairs;
        uint256[] binSteps;
        uint256[] amounts;
        uint256[] virtualAmountsWithoutSlippage;
        uint256[] fees;
    }

    /// @notice Finds the best path given a list of tokens and the input amount wanted from the swap
    /// @param _route List of the tokens to go through
    /// @param _amountIn Swap amount in
    /// @return quote The Quote structure containing the necessary element to perform the swap
    function findBestPathFromAmountIn(address[] calldata _route, uint256 _amountIn)
        external
        view
        returns (Quote memory quote);

    /// @notice Finds the best path given a list of tokens and the output amount wanted from the swap
    /// @param _route List of the tokens to go through
    /// @param _amountOut Swap amount out
    /// @return quote The Quote structure containing the necessary element to perform the swap
    function findBestPathFromAmountOut(address[] calldata _route, uint256 _amountOut)
        external
        view
        returns (Quote memory quote);
}
IUniswapV3Pool.sol 24 lines
pragma solidity ^0.8.4;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (interfaces/external/uniswap/IUniswapV3Pool.sol)

interface IUniswapV3Pool {
    function slot0() external view returns (
        uint160 sqrtPriceX96,
        int24 tick,
        uint16 observationIndex,
        uint16 observationCardinality,
        uint16 observationCardinalityNext,
        uint8 feeProtocol,
        bool unlocked
    );
        
    function token0() external view returns (address);
    function token1() external view returns (address);
    function tickSpacing() external view returns (int24);

    /// @notice Sets the initial price for the pool
    /// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
    /// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
    function initialize(uint160 sqrtPriceX96) external;
}
CommonEventsAndErrors.sol 20 lines
pragma solidity ^0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (libraries/CommonEventsAndErrors.sol)

/// @notice A collection of common events and errors thrown within the Origami contracts
library CommonEventsAndErrors {
    error InsufficientBalance(address token, uint256 required, uint256 balance);
    error InvalidToken(address token);
    error InvalidParam();
    error InvalidAddress(address addr);
    error InvalidAmount(address token, uint256 amount);
    error ExpectedNonZero();
    error Slippage(uint256 minAmountExpected, uint256 actualAmount);
    error IsPaused();
    error UnknownExecuteError(bytes returndata);
    error InvalidAccess();
    error BreachedMaxTotalSupply(uint256 totalSupply, uint256 maxTotalSupply);

    event TokenRecovered(address indexed to, address indexed token, uint256 amount);
}
OrigamiMath.sol 174 lines
pragma solidity ^0.8.19;
// SPDX-License-Identifier: AGPL-3.0-or-later
// Origami (libraries/OrigamiMath.sol)

import { mulDiv as prbMulDiv, PRBMath_MulDiv_Overflow } from "@prb/math/src/Common.sol";
import { CommonEventsAndErrors } from "contracts/libraries/CommonEventsAndErrors.sol";

/**
 * @notice Utilities to operate on fixed point math multipliation and division
 * taking rounding into consideration
 */
library OrigamiMath {
    enum Rounding {
        ROUND_DOWN,
        ROUND_UP
    }

    uint256 public constant BASIS_POINTS_DIVISOR = 10_000;
    uint256 public constant WAD_DECIMALS = 18;
    uint256 public constant WAD = 10 ** WAD_DECIMALS;

    function scaleUp(uint256 amount, uint256 scalar) internal pure returns (uint256) {
        // Special case for scalar == 1, as it's common for token amounts to not need
        // scaling if decimal places are the same
        return scalar == 1 ? amount : amount * scalar;
    }

    function scaleDown(
        uint256 amount, 
        uint256 scalar, 
        Rounding roundingMode
    ) internal pure returns (uint256 result) {
        // Special case for scalar == 1, as it's common for token amounts to not need
        // scaling if decimal places are the same
        unchecked {
            if (scalar == 1) {
                result = amount;
            } else if (roundingMode == Rounding.ROUND_DOWN) {
                result = amount / scalar;
            } else {
                // ROUND_UP uses the same logic as OZ Math.ceilDiv()
                result = amount == 0 ? 0 : (amount - 1) / scalar + 1;
            }
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision,
     * rounding up
     */
    function mulDiv(
        uint256 x, 
        uint256 y, 
        uint256 denominator,
        Rounding roundingMode
    ) internal pure returns (uint256 result) {
        result = prbMulDiv(x, y, denominator);
        if (roundingMode == Rounding.ROUND_UP) {
            if (mulmod(x, y, denominator) != 0) {
                if (result < type(uint256).max) {
                    unchecked {
                        result = result + 1;
                    }
                } else {
                    revert PRBMath_MulDiv_Overflow(x, y, denominator);
                }
            }
        }
    }

    function subtractBps(
        uint256 inputAmount, 
        uint256 basisPoints,
        Rounding roundingMode
    ) internal pure returns (uint256 result) {
        uint256 numeratorBps;
        unchecked {
            numeratorBps = BASIS_POINTS_DIVISOR - basisPoints;
        }

        result = basisPoints < BASIS_POINTS_DIVISOR
            ? mulDiv(
                inputAmount,
                numeratorBps, 
                BASIS_POINTS_DIVISOR, 
                roundingMode
            ) : 0;
    }

    function addBps(
        uint256 inputAmount,
        uint256 basisPoints,
        Rounding roundingMode
    ) internal pure returns (uint256 result) {
        uint256 numeratorBps = BASIS_POINTS_DIVISOR + basisPoints;

        // Round up for max amounts out expected
        result = mulDiv(
            inputAmount,
            numeratorBps, 
            BASIS_POINTS_DIVISOR, 
            roundingMode
        );
    }

    /**
     * @notice Split the `inputAmount` into two parts based on the `basisPoints` fraction.
     * eg: 3333 BPS (33.3%) can be used to split an input amount of 600 into: (result=400, removed=200).
     * @dev The rounding mode is applied to the `result`
     */
    function splitSubtractBps(
        uint256 inputAmount, 
        uint256 basisPoints,
        Rounding roundingMode
    ) internal pure returns (uint256 result, uint256 removed) {
        if (basisPoints == 0) return (inputAmount, 0); // gas shortcut for 0

        result = subtractBps(inputAmount, basisPoints, roundingMode);
        unchecked {
            removed = inputAmount - result;
        }
    }

    /**
     * @notice Reverse the fractional amount of an input.
     * eg: For 3333 BPS (33.3%) and the remainder=400, the result is 600
     */
    function inverseSubtractBps(
        uint256 remainderAmount, 
        uint256 basisPoints,
        Rounding roundingMode
    ) internal pure returns (uint256 result) {
        if (basisPoints == 0) return remainderAmount; // gas shortcut for 0
        if (basisPoints >= BASIS_POINTS_DIVISOR) revert CommonEventsAndErrors.InvalidParam();

        uint256 denominatorBps;
        unchecked {
            denominatorBps = BASIS_POINTS_DIVISOR - basisPoints;
        }
        result = mulDiv(
            remainderAmount,
            BASIS_POINTS_DIVISOR, 
            denominatorBps, 
            roundingMode
        );
    }

    /**
     * @notice Calculate the relative difference of a value to a reference
     * @dev `value` and `referenceValue` must have the same precision
     * The denominator is always the referenceValue
     */
    function relativeDifferenceBps(
        uint256 value,
        uint256 referenceValue,
        Rounding roundingMode
    ) internal pure returns (uint256) {
        if (referenceValue == 0) revert CommonEventsAndErrors.InvalidParam();

        uint256 absDelta;
        unchecked {
            absDelta = value < referenceValue
                ? referenceValue - value
                : value - referenceValue;
        }

        return mulDiv(
            absDelta,
            BASIS_POINTS_DIVISOR,
            referenceValue,
            roundingMode
        );
    }
}

Read Contract

aliasFor 0x2b6173b5 → uint256
allMappedTokens 0x7e1ac748 → address[]
balancerV2BptPrice 0xcbf4f651 → uint256
decimals 0x313ce567 → uint8
div 0x047d3ee7 → uint256
erc4626TokenPrice 0xfd47f60f → uint256
kodiakIslandPrice 0x91b694fc → uint256
kodiakV3Price 0x65b4c6e1 → uint256
mappedTokenAt 0xd74385d9 → address
mul 0x56cdeb0b → uint256
numMappedTokens 0x329aac80 → uint256
oraclePrice 0x843a3b50 → uint256
origamiOraclePrice 0x04b39534 → uint256
owner 0x8da5cb5b → address
priceFnCalldata 0xcd283085 → bytes
repricingTokenPrice 0x7eb11c63 → uint256
scalar 0x0983b122 → uint256
tokenPrice 0x84ba3f69 → uint256
tokenPrices 0x04330676 → uint256[]
tokenizedBalanceSheetTokenPrice 0xc02486d0 → uint256
traderJoeBestPrice 0xa67a6843 → uint256
univ3Price 0x9a59b9bd → uint256
wstEthRatio 0x695ee9ae → uint256

Write Contract 4 functions

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

renounceOwnership 0x715018a6
No parameters
setTokenPriceFunction 0x1f96b34e
address token
bytes fnCalldata
setTokenPriceFunctions 0x5d6179af
tuple[] mappings
transferOwnership 0xf2fde38b
address newOwner

Recent Transactions

No transactions found for this address