Cryo Explorer Ethereum Mainnet

Address Contract Partially Verified

Address 0xfB07a644a9e53879f29f7B3f29362e9c95b1FFA3
Balance 0 ETH
Nonce 1
Code Size 15548 bytes
Indexed Transactions Index loading...
External Etherscan · Sourcify

Contract Bytecode

15548 bytes
0x60806040526004361061023f5760003560e01c80639010d07c1161012e578063ca15c873116100ab578063e06bf20d1161006f578063e06bf20d14610704578063e404d8ce14610724578063e80e8a7d14610744578063e8ddecba14610764578063fd4d4ad21461079757600080fd5b8063ca15c8731461065d578063cbdf382c1461067d578063ce46e046146106b0578063d547741f146106c4578063d7882fdf146106e457600080fd5b8063a217fddf116100f2578063a217fddf146105ad578063a9c63258146105c2578063b187bd26146105e2578063b89bd433146105f7578063c878ab331461062a57600080fd5b80639010d07c146104e157806391d148541461051957806392bd95ea1461053957806393867fb51461056c5780639dc29fac1461058d57600080fd5b806354fd4d50116101bc5780637c8f622d116101805780637c8f622d146104575780638129fc1c146104775780638456cb591461048c5780638cd2403d146104a15780638d0c7827146104c157600080fd5b806354fd4d50146103cc5780635b9f0016146103e85780635c975abb146103fe578063639c35741461041657806371c0feb71461043757600080fd5b8063248a9ca311610203578063248a9ca3146103275780632f2ff15d1461035757806336568abe146103775780633f4ba83a1461039757806340c10f19146103ac57600080fd5b806301ffc9a71461026457806308fc3385146102995780630f1544c4146102c75780631c20fadd146102e75780631ebda06d1461030757600080fd5b3661025f57604051631574f9f360e01b815260040160405180910390fd5b005b600080fd5b34801561027057600080fd5b5061028461027f3660046136b5565b6107ce565b60405190151581526020015b60405180910390f35b3480156102a557600080fd5b506102b96102b43660046136df565b6107f9565b604051908152602001610290565b3480156102d357600080fd5b506102b96102e23660046136df565b61081e565b3480156102f357600080fd5b5061025d61030236600461370d565b610829565b34801561031357600080fd5b5061025d61032236600461374e565b61099f565b34801561033357600080fd5b506102b96103423660046136df565b60009081526065602052604090206001015490565b34801561036357600080fd5b5061025d610372366004613775565b610dd8565b34801561038357600080fd5b5061025d610392366004613775565b610e03565b3480156103a357600080fd5b5061025d610e81565b3480156103b857600080fd5b5061025d6103c73660046137a5565b610ea3565b3480156103d857600080fd5b5060405160038152602001610290565b3480156103f457600080fd5b5061015f546102b9565b34801561040a57600080fd5b5060fb5460ff16610284565b34801561042257600080fd5b50600080516020613c708339815191526102b9565b34801561044357600080fd5b5061025d61045236600461374e565b610f69565b34801561046357600080fd5b5061025d6104723660046137df565b6113a1565b34801561048357600080fd5b5061025d61142f565b34801561049857600080fd5b5061025d6114f0565b3480156104ad57600080fd5b5061025d6104bc366004613821565b611510565b3480156104cd57600080fd5b506102b96104dc366004613893565b611561565b3480156104ed57600080fd5b506105016104fc3660046138b0565b611611565b6040516001600160a01b039091168152602001610290565b34801561052557600080fd5b50610284610534366004613775565b611630565b34801561054557600080fd5b507f89ce14d20697a788f57260f7690044299bde7ea88cfb7e43d120a0c031f1ffc16102b9565b34801561057857600080fd5b50600080516020613c908339815191526102b9565b34801561059957600080fd5b5061025d6105a83660046137a5565b61165b565b3480156105b957600080fd5b506102b9600081565b3480156105ce57600080fd5b5061025d6105dd3660046136df565b611925565b3480156105ee57600080fd5b506102846119ff565b34801561060357600080fd5b507f473e02917e58ac16ae36b64246942eb4bb4dcf262bc3c3c50359aa9af6bb44f96102b9565b34801561063657600080fd5b507f4cbb5676e6e25e1a3b8a36de10472bcac96f97bd8dd87af6f330881b84739eb86102b9565b34801561066957600080fd5b506102b96106783660046136df565b611a12565b34801561068957600080fd5b507f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e344610501565b3480156106bc57600080fd5b506000610284565b3480156106d057600080fd5b5061025d6106df366004613775565b611a29565b3480156106f057600080fd5b506102b96106ff3660046136df565b611a4f565b34801561071057600080fd5b506102b961071f3660046138d2565b611a5a565b34801561073057600080fd5b506102b961073f366004613924565b611eb0565b34801561075057600080fd5b506102b961075f3660046136df565b612097565b34801561077057600080fd5b507f0d0d17bf5382c809d9a3899d6a94e57386dfb2036f0401b94ef3cf6c1a9ab73f6102b9565b3480156107a357600080fd5b506102b96107b2366004613893565b6001600160a01b03166000908152610160602052604090205490565b60006001600160e01b03198216635a05180f60e01b14806107f357506107f3826121fd565b92915050565b60008161080581612232565b61081661081184612253565b6122e4565b519392505050565b60006107f382612253565b81610833816123b6565b600261012d540361088b5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c0060448201526064015b60405180910390fd5b600261012d5560fb5460ff16156108b45760405162461bcd60e51b815260040161088290613961565b338484846108c4848484846123dd565b6108e157604051634ca8886760e01b815260040160405180910390fd5b851561098f5773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b038916036109235761091e6001600160a01b03881687612449565b610937565b6109376001600160a01b0389168888612562565b866001600160a01b0316336001600160a01b0316896001600160a01b03167fc322efa58c9cb2c39cfffdac61d35c8643f5cbf13c6a7d0034de2cf18923aff38960405161098691815260200190565b60405180910390a45b5050600161012d55505050505050565b600080516020613c708339815191526109b881336125e3565b826109c28161260a565b826109cc81612232565b61015f546001600160a01b03861660009081526101606020526040812054906109f582886126b1565b905060007f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015610a57573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610a7b919061398b565b90506000610a8a8383876126c7565b6040516370a0823160e01b8152306004820152909150610b209082906001600160a01b037f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e34416906370a0823190602401602060405180830381865afa158015610af7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610b1b919061398b565b6126b1565b90506000610b2f8287856126e3565b9050610b3b84866139ba565b6001600160a01b038c1660009081526101606020526040812091909155610b6282886139ba565b61015f819055604051630852cd8d60e31b8152600481018590529091507f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b0316906342966c6890602401600060405180830381600087803b158015610bcd57600080fd5b505af1158015610be1573d6000803e3d6000fd5b5050604051632770a7eb60e21b81526001600160a01b037f000000000000000000000000649765821d9f64198c905ec0b2b037a4a52bc373169250639dc29fac9150610c53907f0000000000000000000000001f573d6fb3f13d689ff844b4ce37794d79a7ff1c908f906004016139d1565b600060405180830381600087803b158015610c6d57600080fd5b505af1158015610c81573d6000803e3d6000fd5b505050508b6001600160a01b03168d7f343b2618f119491ea746148809f6073b9cbf1ebf15155ad4661dba2f6dd0f4518d86604051610cca929190918252602082015260400190565b60405180910390a36040516370a0823160e01b81526001600160a01b037f000000000000000000000000649765821d9f64198c905ec0b2b037a4a52bc373811660048301528e917f78892d9576143a8e05c38de593d7fe77e75be9a9f2047dc5de22e6cec00076bf917f0000000000000000000000001f573d6fb3f13d689ff844b4ce37794d79a7ff1c16906370a0823190602401602060405180830381865afa158015610d7c573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610da0919061398b565b83610dab87896139ba565b6040805193845260208401929092529082015260600160405180910390a250505050505050505050505050565b600082815260656020526040902060010154610df481336126ff565b610dfe8383612763565b505050565b6001600160a01b0381163314610e735760405162461bcd60e51b815260206004820152602f60248201527f416363657373436f6e74726f6c3a2063616e206f6e6c792072656e6f756e636560448201526e103937b632b9903337b91039b2b63360891b6064820152608401610882565b610e7d8282612785565b5050565b610e99600080516020613c90833981519152336125e3565b610ea16127a7565b565b7f4cbb5676e6e25e1a3b8a36de10472bcac96f97bd8dd87af6f330881b84739eb8610ece81336125e3565b82610ed8816123b6565b82610ee281612232565b6040516340c10f1960e01b81526001600160a01b037f000000000000000000000000a489c2b5b36835a327851ab917a80562b5afc24416906340c10f1990610f3090889088906004016139d1565b600060405180830381600087803b158015610f4a57600080fd5b505af1158015610f5e573d6000803e3d6000fd5b505050505050505050565b600080516020613c70833981519152610f8281336125e3565b82610f8c8161260a565b82610f9681612232565b6001600160a01b038581166000818152610160602052604080822054905163467e55df60e01b815260048101939093529290917f00000000000000000000000083e1814ba31f7ea95d216204bb45fe75ce09b14f9091169063467e55df90602401602060405180830381865afa158015611014573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611038919061398b565b9050600061104687846139ea565b90508181111561106957604051632dae22ef60e21b815260040160405180910390fd5b600061015f5490506000807f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156110d2573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110f6919061398b565b9050801580156111065750600083115b1561112457604051636a9c61e160e01b815260040160405180910390fd5b61112f8a82856126c7565b9150600061113d8b856139ea565b61015f8190556001600160a01b03808e166000908152610160602052604090819020889055516340c10f1960e01b81529192507f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e34416906340c10f19906111a990309087906004016139d1565b600060405180830381600087803b1580156111c357600080fd5b505af11580156111d7573d6000803e3d6000fd5b50506040516340c10f1960e01b81526001600160a01b037f000000000000000000000000a489c2b5b36835a327851ab917a80562b5afc2441692506340c10f199150611249907f000000000000000000000000649765821d9f64198c905ec0b2b037a4a52bc373908f906004016139d1565b600060405180830381600087803b15801561126357600080fd5b505af1158015611277573d6000803e3d6000fd5b505050508b6001600160a01b03168d7ffd8684b04dc22a1ff327e3387f1b4a1f6bb6ac801505a61ca0c295a823c6de838d866040516112c0929190918252602082015260400190565b60405180910390a36040516370a0823160e01b81526001600160a01b037f000000000000000000000000649765821d9f64198c905ec0b2b037a4a52bc373811660048301528e917f78892d9576143a8e05c38de593d7fe77e75be9a9f2047dc5de22e6cec00076bf917f0000000000000000000000001f573d6fb3f13d689ff844b4ce37794d79a7ff1c16906370a0823190602401602060405180830381865afa158015611372573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611396919061398b565b83610dab87876139ea565b7f000000000000000000000000eef417e1d5cc832e619ae18d2f140de2999dd4fb6113cb8161283a565b836113d5816123b6565b8315611428578361015f60008282546113ee91906139ea565b90915550508215611428576001600160a01b03851660009081526101606020526040812080548692906114229084906139ea565b90915550505b5050505050565b600054610100900460ff1661144a5760005460ff161561144e565b303b155b6114b15760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b6064820152608401610882565b600054610100900460ff161580156114d3576000805461ffff19166101011790555b6114db612863565b80156114ed576000805461ff00191690555b50565b611508600080516020613c90833981519152336125e3565b610ea161289a565b60c9546000906115259061ffff166001613a02565b905061ffff811660031461154b5760405162dc149f60e41b815260040160405180910390fd5b60c9805461ffff191661ffff8316179055505050565b60405163467e55df60e01b81526001600160a01b0382811660048301526000916107f3917f00000000000000000000000083e1814ba31f7ea95d216204bb45fe75ce09b14f169063467e55df90602401602060405180830381865afa1580156115ce573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906115f2919061398b565b6001600160a01b038416600090815261016060205260409020546128f2565b6000828152609760205260408120611629908361290c565b9392505050565b60009182526065602090815260408084206001600160a01b0393909316845291905290205460ff1690565b600261012d54036116ae5760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c006044820152606401610882565b600261012d5560fb5460ff16156116d75760405162461bcd60e51b815260040161088290613961565b33826000836116e8848484846123dd565b61170557604051634ca8886760e01b815260040160405180910390fd5b84156119175773eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b038716036117485760405163c1ab6dc160e01b815260040160405180910390fd5b6001600160a01b037f0000000000000000000000001f573d6fb3f13d689ff844b4ce37794d79a7ff1c8116908716036117fb57604051630852cd8d60e31b8152600481018690527f000000000000000000000000a489c2b5b36835a327851ab917a80562b5afc2446001600160a01b0316906342966c68906024015b600060405180830381600087803b1580156117de57600080fd5b505af11580156117f2573d6000803e3d6000fd5b505050506118d6565b6001600160a01b037f00000000000000000000000048fb253446873234f2febbf9bdeaa72d9d387f9481169087160361187b57604051630852cd8d60e31b8152600481018690527f0000000000000000000000000887ae1251e180d7d453aedebee26e1639f201136001600160a01b0316906342966c68906024016117c4565b604051630852cd8d60e31b8152600481018690526001600160a01b038716906342966c6890602401600060405180830381600087803b1580156118bd57600080fd5b505af11580156118d1573d6000803e3d6000fd5b505050505b60405185815233906001600160a01b038816907fd3fda22e13f8cb743a9ceaca6e14022b6677188d20f3c3047f5c9033e07a4e879060200160405180910390a35b5050600161012d5550505050565b7f0d0d17bf5382c809d9a3899d6a94e57386dfb2036f0401b94ef3cf6c1a9ab73f61195081336125e3565b8161195a81612232565b604051632770a7eb60e21b81526001600160a01b037f000000000000000000000000649765821d9f64198c905ec0b2b037a4a52bc3731690639dc29fac906119c8907f0000000000000000000000001f573d6fb3f13d689ff844b4ce37794d79a7ff1c9087906004016139d1565b600060405180830381600087803b1580156119e257600080fd5b505af11580156119f6573d6000803e3d6000fd5b50505050505050565b6000611a0d60fb5460ff1690565b905090565b60008181526097602052604081206107f390612918565b600082815260656020526040902060010154611a4581336126ff565b610dfe8383612785565b60006107f382612922565b60007f000000000000000000000000eef417e1d5cc832e619ae18d2f140de2999dd4fb611a868161283a565b85611a90816123b6565b85611a9a81612232565b600061015f54905060007f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015611b02573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611b26919061398b565b905080158015611b365750600082115b15611b5457604051636a9c61e160e01b815260040160405180910390fd5b6000611b618a83856126c7565b6040516370a0823160e01b81523060048201529091506000906001600160a01b037f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e34416906370a0823190602401602060405180830381865afa158015611bcb573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611bef919061398b565b905080821115611ca7576000611c0582846139ba565b90506000611c148287876126e3565b9050611c2081876139ea565b61015f556040516340c10f1960e01b81526001600160a01b037f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e34416906340c10f1990611c7290309086906004016139d1565b600060405180830381600087803b158015611c8c57600080fd5b505af1158015611ca0573d6000803e3d6000fd5b5050505050505b60405163a9059cbb60e01b81526001600160a01b037f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e344169063a9059cbb90611cf5908f9086906004016139d1565b6020604051808303816000875af1158015611d14573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611d389190613a28565b50604051630852cd8d60e31b8152600481018c90527f000000000000000000000000a489c2b5b36835a327851ab917a80562b5afc2446001600160a01b0316906342966c6890602401600060405180830381600087803b158015611d9b57600080fd5b505af1158015611daf573d6000803e3d6000fd5b50849250508b159050611dc957611dc6818b6128f2565b90505b8015611e50577f0000000000000000000000000887ae1251e180d7d453aedebee26e1639f201136001600160a01b03166340c10f198e836040518363ffffffff1660e01b8152600401611e1d9291906139d1565b600060405180830381600087803b158015611e3757600080fd5b505af1158015611e4b573d6000803e3d6000fd5b505050505b604080518d8152602081018590529081018290526001600160a01b038e16908f907f98ac1ba20f9c40c6579f93634a34a46bd425744a5ef297e4c739ba0ce1d7f6b59060600160405180910390a350909c9b505050505050505050505050565b60007f000000000000000000000000eef417e1d5cc832e619ae18d2f140de2999dd4fb611edc8161283a565b84611ee6816123b6565b84611ef081612232565b84611efa81612232565b6000611f0588612253565b905080871115611f2857604051633494a40d60e21b815260040160405180910390fd5b6000611f33886122e4565b604051630852cd8d60e31b8152600481018b90529091507f0000000000000000000000000887ae1251e180d7d453aedebee26e1639f201136001600160a01b0316906342966c6890602401600060405180830381600087803b158015611f9857600080fd5b505af1158015611fac573d6000803e3d6000fd5b505082516040516340c10f1960e01b81526001600160a01b037f000000000000000000000000a489c2b5b36835a327851ab917a80562b5afc2441693506340c10f199250611ffe918e916004016139d1565b600060405180830381600087803b15801561201857600080fd5b505af115801561202c573d6000803e3d6000fd5b50508251602080850151604080519384529183018e90528282018e90526060830152516001600160a01b038e1693508e92507f2d3e6c9d7b23425696e79d70b11c80ff35e7e65291f79a03f9aef355706863519181900360800190a3519a9950505050505050505050565b6000816000036120a957506000919050565b60007f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612109573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061212d919061398b565b9050600061213b8285613a45565b6040516370a0823160e01b81523060048201529091506121f590829084906001600160a01b037f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e34416906370a0823190602401602060405180830381865afa1580156121aa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121ce919061398b565b6121d890866139ba565b61015f546121e69190613a45565b6121f090856139ea565b6129b3565b949350505050565b60006001600160e01b03198216637965db0b60e01b14806107f357506301ffc9a760e01b6001600160e01b03198316146107f3565b806000036114ed57604051637c946ed760e01b815260040160405180910390fd5b60006107f38261015f547f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156122bb573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906122df919061398b565b6126e3565b6040805180820190915260008082526020820152600061238f837f00000000000000000000000083e1814ba31f7ea95d216204bb45fe75ce09b14f6001600160a01b0316632aac012c6040518163ffffffff1660e01b8152600401602060405180830381865afa15801561235c573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906123809190613a64565b63ffffffff16620f42406129b3565b905061239b81846139ba565b60408051808201909152908152602081019190915292915050565b6001600160a01b0381166114ed5760405163e6c4247b60e01b815260040160405180910390fd5b60007f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b0390811690851614801561244057506124407f473e02917e58ac16ae36b64246942eb4bb4dcf262bc3c3c50359aa9af6bb44f986611630565b95945050505050565b804710156124995760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a20696e73756666696369656e742062616c616e63650000006044820152606401610882565b6000826001600160a01b03168260405160006040518083038185875af1925050503d80600081146124e6576040519150601f19603f3d011682016040523d82523d6000602084013e6124eb565b606091505b5050905080610dfe5760405162461bcd60e51b815260206004820152603a60248201527f416464726573733a20756e61626c6520746f2073656e642076616c75652c207260448201527f6563697069656e74206d617920686176652072657665727465640000000000006064820152608401610882565b8060000361256f57505050565b73eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee6001600160a01b038416036125cf576040516001600160a01b0383169082156108fc029083906000818181858888f193505050501580156125c9573d6000803e3d6000fd5b50505050565b610dfe6001600160a01b0384168383612a7f565b6125ed8282611630565b610e7d57604051634ca8886760e01b815260040160405180910390fd5b60405163b5af090f60e01b81526001600160a01b0382811660048301527f00000000000000000000000083e1814ba31f7ea95d216204bb45fe75ce09b14f169063b5af090f90602401602060405180830381865afa158015612670573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906126949190613a28565b6114ed57604051630b094f2760e31b815260040160405180910390fd5b60008183106126c05781611629565b5090919050565b6000826000036126d8575082611629565b6121f5848484612ad5565b6000816000036126f4575082611629565b6121f58484846129b3565b6127098282611630565b610e7d57612721816001600160a01b03166014612b25565b61272c836020612b25565b60405160200161273d929190613ab6565b60408051601f198184030181529082905262461bcd60e51b825261088291600401613b2b565b61276d8282612cc1565b6000828152609760205260409020610dfe9082612d47565b61278f8282612d5c565b6000828152609760205260409020610dfe9082612dc3565b60fb5460ff166127f05760405162461bcd60e51b815260206004820152601460248201527314185d5cd8589b194e881b9bdd081c185d5cd95960621b6044820152606401610882565b60fb805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b336001600160a01b038216146114ed57604051634ca8886760e01b815260040160405180910390fd5b600054610100900460ff1661288a5760405162461bcd60e51b815260040161088290613b5e565b612892612dd8565b610ea1612e1f565b60fb5460ff16156128bd5760405162461bcd60e51b815260040161088290613961565b60fb805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a25861281d3390565b6000818311612902576000611629565b61162982846139ba565b60006116298383612f87565b60006107f3825490565b60006107f3827f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b03166318160ddd6040518163ffffffff1660e01b8152600401602060405180830381865afa158015612986573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906129aa919061398b565b61015f546126c7565b6000806129c08585612fb1565b80519091506000036129e4578281602001516129dc9190613bbf565b915050611629565b80518311612a0557604051631a93c68960e11b815260040160405180910390fd5b6000612a12868686613038565b90506000612a208383613053565b8051909150600003612a4657848160200151612a3c9190613bbf565b9350505050611629565b6000858103861690612a5883836130d8565b90506000612a6e612a69848a613bbf565b61310f565b919091029998505050505050505050565b610dfe8363a9059cbb60e01b8484604051602401612a9e9291906139d1565b60408051601f198184030181529190526020810180516001600160e01b03166001600160e01b031990931692909217909152613141565b600080612ae38585856129b3565b90506000612af2868686613038565b11156121f5576000198110612b1a57604051631a93c68960e11b815260040160405180910390fd5b6129dc8160016139ea565b60606000612b34836002613a45565b612b3f9060026139ea565b67ffffffffffffffff811115612b5757612b57613be1565b6040519080825280601f01601f191660200182016040528015612b81576020820181803683370190505b509050600360fc1b81600081518110612b9c57612b9c613bf7565b60200101906001600160f81b031916908160001a905350600f60fb1b81600181518110612bcb57612bcb613bf7565b60200101906001600160f81b031916908160001a9053506000612bef846002613a45565b612bfa9060016139ea565b90505b6001811115612c72576f181899199a1a9b1b9c1cb0b131b232b360811b85600f1660108110612c2e57612c2e613bf7565b1a60f81b828281518110612c4457612c44613bf7565b60200101906001600160f81b031916908160001a90535060049490941c93612c6b81613c0d565b9050612bfd565b5083156116295760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e746044820152606401610882565b612ccb8282611630565b610e7d5760008281526065602090815260408083206001600160a01b03851684529091529020805460ff19166001179055612d033390565b6001600160a01b0316816001600160a01b0316837f2f8788117e7eff1d82e926ec794901d17c78024a50270940304540a733656f0d60405160405180910390a45050565b6000611629836001600160a01b038416613213565b612d668282611630565b15610e7d5760008281526065602090815260408083206001600160a01b0385168085529252808320805460ff1916905551339285917ff6391f5c32d9c69d2a47ea670b442974b53935d1edc7fd64eb21e047a839171b9190a45050565b6000611629836001600160a01b038416613262565b600054610100900460ff16612dff5760405162461bcd60e51b815260040161088290613b5e565b612e07613355565b612e0f61338c565b612e176133bb565b610ea16133ea565b600054610100900460ff16612e465760405162461bcd60e51b815260040161088290613b5e565b7f000000000000000000000000ab05cf7c6c3a288cd36326e4f7b8600e7268e3446001600160a01b03166379ba50976040518163ffffffff1660e01b8152600401600060405180830381600087803b158015612ea157600080fd5b505af1158015612eb5573d6000803e3d6000fd5b50505050612ef17f473e02917e58ac16ae36b64246942eb4bb4dcf262bc3c3c50359aa9af6bb44f9600080516020613c90833981519152613411565b612f297f4cbb5676e6e25e1a3b8a36de10472bcac96f97bd8dd87af6f330881b84739eb8600080516020613c90833981519152613411565b612f617f0d0d17bf5382c809d9a3899d6a94e57386dfb2036f0401b94ef3cf6c1a9ab73f600080516020613c90833981519152613411565b610ea1600080516020613c70833981519152600080516020613c90833981519152613411565b6000826000018281548110612f9e57612f9e613bf7565b9060005260206000200154905092915050565b60408051808201909152600080825260208201526000612fd1848461345c565b90508383028082106130065760405180604001604052808284612ff491906139ba565b815260200182815250925050506107f3565b6040518060400160405280600161301d8585900390565b61302791906139ba565b815260200191909152949350505050565b6000818061304857613048613ba9565b838509949350505050565b6040805180820190915260008082526020820152818360200151106130a05760405180604001604052808460000151815260200183856020015161309791906139ba565b905290506107f3565b6040518060400160405280600185600001516130bc91906139ba565b81526020016130cf856020015185900390565b90529392505050565b6000806130f06130ea84808403613bbf565b60010190565b90508284602001516131029190613bbf565b8451820217949350505050565b60006001815b600881101561313a57838202600203820291508061313281613c24565b915050613115565b5092915050565b6000613196826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b031661346b9092919063ffffffff16565b805190915015610dfe57808060200190518101906131b49190613a28565b610dfe5760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e6044820152691bdd081cdd58d8d9595960b21b6064820152608401610882565b600081815260018301602052604081205461325a575081546001818101845560008481526020808220909301849055845484825282860190935260409020919091556107f3565b5060006107f3565b6000818152600183016020526040812054801561334b5760006132866001836139ba565b855490915060009061329a906001906139ba565b90508181146132ff5760008660000182815481106132ba576132ba613bf7565b90600052602060002001549050808760000184815481106132dd576132dd613bf7565b6000918252602080832090910192909255918252600188019052604090208390555b855486908061331057613310613c3d565b6001900381819060005260206000200160009055905585600101600086815260200190815260200160002060009055600193505050506107f3565b60009150506107f3565b600054610100900460ff1661337c5760405162461bcd60e51b815260040161088290613b5e565b6133846133ea565b610ea161347a565b600054610100900460ff166133b35760405162461bcd60e51b815260040161088290613b5e565b610ea16134df565b600054610100900460ff166133e25760405162461bcd60e51b815260040161088290613b5e565b610ea1613512565b600054610100900460ff16610ea15760405162461bcd60e51b815260040161088290613b5e565b600082815260656020526040808220600101805490849055905190918391839186917fbd79b86ffe0ab8e8776151514217cd7cacd52c909f66475c3af44e129f0b00ff9190a4505050565b60006000198284099392505050565b60606121f58484600085613541565b600054610100900460ff166134a15760405162461bcd60e51b815260040161088290613b5e565b60c9805461ffff191660011790556134c7600080516020613c9083398151915280613411565b610ea1600080516020613c9083398151915233613672565b600054610100900460ff166135065760405162461bcd60e51b815260040161088290613b5e565b60fb805460ff19169055565b600054610100900460ff166135395760405162461bcd60e51b815260040161088290613b5e565b600161012d55565b6060824710156135a25760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f6044820152651c8818d85b1b60d21b6064820152608401610882565b6001600160a01b0385163b6135f95760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e74726163740000006044820152606401610882565b600080866001600160a01b031685876040516136159190613c53565b60006040518083038185875af1925050503d8060008114613652576040519150601f19603f3d011682016040523d82523d6000602084013e613657565b606091505b509150915061366782828661367c565b979650505050505050565b610e7d8282612763565b6060831561368b575081611629565b82511561369b5782518084602001fd5b8160405162461bcd60e51b81526004016108829190613b2b565b6000602082840312156136c757600080fd5b81356001600160e01b03198116811461162957600080fd5b6000602082840312156136f157600080fd5b5035919050565b6001600160a01b03811681146114ed57600080fd5b60008060006060848603121561372257600080fd5b833561372d816136f8565b9250602084013561373d816136f8565b929592945050506040919091013590565b60008060006060848603121561376357600080fd5b83359250602084013561373d816136f8565b6000806040838503121561378857600080fd5b82359150602083013561379a816136f8565b809150509250929050565b600080604083850312156137b857600080fd5b82356137c3816136f8565b946020939093013593505050565b80151581146114ed57600080fd5b6000806000606084860312156137f457600080fd5b83356137ff816136f8565b9250602084013591506040840135613816816137d1565b809150509250925092565b6000806020838503121561383457600080fd5b823567ffffffffffffffff8082111561384c57600080fd5b818501915085601f83011261386057600080fd5b81358181111561386f57600080fd5b86602082850101111561388157600080fd5b60209290920196919550909350505050565b6000602082840312156138a557600080fd5b8135611629816136f8565b600080604083850312156138c357600080fd5b50508035926020909101359150565b600080600080600060a086880312156138ea57600080fd5b8535945060208601356138fc816136f8565b9350604086013592506060860135613913816137d1565b949793965091946080013592915050565b6000806000806080858703121561393a57600080fd5b84359350602085013561394c816136f8565b93969395505050506040820135916060013590565b60208082526010908201526f14185d5cd8589b194e881c185d5cd95960821b604082015260600190565b60006020828403121561399d57600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b6000828210156139cc576139cc6139a4565b500390565b6001600160a01b03929092168252602082015260400190565b600082198211156139fd576139fd6139a4565b500190565b600061ffff808316818516808303821115613a1f57613a1f6139a4565b01949350505050565b600060208284031215613a3a57600080fd5b8151611629816137d1565b6000816000190483118215151615613a5f57613a5f6139a4565b500290565b600060208284031215613a7657600080fd5b815163ffffffff8116811461162957600080fd5b60005b83811015613aa5578181015183820152602001613a8d565b838111156125c95750506000910152565b7f416363657373436f6e74726f6c3a206163636f756e7420000000000000000000815260008351613aee816017850160208801613a8a565b7001034b99036b4b9b9b4b733903937b6329607d1b6017918401918201528351613b1f816028840160208801613a8a565b01602801949350505050565b6020815260008251806020840152613b4a816040850160208701613a8a565b601f01601f19169190910160400192915050565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b634e487b7160e01b600052601260045260246000fd5b600082613bdc57634e487b7160e01b600052601260045260246000fd5b500490565b634e487b7160e01b600052604160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b600081613c1c57613c1c6139a4565b506000190190565b600060018201613c3657613c366139a4565b5060010190565b634e487b7160e01b600052603160045260246000fd5b60008251613c65818460208701613a8a565b919091019291505056feca51b9188e78415f30da725e0d94567b4d65bc6777d4e5d573191e9f55b88a322172861495e7b85edac73e3cd5fbb42dd675baadf627720e687bcfdaca025096a164736f6c634300080d000a

Verified Source Code Partial Match

Compiler: v0.8.13+commit.abaa5c0e EVM: london Optimization: Yes (200 runs)
Token.sol 10 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

/**
 * @dev the main purpose of the Token interfaces is to ensure artificially that we won't use ERC20's standard functions,
 * but only their safe versions, which are provided by SafeERC20 and SafeERC20Ex via the TokenLibrary contract
 */
interface Token {

}
Vault.sol 199 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { ReentrancyGuardUpgradeable } from "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import { PausableUpgradeable } from "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";

import { ITokenGovernance } from "@bancor/token-governance/contracts/ITokenGovernance.sol";

import { IVault, ROLE_ASSET_MANAGER } from "./interfaces/IVault.sol";
import { Upgradeable } from "../utility/Upgradeable.sol";
import { IERC20Burnable } from "../token/interfaces/IERC20Burnable.sol";
import { Token } from "../token/Token.sol";
import { TokenLibrary } from "../token/TokenLibrary.sol";

import { Utils, AccessDenied, NotPayable, InvalidToken } from "../utility/Utils.sol";

abstract contract Vault is IVault, Upgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable, Utils {
    using Address for address payable;
    using SafeERC20 for IERC20;
    using TokenLibrary for Token;

    // the address of the BNT token
    IERC20 internal immutable _bnt;

    // the address of the BNT token governance
    ITokenGovernance internal immutable _bntGovernance;

    // the address of the vBNT token
    IERC20 internal immutable _vbnt;

    // the address of the vBNT token governance
    ITokenGovernance internal immutable _vbntGovernance;

    // solhint-disable func-name-mixedcase

    /**
     * @dev a "virtual" constructor that is only used to set immutable state variables
     */
    constructor(ITokenGovernance initBNTGovernance, ITokenGovernance initVBNTGovernance)
        validAddress(address(initBNTGovernance))
        validAddress(address(initVBNTGovernance))
    {
        _bntGovernance = initBNTGovernance;
        _bnt = initBNTGovernance.token();
        _vbntGovernance = initVBNTGovernance;
        _vbnt = initVBNTGovernance.token();
    }

    /**
     * @dev initializes the contract and its parents
     */
    function __Vault_init() internal onlyInitializing {
        __Upgradeable_init();
        __Pausable_init();
        __ReentrancyGuard_init();

        __Vault_init_unchained();
    }

    /**
     * @dev performs contract-specific initialization
     */
    function __Vault_init_unchained() internal onlyInitializing {}

    // solhint-enable func-name-mixedcase

    /**
     * @dev returns the asset manager role
     */
    function roleAssetManager() external pure returns (bytes32) {
        return ROLE_ASSET_MANAGER;
    }

    // allows execution only by an authorized operation
    modifier whenAuthorized(
        address caller,
        Token token,
        address payable target,
        uint256 amount
    ) {
        if (!isAuthorizedWithdrawal(caller, token, target, amount)) {
            revert AccessDenied();
        }

        _;
    }

    /**
     * @dev returns whether withdrawals are currently paused
     */
    function isPaused() external view returns (bool) {
        return paused();
    }

    /**
     * @dev pauses withdrawals
     *
     * requirements:
     *
     * - the caller must have the ROLE_ADMIN privileges
     */
    function pause() external onlyAdmin {
        _pause();
    }

    /**
     * @dev unpauses withdrawals
     *
     * requirements:
     *
     * - the caller must have the ROLE_ADMIN privileges
     */
    function unpause() external onlyAdmin {
        _unpause();
    }

    /**
     * @inheritdoc IVault
     */
    function withdrawFunds(
        Token token,
        address payable target,
        uint256 amount
    ) external validAddress(target) nonReentrant whenNotPaused whenAuthorized(msg.sender, token, target, amount) {
        if (amount == 0) {
            return;
        }

        if (token.isNative()) {
            // using a regular transfer here would revert due to exceeding the 2300 gas limit which is why we're using
            // call instead (via sendValue), which the 2300 gas limit does not apply for
            target.sendValue(amount);
        } else {
            token.safeTransfer(target, amount);
        }

        emit FundsWithdrawn({ token: token, caller: msg.sender, target: target, amount: amount });
    }

    /**
     * @inheritdoc IVault
     */
    function burn(Token token, uint256 amount)
        external
        nonReentrant
        whenNotPaused
        whenAuthorized(msg.sender, token, payable(address(0)), amount)
    {
        if (amount == 0) {
            return;
        }

        if (token.isNative()) {
            revert InvalidToken();
        }

        // allow vaults to burn BNT and vBNT via their respective token governance modules
        if (token.isEqual(_bnt)) {
            _bntGovernance.burn(amount);
        } else if (token.isEqual(_vbnt)) {
            _vbntGovernance.burn(amount);
        } else {
            IERC20Burnable(address(token)).burn(amount);
        }

        emit FundsBurned({ token: token, caller: msg.sender, amount: amount });
    }

    /**
     * @dev returns whether the given caller is allowed access to the given token
     */
    function isAuthorizedWithdrawal(
        address caller,
        Token token,
        address target,
        uint256 amount
    ) internal view virtual returns (bool);

    /**
     * @inheritdoc IVault
     */
    function isPayable() public view virtual returns (bool);

    /**
     * @dev authorize the contract to receive the native token
     *
     * requirements:
     *
     * - isPayable must return true
     */
    receive() external payable {
        if (!isPayable()) {
            revert NotPayable();
        }
    }
}
BNTPool.sol 640 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";

import { ITokenGovernance } from "@bancor/token-governance/contracts/ITokenGovernance.sol";

import { IVersioned } from "../utility/interfaces/IVersioned.sol";
import { Upgradeable } from "../utility/Upgradeable.sol";
import { InvalidParam, InvalidStakedBalance } from "../utility/Utils.sol";
import { PPM_RESOLUTION } from "../utility/Constants.sol";
import { MathEx } from "../utility/MathEx.sol";

import { IBancorNetwork } from "../network/interfaces/IBancorNetwork.sol";
import { INetworkSettings, NotWhitelisted } from "../network/interfaces/INetworkSettings.sol";

import { IMasterVault } from "../vaults/interfaces/IMasterVault.sol";

// prettier-ignore
import {
    IBNTPool,
    ROLE_BNT_POOL_TOKEN_MANAGER,
    ROLE_BNT_MANAGER,
    ROLE_VAULT_MANAGER,
    ROLE_FUNDING_MANAGER
} from "./interfaces/IBNTPool.sol";

import { IPoolToken } from "./interfaces/IPoolToken.sol";

import { Token } from "../token/Token.sol";
import { TokenLibrary } from "../token/TokenLibrary.sol";

import { Vault } from "../vaults/Vault.sol";
import { IVault } from "../vaults/interfaces/IVault.sol";

/**
 * @dev BNT Pool contract
 */
contract BNTPool is IBNTPool, Vault {
    using TokenLibrary for Token;

    error FundingLimitExceeded();

    struct InternalWithdrawalAmounts {
        uint256 bntAmount;
        uint256 withdrawalFeeAmount;
    }

    // the network contract
    IBancorNetwork private immutable _network;

    // the network settings contract
    INetworkSettings private immutable _networkSettings;

    // the master vault contract
    IMasterVault private immutable _masterVault;

    // the BNT pool token
    IPoolToken internal immutable _poolToken;

    // the total staked BNT balance in the network
    uint256 private _stakedBalance;

    // a mapping between pools and their current funding
    mapping(Token => uint256) private _currentPoolFunding;

    // upgrade forward-compatibility storage gap
    uint256[MAX_GAP - 2] private __gap;

    /**
     * @dev triggered when liquidity is deposited
     */
    event TokensDeposited(
        bytes32 indexed contextId,
        address indexed provider,
        uint256 bntAmount,
        uint256 poolTokenAmount,
        uint256 vbntAmount
    );

    /**
     * @dev triggered when liquidity is withdrawn
     */
    event TokensWithdrawn(
        bytes32 indexed contextId,
        address indexed provider,
        uint256 bntAmount,
        uint256 poolTokenAmount,
        uint256 vbntAmount,
        uint256 withdrawalFeeAmount
    );

    /**
     * @dev triggered when funding is requested
     */
    event FundingRequested(bytes32 indexed contextId, Token indexed pool, uint256 bntAmount, uint256 poolTokenAmount);

    /**
     * @dev triggered when funding is renounced
     */
    event FundingRenounced(bytes32 indexed contextId, Token indexed pool, uint256 bntAmount, uint256 poolTokenAmount);

    /**
     * @dev triggered when the total liquidity in the BNT pool is updated
     */
    event TotalLiquidityUpdated(
        bytes32 indexed contextId,
        uint256 liquidity,
        uint256 stakedBalance,
        uint256 poolTokenSupply
    );

    /**
     * @dev a "virtual" constructor that is only used to set immutable state variables
     */
    constructor(
        IBancorNetwork initNetwork,
        ITokenGovernance initBNTGovernance,
        ITokenGovernance initVBNTGovernance,
        INetworkSettings initNetworkSettings,
        IMasterVault initMasterVault,
        IPoolToken initBNTPoolToken
    )
        Vault(initBNTGovernance, initVBNTGovernance)
        validAddress(address(initNetwork))
        validAddress(address(initNetworkSettings))
        validAddress(address(initMasterVault))
        validAddress(address(initBNTPoolToken))
    {
        _network = initNetwork;
        _networkSettings = initNetworkSettings;
        _masterVault = initMasterVault;
        _poolToken = initBNTPoolToken;
    }

    /**
     * @dev fully initializes the contract and its parents
     */
    function initialize() external initializer {
        __BNTPool_init();
    }

    // solhint-disable func-name-mixedcase

    /**
     * @dev initializes the contract and its parents
     */
    function __BNTPool_init() internal onlyInitializing {
        __Vault_init();

        __BNTPool_init_unchained();
    }

    /**
     * @dev performs contract-specific initialization
     */
    function __BNTPool_init_unchained() internal onlyInitializing {
        _poolToken.acceptOwnership();

        // set up administrative roles
        _setRoleAdmin(ROLE_BNT_POOL_TOKEN_MANAGER, ROLE_ADMIN);
        _setRoleAdmin(ROLE_BNT_MANAGER, ROLE_ADMIN);
        _setRoleAdmin(ROLE_VAULT_MANAGER, ROLE_ADMIN);
        _setRoleAdmin(ROLE_FUNDING_MANAGER, ROLE_ADMIN);
    }

    // solhint-enable func-name-mixedcase

    modifier poolWhitelisted(Token pool) {
        _poolWhitelisted(pool);

        _;
    }

    /**
     * @dev validates that the provided pool is whitelisted
     */
    function _poolWhitelisted(Token pool) internal view {
        if (!_networkSettings.isTokenWhitelisted(pool)) {
            revert NotWhitelisted();
        }
    }

    /**
     * @inheritdoc Upgradeable
     */
    function version() public pure override(IVersioned, Upgradeable) returns (uint16) {
        return 3;
    }

    /**
     * @inheritdoc Vault
     */
    function isPayable() public pure override(IVault, Vault) returns (bool) {
        return false;
    }

    /**
     * @dev returns the BNT pool token manager role
     */
    function roleBNTPoolTokenManager() external pure returns (bytes32) {
        return ROLE_BNT_POOL_TOKEN_MANAGER;
    }

    /**
     * @dev returns the BNT manager role
     */
    function roleBNTManager() external pure returns (bytes32) {
        return ROLE_BNT_MANAGER;
    }

    /**
     * @dev returns the vault manager role
     */
    function roleVaultManager() external pure returns (bytes32) {
        return ROLE_VAULT_MANAGER;
    }

    /**
     * @dev returns the funding manager role
     */
    function roleFundingManager() external pure returns (bytes32) {
        return ROLE_FUNDING_MANAGER;
    }

    /**
     * @dev returns whether the given caller is allowed access to the given token
     *
     * requirements:
     *
     * - the token must be the BNT pool token
     * - the caller must have the ROLE_BNT_POOL_TOKEN_MANAGER role
     */
    function isAuthorizedWithdrawal(
        address caller,
        Token token,
        address, /* target */
        uint256 /* amount */
    ) internal view override returns (bool) {
        return token.isEqual(_poolToken) && hasRole(ROLE_BNT_POOL_TOKEN_MANAGER, caller);
    }

    /**
     * @inheritdoc IBNTPool
     */
    function poolToken() external view returns (IPoolToken) {
        return _poolToken;
    }

    /**
     * @inheritdoc IBNTPool
     */
    function stakedBalance() external view returns (uint256) {
        return _stakedBalance;
    }

    /**
     * @inheritdoc IBNTPool
     */
    function currentPoolFunding(Token pool) external view returns (uint256) {
        return _currentPoolFunding[pool];
    }

    /**
     * @inheritdoc IBNTPool
     */
    function availableFunding(Token pool) external view returns (uint256) {
        return MathEx.subMax0(_networkSettings.poolFundingLimit(pool), _currentPoolFunding[pool]);
    }

    /**
     * @inheritdoc IBNTPool
     */
    function poolTokenToUnderlying(uint256 poolTokenAmount) external view returns (uint256) {
        return _poolTokenToUnderlying(poolTokenAmount);
    }

    /**
     * @inheritdoc IBNTPool
     */
    function underlyingToPoolToken(uint256 bntAmount) external view returns (uint256) {
        return _underlyingToPoolToken(bntAmount);
    }

    /**
     * @inheritdoc IBNTPool
     */
    function poolTokenAmountToBurn(uint256 bntAmountToDistribute) external view returns (uint256) {
        if (bntAmountToDistribute == 0) {
            return 0;
        }

        uint256 poolTokenSupply = _poolToken.totalSupply();
        uint256 val = bntAmountToDistribute * poolTokenSupply;

        return
            MathEx.mulDivF(
                val,
                poolTokenSupply,
                val + _stakedBalance * (poolTokenSupply - _poolToken.balanceOf(address(this)))
            );
    }

    /**
     * @inheritdoc IBNTPool
     */
    function mint(address recipient, uint256 bntAmount)
        external
        onlyRoleMember(ROLE_BNT_MANAGER)
        validAddress(recipient)
        greaterThanZero(bntAmount)
    {
        _bntGovernance.mint(recipient, bntAmount);
    }

    /**
     * @inheritdoc IBNTPool
     */
    function burnFromVault(uint256 bntAmount) external onlyRoleMember(ROLE_VAULT_MANAGER) greaterThanZero(bntAmount) {
        _masterVault.burn(Token(address(_bnt)), bntAmount);
    }

    /**
     * @inheritdoc IBNTPool
     */
    function depositFor(
        bytes32 contextId,
        address provider,
        uint256 bntAmount,
        bool isMigrating,
        uint256 originalVBNTAmount
    ) external only(address(_network)) validAddress(provider) greaterThanZero(bntAmount) returns (uint256) {
        // calculate the required pool token amount
        uint256 currentStakedBalance = _stakedBalance;
        uint256 poolTokenTotalSupply = _poolToken.totalSupply();
        if (poolTokenTotalSupply == 0 && currentStakedBalance > 0) {
            revert InvalidStakedBalance();
        }

        uint256 poolTokenAmount = _underlyingToPoolToken(bntAmount, poolTokenTotalSupply, currentStakedBalance);

        // if the protocol doesn't have enough pool tokens, mint new ones
        uint256 poolTokenBalance = _poolToken.balanceOf(address(this));
        if (poolTokenAmount > poolTokenBalance) {
            uint256 newPoolTokenAmount = poolTokenAmount - poolTokenBalance;
            uint256 increaseStakedBalanceAmount = _poolTokenToUnderlying(
                newPoolTokenAmount,
                currentStakedBalance,
                poolTokenTotalSupply
            );

            // update the staked balance
            _stakedBalance = currentStakedBalance + increaseStakedBalanceAmount;

            // mint pool tokens to the protocol
            _poolToken.mint(address(this), newPoolTokenAmount);
        }

        // transfer pool tokens from the protocol to the provider
        _poolToken.transfer(provider, poolTokenAmount);

        // burn the previously received BNT
        _bntGovernance.burn(bntAmount);

        uint256 vbntAmount = poolTokenAmount;

        // the provider should receive pool tokens and vBNT in equal amounts. since the provider might already have
        // some vBNT during migration, the contract only mints the delta between the full amount and the amount the
        // provider already has
        if (isMigrating) {
            vbntAmount = MathEx.subMax0(vbntAmount, originalVBNTAmount);
        }

        // mint vBNT to the provider
        if (vbntAmount > 0) {
            _vbntGovernance.mint(provider, vbntAmount);
        }

        emit TokensDeposited({
            contextId: contextId,
            provider: provider,
            bntAmount: bntAmount,
            poolTokenAmount: poolTokenAmount,
            vbntAmount: vbntAmount
        });

        return poolTokenAmount;
    }

    /**
     * @inheritdoc IBNTPool
     */
    function withdraw(
        bytes32 contextId,
        address provider,
        uint256 poolTokenAmount,
        uint256 bntAmount
    )
        external
        only(address(_network))
        validAddress(provider)
        greaterThanZero(poolTokenAmount)
        greaterThanZero(bntAmount)
        returns (uint256)
    {
        // ensure that the provided amounts correspond to the state of the pool. Note the pool tokens should
        // have been already deposited back from the network
        uint256 underlyingAmount = _poolTokenToUnderlying(poolTokenAmount);
        if (bntAmount > underlyingAmount) {
            revert InvalidParam();
        }

        InternalWithdrawalAmounts memory amounts = _withdrawalAmounts(bntAmount);

        // burn the respective vBNT amount
        _vbntGovernance.burn(poolTokenAmount);

        // mint BNT to the provider
        _bntGovernance.mint(provider, amounts.bntAmount);

        emit TokensWithdrawn({
            contextId: contextId,
            provider: provider,
            bntAmount: amounts.bntAmount,
            poolTokenAmount: poolTokenAmount,
            vbntAmount: poolTokenAmount,
            withdrawalFeeAmount: amounts.withdrawalFeeAmount
        });

        return amounts.bntAmount;
    }

    /**
     * @inheritdoc IBNTPool
     */
    function withdrawalAmount(uint256 poolTokenAmount)
        external
        view
        greaterThanZero(poolTokenAmount)
        returns (uint256)
    {
        return _withdrawalAmounts(_poolTokenToUnderlying(poolTokenAmount)).bntAmount;
    }

    /**
     * @inheritdoc IBNTPool
     */
    function requestFunding(
        bytes32 contextId,
        Token pool,
        uint256 bntAmount
    ) external onlyRoleMember(ROLE_FUNDING_MANAGER) poolWhitelisted(pool) greaterThanZero(bntAmount) {
        uint256 currentFunding = _currentPoolFunding[pool];
        uint256 fundingLimit = _networkSettings.poolFundingLimit(pool);
        uint256 newFunding = currentFunding + bntAmount;

        // verify that the new funding amount doesn't exceed the limit
        if (newFunding > fundingLimit) {
            revert FundingLimitExceeded();
        }

        // calculate the pool token amount to mint
        uint256 currentStakedBalance = _stakedBalance;
        uint256 poolTokenAmount;
        uint256 poolTokenTotalSupply = _poolToken.totalSupply();
        if (poolTokenTotalSupply == 0 && currentStakedBalance > 0) {
            revert InvalidStakedBalance();
        }

        poolTokenAmount = _underlyingToPoolToken(bntAmount, poolTokenTotalSupply, currentStakedBalance);

        // update the staked balance
        uint256 newStakedBalance = currentStakedBalance + bntAmount;
        _stakedBalance = newStakedBalance;

        // update the current funding amount
        _currentPoolFunding[pool] = newFunding;

        // mint pool tokens to the protocol
        _poolToken.mint(address(this), poolTokenAmount);

        // mint BNT to the vault
        _bntGovernance.mint(address(_masterVault), bntAmount);

        emit FundingRequested({
            contextId: contextId,
            pool: pool,
            bntAmount: bntAmount,
            poolTokenAmount: poolTokenAmount
        });

        emit TotalLiquidityUpdated({
            contextId: contextId,
            liquidity: _bnt.balanceOf(address(_masterVault)),
            stakedBalance: newStakedBalance,
            poolTokenSupply: poolTokenTotalSupply + poolTokenAmount
        });
    }

    /**
     * @inheritdoc IBNTPool
     */
    function renounceFunding(
        bytes32 contextId,
        Token pool,
        uint256 bntAmount
    ) external onlyRoleMember(ROLE_FUNDING_MANAGER) poolWhitelisted(pool) greaterThanZero(bntAmount) {
        uint256 currentStakedBalance = _stakedBalance;

        // calculate the final amount to deduct from the current pool funding
        uint256 currentFunding = _currentPoolFunding[pool];
        uint256 reduceFundingAmount = Math.min(currentFunding, bntAmount);

        // calculate the amount of pool tokens to burn
        // note that the given amount can exceed the total available but the request shouldn't fail
        uint256 poolTokenTotalSupply = _poolToken.totalSupply();
        uint256 poolTokenAmount = _underlyingToPoolToken(
            reduceFundingAmount,
            poolTokenTotalSupply,
            currentStakedBalance
        );

        // ensure the amount of pool tokens doesn't exceed the total available
        poolTokenAmount = Math.min(poolTokenAmount, _poolToken.balanceOf(address(this)));

        // calculate the final amount to deduct from the staked balance
        uint256 reduceStakedBalanceAmount = _poolTokenToUnderlying(
            poolTokenAmount,
            currentStakedBalance,
            poolTokenTotalSupply
        );

        // update the current pool funding. Note that the given amount can exceed the funding amount but the
        // request shouldn't fail (and the funding amount cannot get negative)
        _currentPoolFunding[pool] = currentFunding - reduceFundingAmount;

        // update the staked balance
        uint256 newStakedBalance = currentStakedBalance - reduceStakedBalanceAmount;
        _stakedBalance = newStakedBalance;

        // burn pool tokens from the protocol
        _poolToken.burn(poolTokenAmount);

        // burn all BNT from the master vault
        _masterVault.burn(Token(address(_bnt)), bntAmount);

        emit FundingRenounced({
            contextId: contextId,
            pool: pool,
            bntAmount: bntAmount,
            poolTokenAmount: poolTokenAmount
        });

        emit TotalLiquidityUpdated({
            contextId: contextId,
            liquidity: _bnt.balanceOf(address(_masterVault)),
            stakedBalance: newStakedBalance,
            poolTokenSupply: poolTokenTotalSupply - poolTokenAmount
        });
    }

    /**
     * @inheritdoc IBNTPool
     */
    function onFeesCollected(
        Token pool,
        uint256 feeAmount,
        bool isTradeFee
    ) external only(address(_network)) validAddress(address(pool)) {
        if (feeAmount == 0) {
            return;
        }

        // increase the staked balance by the given amount
        _stakedBalance += feeAmount;

        if (isTradeFee) {
            // increase the current funding for the specified pool by the given amount
            _currentPoolFunding[pool] += feeAmount;
        }
    }

    /**
     * @dev converts the specified pool token amount to the underlying BNT amount
     */
    function _poolTokenToUnderlying(uint256 poolTokenAmount) private view returns (uint256) {
        return _poolTokenToUnderlying(poolTokenAmount, _stakedBalance, _poolToken.totalSupply());
    }

    /**
     * @dev converts the specified pool token amount to the underlying BNT amount
     */
    function _poolTokenToUnderlying(
        uint256 poolTokenAmount,
        uint256 currentStakedBalance,
        uint256 poolTokenTotalSupply
    ) private pure returns (uint256) {
        // if no pool token supply exists yet, use a one-to-one pool token to BNT rate
        if (poolTokenTotalSupply == 0) {
            return poolTokenAmount;
        }

        return MathEx.mulDivF(poolTokenAmount, currentStakedBalance, poolTokenTotalSupply);
    }

    /**
     * @dev converts the specified underlying BNT amount to pool token amount
     */
    function _underlyingToPoolToken(uint256 bntAmount) private view returns (uint256) {
        return _underlyingToPoolToken(bntAmount, _poolToken.totalSupply(), _stakedBalance);
    }

    /**
     * @dev converts the specified underlying BNT amount to pool token amount
     */
    function _underlyingToPoolToken(
        uint256 bntAmount,
        uint256 poolTokenTotalSupply,
        uint256 currentStakedBalance
    ) private pure returns (uint256) {
        // if no pool token supply exists yet, use a one-to-one pool token to BNT rate
        if (poolTokenTotalSupply == 0) {
            return bntAmount;
        }

        return MathEx.mulDivC(bntAmount, poolTokenTotalSupply, currentStakedBalance);
    }

    /**
     * @dev returns withdrawal amounts
     */
    function _withdrawalAmounts(uint256 bntAmount) internal view returns (InternalWithdrawalAmounts memory) {
        // deduct the exit fee from BNT amount
        uint256 withdrawalFeeAmount = MathEx.mulDivF(bntAmount, _networkSettings.withdrawalFeePPM(), PPM_RESOLUTION);

        bntAmount -= withdrawalFeeAmount;

        return InternalWithdrawalAmounts({ bntAmount: bntAmount, withdrawalFeeAmount: withdrawalFeeAmount });
    }
}
Utils.sol 93 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { PPM_RESOLUTION } from "./Constants.sol";

error AccessDenied();
error AlreadyExists();
error DoesNotExist();
error InvalidAddress();
error InvalidExternalAddress();
error InvalidFee();
error InvalidPool();
error InvalidPoolCollection();
error InvalidStakedBalance();
error InvalidToken();
error InvalidParam();
error NotEmpty();
error NotPayable();
error ZeroValue();

/**
 * @dev common utilities
 */
abstract contract Utils {
    // allows execution by the caller only
    modifier only(address caller) {
        _only(caller);

        _;
    }

    function _only(address caller) internal view {
        if (msg.sender != caller) {
            revert AccessDenied();
        }
    }

    // verifies that a value is greater than zero
    modifier greaterThanZero(uint256 value) {
        _greaterThanZero(value);

        _;
    }

    // error message binary size optimization
    function _greaterThanZero(uint256 value) internal pure {
        if (value == 0) {
            revert ZeroValue();
        }
    }

    // validates an address - currently only checks that it isn't null
    modifier validAddress(address addr) {
        _validAddress(addr);

        _;
    }

    // error message binary size optimization
    function _validAddress(address addr) internal pure {
        if (addr == address(0)) {
            revert InvalidAddress();
        }
    }

    // validates an external address - currently only checks that it isn't null or this
    modifier validExternalAddress(address addr) {
        _validExternalAddress(addr);

        _;
    }

    // error message binary size optimization
    function _validExternalAddress(address addr) internal view {
        if (addr == address(0) || addr == address(this)) {
            revert InvalidExternalAddress();
        }
    }

    // ensures that the fee is valid
    modifier validFee(uint32 fee) {
        _validFee(fee);

        _;
    }

    // error message binary size optimization
    function _validFee(uint32 fee) internal pure {
        if (fee > PPM_RESOLUTION) {
            revert InvalidFee();
        }
    }
}
MathEx.sol 339 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { Math } from "@openzeppelin/contracts/utils/math/Math.sol";
import { Fraction, InvalidFraction } from "./Fraction.sol";

import { PPM_RESOLUTION } from "./Constants.sol";

uint256 constant ONE = 0x80000000000000000000000000000000;
uint256 constant LN2 = 0x58b90bfbe8e7bcd5e4f1d9cc01f97b57;

struct Uint512 {
    uint256 hi; // 256 most significant bits
    uint256 lo; // 256 least significant bits
}

struct Sint256 {
    uint256 value;
    bool isNeg;
}

/**
 * @dev this library provides a set of complex math operations
 */
library MathEx {
    error Overflow();

    /**
     * @dev returns `2 ^ f` by calculating `e ^ (f * ln(2))`, where `e` is Euler's number:
     * - Rewrite the input as a sum of binary exponents and a single residual r, as small as possible
     * - The exponentiation of each binary exponent is given (pre-calculated)
     * - The exponentiation of r is calculated via Taylor series for e^x, where x = r
     * - The exponentiation of the input is calculated by multiplying the intermediate results above
     * - For example: e^5.521692859 = e^(4 + 1 + 0.5 + 0.021692859) = e^4 * e^1 * e^0.5 * e^0.021692859
     */
    function exp2(Fraction memory f) internal pure returns (Fraction memory) {
        uint256 x = MathEx.mulDivF(LN2, f.n, f.d);
        uint256 y;
        uint256 z;
        uint256 n;

        if (x >= (ONE << 4)) {
            revert Overflow();
        }

        unchecked {
            z = y = x % (ONE >> 3); // get the input modulo 2^(-3)
            z = (z * y) / ONE;
            n += z * 0x10e1b3be415a0000; // add y^02 * (20! / 02!)
            z = (z * y) / ONE;
            n += z * 0x05a0913f6b1e0000; // add y^03 * (20! / 03!)
            z = (z * y) / ONE;
            n += z * 0x0168244fdac78000; // add y^04 * (20! / 04!)
            z = (z * y) / ONE;
            n += z * 0x004807432bc18000; // add y^05 * (20! / 05!)
            z = (z * y) / ONE;
            n += z * 0x000c0135dca04000; // add y^06 * (20! / 06!)
            z = (z * y) / ONE;
            n += z * 0x0001b707b1cdc000; // add y^07 * (20! / 07!)
            z = (z * y) / ONE;
            n += z * 0x000036e0f639b800; // add y^08 * (20! / 08!)
            z = (z * y) / ONE;
            n += z * 0x00000618fee9f800; // add y^09 * (20! / 09!)
            z = (z * y) / ONE;
            n += z * 0x0000009c197dcc00; // add y^10 * (20! / 10!)
            z = (z * y) / ONE;
            n += z * 0x0000000e30dce400; // add y^11 * (20! / 11!)
            z = (z * y) / ONE;
            n += z * 0x000000012ebd1300; // add y^12 * (20! / 12!)
            z = (z * y) / ONE;
            n += z * 0x0000000017499f00; // add y^13 * (20! / 13!)
            z = (z * y) / ONE;
            n += z * 0x0000000001a9d480; // add y^14 * (20! / 14!)
            z = (z * y) / ONE;
            n += z * 0x00000000001c6380; // add y^15 * (20! / 15!)
            z = (z * y) / ONE;
            n += z * 0x000000000001c638; // add y^16 * (20! / 16!)
            z = (z * y) / ONE;
            n += z * 0x0000000000001ab8; // add y^17 * (20! / 17!)
            z = (z * y) / ONE;
            n += z * 0x000000000000017c; // add y^18 * (20! / 18!)
            z = (z * y) / ONE;
            n += z * 0x0000000000000014; // add y^19 * (20! / 19!)
            z = (z * y) / ONE;
            n += z * 0x0000000000000001; // add y^20 * (20! / 20!)
            n = n / 0x21c3677c82b40000 + y + ONE; // divide by 20! and then add y^1 / 1! + y^0 / 0!

            if ((x & (ONE >> 3)) != 0)
                n = (n * 0x1c3d6a24ed82218787d624d3e5eba95f9) / 0x18ebef9eac820ae8682b9793ac6d1e776; // multiply by e^(2^-3)
            if ((x & (ONE >> 2)) != 0)
                n = (n * 0x18ebef9eac820ae8682b9793ac6d1e778) / 0x1368b2fc6f9609fe7aceb46aa619baed4; // multiply by e^(2^-2)
            if ((x & (ONE >> 1)) != 0)
                n = (n * 0x1368b2fc6f9609fe7aceb46aa619baed5) / 0x0bc5ab1b16779be3575bd8f0520a9f21f; // multiply by e^(2^-1)
            if ((x & (ONE << 0)) != 0)
                n = (n * 0x0bc5ab1b16779be3575bd8f0520a9f21e) / 0x0454aaa8efe072e7f6ddbab84b40a55c9; // multiply by e^(2^+0)
            if ((x & (ONE << 1)) != 0)
                n = (n * 0x0454aaa8efe072e7f6ddbab84b40a55c5) / 0x00960aadc109e7a3bf4578099615711ea; // multiply by e^(2^+1)
            if ((x & (ONE << 2)) != 0)
                n = (n * 0x00960aadc109e7a3bf4578099615711d7) / 0x0002bf84208204f5977f9a8cf01fdce3d; // multiply by e^(2^+2)
            if ((x & (ONE << 3)) != 0)
                n = (n * 0x0002bf84208204f5977f9a8cf01fdc307) / 0x0000003c6ab775dd0b95b4cbee7e65d11; // multiply by e^(2^+3)
        }

        return Fraction({ n: n, d: ONE });
    }

    /**
     * @dev returns a fraction with reduced components
     */
    function reducedFraction(Fraction memory fraction, uint256 max) internal pure returns (Fraction memory) {
        uint256 scale = Math.ceilDiv(Math.max(fraction.n, fraction.d), max);
        Fraction memory reduced = Fraction({ n: fraction.n / scale, d: fraction.d / scale });
        if (reduced.d == 0) {
            revert InvalidFraction();
        }

        return reduced;
    }

    /**
     * @dev returns the weighted average of two fractions
     */
    function weightedAverage(
        Fraction memory fraction1,
        Fraction memory fraction2,
        uint256 weight1,
        uint256 weight2
    ) internal pure returns (Fraction memory) {
        return
            Fraction({
                n: fraction1.n * fraction2.d * weight1 + fraction1.d * fraction2.n * weight2,
                d: fraction1.d * fraction2.d * (weight1 + weight2)
            });
    }

    /**
     * @dev returns whether or not the deviation of an offset sample from a base sample is within a permitted range
     * for example, if the maximum permitted deviation is 5%, then evaluate `95% * base <= offset <= 105% * base`
     */
    function isInRange(
        Fraction memory baseSample,
        Fraction memory offsetSample,
        uint32 maxDeviationPPM
    ) internal pure returns (bool) {
        Uint512 memory min = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION - maxDeviationPPM));
        Uint512 memory mid = mul512(baseSample.d, offsetSample.n * PPM_RESOLUTION);
        Uint512 memory max = mul512(baseSample.n, offsetSample.d * (PPM_RESOLUTION + maxDeviationPPM));
        return lte512(min, mid) && lte512(mid, max);
    }

    /**
     * @dev returns an `Sint256` positive representation of an unsigned integer
     */
    function toPos256(uint256 n) internal pure returns (Sint256 memory) {
        return Sint256({ value: n, isNeg: false });
    }

    /**
     * @dev returns an `Sint256` negative representation of an unsigned integer
     */
    function toNeg256(uint256 n) internal pure returns (Sint256 memory) {
        return Sint256({ value: n, isNeg: true });
    }

    /**
     * @dev returns the largest integer smaller than or equal to `x * y / z`
     */
    function mulDivF(
        uint256 x,
        uint256 y,
        uint256 z
    ) internal pure returns (uint256) {
        Uint512 memory xy = mul512(x, y);

        // if `x * y < 2 ^ 256`
        if (xy.hi == 0) {
            return xy.lo / z;
        }

        // assert `x * y / z < 2 ^ 256`
        if (xy.hi >= z) {
            revert Overflow();
        }

        uint256 m = _mulMod(x, y, z); // `m = x * y % z`
        Uint512 memory n = _sub512(xy, m); // `n = x * y - m` hence `n / z = floor(x * y / z)`

        // if `n < 2 ^ 256`
        if (n.hi == 0) {
            return n.lo / z;
        }

        uint256 p = _unsafeSub(0, z) & z; // `p` is the largest power of 2 which `z` is divisible by
        uint256 q = _div512(n, p); // `n` is divisible by `p` because `n` is divisible by `z` and `z` is divisible by `p`
        uint256 r = _inv256(z / p); // `z / p = 1 mod 2` hence `inverse(z / p) = 1 mod 2 ^ 256`
        return _unsafeMul(q, r); // `q * r = (n / p) * inverse(z / p) = n / z`
    }

    /**
     * @dev returns the smallest integer larger than or equal to `x * y / z`
     */
    function mulDivC(
        uint256 x,
        uint256 y,
        uint256 z
    ) internal pure returns (uint256) {
        uint256 w = mulDivF(x, y, z);
        if (_mulMod(x, y, z) > 0) {
            if (w >= type(uint256).max) {
                revert Overflow();
            }

            return w + 1;
        }
        return w;
    }

    /**
     * @dev returns the maximum of `n1 - n2` and 0
     */
    function subMax0(uint256 n1, uint256 n2) internal pure returns (uint256) {
        return n1 > n2 ? n1 - n2 : 0;
    }

    /**
     * @dev returns the value of `x > y`
     */
    function gt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
        return x.hi > y.hi || (x.hi == y.hi && x.lo > y.lo);
    }

    /**
     * @dev returns the value of `x < y`
     */
    function lt512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
        return x.hi < y.hi || (x.hi == y.hi && x.lo < y.lo);
    }

    /**
     * @dev returns the value of `x >= y`
     */
    function gte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
        return !lt512(x, y);
    }

    /**
     * @dev returns the value of `x <= y`
     */
    function lte512(Uint512 memory x, Uint512 memory y) internal pure returns (bool) {
        return !gt512(x, y);
    }

    /**
     * @dev returns the value of `x * y`
     */
    function mul512(uint256 x, uint256 y) internal pure returns (Uint512 memory) {
        uint256 p = _mulModMax(x, y);
        uint256 q = _unsafeMul(x, y);
        if (p >= q) {
            return Uint512({ hi: p - q, lo: q });
        }
        return Uint512({ hi: _unsafeSub(p, q) - 1, lo: q });
    }

    /**
     * @dev returns the value of `x - y`, given that `x >= y`
     */
    function _sub512(Uint512 memory x, uint256 y) private pure returns (Uint512 memory) {
        if (x.lo >= y) {
            return Uint512({ hi: x.hi, lo: x.lo - y });
        }
        return Uint512({ hi: x.hi - 1, lo: _unsafeSub(x.lo, y) });
    }

    /**
     * @dev returns the value of `x / pow2n`, given that `x` is divisible by `pow2n`
     */
    function _div512(Uint512 memory x, uint256 pow2n) private pure returns (uint256) {
        uint256 pow2nInv = _unsafeAdd(_unsafeSub(0, pow2n) / pow2n, 1); // `1 << (256 - n)`
        return _unsafeMul(x.hi, pow2nInv) | (x.lo / pow2n); // `(x.hi << (256 - n)) | (x.lo >> n)`
    }

    /**
     * @dev returns the inverse of `d` modulo `2 ^ 256`, given that `d` is congruent to `1` modulo `2`
     */
    function _inv256(uint256 d) private pure returns (uint256) {
        // approximate the root of `f(x) = 1 / x - d` using the newton–raphson convergence method
        uint256 x = 1;
        for (uint256 i = 0; i < 8; i++) {
            x = _unsafeMul(x, _unsafeSub(2, _unsafeMul(x, d))); // `x = x * (2 - x * d) mod 2 ^ 256`
        }
        return x;
    }

    /**
     * @dev returns `(x + y) % 2 ^ 256`
     */
    function _unsafeAdd(uint256 x, uint256 y) private pure returns (uint256) {
        unchecked {
            return x + y;
        }
    }

    /**
     * @dev returns `(x - y) % 2 ^ 256`
     */
    function _unsafeSub(uint256 x, uint256 y) private pure returns (uint256) {
        unchecked {
            return x - y;
        }
    }

    /**
     * @dev returns `(x * y) % 2 ^ 256`
     */
    function _unsafeMul(uint256 x, uint256 y) private pure returns (uint256) {
        unchecked {
            return x * y;
        }
    }

    /**
     * @dev returns `x * y % (2 ^ 256 - 1)`
     */
    function _mulModMax(uint256 x, uint256 y) private pure returns (uint256) {
        return mulmod(x, y, type(uint256).max);
    }

    /**
     * @dev returns `x * y % z`
     */
    function _mulMod(
        uint256 x,
        uint256 y,
        uint256 z
    ) private pure returns (uint256) {
        return mulmod(x, y, z);
    }
}
Fraction.sol 14 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

struct Fraction {
    uint256 n;
    uint256 d;
}

struct Fraction112 {
    uint112 n;
    uint112 d;
}

error InvalidFraction();
SafeERC20Ex.sol 35 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

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

/**
 * @dev extends the SafeERC20 library with additional operations
 */
library SafeERC20Ex {
    using SafeERC20 for IERC20;

    /**
     * @dev ensures that the spender has sufficient allowance
     */
    function ensureApprove(
        IERC20 token,
        address spender,
        uint256 amount
    ) internal {
        if (amount == 0) {
            return;
        }

        uint256 allowance = token.allowance(address(this), spender);
        if (allowance >= amount) {
            return;
        }

        if (allowance > 0) {
            token.safeApprove(spender, 0);
        }
        token.safeApprove(spender, amount);
    }
}
Constants.sol 4 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

uint32 constant PPM_RESOLUTION = 1_000_000;
TokenLibrary.sol 165 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

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

import { SafeERC20Ex } from "./SafeERC20Ex.sol";

import { Token } from "./Token.sol";

/**
 * @dev This library implements ERC20 and SafeERC20 utilities for both the native token and for ERC20 tokens
 */
library TokenLibrary {
    using SafeERC20 for IERC20;
    using SafeERC20Ex for IERC20;

    error PermitUnsupported();

    // the address that represents the native token reserve
    address private constant NATIVE_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;

    // the symbol that represents the native token
    string private constant NATIVE_TOKEN_SYMBOL = "ETH";

    // the decimals for the native token
    uint8 private constant NATIVE_TOKEN_DECIMALS = 18;

    // the token representing the native token
    Token public constant NATIVE_TOKEN = Token(NATIVE_TOKEN_ADDRESS);

    /**
     * @dev returns whether the provided token represents an ERC20 or the native token reserve
     */
    function isNative(Token token) internal pure returns (bool) {
        return address(token) == NATIVE_TOKEN_ADDRESS;
    }

    /**
     * @dev returns the symbol of the native token/ERC20 token
     */
    function symbol(Token token) internal view returns (string memory) {
        if (isNative(token)) {
            return NATIVE_TOKEN_SYMBOL;
        }

        return toERC20(token).symbol();
    }

    /**
     * @dev returns the decimals of the native token/ERC20 token
     */
    function decimals(Token token) internal view returns (uint8) {
        if (isNative(token)) {
            return NATIVE_TOKEN_DECIMALS;
        }

        return toERC20(token).decimals();
    }

    /**
     * @dev returns the balance of the native token/ERC20 token
     */
    function balanceOf(Token token, address account) internal view returns (uint256) {
        if (isNative(token)) {
            return account.balance;
        }

        return toIERC20(token).balanceOf(account);
    }

    /**
     * @dev transfers a specific amount of the native token/ERC20 token
     */
    function safeTransfer(
        Token token,
        address to,
        uint256 amount
    ) internal {
        if (amount == 0) {
            return;
        }

        if (isNative(token)) {
            payable(to).transfer(amount);
        } else {
            toIERC20(token).safeTransfer(to, amount);
        }
    }

    /**
     * @dev transfers a specific amount of the native token/ERC20 token from a specific holder using the allowance mechanism
     *
     * note that the function does not perform any action if the native token is provided
     */
    function safeTransferFrom(
        Token token,
        address from,
        address to,
        uint256 amount
    ) internal {
        if (amount == 0 || isNative(token)) {
            return;
        }

        toIERC20(token).safeTransferFrom(from, to, amount);
    }

    /**
     * @dev approves a specific amount of the native token/ERC20 token from a specific holder
     *
     * note that the function does not perform any action if the native token is provided
     */
    function safeApprove(
        Token token,
        address spender,
        uint256 amount
    ) internal {
        if (isNative(token)) {
            return;
        }

        toIERC20(token).safeApprove(spender, amount);
    }

    /**
     * @dev ensures that the spender has sufficient allowance
     *
     * note that the function does not perform any action if the native token is provided
     */
    function ensureApprove(
        Token token,
        address spender,
        uint256 amount
    ) internal {
        if (isNative(token)) {
            return;
        }

        toIERC20(token).ensureApprove(spender, amount);
    }

    /**
     * @dev compares between a token and another raw ERC20 token
     */
    function isEqual(Token token, IERC20 erc20Token) internal pure returns (bool) {
        return toIERC20(token) == erc20Token;
    }

    /**
     * @dev utility function that converts a token to an IERC20
     */
    function toIERC20(Token token) internal pure returns (IERC20) {
        return IERC20(address(token));
    }

    /**
     * @dev utility function that converts a token to an ERC20
     */
    function toERC20(Token token) internal pure returns (ERC20) {
        return ERC20(address(token));
    }
}
Upgradeable.sol 108 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { AccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol";

import { IUpgradeable } from "./interfaces/IUpgradeable.sol";

import { AccessDenied } from "./Utils.sol";

/**
 * @dev this contract provides common utilities for upgradeable contracts
 *
 * note that we're using the Transparent Upgradeable Proxy pattern and *not* the Universal Upgradeable Proxy Standard
 * (UUPS) pattern, therefore initializing the implementation contracts is not necessary or required
 */
abstract contract Upgradeable is IUpgradeable, AccessControlEnumerableUpgradeable {
    error AlreadyInitialized();

    // the admin role is used to allow a non-proxy admin to perform additional initialization/setup during contract
    // upgrades
    bytes32 internal constant ROLE_ADMIN = keccak256("ROLE_ADMIN");

    uint32 internal constant MAX_GAP = 50;

    uint16 internal _initializations;

    // upgrade forward-compatibility storage gap
    uint256[MAX_GAP - 1] private __gap;

    // solhint-disable func-name-mixedcase

    /**
     * @dev initializes the contract and its parents
     */
    function __Upgradeable_init() internal onlyInitializing {
        __AccessControl_init();

        __Upgradeable_init_unchained();
    }

    /**
     * @dev performs contract-specific initialization
     */
    function __Upgradeable_init_unchained() internal onlyInitializing {
        _initializations = 1;

        // set up administrative roles
        _setRoleAdmin(ROLE_ADMIN, ROLE_ADMIN);

        // allow the deployer to initially be the admin of the contract
        _setupRole(ROLE_ADMIN, msg.sender);
    }

    // solhint-enable func-name-mixedcase

    modifier onlyAdmin() {
        _hasRole(ROLE_ADMIN, msg.sender);

        _;
    }

    modifier onlyRoleMember(bytes32 role) {
        _hasRole(role, msg.sender);

        _;
    }

    function version() public view virtual override returns (uint16);

    /**
     * @dev returns the admin role
     */
    function roleAdmin() external pure returns (bytes32) {
        return ROLE_ADMIN;
    }

    /**
     * @dev performs post-upgrade initialization
     *
     * requirements:
     *
     * - this must can be called only once per-upgrade
     */
    function postUpgrade(bytes calldata data) external {
        uint16 initializations = _initializations + 1;

        if (initializations != version()) {
            revert AlreadyInitialized();
        }

        _initializations = initializations;

        _postUpgrade(data);
    }

    /**
     * @dev an optional post-upgrade callback that can be implemented by child contracts
     */
    function _postUpgrade(
        bytes calldata /* data */
    ) internal virtual {}

    function _hasRole(bytes32 role, address account) internal view {
        if (!hasRole(role, account)) {
            revert AccessDenied();
        }
    }
}
FractionLibrary.sol 90 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { Fraction, Fraction112, InvalidFraction } from "./Fraction.sol";
import { MathEx } from "./MathEx.sol";

// solhint-disable-next-line func-visibility
function zeroFraction() pure returns (Fraction memory) {
    return Fraction({ n: 0, d: 1 });
}

// solhint-disable-next-line func-visibility
function zeroFraction112() pure returns (Fraction112 memory) {
    return Fraction112({ n: 0, d: 1 });
}

/**
 * @dev this library provides a set of fraction operations
 */
library FractionLibrary {
    /**
     * @dev returns whether a standard fraction is valid
     */
    function isValid(Fraction memory fraction) internal pure returns (bool) {
        return fraction.d != 0;
    }

    /**
     * @dev returns whether a 112-bit fraction is valid
     */
    function isValid(Fraction112 memory fraction) internal pure returns (bool) {
        return fraction.d != 0;
    }

    /**
     * @dev returns whether a standard fraction is positive
     */
    function isPositive(Fraction memory fraction) internal pure returns (bool) {
        return isValid(fraction) && fraction.n != 0;
    }

    /**
     * @dev returns whether a 112-bit fraction is positive
     */
    function isPositive(Fraction112 memory fraction) internal pure returns (bool) {
        return isValid(fraction) && fraction.n != 0;
    }

    /**
     * @dev returns the inverse of a given fraction
     */
    function inverse(Fraction memory fraction) internal pure returns (Fraction memory) {
        Fraction memory invFraction = Fraction({ n: fraction.d, d: fraction.n });

        if (!isValid(invFraction)) {
            revert InvalidFraction();
        }

        return invFraction;
    }

    /**
     * @dev returns the inverse of a given fraction
     */
    function inverse(Fraction112 memory fraction) internal pure returns (Fraction112 memory) {
        Fraction112 memory invFraction = Fraction112({ n: fraction.d, d: fraction.n });

        if (!isValid(invFraction)) {
            revert InvalidFraction();
        }

        return invFraction;
    }

    /**
     * @dev reduces a standard fraction to a 112-bit fraction
     */
    function toFraction112(Fraction memory fraction) internal pure returns (Fraction112 memory) {
        Fraction memory reducedFraction = MathEx.reducedFraction(fraction, type(uint112).max);

        return Fraction112({ n: uint112(reducedFraction.n), d: uint112(reducedFraction.d) });
    }

    /**
     * @dev expands a 112-bit fraction to a standard fraction
     */
    function fromFraction112(Fraction112 memory fraction) internal pure returns (Fraction memory) {
        return Fraction({ n: fraction.n, d: fraction.d });
    }
}
IVault.sol 40 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";

import { Token } from "../../token/Token.sol";

// the asset manager role is required to access all the funds
bytes32 constant ROLE_ASSET_MANAGER = keccak256("ROLE_ASSET_MANAGER");

interface IVault is IUpgradeable {
    /**
     * @dev triggered when tokens have been withdrawn from the vault
     */
    event FundsWithdrawn(Token indexed token, address indexed caller, address indexed target, uint256 amount);

    /**
     * @dev triggered when tokens have been burned from the vault
     */
    event FundsBurned(Token indexed token, address indexed caller, uint256 amount);

    /**
     * @dev tells whether the vault accepts native token deposits
     */
    function isPayable() external view returns (bool);

    /**
     * @dev withdraws funds held by the contract and sends them to an account
     */
    function withdrawFunds(
        Token token,
        address payable target,
        uint256 amount
    ) external;

    /**
     * @dev burns funds held by the contract
     */
    function burn(Token token, uint256 amount) external;
}
IBNTPool.sol 160 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { IPoolToken } from "./IPoolToken.sol";

import { Token } from "../../token/Token.sol";

import { IVault } from "../../vaults/interfaces/IVault.sol";

// the BNT pool token manager role is required to access the BNT pool tokens
bytes32 constant ROLE_BNT_POOL_TOKEN_MANAGER = keccak256("ROLE_BNT_POOL_TOKEN_MANAGER");

// the BNT manager role is required to request the BNT pool to mint BNT
bytes32 constant ROLE_BNT_MANAGER = keccak256("ROLE_BNT_MANAGER");

// the vault manager role is required to request the BNT pool to burn BNT from the master vault
bytes32 constant ROLE_VAULT_MANAGER = keccak256("ROLE_VAULT_MANAGER");

// the funding manager role is required to request or renounce funding from the BNT pool
bytes32 constant ROLE_FUNDING_MANAGER = keccak256("ROLE_FUNDING_MANAGER");

/**
 * @dev BNT Pool interface
 */
interface IBNTPool is IVault {
    /**
     * @dev returns the BNT pool token contract
     */
    function poolToken() external view returns (IPoolToken);

    /**
     * @dev returns the total staked BNT balance in the network
     */
    function stakedBalance() external view returns (uint256);

    /**
     * @dev returns the current funding of given pool
     */
    function currentPoolFunding(Token pool) external view returns (uint256);

    /**
     * @dev returns the available BNT funding for a given pool
     */
    function availableFunding(Token pool) external view returns (uint256);

    /**
     * @dev converts the specified pool token amount to the underlying BNT amount
     */
    function poolTokenToUnderlying(uint256 poolTokenAmount) external view returns (uint256);

    /**
     * @dev converts the specified underlying BNT amount to pool token amount
     */
    function underlyingToPoolToken(uint256 bntAmount) external view returns (uint256);

    /**
     * @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
     * amount
     */
    function poolTokenAmountToBurn(uint256 bntAmountToDistribute) external view returns (uint256);

    /**
     * @dev mints BNT to the recipient
     *
     * requirements:
     *
     * - the caller must have the ROLE_BNT_MANAGER role
     */
    function mint(address recipient, uint256 bntAmount) external;

    /**
     * @dev burns BNT from the vault
     *
     * requirements:
     *
     * - the caller must have the ROLE_VAULT_MANAGER role
     */
    function burnFromVault(uint256 bntAmount) external;

    /**
     * @dev deposits BNT liquidity on behalf of a specific provider and returns the respective pool token amount
     *
     * requirements:
     *
     * - the caller must be the network contract
     * - BNT tokens must have been already deposited into the contract
     */
    function depositFor(
        bytes32 contextId,
        address provider,
        uint256 bntAmount,
        bool isMigrating,
        uint256 originalVBNTAmount
    ) external returns (uint256);

    /**
     * @dev withdraws BNT liquidity on behalf of a specific provider and returns the withdrawn BNT amount
     *
     * requirements:
     *
     * - the caller must be the network contract
     * - bnBNT token must have been already deposited into the contract
     * - vBNT token must have been already deposited into the contract
     */
    function withdraw(
        bytes32 contextId,
        address provider,
        uint256 poolTokenAmount,
        uint256 bntAmount
    ) external returns (uint256);

    /**
     * @dev returns the withdrawn BNT amount
     */
    function withdrawalAmount(uint256 poolTokenAmount) external view returns (uint256);

    /**
     * @dev requests BNT funding
     *
     * requirements:
     *
     * - the caller must have the ROLE_FUNDING_MANAGER role
     * - the token must have been whitelisted
     * - the request amount should be below the funding limit for a given pool
     * - the average rate of the pool must not deviate too much from its spot rate
     */
    function requestFunding(
        bytes32 contextId,
        Token pool,
        uint256 bntAmount
    ) external;

    /**
     * @dev renounces BNT funding
     *
     * requirements:
     *
     * - the caller must have the ROLE_FUNDING_MANAGER role
     * - the token must have been whitelisted
     * - the average rate of the pool must not deviate too much from its spot rate
     */
    function renounceFunding(
        bytes32 contextId,
        Token pool,
        uint256 bntAmount
    ) external;

    /**
     * @dev notifies the pool of accrued fees
     *
     * requirements:
     *
     * - the caller must be the network contract
     */
    function onFeesCollected(
        Token pool,
        uint256 feeAmount,
        bool isTradeFee
    ) external;
}
IOwned.sol 27 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

/**
 * @dev Owned interface
 */
interface IOwned {
    /**
     * @dev returns the address of the current owner
     */
    function owner() external view returns (address);

    /**
     * @dev allows transferring the contract ownership
     *
     * requirements:
     *
     * - the caller must be the owner of the contract
     * - the new owner still needs to accept the transfer
     */
    function transferOwnership(address ownerCandidate) external;

    /**
     * @dev used by a new owner to accept an ownership transfer
     */
    function acceptOwnership() external;
}
Address.sol 222 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library Address {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionDelegateCall(target, data, "Address: low-level delegate call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a delegate call.
     *
     * _Available since v3.4._
     */
    function functionDelegateCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(isContract(target), "Address: delegate call to non-contract");

        (bool success, bytes memory returndata) = target.delegatecall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
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;
    }
}
IPoolToken.sol 30 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

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

import { IERC20Burnable } from "../../token/interfaces/IERC20Burnable.sol";
import { Token } from "../../token/Token.sol";

import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { IOwned } from "../../utility/interfaces/IOwned.sol";

/**
 * @dev Pool Token interface
 */
interface IPoolToken is IVersioned, IOwned, IERC20, IERC20Permit, IERC20Burnable {
    /**
     * @dev returns the address of the reserve token
     */
    function reserveToken() external view returns (Token);

    /**
     * @dev increases the token supply and sends the new tokens to the given account
     *
     * requirements:
     *
     * - the caller must be the owner of the contract
     */
    function mint(address recipient, uint256 amount) external;
}
Math.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a / b + (a % b == 0 ? 0 : 1);
    }
}
IVersioned.sol 9 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

/**
 * @dev an interface for a versioned contract
 */
interface IVersioned {
    function version() external view returns (uint16);
}
IMasterVault.sol 6 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { IVault } from "./IVault.sol";

interface IMasterVault is IVault {}
ERC20.sol 383 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.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.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * 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}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * 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 value {ERC20} uses, unless this function is
     * 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, _allowances[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 = _allowances[owner][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(owner, spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * 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;
        }
        _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;
        _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;
        }
        _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 Spend `amount` form the allowance of `owner` toward `spender`.
     *
     * 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 {}
}
IERC20Burnable.sol 21 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

/**
 * @dev burnable ERC20 interface
 */
interface IERC20Burnable {
    /**
     * @dev Destroys tokens from the caller.
     */
    function burn(uint256 amount) external;

    /**
     * @dev Destroys tokens from a recipient, deducting from the caller's allowance
     *
     * requirements:
     *
     * - the caller must have allowance for recipient's tokens of at least the specified amount
     */
    function burnFrom(address recipient, uint256 amount) external;
}
IUpgradeable.sol 13 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { IVersioned } from "./IVersioned.sol";

import { IAccessControlEnumerableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlEnumerableUpgradeable.sol";

/**
 * @dev this is the common interface for upgradeable contracts
 */
interface IUpgradeable is IAccessControlEnumerableUpgradeable, IVersioned {

}
IERC20.sol 82 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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);

    /**
     * @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);
}
IPoolCollection.sol 256 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { IVersioned } from "../../utility/interfaces/IVersioned.sol";
import { Fraction112 } from "../../utility/FractionLibrary.sol";

import { Token } from "../../token/Token.sol";

import { IPoolToken } from "./IPoolToken.sol";

struct PoolLiquidity {
    uint128 bntTradingLiquidity; // the BNT trading liquidity
    uint128 baseTokenTradingLiquidity; // the base token trading liquidity
    uint256 stakedBalance; // the staked balance
}

struct AverageRates {
    uint32 blockNumber;
    Fraction112 rate;
    Fraction112 invRate;
}

struct Pool {
    IPoolToken poolToken; // the pool token of the pool
    uint32 tradingFeePPM; // the trading fee (in units of PPM)
    bool tradingEnabled; // whether trading is enabled
    bool depositingEnabled; // whether depositing is enabled
    AverageRates averageRates; // the recent average rates
    PoolLiquidity liquidity; // the overall liquidity in the pool
}

struct WithdrawalAmounts {
    uint256 totalAmount;
    uint256 baseTokenAmount;
    uint256 bntAmount;
}

// trading enabling/disabling reasons
uint8 constant TRADING_STATUS_UPDATE_DEFAULT = 0;
uint8 constant TRADING_STATUS_UPDATE_ADMIN = 1;
uint8 constant TRADING_STATUS_UPDATE_MIN_LIQUIDITY = 2;
uint8 constant TRADING_STATUS_UPDATE_INVALID_STATE = 3;

struct TradeAmountAndFee {
    uint256 amount; // the source/target amount (depending on the context) resulting from the trade
    uint256 tradingFeeAmount; // the trading fee amount
    uint256 networkFeeAmount; // the network fee amount (always in units of BNT)
}

/**
 * @dev Pool Collection interface
 */
interface IPoolCollection is IVersioned {
    /**
     * @dev returns the type of the pool
     */
    function poolType() external view returns (uint16);

    /**
     * @dev returns the default trading fee (in units of PPM)
     */
    function defaultTradingFeePPM() external view returns (uint32);

    /**
     * @dev returns the network fee (in units of PPM)
     */
    function networkFeePPM() external view returns (uint32);

    /**
     * @dev returns all the pools which are managed by this pool collection
     */
    function pools() external view returns (Token[] memory);

    /**
     * @dev returns the number of all the pools which are managed by this pool collection
     */
    function poolCount() external view returns (uint256);

    /**
     * @dev returns whether a pool is valid
     */
    function isPoolValid(Token pool) external view returns (bool);

    /**
     * @dev returns the overall liquidity in the pool
     */
    function poolLiquidity(Token pool) external view returns (PoolLiquidity memory);

    /**
     * @dev returns the pool token of the pool
     */
    function poolToken(Token pool) external view returns (IPoolToken);

    /**
     * @dev returns the trading fee (in units of PPM)
     */
    function tradingFeePPM(Token pool) external view returns (uint32);

    /**
     * @dev returns whether trading is enabled
     */
    function tradingEnabled(Token pool) external view returns (bool);

    /**
     * @dev returns whether depositing is enabled
     */
    function depositingEnabled(Token pool) external view returns (bool);

    /**
     * @dev returns whether the pool is stable
     */
    function isPoolStable(Token pool) external view returns (bool);

    /**
     * @dev converts the specified pool token amount to the underlying base token amount
     */
    function poolTokenToUnderlying(Token pool, uint256 poolTokenAmount) external view returns (uint256);

    /**
     * @dev converts the specified underlying base token amount to pool token amount
     */
    function underlyingToPoolToken(Token pool, uint256 baseTokenAmount) external view returns (uint256);

    /**
     * @dev returns the number of pool token to burn in order to increase everyone's underlying value by the specified
     * amount
     */
    function poolTokenAmountToBurn(
        Token pool,
        uint256 baseTokenAmountToDistribute,
        uint256 protocolPoolTokenAmount
    ) external view returns (uint256);

    /**
     * @dev creates a new pool
     *
     * requirements:
     *
     * - the caller must be the network contract
     * - the pool should have been whitelisted
     * - the pool isn't already defined in the collection
     */
    function createPool(Token token) external;

    /**
     * @dev deposits base token liquidity on behalf of a specific provider and returns the respective pool token amount
     *
     * requirements:
     *
     * - the caller must be the network contract
     * - assumes that the base token has been already deposited in the vault
     */
    function depositFor(
        bytes32 contextId,
        address provider,
        Token pool,
        uint256 baseTokenAmount
    ) external returns (uint256);

    /**
     * @dev handles some of the withdrawal-related actions and returns the withdrawn base token amount
     *
     * requirements:
     *
     * - the caller must be the network contract
     * - the caller must have approved the collection to transfer/burn the pool token amount on its behalf
     */
    function withdraw(
        bytes32 contextId,
        address provider,
        Token pool,
        uint256 poolTokenAmount,
        uint256 baseTokenAmount
    ) external returns (uint256);

    /**
     * @dev returns the amounts that would be returned if the position is currently withdrawn,
     * along with the breakdown of the base token and the BNT compensation
     */
    function withdrawalAmounts(Token pool, uint256 poolTokenAmount) external view returns (WithdrawalAmounts memory);

    /**
     * @dev performs a trade by providing the source amount and returns the target amount and the associated fee
     *
     * requirements:
     *
     * - the caller must be the network contract
     */
    function tradeBySourceAmount(
        bytes32 contextId,
        Token sourceToken,
        Token targetToken,
        uint256 sourceAmount,
        uint256 minReturnAmount
    ) external returns (TradeAmountAndFee memory);

    /**
     * @dev performs a trade by providing the target amount and returns the required source amount and the associated fee
     *
     * requirements:
     *
     * - the caller must be the network contract
     */
    function tradeByTargetAmount(
        bytes32 contextId,
        Token sourceToken,
        Token targetToken,
        uint256 targetAmount,
        uint256 maxSourceAmount
    ) external returns (TradeAmountAndFee memory);

    /**
     * @dev returns the output amount and fee when trading by providing the source amount
     */
    function tradeOutputAndFeeBySourceAmount(
        Token sourceToken,
        Token targetToken,
        uint256 sourceAmount
    ) external view returns (TradeAmountAndFee memory);

    /**
     * @dev returns the input amount and fee when trading by providing the target amount
     */
    function tradeInputAndFeeByTargetAmount(
        Token sourceToken,
        Token targetToken,
        uint256 targetAmount
    ) external view returns (TradeAmountAndFee memory);

    /**
     * @dev notifies the pool of accrued fees
     *
     * requirements:
     *
     * - the caller must be the network contract
     */
    function onFeesCollected(Token pool, uint256 feeAmount) external;

    /**
     * @dev migrates a pool to this pool collection
     *
     * requirements:
     *
     * - the caller must be the pool migrator contract
     */
    function migratePoolIn(Token pool, Pool calldata data) external;

    /**
     * @dev migrates a pool from this pool collection
     *
     * requirements:
     *
     * - the caller must be the pool migrator contract
     */
    function migratePoolOut(Token pool, IPoolCollection targetPoolCollection) external;
}
IBancorNetwork.sol 190 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

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

import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";

import { Token } from "../../token/Token.sol";

import { IPoolCollection } from "../../pools/interfaces/IPoolCollection.sol";
import { IPoolToken } from "../../pools/interfaces/IPoolToken.sol";

/**
 * @dev Flash-loan recipient interface
 */
interface IFlashLoanRecipient {
    /**
     * @dev a flash-loan recipient callback after each the caller must return the borrowed amount and an additional fee
     */
    function onFlashLoan(
        address caller,
        IERC20 erc20Token,
        uint256 amount,
        uint256 feeAmount,
        bytes memory data
    ) external;
}

/**
 * @dev Bancor Network interface
 */
interface IBancorNetwork is IUpgradeable {
    /**
     * @dev returns the set of all valid pool collections
     */
    function poolCollections() external view returns (IPoolCollection[] memory);

    /**
     * @dev returns the set of all liquidity pools
     */
    function liquidityPools() external view returns (Token[] memory);

    /**
     * @dev returns the respective pool collection for the provided pool
     */
    function collectionByPool(Token pool) external view returns (IPoolCollection);

    /**
     * @dev creates new pools
     *
     * requirements:
     *
     * - none of the pools already exists
     */
    function createPools(Token[] calldata tokens, IPoolCollection poolCollection) external;

    /**
     * @dev migrates a list of pools between pool collections
     *
     * notes:
     *
     * - invalid or incompatible pools will be skipped gracefully
     */
    function migratePools(Token[] calldata pools, IPoolCollection newPoolCollection) external;

    /**
     * @dev deposits liquidity for the specified provider and returns the respective pool token amount
     *
     * requirements:
     *
     * - the caller must have approved the network to transfer the tokens on its behalf (except for in the
     *   native token case)
     */
    function depositFor(
        address provider,
        Token pool,
        uint256 tokenAmount
    ) external payable returns (uint256);

    /**
     * @dev deposits liquidity for the current provider and returns the respective pool token amount
     *
     * requirements:
     *
     * - the caller must have approved the network to transfer the tokens on its behalf (except for in the
     *   native token case)
     */
    function deposit(Token pool, uint256 tokenAmount) external payable returns (uint256);

    /**
     * @dev initiates liquidity withdrawal
     *
     * requirements:
     *
     * - the caller must have approved the contract to transfer the pool token amount on its behalf
     */
    function initWithdrawal(IPoolToken poolToken, uint256 poolTokenAmount) external returns (uint256);

    /**
     * @dev cancels a withdrawal request, and returns the number of pool token amount associated with the withdrawal
     * request
     *
     * requirements:
     *
     * - the caller must have already initiated a withdrawal and received the specified id
     */
    function cancelWithdrawal(uint256 id) external returns (uint256);

    /**
     * @dev withdraws liquidity and returns the withdrawn amount
     *
     * requirements:
     *
     * - the provider must have already initiated a withdrawal and received the specified id
     * - the specified withdrawal request is eligible for completion
     * - the provider must have approved the network to transfer vBNT amount on its behalf, when withdrawing BNT
     * liquidity
     */
    function withdraw(uint256 id) external returns (uint256);

    /**
     * @dev performs a trade by providing the input source amount, sends the proceeds to the optional beneficiary (or
     * to the address of the caller, in case it's not supplied), and returns the trade target amount
     *
     * requirements:
     *
     * - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
     *   native token case)
     */
    function tradeBySourceAmount(
        Token sourceToken,
        Token targetToken,
        uint256 sourceAmount,
        uint256 minReturnAmount,
        uint256 deadline,
        address beneficiary
    ) external payable returns (uint256);

    /**
     * @dev performs a trade by providing the output target amount, sends the proceeds to the optional beneficiary (or
     * to the address of the caller, in case it's not supplied), and returns the trade source amount
     *
     * requirements:
     *
     * - the caller must have approved the network to transfer the source tokens on its behalf (except for in the
     *   native token case)
     */
    function tradeByTargetAmount(
        Token sourceToken,
        Token targetToken,
        uint256 targetAmount,
        uint256 maxSourceAmount,
        uint256 deadline,
        address beneficiary
    ) external payable returns (uint256);

    /**
     * @dev provides a flash-loan
     *
     * requirements:
     *
     * - the recipient's callback must return *at least* the borrowed amount and fee back to the specified return address
     */
    function flashLoan(
        Token token,
        uint256 amount,
        IFlashLoanRecipient recipient,
        bytes calldata data
    ) external;

    /**
     * @dev deposits liquidity during a migration
     */
    function migrateLiquidity(
        Token token,
        address provider,
        uint256 amount,
        uint256 availableAmount,
        uint256 originalAmount
    ) external payable;

    /**
     * @dev withdraws pending network fees, and returns the amount of fees withdrawn
     *
     * requirements:
     *
     * - the caller must have the ROLE_NETWORK_FEE_MANAGER privilege
     */
    function withdrawNetworkFees(address recipient) external returns (uint256);
}
IClaimable.sol 11 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;

/// @title Claimable contract interface
interface IClaimable {
    function owner() external view returns (address);

    function transferOwnership(address newOwner) external;

    function acceptOwnership() external;
}
INetworkSettings.sol 60 lines
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.8.13;

import { IUpgradeable } from "../../utility/interfaces/IUpgradeable.sol";

import { Token } from "../../token/Token.sol";

error NotWhitelisted();

struct VortexRewards {
    // the percentage of converted BNT to be sent to the initiator of the burning event (in units of PPM)
    uint32 burnRewardPPM;
    // the maximum burn reward to be sent to the initiator of the burning event
    uint256 burnRewardMaxAmount;
}

/**
 * @dev Network Settings interface
 */
interface INetworkSettings is IUpgradeable {
    /**
     * @dev returns the protected tokens whitelist
     */
    function protectedTokenWhitelist() external view returns (Token[] memory);

    /**
     * @dev checks whether a given token is whitelisted
     */
    function isTokenWhitelisted(Token pool) external view returns (bool);

    /**
     * @dev returns the BNT funding limit for a given pool
     */
    function poolFundingLimit(Token pool) external view returns (uint256);

    /**
     * @dev returns the minimum BNT trading liquidity required before the system enables trading in the relevant pool
     */
    function minLiquidityForTrading() external view returns (uint256);

    /**
     * @dev returns the withdrawal fee (in units of PPM)
     */
    function withdrawalFeePPM() external view returns (uint32);

    /**
     * @dev returns the default flash-loan fee (in units of PPM)
     */
    function defaultFlashLoanFeePPM() external view returns (uint32);

    /**
     * @dev returns the flash-loan fee (in units of PPM) of a pool
     */
    function flashLoanFeePPM(Token pool) external view returns (uint32);

    /**
     * @dev returns the vortex settings
     */
    function vortexRewards() external view returns (VortexRewards memory);
}
IMintableToken.sol 13 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;

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

import "./IClaimable.sol";

/// @title Mintable Token interface
interface IMintableToken is IERC20, IClaimable {
    function issue(address to, uint256 amount) external;

    function destroy(address from, uint256 amount) external;
}
ITokenGovernance.sol 23 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.12;

import "./IMintableToken.sol";

/// @title The interface for mintable/burnable token governance.
interface ITokenGovernance {
    // The address of the mintable ERC20 token.
    function token() external view returns (IMintableToken);

    /// @dev Mints new tokens.
    ///
    /// @param to Account to receive the new amount.
    /// @param amount Amount to increase the supply by.
    ///
    function mint(address to, uint256 amount) external;

    /// @dev Burns tokens from the caller.
    ///
    /// @param amount Amount to decrease the supply by.
    ///
    function burn(uint256 amount) external;
}
SafeERC20.sol 99 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";
import "../../../utils/Address.sol";

/**
 * @title SafeERC20
 * @dev Wrappers around ERC20 operations that throw on failure (when the token
 * contract returns false). Tokens that return no value (and instead revert or
 * throw on failure) are also supported, non-reverting calls are assumed to be
 * successful.
 * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
 * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
 */
library SafeERC20 {
    using Address for address;

    function safeTransfer(
        IERC20 token,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
    }

    function safeTransferFrom(
        IERC20 token,
        address from,
        address to,
        uint256 value
    ) internal {
        _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
    }

    /**
     * @dev Deprecated. This function has issues similar to the ones found in
     * {IERC20-approve}, and its usage is discouraged.
     *
     * Whenever possible, use {safeIncreaseAllowance} and
     * {safeDecreaseAllowance} instead.
     */
    function safeApprove(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        // safeApprove should only be called when setting an initial allowance,
        // or when resetting it to zero. To increase and decrease it, use
        // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
        require(
            (value == 0) || (token.allowance(address(this), spender) == 0),
            "SafeERC20: approve from non-zero to non-zero allowance"
        );
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
    }

    function safeIncreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        uint256 newAllowance = token.allowance(address(this), spender) + value;
        _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
    }

    function safeDecreaseAllowance(
        IERC20 token,
        address spender,
        uint256 value
    ) internal {
        unchecked {
            uint256 oldAllowance = token.allowance(address(this), spender);
            require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
            uint256 newAllowance = oldAllowance - value;
            _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
        }
    }

    /**
     * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
     * on the return value: the return value is optional (but if data is returned, it must not be false).
     * @param token The token targeted by the call.
     * @param data The call data (encoded using abi.encode or one of its variants).
     */
    function _callOptionalReturn(IERC20 token, bytes memory data) private {
        // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
        // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
        // the target address contains contract code and also asserts for success in the low-level call.

        bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
        if (returndata.length > 0) {
            // Return data is optional
            require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
        }
    }
}
AddressUpgradeable.sol 195 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)

pragma solidity ^0.8.1;

/**
 * @dev Collection of functions related to the address type
 */
library AddressUpgradeable {
    /**
     * @dev Returns true if `account` is a contract.
     *
     * [IMPORTANT]
     * ====
     * It is unsafe to assume that an address for which this function returns
     * false is an externally-owned account (EOA) and not a contract.
     *
     * Among others, `isContract` will return false for the following
     * types of addresses:
     *
     *  - an externally-owned account
     *  - a contract in construction
     *  - an address where a contract will be created
     *  - an address where a contract lived, but was destroyed
     * ====
     *
     * [IMPORTANT]
     * ====
     * You shouldn't rely on `isContract` to protect against flash loan attacks!
     *
     * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
     * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
     * constructor.
     * ====
     */
    function isContract(address account) internal view returns (bool) {
        // This method relies on extcodesize/address.code.length, which returns 0
        // for contracts in construction, since the code is only stored at the end
        // of the constructor execution.

        return account.code.length > 0;
    }

    /**
     * @dev Replacement for Solidity's `transfer`: sends `amount` wei to
     * `recipient`, forwarding all available gas and reverting on errors.
     *
     * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
     * of certain opcodes, possibly making contracts go over the 2300 gas limit
     * imposed by `transfer`, making them unable to receive funds via
     * `transfer`. {sendValue} removes this limitation.
     *
     * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
     *
     * IMPORTANT: because control is transferred to `recipient`, care must be
     * taken to not create reentrancy vulnerabilities. Consider using
     * {ReentrancyGuard} or the
     * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
     */
    function sendValue(address payable recipient, uint256 amount) internal {
        require(address(this).balance >= amount, "Address: insufficient balance");

        (bool success, ) = recipient.call{value: amount}("");
        require(success, "Address: unable to send value, recipient may have reverted");
    }

    /**
     * @dev Performs a Solidity function call using a low level `call`. A
     * plain `call` is an unsafe replacement for a function call: use this
     * function instead.
     *
     * If `target` reverts with a revert reason, it is bubbled up by this
     * function (like regular Solidity function calls).
     *
     * Returns the raw returned data. To convert to the expected return value,
     * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
     *
     * Requirements:
     *
     * - `target` must be a contract.
     * - calling `target` with `data` must not revert.
     *
     * _Available since v3.1._
     */
    function functionCall(address target, bytes memory data) internal returns (bytes memory) {
        return functionCall(target, data, "Address: low-level call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
     * `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, 0, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but also transferring `value` wei to `target`.
     *
     * Requirements:
     *
     * - the calling contract must have an ETH balance of at least `value`.
     * - the called Solidity function must be `payable`.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value
    ) internal returns (bytes memory) {
        return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
    }

    /**
     * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
     * with `errorMessage` as a fallback revert reason when `target` reverts.
     *
     * _Available since v3.1._
     */
    function functionCallWithValue(
        address target,
        bytes memory data,
        uint256 value,
        string memory errorMessage
    ) internal returns (bytes memory) {
        require(address(this).balance >= value, "Address: insufficient balance for call");
        require(isContract(target), "Address: call to non-contract");

        (bool success, bytes memory returndata) = target.call{value: value}(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
        return functionStaticCall(target, data, "Address: low-level static call failed");
    }

    /**
     * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
     * but performing a static call.
     *
     * _Available since v3.3._
     */
    function functionStaticCall(
        address target,
        bytes memory data,
        string memory errorMessage
    ) internal view returns (bytes memory) {
        require(isContract(target), "Address: static call to non-contract");

        (bool success, bytes memory returndata) = target.staticcall(data);
        return verifyCallResult(success, returndata, errorMessage);
    }

    /**
     * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
     * revert reason using the provided one.
     *
     * _Available since v4.3._
     */
    function verifyCallResult(
        bool success,
        bytes memory returndata,
        string memory errorMessage
    ) internal pure returns (bytes memory) {
        if (success) {
            return returndata;
        } else {
            // Look for revert reason and bubble it up if present
            if (returndata.length > 0) {
                // The easiest way to bubble the revert reason is using memory via assembly

                assembly {
                    let returndata_size := mload(returndata)
                    revert(add(32, returndata), returndata_size)
                }
            } else {
                revert(errorMessage);
            }
        }
    }
}
ContextUpgradeable.sol 37 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @dev Provides information about the current execution context, including the
 * sender of the transaction and its data. While these are generally available
 * via msg.sender and msg.data, they should not be accessed in such a direct
 * manner, since when dealing with meta-transactions the account sending and
 * paying for execution may not be the actual sender (as far as an application
 * is concerned).
 *
 * This contract is only required for intermediate, library-like contracts.
 */
abstract contract ContextUpgradeable is Initializable {
    function __Context_init() internal onlyInitializing {
    }

    function __Context_init_unchained() internal onlyInitializing {
    }
    function _msgSender() internal view virtual returns (address) {
        return msg.sender;
    }

    function _msgData() internal view virtual returns (bytes calldata) {
        return msg.data;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}
StringsUpgradeable.sol 67 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library StringsUpgradeable {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }
}
Initializable.sol 80 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol)

pragma solidity ^0.8.0;

import "../../utils/AddressUpgradeable.sol";

/**
 * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
 * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an
 * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
 * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
 *
 * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
 * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
 *
 * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
 * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
 *
 * [CAUTION]
 * ====
 * Avoid leaving a contract uninitialized.
 *
 * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
 * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
 * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
 *
 * [.hljs-theme-light.nopadding]
 * ```
 * /// @custom:oz-upgrades-unsafe-allow constructor
 * constructor() initializer {}
 * ```
 * ====
 */
abstract contract Initializable {
    /**
     * @dev Indicates that the contract has been initialized.
     */
    bool private _initialized;

    /**
     * @dev Indicates that the contract is in the process of being initialized.
     */
    bool private _initializing;

    /**
     * @dev Modifier to protect an initializer function from being invoked twice.
     */
    modifier initializer() {
        // If the contract is initializing we ignore whether _initialized is set in order to support multiple
        // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
        // contract may have been reentered.
        require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");

        bool isTopLevelCall = !_initializing;
        if (isTopLevelCall) {
            _initializing = true;
            _initialized = true;
        }

        _;

        if (isTopLevelCall) {
            _initializing = false;
        }
    }

    /**
     * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
     * {initializer} modifier, directly or indirectly.
     */
    modifier onlyInitializing() {
        require(_initializing, "Initializable: contract is not initializing");
        _;
    }

    function _isConstructor() private view returns (bool) {
        return !AddressUpgradeable.isContract(address(this));
    }
}
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);
}
PausableUpgradeable.sol 103 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    function __Pausable_init() internal onlyInitializing {
        __Pausable_init_unchained();
    }

    function __Pausable_init_unchained() internal onlyInitializing {
        _paused = false;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        require(!paused(), "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        require(paused(), "Pausable: not paused");
        _;
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}
draft-IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-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);
}
AccessControlUpgradeable.sol 236 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that allows children to implement role-based access
 * control mechanisms. This is a lightweight version that doesn't allow enumerating role
 * members except through off-chain means by accessing the contract event logs. Some
 * applications may benefit from on-chain enumerability, for those cases see
 * {AccessControlEnumerable}.
 *
 * Roles are referred to by their `bytes32` identifier. These should be exposed
 * in the external API and be unique. The best way to achieve this is by
 * using `public constant` hash digests:
 *
 * ```
 * bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
 * ```
 *
 * Roles can be used to represent a set of permissions. To restrict access to a
 * function call, use {hasRole}:
 *
 * ```
 * function foo() public {
 *     require(hasRole(MY_ROLE, msg.sender));
 *     ...
 * }
 * ```
 *
 * Roles can be granted and revoked dynamically via the {grantRole} and
 * {revokeRole} functions. Each role has an associated admin role, and only
 * accounts that have a role's admin role can call {grantRole} and {revokeRole}.
 *
 * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
 * that only accounts with this role will be able to grant or revoke other
 * roles. More complex role relationships can be created by using
 * {_setRoleAdmin}.
 *
 * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
 * grant and revoke this role. Extra precautions should be taken to secure
 * accounts that have been granted it.
 */
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
    function __AccessControl_init() internal onlyInitializing {
    }

    function __AccessControl_init_unchained() internal onlyInitializing {
    }
    struct RoleData {
        mapping(address => bool) members;
        bytes32 adminRole;
    }

    mapping(bytes32 => RoleData) private _roles;

    bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;

    /**
     * @dev Modifier that checks that an account has a specific role. Reverts
     * with a standardized message including the required role.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     *
     * _Available since v4.1._
     */
    modifier onlyRole(bytes32 role) {
        _checkRole(role, _msgSender());
        _;
    }

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) public view virtual override returns (bool) {
        return _roles[role].members[account];
    }

    /**
     * @dev Revert with a standard message if `account` is missing `role`.
     *
     * The format of the revert reason is given by the following regular expression:
     *
     *  /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
     */
    function _checkRole(bytes32 role, address account) internal view virtual {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        StringsUpgradeable.toHexString(uint160(account), 20),
                        " is missing role ",
                        StringsUpgradeable.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {
        return _roles[role].adminRole;
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _grantRole(role, account);
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
        _revokeRole(role, account);
    }

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been revoked `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) public virtual override {
        require(account == _msgSender(), "AccessControl: can only renounce roles for self");

        _revokeRole(role, account);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event. Note that unlike {grantRole}, this function doesn't perform any
     * checks on the calling account.
     *
     * [WARNING]
     * ====
     * This function should only be called from the constructor when setting
     * up the initial roles for the system.
     *
     * Using this function in any other way is effectively circumventing the admin
     * system imposed by {AccessControl}.
     * ====
     *
     * NOTE: This function is deprecated in favor of {_grantRole}.
     */
    function _setupRole(bytes32 role, address account) internal virtual {
        _grantRole(role, account);
    }

    /**
     * @dev Sets `adminRole` as ``role``'s admin role.
     *
     * Emits a {RoleAdminChanged} event.
     */
    function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
        bytes32 previousAdminRole = getRoleAdmin(role);
        _roles[role].adminRole = adminRole;
        emit RoleAdminChanged(role, previousAdminRole, adminRole);
    }

    /**
     * @dev Grants `role` to `account`.
     *
     * Internal function without access restriction.
     */
    function _grantRole(bytes32 role, address account) internal virtual {
        if (!hasRole(role, account)) {
            _roles[role].members[account] = true;
            emit RoleGranted(role, account, _msgSender());
        }
    }

    /**
     * @dev Revokes `role` from `account`.
     *
     * Internal function without access restriction.
     */
    function _revokeRole(bytes32 role, address account) internal virtual {
        if (hasRole(role, account)) {
            _roles[role].members[account] = false;
            emit RoleRevoked(role, account, _msgSender());
        }
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}
IAccessControlUpgradeable.sol 88 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)

pragma solidity ^0.8.0;

/**
 * @dev External interface of AccessControl declared to support ERC165 detection.
 */
interface IAccessControlUpgradeable {
    /**
     * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
     *
     * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
     * {RoleAdminChanged} not being emitted signaling this.
     *
     * _Available since v3.1._
     */
    event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);

    /**
     * @dev Emitted when `account` is granted `role`.
     *
     * `sender` is the account that originated the contract call, an admin role
     * bearer except when using {AccessControl-_setupRole}.
     */
    event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Emitted when `account` is revoked `role`.
     *
     * `sender` is the account that originated the contract call:
     *   - if using `revokeRole`, it is the admin role bearer
     *   - if using `renounceRole`, it is the role bearer (i.e. `account`)
     */
    event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);

    /**
     * @dev Returns `true` if `account` has been granted `role`.
     */
    function hasRole(bytes32 role, address account) external view returns (bool);

    /**
     * @dev Returns the admin role that controls `role`. See {grantRole} and
     * {revokeRole}.
     *
     * To change a role's admin, use {AccessControl-_setRoleAdmin}.
     */
    function getRoleAdmin(bytes32 role) external view returns (bytes32);

    /**
     * @dev Grants `role` to `account`.
     *
     * If `account` had not been already granted `role`, emits a {RoleGranted}
     * event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function grantRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from `account`.
     *
     * If `account` had been granted `role`, emits a {RoleRevoked} event.
     *
     * Requirements:
     *
     * - the caller must have ``role``'s admin role.
     */
    function revokeRole(bytes32 role, address account) external;

    /**
     * @dev Revokes `role` from the calling account.
     *
     * Roles are often managed via {grantRole} and {revokeRole}: this function's
     * purpose is to provide a mechanism for accounts to lose their privileges
     * if they are compromised (such as when a trusted device is misplaced).
     *
     * If the calling account had been granted `role`, emits a {RoleRevoked}
     * event.
     *
     * Requirements:
     *
     * - the caller must be `account`.
     */
    function renounceRole(bytes32 role, address account) external;
}
ReentrancyGuardUpgradeable.sol 75 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuardUpgradeable is Initializable {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    function __ReentrancyGuard_init() internal onlyInitializing {
        __ReentrancyGuard_init_unchained();
    }

    function __ReentrancyGuard_init_unchained() internal onlyInitializing {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}
ERC165Upgradeable.sol 42 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)

pragma solidity ^0.8.0;

import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";

/**
 * @dev Implementation of the {IERC165} interface.
 *
 * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
 * for the additional interface id that will be supported. For example:
 *
 * ```solidity
 * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
 *     return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
 * }
 * ```
 *
 * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
 */
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
    function __ERC165_init() internal onlyInitializing {
    }

    function __ERC165_init_unchained() internal onlyInitializing {
    }
    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IERC165Upgradeable).interfaceId;
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[50] private __gap;
}
IERC165Upgradeable.sol 25 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC165 standard, as defined in the
 * https://eips.ethereum.org/EIPS/eip-165[EIP].
 *
 * Implementers can declare support of contract interfaces, which can then be
 * queried by others ({ERC165Checker}).
 *
 * For an implementation, see {ERC165}.
 */
interface IERC165Upgradeable {
    /**
     * @dev Returns true if this contract implements the interface defined by
     * `interfaceId`. See the corresponding
     * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
     * to learn more about how these ids are created.
     *
     * This function call must use less than 30 000 gas.
     */
    function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
EnumerableSetUpgradeable.sol 357 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)

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.
 *
 * ```
 * 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.
 */
library EnumerableSetUpgradeable {
    // 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) {
        return _values(set._inner);
    }

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

        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 on 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;

        assembly {
            result := store
        }

        return result;
    }
}
AccessControlEnumerableUpgradeable.sol 77 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControlEnumerableUpgradeable.sol";
import "./AccessControlUpgradeable.sol";
import "../utils/structs/EnumerableSetUpgradeable.sol";
import "../proxy/utils/Initializable.sol";

/**
 * @dev Extension of {AccessControl} that allows enumerating the members of each role.
 */
abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {
    function __AccessControlEnumerable_init() internal onlyInitializing {
    }

    function __AccessControlEnumerable_init_unchained() internal onlyInitializing {
    }
    using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;

    mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;

    /**
     * @dev See {IERC165-supportsInterface}.
     */
    function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
        return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);
    }

    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {
        return _roleMembers[role].at(index);
    }

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {
        return _roleMembers[role].length();
    }

    /**
     * @dev Overload {_grantRole} to track enumerable memberships
     */
    function _grantRole(bytes32 role, address account) internal virtual override {
        super._grantRole(role, account);
        _roleMembers[role].add(account);
    }

    /**
     * @dev Overload {_revokeRole} to track enumerable memberships
     */
    function _revokeRole(bytes32 role, address account) internal virtual override {
        super._revokeRole(role, account);
        _roleMembers[role].remove(account);
    }

    /**
     * @dev This empty reserved space is put in place to allow future versions to add new
     * variables without shifting down storage in the inheritance chain.
     * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
     */
    uint256[49] private __gap;
}
IAccessControlEnumerableUpgradeable.sol 31 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)

pragma solidity ^0.8.0;

import "./IAccessControlUpgradeable.sol";

/**
 * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
 */
interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {
    /**
     * @dev Returns one of the accounts that have `role`. `index` must be a
     * value between 0 and {getRoleMemberCount}, non-inclusive.
     *
     * Role bearers are not sorted in any particular way, and their ordering may
     * change at any point.
     *
     * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
     * you perform all queries on the same block. See the following
     * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
     * for more information.
     */
    function getRoleMember(bytes32 role, uint256 index) external view returns (address);

    /**
     * @dev Returns the number of accounts that have `role`. Can be used
     * together with {getRoleMember} to enumerate all bearers of a role.
     */
    function getRoleMemberCount(bytes32 role) external view returns (uint256);
}

Read Contract

DEFAULT_ADMIN_ROLE 0xa217fddf → bytes32
availableFunding 0x8d0c7827 → uint256
currentPoolFunding 0xfd4d4ad2 → uint256
getRoleAdmin 0x248a9ca3 → bytes32
getRoleMember 0x9010d07c → address
getRoleMemberCount 0xca15c873 → uint256
hasRole 0x91d14854 → bool
isPaused 0xb187bd26 → bool
isPayable 0xce46e046 → bool
paused 0x5c975abb → bool
poolToken 0xcbdf382c → address
poolTokenAmountToBurn 0xe80e8a7d → uint256
poolTokenToUnderlying 0x0f1544c4 → uint256
roleAdmin 0x93867fb5 → bytes32
roleAssetManager 0x92bd95ea → bytes32
roleBNTManager 0xc878ab33 → bytes32
roleBNTPoolTokenManager 0xb89bd433 → bytes32
roleFundingManager 0x639c3574 → bytes32
roleVaultManager 0xe8ddecba → bytes32
stakedBalance 0x5b9f0016 → uint256
supportsInterface 0x01ffc9a7 → bool
underlyingToPoolToken 0xd7882fdf → uint256
version 0x54fd4d50 → uint16
withdrawalAmount 0x08fc3385 → uint256

Write Contract 16 functions

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

burn 0x9dc29fac
address token
uint256 amount
burnFromVault 0xa9c63258
uint256 bntAmount
depositFor 0xe06bf20d
bytes32 contextId
address provider
uint256 bntAmount
bool isMigrating
uint256 originalVBNTAmount
returns: uint256
grantRole 0x2f2ff15d
bytes32 role
address account
initialize 0x8129fc1c
No parameters
mint 0x40c10f19
address recipient
uint256 bntAmount
onFeesCollected 0x7c8f622d
address pool
uint256 feeAmount
bool isTradeFee
pause 0x8456cb59
No parameters
postUpgrade 0x8cd2403d
bytes data
renounceFunding 0x1ebda06d
bytes32 contextId
address pool
uint256 bntAmount
renounceRole 0x36568abe
bytes32 role
address account
requestFunding 0x71c0feb7
bytes32 contextId
address pool
uint256 bntAmount
revokeRole 0xd547741f
bytes32 role
address account
unpause 0x3f4ba83a
No parameters
withdraw 0xe404d8ce
bytes32 contextId
address provider
uint256 poolTokenAmount
uint256 bntAmount
returns: uint256
withdrawFunds 0x1c20fadd
address token
address target
uint256 amount

Recent Transactions

Transaction index is loading. Only unfinalized transactions are shown while the index starts up.