Address Contract Partially Verified
Address
0x00041A81E413e4C02f26561C890f2b863A5Fb06A
Balance
0 ETH
Nonce
1
Code Size
19707 bytes
Creator
0x83CE9e95...12e3 at tx 0x61a59158...011573
Indexed Transactions
0
Contract Bytecode
19707 bytes
0x608060405234801561001057600080fd5b506004361061030a5760003560e01c8063840e493f1161019c578063ba087652116100ee578063e2230f6011610097578063e74b981b11610071578063e74b981b1461072f578063efb2873c14610742578063fafe6cad1461075557600080fd5b8063e2230f60146106f2578063e522538114610712578063e6432a341461071a57600080fd5b8063d505accf116100c8578063d505accf14610693578063d905777e146106a6578063dd62ed3e146106b957600080fd5b8063ba08765214610647578063ce96cb771461065a578063d4b839921461066d57600080fd5b806388a8d60211610150578063a457c2d71161012a578063a457c2d71461060e578063a9059cbb14610621578063b460af941461063457600080fd5b806388a8d602146105cc578063927d7953146105f357806395d89b411461060657600080fd5b806384b0196e1161018157806384b0196e1461058b578063867904b4146105a6578063886f039a146105b957600080fd5b8063840e493f146105635780638456cb591461058357600080fd5b8063313ce567116102605780634cdad5061161020957806370a08231116101e357806370a082311461050157806376d5de851461052a5780637ecebe001461055057600080fd5b80634cdad506146104bd5780635c975abb146104d05780636f307dc3146104db57600080fd5b80633f4ba83a1161023a5780633f4ba83a1461049857806346904840146104a25780634a7d0369146104b557600080fd5b8063313ce5671461044c5780633644e5151461047d578063395093511461048557600080fd5b806318160ddd116102c2578063204f83f91161029c578063204f83f9146103ff57806323b872dd1461042657806325a8d87d1461043957600080fd5b806318160ddd146103db5780631ad8b03b146103e35780631dc7f521146103ec57600080fd5b80630835dda7116102f35780630835dda714610368578063095ea7b3146103975780630a28a477146103ba57600080fd5b806303eadcfc1461030f57806306fdde0314610353575b600080fd5b6103367f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c14881565b6040516001600160a01b0390911681526020015b60405180910390f35b61035b610768565b60405161034a9190614560565b6103706107e7565b6040805182516001600160801b03908116825260209384015116928101929092520161034a565b6103aa6103a536600461458a565b61084b565b604051901515815260200161034a565b6103cd6103c83660046145b4565b610865565b60405190815260200161034a565b6002546103cd565b6103cd600d5481565b6103cd6103fa3660046145b4565b6108a0565b6103cd7f000000000000000000000000000000000000000000000000000000006772435581565b6103aa6104343660046145cd565b6109f5565b6103cd6104473660046145b4565b610a1b565b60405160ff7f000000000000000000000000000000000000000000000000000000000000001216815260200161034a565b6103cd610b3f565b6103aa61049336600461458a565b610b4e565b6104a0610b8d565b005b600c54610336906001600160a01b031681565b6104a0610bdf565b6103cd6104cb3660046145b4565b610c7d565b600a5460ff166103aa565b7f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2610336565b6103cd61050f366004614609565b6001600160a01b031660009081526020819052604090205490565b7f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e610336565b6103cd61055e366004614609565b610cb8565b6103cd610571366004614609565b600e6020526000908152604090205481565b6104a0610cd6565b610593610d26565b60405161034a9796959493929190614624565b6103cd6105b436600461458a565b610dcb565b6104a06105c73660046146d6565b61122c565b6103367f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d81565b6103cd6106013660046145cd565b611365565b61035b611737565b6103aa61061c36600461458a565b6117a1565b6103aa61062f36600461458a565b61185b565b6103cd610642366004614709565b611869565b6103cd610655366004614709565b611a8a565b6103cd610668366004614609565b611c98565b7f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148610336565b6104a06106a1366004614745565b611cec565b6103cd6106b4366004614609565b611e50565b6103cd6106c73660046146d6565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b6103cd610700366004614609565b600f6020526000908152604090205481565b6103cd611eca565b610722612227565b60405161034a91906147b8565b6104a061073d366004614609565b6123ef565b6104a06107503660046145cd565b6124b1565b6103cd610763366004614609565b6127d6565b606060006107957f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148612909565b9050806107c17f000000000000000000000000000000000000000000000000000000006772435561294b565b6040516020016107d292919061483e565b60405160208183030381529060405291505090565b604080518082019091526000808252602082015260095460020361081e5760405163588d6e8d60e11b815260040160405180910390fd5b5060408051808201909152600b546001600160801b038082168352600160801b9091041660208201525b90565b60003361085981858561298f565b60019150505b92915050565b60007f000000000000000000000000000000000000000000000000000000006772435542101561089757506000919050565b61085f82610a1b565b60006108ae60095460021490565b156108cc5760405163588d6e8d60e11b815260040160405180910390fd5b604080518082018252600b546001600160801b038082168352600160801b909104166020808301919091528251637a8f0c0d60e11b815292519192600092610988926001600160a01b037f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148169263f51e181a92600480830193928290030181865afa15801561095f573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061098391906148bf565b612ae7565b82519091506001600160801b03166000036109c9576001600160801b03808216808452602084015190911610156109c9576001600160801b03811660208301525b60006109d58386612b6a565b90506109ea816001600160801b038416612b8c565b93505050505b919050565b600033610a03858285612ba1565b610a0e858585612c33565b60019150505b9392505050565b6000610a2960095460021490565b15610a475760405163588d6e8d60e11b815260040160405180910390fd5b604080518082018252600b546001600160801b038082168352600160801b909104166020808301919091528251637a8f0c0d60e11b815292519192600092610ada926001600160a01b037f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148169263f51e181a92600480830193928290030181865afa15801561095f573d6000803e3d6000fd5b82519091506001600160801b0316600003610b1b576001600160801b0380821680845260208401519091161015610b1b576001600160801b03811660208301525b610b3782610b32866001600160801b038516612e20565b612e35565b949350505050565b6000610b49612e57565b905090565b3360008181526001602090815260408083206001600160a01b03871684529091528120549091906108599082908690610b889087906148ee565b61298f565b336001600160a01b037f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d1614610bd5576040516282b42960e81b815260040160405180910390fd5b610bdd612f82565b565b336001600160a01b037f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d1614610c27576040516282b42960e81b815260040160405180910390fd5b60006001600d54610c389190614901565b6001600d55600c54909150610c7a906001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc28116911683612fd4565b50565b60007f0000000000000000000000000000000000000000000000000000000067724355421015610caf57506000919050565b61085f826108a0565b6001600160a01b03811660009081526007602052604081205461085f565b336001600160a01b037f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d1614610d1e576040516282b42960e81b815260040160405180910390fd5b610bdd61307d565b600060608082808083610d5a7f4e6170696572205072696e636970616c20546f6b656e0000000000000000001660056130ba565b610d857f310000000000000000000000000000000000000000000000000000000000000160066130ba565b604080516000808252602082019092527f0f000000000000000000000000000000000000000000000000000000000000009b939a50919850469750309650945092509050565b6000610dd5613165565b610ddd6131be565b7f00000000000000000000000000000000000000000000000000000000677243554210610e36576040517fa55598b400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b038381166000908152600e6020908152604080832054600b548251637a8f0c0d60e11b815292519195600160801b9091046001600160801b031694937f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1489091169263f51e181a92600480830193928290030181865afa158015610ec4573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ee891906148bf565b905081811115610f1c57809150610efe81612ae7565b600b80546001600160801b03928316600160801b0292169190911790555b6000610f4b867f000000000000000000000000000000000000000000000000000000000000001e612710613211565b6001600160a01b0388166000908152600e60205260408120859055600d80549293508392909190610f7d9084906148ee565b90915550508315611053576040516370a0823160e01b81526001600160a01b0388811660048301526000917f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e909116906370a0823190602401602060405180830381865afa158015610ff3573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061101791906148bf565b9050611024848683613237565b6001600160a01b0389166000908152600f60205260408120805490919061104c9084906148ee565b9091555050505b6110886001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc21633308961327a565b60006001600160a01b037f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1481663b6b55f256110c3848a614901565b6040518263ffffffff1660e01b81526004016110e191815260200190565b6020604051808303816000875af1158015611100573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061112491906148bf565b90506111308185612b8c565b955061113c88876132cb565b6040517f40c10f190000000000000000000000000000000000000000000000000000000081526001600160a01b038981166004830152602482018890527f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e16906340c10f1990604401600060405180830381600087803b1580156111bf57600080fd5b505af11580156111d3573d6000803e3d6000fd5b505060408051898152602081018590526001600160a01b038c1693503392507fca1340aac4caf2122faa48803f9cafe2fca0c643e9c0cc5e876d0f7c436b7ab2910160405180910390a3505050505061085f6001600955565b336001600160a01b037f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d1614611274576040516282b42960e81b815260040160405180910390fd5b7f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1486001600160a01b0316826001600160a01b0316036112df576040517f093e1cdb00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6040516370a0823160e01b81523060048201526000906001600160a01b038416906370a0823190602401602060405180830381865afa158015611326573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061134a91906148bf565b90506113606001600160a01b0384168383612fd4565b505050565b600061136f613165565b6001600160a01b0384166000908152600e6020908152604080832054600f90925282205490918290036113b55760405163647cb25160e11b815260040160405180910390fd5b60408051808201909152600b546001600160801b038082168352600160801b9091041660208201526113e68161338b565b506040516370a0823160e01b81526001600160a01b0388811660048301526000917f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e909116906370a0823190602401602060405180830381865afa158015611452573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061147691906148bf565b905061149082602001516001600160801b03168583613237565b61149a90846148ee565b925060006114be83602001516001600160801b031688612e2090919063ffffffff16565b602080850180516001600160a01b038d166000908152600e909352604083206001600160801b039182169055865191518116600160801b02911617600b559091508261150a898761492a565b6115149190614957565b90506115208186614901565b6001600160a01b038b166000908152600f60205260409020556115438a89613497565b6040517fec60bcf30000000000000000000000000000000000000000000000000000000081526001600160a01b038b81166004830152336024830152604482018a90527f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e169063ec60bcf390606401600060405180830381600087803b1580156115cc57600080fd5b505af11580156115e0573d6000803e3d6000fd5b505050506116457f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148828461161491906148ee565b6001600160a01b037f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148169190612fd4565b6040516330733b3360e21b81526001600160a01b038a811660048301526000917f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1489091169063c1cceccc9060240160408051808303816000875af11580156116b1573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116d5919061496b565b509050896001600160a01b03168b6001600160a01b03167ff3d921cd57d5d4836e9a32ae95e25d8cded74cc5dce6dd08b4fb87283c50d2e48360405161171d91815260200190565b60405180910390a39650505050505050610a146001600955565b606060006117647f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1486134bc565b9050806117907f000000000000000000000000000000000000000000000000000000006772435561294b565b6040516020016107d292919061498f565b3360008181526001602090815260408083206001600160a01b0387168452909152812054909190838110156118435760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f7760448201527f207a65726f00000000000000000000000000000000000000000000000000000060648201526084015b60405180910390fd5b611850828686840361298f565b506001949350505050565b600033610859818585612c33565b6000611873613165565b7f00000000000000000000000000000000000000000000000000000000677243554210156118cd576040517f0d0ad5f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60408051808201909152600b546001600160801b038082168352600160801b90910416602082015260006119008261338b565b9050600061190e8783612e20565b9050600061191c8483612e35565b845160208601516001600160801b03908116600160801b02911617600b5590506119468682613497565b61199a6001600160a01b037f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148167f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c14884612fd4565b6040516330733b3360e21b81526001600160a01b0388811660048301526000917f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1489091169063c1cceccc9060240160408051808303816000875af1158015611a06573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611a2a919061496b565b509050876001600160a01b0316876001600160a01b03167fd12200efa34901b99367694174c3b0d32c99585fdf37c7c26892136ddd0836d983604051611a7291815260200190565b60405180910390a3509350505050610a146001600955565b6000611a94613165565b7f0000000000000000000000000000000000000000000000000000000067724355421015611aee576040517f0d0ad5f400000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b60408051808201909152600b546001600160801b038082168352600160801b909104166020820152611b1f8161338b565b506000611b2c8287612b6a565b825160208401516001600160801b03908116600160801b02911617600b559050611b568487613497565b611baa6001600160a01b037f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148167f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c14883612fd4565b6040516330733b3360e21b81526001600160a01b0386811660048301526000917f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1489091169063c1cceccc9060240160408051808303816000875af1158015611c16573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611c3a919061496b565b509050856001600160a01b0316856001600160a01b03167fd12200efa34901b99367694174c3b0d32c99585fdf37c7c26892136ddd0836d983604051611c8291815260200190565b60405180910390a392505050610a146001600955565b60007f0000000000000000000000000000000000000000000000000000000067724355421015611cca57506000919050565b61085f6103fa836001600160a01b031660009081526020819052604090205490565b83421115611d3c5760405162461bcd60e51b815260206004820152601d60248201527f45524332305065726d69743a206578706972656420646561646c696e65000000604482015260640161183a565b60007f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9888888611d6b8c6134ea565b6040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810186905260e0016040516020818303038152906040528051906020012090506000611dc682613512565b90506000611dd68287878761355a565b9050896001600160a01b0316816001600160a01b031614611e395760405162461bcd60e51b815260206004820152601e60248201527f45524332305065726d69743a20696e76616c6964207369676e61747572650000604482015260640161183a565b611e448a8a8a61298f565b50505050505050505050565b6000611e5e60095460021490565b15611e7c5760405163588d6e8d60e11b815260040160405180910390fd5b7f0000000000000000000000000000000000000000000000000000000067724355421015611eac57506000919050565b6001600160a01b03821660009081526020819052604090205461085f565b6000611ed4613165565b611edc6131be565b336000908152600e6020908152604080832054600f9092528220549091829003611f195760405163647cb25160e11b815260040160405180910390fd5b60408051808201909152600b546001600160801b038082168352600160801b909104166020820152611f4a8161338b565b506040516370a0823160e01b81523360048201526000907f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e6001600160a01b0316906370a0823190602401602060405180830381865afa158015611fb2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fd691906148bf565b9050611ff082602001516001600160801b03168583613237565b611ffa90846148ee565b60208084018051336000908152600e845260408082206001600160801b039384169055600f90945292832092909255845190518216600160801b02911617600b5592507f000000000000000000000000000000000000000000000000000000006772435542106120fe576040517f9dc29fac000000000000000000000000000000000000000000000000000000008152336004820152602481018290527f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e6001600160a01b031690639dc29fac90604401600060405180830381600087803b1580156120e557600080fd5b505af11580156120f9573d6000803e3d6000fd5b505050505b6121526001600160a01b037f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148167f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c14885612fd4565b6040516330733b3360e21b81523360048201526000907f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1486001600160a01b03169063c1cceccc9060240160408051808303816000875af11580156121ba573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906121de919061496b565b5060405185815290915033907f4256a058fa2b123d727576d3d31e3a272db98ee5fe264e229610ce43dc8499999060200160405180910390a29450505050506108486001600955565b6040805161010081018252600080825260208201819052918101829052606081018290526080810182905260a0810182905260c0810182905260e081019190915260095460020361228b5760405163588d6e8d60e11b815260040160405180910390fd5b604080518082018252600b546001600160801b038082168352600160801b909104811660208084019182528451610100810186526001600160a01b037f000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2811682527f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1488116928201929092527f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e8216958101959095527f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c148166060850152825182166080850152511660a08301529060c081016123a57f000000000000000000000000000000000000000000000000000000000000001e613582565b67ffffffffffffffff1681526020016123dd7f0000000000000000000000000000000000000000000000000000000067724355613582565b67ffffffffffffffff16905291505090565b336001600160a01b037f0000000000000000000000006e2e673a0b1d334c9caa0e2d50a10dab3736bd9d1614612437576040516282b42960e81b815260040160405180910390fd5b6001600160a01b038116612477576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b600c80547fffffffffffffffffffffffff0000000000000000000000000000000000000000166001600160a01b0392909216919091179055565b6124b9613165565b6124c16131be565b336001600160a01b037f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e1614612523576040517fb114ba9800000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6001600160a01b038316158061254057506001600160a01b038216155b15612577576040517fd92e233d00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b80156127cc57604080518082018252600b546001600160801b038082168352600160801b909104166020808301919091526001600160a01b0386166000908152600e9091529182205490918190036125e25760405163647cb25160e11b815260040160405180910390fd5b6125eb8261338b565b5060208201516040516370a0823160e01b81526001600160a01b038781166004830152612691926001600160801b03169184917f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e16906370a08231906024015b602060405180830381865afa158015612668573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061268c91906148bf565b613237565b6001600160a01b0386166000908152600f6020526040812080549091906126b99084906148ee565b90915550506020808301516001600160a01b038088166000908152600e90935260408084206001600160801b0390931690925586168252902054801561278a5760208301516040516370a0823160e01b81526001600160a01b03878116600483015261275c926001600160801b03169184917f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e16906370a082319060240161264b565b6001600160a01b0386166000908152600f6020526040812080549091906127849084906148ee565b90915550505b5050602080820180516001600160a01b0386166000908152600e90935260409092206001600160801b039283169055915191518116600160801b02911617600b555b6113606001600955565b6001600160a01b0381166000908152600e6020908152604080832054600f90925282205481830361280b575060009392505050565b60408051808201909152600b546001600160801b038082168352600160801b909104166020820152600061283e8261338b565b6040516370a0823160e01b81526001600160a01b0388811660048301529192506000917f000000000000000000000000a754393650a7cce57a1025d370885a3d0eb7d88e16906370a0823190602401602060405180830381865afa1580156128aa573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906128ce91906148bf565b90506128e883602001516001600160801b03168683613237565b6128f290856148ee565b93506128fe8483612b8c565b979650505050505050565b60606000612937837f06fdde0300000000000000000000000000000000000000000000000000000000613602565b9050805160000361085f57610a148361375b565b6060600080600061295b85613766565b92509250925082828260405160200161297693929190614a10565b6040516020818303038152906040529350505050919050565b6001600160a01b038316612a0a5760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f2061646460448201527f7265737300000000000000000000000000000000000000000000000000000000606482015260840161183a565b6001600160a01b038216612a865760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f20616464726560448201527f7373000000000000000000000000000000000000000000000000000000000000606482015260840161183a565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925910160405180910390a3505050565b60006001600160801b03821115612b665760405162461bcd60e51b815260206004820152602760248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203160448201527f3238206269747300000000000000000000000000000000000000000000000000606482015260840161183a565b5090565b6000610a1483602001516001600160801b031683612e2090919063ffffffff16565b6000610a148383670de0b6b3a76400006137a9565b6001600160a01b038381166000908152600160209081526040808320938616835292905220546000198114612c2d5781811015612c205760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e6365000000604482015260640161183a565b612c2d848484840361298f565b50505050565b6001600160a01b038316612caf5760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f20616460448201527f6472657373000000000000000000000000000000000000000000000000000000606482015260840161183a565b6001600160a01b038216612d2b5760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201527f6573730000000000000000000000000000000000000000000000000000000000606482015260840161183a565b6001600160a01b03831660009081526020819052604090205481811015612dba5760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e742065786365656473206260448201527f616c616e63650000000000000000000000000000000000000000000000000000606482015260840161183a565b6001600160a01b03848116600081815260208181526040808320878703905593871680835291849020805487019055925185815290927fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3612c2d565b6000610a1483670de0b6b3a7640000846137a9565b6000610a1483602001516001600160801b0316836137c790919063ffffffff16565b6000306001600160a01b037f00000000000000000000000000041a81e413e4c02f26561c890f2b863a5fb06a16148015612eb057507f000000000000000000000000000000000000000000000000000000000000000146145b15612eda57507fff52cccba99c39bbbd301915cdfa8d7abf734b1dc95d59ac6e3002d38b37b46790565b610b49604080517f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f60208201527fbaafafe8a9d41290867f49361cc814b25bf07089ebe68fa3f203fa7ce15b98e3918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc660608201524660808201523060a082015260009060c00160405160208183030381529060405280519060200120905090565b612f8a6137dc565b600a805460ff191690557f5db9ee0a495bf2e6ff9c91a7834c1ba4fdd244a5e8aa4e537bd38aeae4b073aa335b6040516001600160a01b03909116815260200160405180910390a1565b6040516001600160a01b0383166024820152604481018290526113609084907fa9059cbb00000000000000000000000000000000000000000000000000000000906064015b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff000000000000000000000000000000000000000000000000000000009093169290921790915261382e565b6130856131be565b600a805460ff191660011790557f62e78cea01bee320cd4e420270b5ea74000d11b0c9f74754ebdbfc544b05a258612fb73390565b606060ff83146130d4576130cd83613916565b905061085f565b8180546130e090614a86565b80601f016020809104026020016040519081016040528092919081815260200182805461310c90614a86565b80156131595780601f1061312e57610100808354040283529160200191613159565b820191906000526020600020905b81548152906001019060200180831161313c57829003601f168201915b5050505050905061085f565b6002600954036131b75760405162461bcd60e51b815260206004820152601f60248201527f5265656e7472616e637947756172643a207265656e7472616e742063616c6c00604482015260640161183a565b6002600955565b600a5460ff1615610bdd5760405162461bcd60e51b815260206004820152601060248201527f5061757361626c653a2070617573656400000000000000000000000000000000604482015260640161183a565b600082600019048411830215820261322857600080fd5b50910281810615159190040190565b6000806132448386613955565b905060006132528486612e20565b905081811161326657600092505050610a14565b6132708282614901565b9695505050505050565b6040516001600160a01b0380851660248301528316604482015260648101829052612c2d9085907f23b872dd0000000000000000000000000000000000000000000000000000000090608401613019565b6001600160a01b0382166133215760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f206164647265737300604482015260640161183a565b806002600082825461333391906148ee565b90915550506001600160a01b038216600081815260208181526040808320805486019055518481527fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a35b5050565b6000807f000000000000000000000000af5feb6d44602ebebe0f3c44dc3bc24a8714c1486001600160a01b031663f51e181a6040518163ffffffff1660e01b8152600401602060405180830381865afa1580156133ec573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061341091906148bf565b83519091506001600160801b0316156134295792915050565b7f000000000000000000000000000000000000000000000000000000006772435542106134655761345981612ae7565b6001600160801b031683525b82602001516001600160801b031681111561085f5761348381612ae7565b6001600160801b0316602084015292915050565b6001600160a01b03821633146134b2576134b2823383612ba1565b613387828261396a565b60606000612937837f95d89b4100000000000000000000000000000000000000000000000000000000613602565b6001600160a01b03811660009081526007602052604090208054600181018255905b50919050565b600061085f61351f612e57565b836040517f19010000000000000000000000000000000000000000000000000000000000008152600281019290925260228201526042902090565b600080600061356b87878787613ad3565b9150915061357881613b97565b5095945050505050565b600067ffffffffffffffff821115612b665760405162461bcd60e51b815260206004820152602660248201527f53616665436173743a2076616c756520646f65736e27742066697420696e203660448201527f3420626974730000000000000000000000000000000000000000000000000000606482015260840161183a565b60408051600481526024810182526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff167fffffffff000000000000000000000000000000000000000000000000000000008516179052905160609160009182916001600160a01b038716916136799190614aba565b600060405180830381855afa9150503d80600081146136b4576040519150601f19603f3d011682016040523d82523d6000602084013e6136b9565b606091505b50915091508115806136ca57508051155b156136e857604051806020016040528060008152509250505061085f565b805160200361371c5760008180602001905181019061370791906148bf565b905061371281613cfc565b935050505061085f565b604081511115613743578080602001905181019061373a9190614ad6565b9250505061085f565b50506040805160208101909152600081529392505050565b606061085f82613e70565b6060806060600080600061377987613e86565b92509250925061378881613eac565b955061379382613eac565b945061379e83613eac565b959794965050505050565b60008260001904841183021582026137c057600080fd5b5091020490565b6000610a148383670de0b6b3a7640000613211565b600a5460ff16610bdd5760405162461bcd60e51b815260206004820152601460248201527f5061757361626c653a206e6f7420706175736564000000000000000000000000604482015260640161183a565b6000613883826040518060400160405280602081526020017f5361666545524332303a206c6f772d6c6576656c2063616c6c206661696c6564815250856001600160a01b0316613feb9092919063ffffffff16565b90508051600014806138a45750808060200190518101906138a49190614b78565b6113605760405162461bcd60e51b815260206004820152602a60248201527f5361666545524332303a204552433230206f7065726174696f6e20646964206e60448201527f6f74207375636365656400000000000000000000000000000000000000000000606482015260840161183a565b6060600061392383613ffa565b604080516020808252818301909252919250600091906020820181803683375050509182525060208101929092525090565b6000610a1483670de0b6b3a764000084613211565b6001600160a01b0382166139e65760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f2061646472657360448201527f7300000000000000000000000000000000000000000000000000000000000000606482015260840161183a565b6001600160a01b03821660009081526020819052604090205481811015613a755760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e60448201527f6365000000000000000000000000000000000000000000000000000000000000606482015260840161183a565b6001600160a01b0383166000818152602081815260408083208686039055600280548790039055518581529192917fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef910160405180910390a3505050565b6000807f7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0831115613b0a5750600090506003613b8e565b6040805160008082526020820180845289905260ff881692820192909252606081018690526080810185905260019060a0016020604051602081039080840390855afa158015613b5e573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116613b8757600060019250925050613b8e565b9150600090505b94509492505050565b6000816004811115613bab57613bab614b9a565b03613bb35750565b6001816004811115613bc757613bc7614b9a565b03613c145760405162461bcd60e51b815260206004820152601860248201527f45434453413a20696e76616c6964207369676e61747572650000000000000000604482015260640161183a565b6002816004811115613c2857613c28614b9a565b03613c755760405162461bcd60e51b815260206004820152601f60248201527f45434453413a20696e76616c6964207369676e6174757265206c656e67746800604482015260640161183a565b6003816004811115613c8957613c89614b9a565b03610c7a5760405162461bcd60e51b815260206004820152602260248201527f45434453413a20696e76616c6964207369676e6174757265202773272076616c60448201527f7565000000000000000000000000000000000000000000000000000000000000606482015260840161183a565b604080516020808252818301909252606091600091906020820181803683370190505090506000805b6020811015613dbb576000858260208110613d4257613d42614bb0565b1a60f81b90507fff00000000000000000000000000000000000000000000000000000000000000811615613da85780848481518110613d8357613d83614bb0565b60200101906001600160f81b031916908160001a90535082613da481614bc6565b9350505b5080613db381614bc6565b915050613d25565b5060008167ffffffffffffffff811115613dd757613dd7614914565b6040519080825280601f01601f191660200182016040528015613e01576020820181803683370190505b50905060005b82811015613e6757838181518110613e2157613e21614bb0565b602001015160f81c60f81b828281518110613e3e57613e3e614bb0565b60200101906001600160f81b031916908160001a90535080613e5f81614bc6565b915050613e07565b50949350505050565b606061085f6001600160a01b038316601461403b565b60008080613e9f613e9a6201518086614957565b61421c565b9196909550909350915050565b606081600003613eef57505060408051808201909152600181527f3000000000000000000000000000000000000000000000000000000000000000602082015290565b8160005b8115613f195780613f0381614bc6565b9150613f129050600a83614957565b9150613ef3565b60008167ffffffffffffffff811115613f3457613f34614914565b6040519080825280601f01601f191660200182016040528015613f5e576020820181803683370190505b509050815b8515613e6757613f74600182614901565b90506000613f83600a88614957565b613f8e90600a61492a565b613f989088614901565b613fa3906030614be0565b905060008160f81b905080848481518110613fc057613fc0614bb0565b60200101906001600160f81b031916908160001a905350613fe2600a89614957565b97505050613f63565b6060610b378484600085614390565b600060ff8216601f81111561085f576040517fb3512b0c00000000000000000000000000000000000000000000000000000000815260040160405180910390fd5b6060600061404a83600261492a565b6140559060026148ee565b67ffffffffffffffff81111561406d5761406d614914565b6040519080825280601f01601f191660200182016040528015614097576020820181803683370190505b5090507f3000000000000000000000000000000000000000000000000000000000000000816000815181106140ce576140ce614bb0565b60200101906001600160f81b031916908160001a9053507f78000000000000000000000000000000000000000000000000000000000000008160018151811061411957614119614bb0565b60200101906001600160f81b031916908160001a905350600061413d84600261492a565b6141489060016148ee565b90505b60018111156141cd577f303132333435363738396162636465660000000000000000000000000000000085600f166010811061418957614189614bb0565b1a60f81b82828151811061419f5761419f614bb0565b60200101906001600160f81b031916908160001a90535060049490941c936141c681614bf9565b905061414b565b508315610a145760405162461bcd60e51b815260206004820181905260248201527f537472696e67733a20686578206c656e67746820696e73756666696369656e74604482015260640161183a565b60008080838162253d8c6142338362010bd9614c10565b61423d9190614c10565b9050600062023ab1614250836004614c38565b61425a9190614c84565b9050600461426b8262023ab1614c38565b614276906003614c10565b6142809190614c84565b61428a9083614cce565b9150600062164b0961429d846001614c10565b6142a990610fa0614c38565b6142b39190614c84565b905060046142c3826105b5614c38565b6142cd9190614c84565b6142d79084614cce565b6142e290601f614c10565b9250600061098f6142f4856050614c38565b6142fe9190614c84565b9050600060506143108361098f614c38565b61431a9190614c84565b6143249086614cce565b9050614331600b83614c84565b945061433e85600c614c38565b614349836002614c10565b6143539190614cce565b91508483614362603187614cce565b61436d906064614c38565b6143779190614c10565b6143819190614c10565b9a919950975095505050505050565b6060824710156144085760405162461bcd60e51b815260206004820152602660248201527f416464726573733a20696e73756666696369656e742062616c616e636520666f60448201527f722063616c6c0000000000000000000000000000000000000000000000000000606482015260840161183a565b600080866001600160a01b031685876040516144249190614aba565b60006040518083038185875af1925050503d8060008114614461576040519150601f19603f3d011682016040523d82523d6000602084013e614466565b606091505b50915091506128fe87838387606083156144e15782516000036144da576001600160a01b0385163b6144da5760405162461bcd60e51b815260206004820152601d60248201527f416464726573733a2063616c6c20746f206e6f6e2d636f6e7472616374000000604482015260640161183a565b5081610b37565b610b3783838151156144f65781518083602001fd5b8060405162461bcd60e51b815260040161183a9190614560565b60005b8381101561452b578181015183820152602001614513565b50506000910152565b6000815180845261454c816020860160208601614510565b601f01601f19169290920160200192915050565b602081526000610a146020830184614534565b80356001600160a01b03811681146109f057600080fd5b6000806040838503121561459d57600080fd5b6145a683614573565b946020939093013593505050565b6000602082840312156145c657600080fd5b5035919050565b6000806000606084860312156145e257600080fd5b6145eb84614573565b92506145f960208501614573565b9150604084013590509250925092565b60006020828403121561461b57600080fd5b610a1482614573565b7fff00000000000000000000000000000000000000000000000000000000000000881681526000602060e08184015261466060e084018a614534565b8381036040850152614672818a614534565b606085018990526001600160a01b038816608086015260a0850187905284810360c0860152855180825283870192509083019060005b818110156146c4578351835292840192918401916001016146a8565b50909c9b505050505050505050505050565b600080604083850312156146e957600080fd5b6146f283614573565b915061470060208401614573565b90509250929050565b60008060006060848603121561471e57600080fd5b8335925061472e60208501614573565b915061473c60408501614573565b90509250925092565b600080600080600080600060e0888a03121561476057600080fd5b61476988614573565b965061477760208901614573565b95506040880135945060608801359350608088013560ff8116811461479b57600080fd5b9699959850939692959460a0840135945060c09093013592915050565b6000610100820190506001600160a01b03808451168352806020850151166020840152806040850151166040840152806060850151166060840152506080830151608083015260a083015160a083015267ffffffffffffffff60c08401511660c083015260e083015161483760e084018267ffffffffffffffff169052565b5092915050565b7f4e6170696572205072696e636970616c20546f6b656e20000000000000000000815260008351614876816017850160208801614510565b7f400000000000000000000000000000000000000000000000000000000000000060179184019182015283516148b3816018840160208801614510565b01601801949350505050565b6000602082840312156148d157600080fd5b5051919050565b634e487b7160e01b600052601160045260246000fd5b8082018082111561085f5761085f6148d8565b8181038181111561085f5761085f6148d8565b634e487b7160e01b600052604160045260246000fd5b808202811582820484141761085f5761085f6148d8565b634e487b7160e01b600052601260045260246000fd5b60008261496657614966614941565b500490565b6000806040838503121561497e57600080fd5b505080516020909101519092909150565b7f50542d00000000000000000000000000000000000000000000000000000000008152600083516149c7816003850160208801614510565b7f40000000000000000000000000000000000000000000000000000000000000006003918401918201528351614a04816004840160208801614510565b01600401949350505050565b60008451614a22818460208901614510565b80830190507f2d000000000000000000000000000000000000000000000000000000000000008082528551614a5e816001850160208a01614510565b60019201918201528351614a79816002840160208801614510565b0160020195945050505050565b600181811c90821680614a9a57607f821691505b60208210810361350c57634e487b7160e01b600052602260045260246000fd5b60008251614acc818460208701614510565b9190910192915050565b600060208284031215614ae857600080fd5b815167ffffffffffffffff80821115614b0057600080fd5b818401915084601f830112614b1457600080fd5b815181811115614b2657614b26614914565b604051601f8201601f19908116603f01168101908382118183101715614b4e57614b4e614914565b81604052828152876020848701011115614b6757600080fd5b6128fe836020830160208801614510565b600060208284031215614b8a57600080fd5b81518015158114610a1457600080fd5b634e487b7160e01b600052602160045260246000fd5b634e487b7160e01b600052603260045260246000fd5b60006000198203614bd957614bd96148d8565b5060010190565b60ff818116838216019081111561085f5761085f6148d8565b600081614c0857614c086148d8565b506000190190565b8082018281126000831280158216821582161715614c3057614c306148d8565b505092915050565b808202600082127f800000000000000000000000000000000000000000000000000000000000000084141615614c7057614c706148d8565b818105831482151761085f5761085f6148d8565b600082614c9357614c93614941565b60001983147f800000000000000000000000000000000000000000000000000000000000000083141615614cc957614cc96148d8565b500590565b8181036000831280158383131683831282161715614837576148376148d856fea164736f6c6343000813000a
Verified Source Code Partial Match
Compiler: v0.8.19+commit.7dd6d404
EVM: paris
Optimization: Yes (2000 runs)
Tranche.sol 679 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.19;
// interfaces
import {IERC20} from "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
import {IERC5095} from "./interfaces/IERC5095.sol";
import {ITranche} from "./interfaces/ITranche.sol";
import {IYieldToken} from "./interfaces/IYieldToken.sol";
import {ITrancheFactory} from "./interfaces/ITrancheFactory.sol";
import {IBaseAdapter} from "./interfaces/IBaseAdapter.sol";
// libs
import {Math} from "@openzeppelin/[email protected]/utils/math/Math.sol";
import {FixedPointMathLib} from "./utils/FixedPointMathLib.sol";
import {SafeCast} from "@openzeppelin/[email protected]/utils/math/SafeCast.sol";
import {SafeERC20Namer} from "./utils/SafeERC20Namer.sol";
import {SafeERC20} from "@openzeppelin/[email protected]/token/ERC20/utils/SafeERC20.sol";
import {MAX_BPS} from "./Constants.sol";
// inheriting
import {ERC20Permit, ERC20} from "@openzeppelin/[email protected]/token/ERC20/extensions/ERC20Permit.sol";
import {Pausable} from "@openzeppelin/[email protected]/security/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/[email protected]/security/ReentrancyGuard.sol";
import {BaseToken} from "./BaseToken.sol";
/// @title Tranche
/// @author Napier Labs
/// @author 0xbakuchi
/// @notice Tranche divides a yield-bearing token into two tokens: principal token and yield token.
/// This contract itself is a principal token.
/// Users can interact with this contract to issue, redeem tokens, and gather yield.
/// Both the Principal and Yield tokens share the same decimal notation as the underlying token.
/// Math:
/// - Yield Stripping Math paper: https://github.com/Napier-Lab/napier-v1/blob/main/assets/Yield_Stripping_Math__1_.pdf
/// - Hackmd: https://hackmd.io/W2mPhP7YRjGxqnAc93omLg?both
/// PT/YT and Target token conversion is defined as:
/// P = T * scale / 1e18
/// = T * price * 10^(18 + uDecimals - tDecimals) / 1e18
/// Where P is amount of PT and T is amount of Target.
/// @dev Supported Tokens:
/// - Underlying token can be rebased token.
/// - Underlying must not be ERC777 token.
/// - Target token can not be rebased token.
contract Tranche is BaseToken, ReentrancyGuard, Pausable, ITranche {
using SafeERC20 for IERC20;
using FixedPointMathLib for uint256;
using SafeCast for uint256;
uint8 internal immutable uDecimals;
/// @notice Represents the underlying token where users deposit (e.g. DAI)
IERC20 internal immutable _underlying;
/// @notice Represents the yield-bearing token (e.g. cDAI)
IERC20 internal immutable _target;
/// @notice Represents the Yield token that represents the right to claim the yield
IYieldToken internal immutable _yt;
/// @notice An adapter that interacts with the yield source (e.g. Compound)
IBaseAdapter public immutable adapter;
/// @notice Address of the management account
address public immutable management;
// Principal token Parameters
/// @inheritdoc IERC5095
/// @notice The timestamp of maturity in unix seconds
uint256 public immutable override(BaseToken, IERC5095) maturity;
/// @notice The fee for issuing new tokens (10000 = 100%)
uint256 internal immutable issuanceFeeBps;
//////////////////////////////////////////////////
// State Variables
//////////////////////////////////////////////////
/// @notice Variables tracking the yield-bearing token's scales
/// @dev This is used to calculate the claimable yield and is updated on every issue, collect, and redeemYT action.
/// - `mscale` represents the scale of the yield-bearing token at or after maturity,
/// it is set only at the time of users redeeming, redeemingYT and collecting at/after maturity.
/// - `maxscale` represents the maximum scale of the yield-bearing token since the Tranche's creation till now.
GlobalScales internal gscales;
/// @dev The address that receives the issuance fees. This address can be changed by the `management`.
address public feeRecipient;
/// @notice The total amount of fees collected by the protocol since the last claim.
/// @dev Every time a user issues PT and YT, the issuance fee is collected and added to this variable.
uint256 public protocolFees;
/// @notice Keeps track of the scale of the target token at the last user action.
/// @dev It is used for calculating the yield that can be claimed. It gets updated on every user action.
/// user -> lscale (last scale)
/// See "Yield Stripping Math" for more details.
mapping(address => uint256) public lscales;
/// @notice Keeps track of the yield not claimed by each user in units of the target token.
/// @dev This value is reset to 0 on every issue, collect and redeemYT action. Every YT transfer also increases this value.
mapping(address => uint256) public unclaimedYields;
/* ================== MODIFIERS =================== */
/// @notice Revert if timestamp is before maturity
modifier expired() {
if (block.timestamp < maturity) revert TimestampBeforeMaturity();
_;
}
/// @notice Revert if timestamp is at or after maturity
modifier notExpired() {
if (block.timestamp >= maturity) revert TimestampAfterMaturity();
_;
}
/// @notice Revert if reentrancy guard is already set to `entered`
modifier notEntered() {
if (_reentrancyGuardEntered()) revert ReentrancyGuarded();
_;
}
/// @notice Revert if msg sender is not management address
modifier onlyManagement() {
if (msg.sender != management) revert Unauthorized();
_;
}
/// @dev Assume Tranche is deployed from a factory.
/// Doesn't take constructor arguments directly so that CREATE2 address is independent of the constructor arguments.
/// The arguments are fetched through a callback to the factory.
/// @custom:param _args The arguments for the Tranche contract.
///
/// The constructor is `payable` to remove msg.value check and reduce about 198 gas cost at deployment time.
/// This is acceptable because the factory contract doesn't deploy Tranche with ETH.
constructor() payable ERC20("Napier Principal Token", "ePT") ERC20Permit("Napier Principal Token") {
// Retrieve constructor arguments from the factory
ITrancheFactory.TrancheInitArgs memory args = ITrancheFactory(msg.sender).args();
address underlying_ = IBaseAdapter(args.adapter).underlying();
address target_ = IBaseAdapter(args.adapter).target();
// Initialize immutable and state variables
feeRecipient = args.management;
management = args.management;
_underlying = IERC20(underlying_);
_target = IERC20(target_);
_yt = IYieldToken(args.yt);
adapter = IBaseAdapter(args.adapter);
issuanceFeeBps = args.issuanceFee;
maturity = args.maturity;
uDecimals = ERC20(underlying_).decimals();
// Set maxscale to the current scale
gscales.maxscale = IBaseAdapter(args.adapter).scale().toUint128();
IERC20(underlying_).forceApprove(args.adapter, type(uint256).max);
emit SeriesCreated(args.adapter, args.maturity, args.issuanceFee);
}
/* ================== MUTATIVE METHODS =================== */
/// @inheritdoc ITranche
/// @notice This function issues Principal Token (PT) and Yield Token (YT) to `to` in exchange for `underlyingAmount` of underlying token.
/// Issuance Fee is charged on the amount of underlying token used to issue PT and YT.
/// If `to` has accrued some yield, it will be added to the user's unclaimed yield and can be claimed later.
/// @dev The function will be reverted if the maturity has passed.
/// @param to The recipient of PT and YT
/// @param underlyingAmount The amount of underlying token to be deposited. (in units of underlying token)
/// @return issued The amount of PT and YT minted
function issue(
address to,
uint256 underlyingAmount
) external nonReentrant whenNotPaused notExpired returns (uint256 issued) {
uint256 _lscale = lscales[to];
uint256 _maxscale = gscales.maxscale;
// NOTE: Updating mscale/maxscale in the cache before the issue to determine the accrued yield.
uint256 cscale = adapter.scale();
if (cscale > _maxscale) {
// If the current scale is greater than the maxscale, update scales
_maxscale = cscale;
gscales.maxscale = cscale.toUint128();
}
// Deduct the issuance fee from the amount of underlying token deposited by the user
// Fee should be rounded up towards the protocol (against the user) so that issued principal is rounded down
// ```
// fee = u * feeBps
// shares = (u - fee) / s
// ptIssued = shares * S
// ```
// where u = underlyingAmount, s = current scale and S = maxscale
uint256 fee = underlyingAmount.mulDivUp(issuanceFeeBps, MAX_BPS);
// Updating user's last scale to the latest maxscale
lscales[to] = _maxscale;
protocolFees += fee;
// If recipient has unclaimed interest, add it to the user's unclaimed yield.
// Reminder: lscale is the last scale when the YT balance of the user was updated.
if (_lscale != 0) {
uint256 yBal = _yt.balanceOf(to);
unclaimedYields[to] += _computeAccruedInterestInTarget(_maxscale, _lscale, yBal);
}
_underlying.safeTransferFrom(msg.sender, address(this), underlyingAmount);
uint256 shares = adapter.deposit(underlyingAmount - fee);
// Compute the amount of PT and YT to be minted
// See above for the formula
issued = shares.mulWadDown(_maxscale);
// Mint PT and YT to user
_mint(to, issued);
_yt.mint(to, issued);
emit Issue(msg.sender, to, issued, shares);
}
/// @inheritdoc ITranche
/// @notice Withdraws underlying tokens from the caller in exchange for `amount` of PT and YT.
/// 1 PT + 1 YT = 1 Target token (e.g. 1 wstETH). This equation is always true
/// because PT represents the principal amount of the Target token and YT represents the yield of the Target token.
/// Basically, anyone can burn `x` PT and `x` YT to withdraw `x` Target tokens anytime.
///
/// Withdrawn amount will be the sum of the following:
/// - amount derived from PT + YT burn
/// - amount of unclaimed yield
/// - amount of accrued yield from the last time when the YT balance was updated to now
/// @notice If the caller is not `from`, `from` must have approved the caller to spend `pyAmount` for PT and YT prior to calling this function.
/// @dev Reverts if the caller does not have enough PT and YT.
/// @param from The owner of PT and YT.
/// @param to The recipient of the redeemed underlying tokens.
/// @param pyAmount The amount of principal token (and yield token) to redeem in units of underlying tokens.
/// @return (uint256) The amount of underlying tokens redeemed.
function redeemWithYT(address from, address to, uint256 pyAmount) external nonReentrant returns (uint256) {
uint256 _lscale = lscales[from];
uint256 accruedInTarget = unclaimedYields[from];
// Calculate the accrued interest in Target token
// The lscale should not be 0 because the user should have some YT balance
if (_lscale == 0) revert NoAccruedYield();
GlobalScales memory _gscales = gscales;
_updateGlobalScalesCache(_gscales);
uint256 ytBal = _yt.balanceOf(from);
// Compute the accrued yield from the time when the YT balance is updated last to now
// The accrued yield in units of target is computed as:
// Formula: yield = ytBalance * (1/lscale - 1/maxscale)
// Sum up the accrued yield, plus the unclaimed yield from the last time to now
accruedInTarget += _computeAccruedInterestInTarget(
_gscales.maxscale,
_lscale,
// Use yt balance instead of `pyAmount`
// because we'll update the user's lscale to the current maxscale after this line
// regardless of whether the user redeems all of their yt or not.
// Otherwise, the user will lose some accrued yield from the last time to now.
ytBal
);
// Compute shares equivalent to the amount of principal token to redeem
uint256 sharesRedeemed = pyAmount.divWadDown(_gscales.maxscale);
// Update the local scale and accrued yield of `from`
lscales[from] = _gscales.maxscale;
gscales = _gscales;
uint256 accruedProportional = (accruedInTarget * pyAmount) / ytBal;
unclaimedYields[from] = accruedInTarget - accruedProportional;
// Burn PT and YT tokens from `from`
_burnFrom(from, pyAmount);
_yt.burnFrom(from, msg.sender, pyAmount);
// Withdraw underlying tokens from the adapter and transfer them to the user
_target.safeTransfer(address(adapter), sharesRedeemed + accruedProportional);
(uint256 amountWithdrawn, ) = adapter.prefundedRedeem(to);
emit RedeemWithYT(from, to, amountWithdrawn);
return amountWithdrawn;
}
/// @inheritdoc IERC5095
/// @notice If the sender is not `from`, it must have approval from `from` to redeem `principalAmount` PT.
/// Redeems `principalAmount` PT from `from` and transfers underlying tokens to `to`.
/// @dev Reverts if maturity has not passed.
/// @param principalAmount The amount of principal tokens to redeem in units of underlying tokens.
/// @param to The recipient of the redeemed underlying tokens.
/// @param from The owner of the PT.
/// @return (uint256) The amount of underlying tokens redeemed.
function redeem(
uint256 principalAmount,
address to,
address from
) external override nonReentrant expired returns (uint256) {
GlobalScales memory _gscales = gscales;
_updateGlobalScalesCache(_gscales);
// Compute the shares to be redeemed
uint256 shares = _computeSharesRedeemed(_gscales, principalAmount);
gscales = _gscales;
// Burn PT tokens from `from`
_burnFrom(from, principalAmount);
// Withdraw underlying tokens from the adapter and transfer them to `to`
_target.safeTransfer(address(adapter), shares);
(uint256 underlyingWithdrawn, ) = adapter.prefundedRedeem(to);
emit Redeem(from, to, underlyingWithdrawn);
return underlyingWithdrawn;
}
/// @inheritdoc IERC5095
/// @notice If the sender is not `from`, it must have approval from `from` to redeem an equivalent amount of principal tokens.
/// Redeems PT equivalent to `underlyingAmount` underlying tokens from `from` and transfers underlying tokens to `to`.
/// @notice Note: The function doesn't comply with EIP-5095. `to` may receive an amount of underlying tokens not exactly equal to the input parameter `underlyingAmount`
/// @dev Reverts if maturity has not passed.
/// @param underlyingAmount The amount of underlying tokens to redeem in units of underlying tokens.
/// @param to The recipient of the redeemed underlying tokens.
/// @param from The owner of the PT.
/// @return (uint256) The amount of principal tokens redeemed.
function withdraw(
uint256 underlyingAmount,
address to,
address from
) external override nonReentrant expired returns (uint256) {
GlobalScales memory _gscales = gscales;
uint256 cscale = _updateGlobalScalesCache(_gscales);
// Compute the shares to be redeemed
uint256 sharesRedeem = underlyingAmount.divWadDown(cscale);
uint256 principalAmount = _computePrincipalTokenRedeemed(_gscales, sharesRedeem);
// Update the global scales
gscales = _gscales;
// Burn PT tokens from `from`
_burnFrom(from, principalAmount);
// Withdraw underlying tokens from the adapter and transfer them to `to`
_target.safeTransfer(address(adapter), sharesRedeem);
(uint256 underlyingWithdrawn, ) = adapter.prefundedRedeem(to);
emit Redeem(from, to, underlyingWithdrawn);
return principalAmount;
}
/// @notice Before transferring YT, update the accrued yield for the sender and receiver.
/// NOTE: Every YT transfer will trigger this function to track accrued yield for each user.
/// @dev This function is only callable by the Yield Token contract when the user transfers YT to another user.
/// NOTE: YT is not burned in this function even if the maturity has passed.
/// @param from The address to transfer the Yield Token from.
/// @param to The address to transfer the Yield Token to (CAN be the same as `from`).
/// NOTE: `from` and `to` SHOULD NOT be zero addresses.
/// @param value The amount of Yield Token transferred to `to` (CAN be 0).
function updateUnclaimedYield(address from, address to, uint256 value) external nonReentrant whenNotPaused {
if (msg.sender != address(_yt)) revert OnlyYT();
if (from == address(0) || to == address(0)) revert ZeroAddress();
if (value == 0) return;
GlobalScales memory _gscales = gscales;
uint256 _lscaleFrom = lscales[from];
// If the lscale is 0, it means the user have never hold any YT before
// because the lscale is always set to maxscale when the YT is transferrred or minted.
// This doesn't mean current YT balance is 0 because the user could have transferred all YT out or burned YT.
// Thus there is no accrued interest for the user.
if (_lscaleFrom == 0) revert NoAccruedYield();
_updateGlobalScalesCache(_gscales);
// Calculate the accrued interest in Target token for `from`
unclaimedYields[from] += _computeAccruedInterestInTarget(_gscales.maxscale, _lscaleFrom, _yt.balanceOf(from));
lscales[from] = _gscales.maxscale;
// Calculate the accrued interest in Target token for `to`. `from` and `to` can be equal.
uint256 _lscaleReceiver = lscales[to];
if (_lscaleReceiver != 0) {
unclaimedYields[to] +=
_computeAccruedInterestInTarget(_gscales.maxscale, _lscaleReceiver, _yt.balanceOf(to)); // prettier-ignore
}
lscales[to] = _gscales.maxscale;
// update global scales
gscales = _gscales;
}
/// @notice Collects yield for `msg.sender` and converts it to underlying token and transfers it to `msg.sender`.
/// NOTE: If the maturity has passed, YT will be burned.
/// The withdrwan amount of underlying token is the sum of the following:
/// - Amount of unclaimed yield
/// - Amount of accrued yield from the time when the YT balance was updated to now
/// @dev Anyone can call this function to collect yield for themselves.
/// @return The collected yield in underlying token.
function collect() public nonReentrant whenNotPaused returns (uint256) {
uint256 _lscale = lscales[msg.sender];
uint256 accruedInTarget = unclaimedYields[msg.sender];
if (_lscale == 0) revert NoAccruedYield();
GlobalScales memory _gscales = gscales;
_updateGlobalScalesCache(_gscales);
uint256 yBal = _yt.balanceOf(msg.sender);
accruedInTarget += _computeAccruedInterestInTarget(_gscales.maxscale, _lscale, yBal);
lscales[msg.sender] = _gscales.maxscale;
delete unclaimedYields[msg.sender];
gscales = _gscales;
// If matured, burn all the YT balance of the user
if (block.timestamp >= maturity) _yt.burn(msg.sender, yBal);
// Convert the accrued yield in Target token to underlying token and transfer it to the `msg.sender`
// Target token may revert if zero-amount transfer is not allowed.
_target.safeTransfer(address(adapter), accruedInTarget);
(uint256 accrued, ) = adapter.prefundedRedeem(msg.sender);
emit Collect(msg.sender, accruedInTarget);
return accrued;
}
function claimProtocolFees() external onlyManagement {
uint256 fees = protocolFees - 1;
protocolFees = 1;
_underlying.safeTransfer(feeRecipient, fees);
}
/* ================== VIEW METHODS =================== */
/// @inheritdoc ITranche
/// @dev This function is useful for off-chain services to get the accrued yield of a user.
/// @dev This function must not revert in any case.
function previewCollect(address account) external view returns (uint256) {
uint256 _lscale = lscales[account];
uint256 accruedInTarget = unclaimedYields[account];
// If the lscale is 0, it means the user have never hold any YT before
if (_lscale == 0) return 0;
GlobalScales memory _gscales = gscales;
uint256 cscale = _updateGlobalScalesCache(_gscales);
// At this point, the scales cache is up to date.
// Calculate the accrued yield in Target token for `account`
uint256 yBal = _yt.balanceOf(account);
accruedInTarget += _computeAccruedInterestInTarget(_gscales.maxscale, _lscale, yBal);
// Convert the accrued yield to underlying token
return accruedInTarget.mulWadDown(cscale);
}
/// @inheritdoc IERC5095
function maxRedeem(address owner) external view override notEntered returns (uint256) {
// Before maturity, PT can't be redeemed. Return 0.
if (block.timestamp < maturity) return 0;
return balanceOf(owner);
}
/// @inheritdoc IERC5095
function maxWithdraw(address owner) external view override returns (uint256 maxUnderlyingAmount) {
if (block.timestamp < maturity) return 0;
return convertToUnderlying(balanceOf(owner));
}
/// @inheritdoc IERC5095
function previewRedeem(uint256 principalAmount) external view override returns (uint256 underlyingAmount) {
if (block.timestamp < maturity) return 0;
return convertToUnderlying(principalAmount);
}
/// @inheritdoc IERC5095
function previewWithdraw(uint256 underlyingAmount) external view override returns (uint256 principalAmount) {
if (block.timestamp < maturity) return 0;
return convertToPrincipal(underlyingAmount);
}
/// @inheritdoc IERC5095
/// @dev Before maturity, the amount of underlying returned is as if the PTs would be at maturity.
function convertToUnderlying(
uint256 principalAmount
) public view override notEntered returns (uint256 underlyingAmount) {
GlobalScales memory _gscales = gscales; // Load gscales into memory
uint128 cscale = adapter.scale().toUint128();
if (_gscales.mscale == 0) {
// Simulate the settlement as if it is settled now
_gscales.mscale = cscale;
if (cscale > _gscales.maxscale) {
_gscales.maxscale = cscale;
}
}
uint256 shares = _computeSharesRedeemed(_gscales, principalAmount);
return shares.mulWadDown(cscale);
}
/// @inheritdoc IERC5095
/// @dev Before maturity, the amount of underlying returned is as if the PTs would be at maturity.
function convertToPrincipal(uint256 underlyingAmount) public view override notEntered returns (uint256) {
GlobalScales memory _gscales = gscales; // Load gscales into memory
uint128 cscale = adapter.scale().toUint128();
if (_gscales.mscale == 0) {
// Simulate the settlement as if it is settled now
_gscales.mscale = cscale;
if (cscale > _gscales.maxscale) {
_gscales.maxscale = cscale;
}
}
return _computePrincipalTokenRedeemed(_gscales, underlyingAmount.divWadDown(cscale));
}
/* ================== METADATA =================== */
/// @inheritdoc ITranche
/// @dev We return the address type instead of IERC20 to avoid additional dependencies for integrators.
function yieldToken() external view returns (address) {
return address(_yt);
}
/// @inheritdoc IERC5095
/// @dev We return the address type instead of IERC20 to avoid additional dependencies for integrators.
function underlying() external view returns (address) {
return address(_underlying);
}
/// @inheritdoc BaseToken
/// @dev We return the address type instead of IERC20 to avoid additional dependencies for integrators.
function target() external view override returns (address) {
return address(_target);
}
/// @inheritdoc ERC20
function name() public view override returns (string memory) {
string memory tokenName = SafeERC20Namer.tokenName(address(_target));
return string.concat("Napier Principal Token ", tokenName, "@", _toDateString(maturity));
}
/// @inheritdoc ERC20
function symbol() public view override returns (string memory) {
string memory tokenSymbol = SafeERC20Namer.tokenSymbol(address(_target));
return string.concat("PT-", tokenSymbol, "@", _toDateString(maturity));
}
/// @inheritdoc ERC20
function decimals() public view override returns (uint8) {
return uDecimals;
}
/// @notice get the global scales
function getGlobalScales() external view notEntered returns (GlobalScales memory) {
return gscales;
}
/// @inheritdoc ITranche
/// @notice This function is useful for off-chain services to get the series information.
function getSeries() external view notEntered returns (Series memory) {
GlobalScales memory _gscales = gscales;
return
Series({
underlying: address(_underlying),
target: address(_target),
yt: address(_yt),
adapter: address(adapter),
mscale: _gscales.mscale,
maxscale: _gscales.maxscale,
issuanceFee: issuanceFeeBps.toUint64(),
maturity: maturity.toUint64()
});
}
/* ================== PERMISSIONED METHODS =================== */
function setFeeRecipient(address _feeRecipient) external onlyManagement {
if (_feeRecipient == address(0)) revert ZeroAddress();
feeRecipient = _feeRecipient;
}
/// @notice Rescue a token from the contract. Usually used for tokens sent by a mistake.
/// @param token erc20 token
/// @param recipient recipient of the tokens
function recoverERC20(address token, address recipient) external onlyManagement {
if (token == address(_target)) revert ProtectedToken();
uint256 balance = IERC20(token).balanceOf(address(this));
IERC20(token).safeTransfer(recipient, balance);
}
/// @notice Pause issue, collect and updateUnclaimedYield
/// @dev only callable by management
function pause() external onlyManagement {
_pause();
}
/// @notice Unpause issue, collect and updateUnclaimedYield
/// @dev only callable by management
function unpause() external onlyManagement {
_unpause();
}
/* ================== INTERNAL METHODS =================== */
/* ================== UTIL METHODS =================== */
function _burnFrom(address owner, uint256 amount) internal {
if (owner != msg.sender) {
_spendAllowance(owner, msg.sender, amount);
}
_burn(owner, amount);
}
/// @notice Updates the global scales cache.
/// If the maturity has passed, updates the maturity scale `mscale` if it's not updated yet. (Settlement)
/// @return cscale The current scale of the adapter.
function _updateGlobalScalesCache(GlobalScales memory _cache) internal view returns (uint256) {
// Get the current scale of the adapter
uint256 cscale = adapter.scale();
if (_cache.mscale != 0) return cscale; // Skip if already settled
// If mscale == 0 and maturity has passed, settle the _cache.
if (block.timestamp >= maturity) {
_cache.mscale = cscale.toUint128();
}
// Update the _cache's maxscale
if (cscale > _cache.maxscale) {
_cache.maxscale = cscale.toUint128();
}
return cscale;
}
/// @notice Computes the amount of Target tokens to be redeemed for the given PT amount.
/// @dev This function is responsible for the logic of computing the amount of Target tokens to be redeemed.
/// @param _gscales Local cache of global scales.
/// @param _principalAmount PT amount to redeem in units of underlying tokens.
function _computeSharesRedeemed(
GlobalScales memory _gscales,
uint256 _principalAmount
) internal pure returns (uint256) {
// Formula: shares = principalAmount / maxscale
return _principalAmount.divWadDown(_gscales.maxscale);
}
/// @notice Computes the amount of PT to be redeemed for the given shares amount.
/// @param _gscales Local cache of global scales.
/// @param _shares Amount of Target tokens equivalent to the amount of PT to be redeemed (in units of Target tokens).
function _computePrincipalTokenRedeemed(
GlobalScales memory _gscales,
uint256 _shares
) internal pure returns (uint256) {
// Formula: principalAmount = shares * maxscale
return _shares.mulWadUp(_gscales.maxscale);
}
/// @notice Computes the amount of accrued interest in the Target.
/// e.g. if the Target scale increases by 5% since the last time the account collected and the account has 100 YT,
/// then the account will receive 100 * 5% = 5 Target as interest, which is equivalent to 5 * `maxscale` Underlying now.
/// @dev `_maxscale` should be updated before calling this function.
/// @param _maxscale The latest max scale of the series (assume non-zero).
/// @param _lscale The user-stored last scale (_lscale MUST be non-zero).
/// @param _yBal The user's current balance of Yield Token.
/// @return accruedInTarget The accrued interest in Target token. (rounded down)
function _computeAccruedInterestInTarget(
uint256 _maxscale,
uint256 _lscale,
uint256 _yBal
) internal pure returns (uint256) {
// Hackmd: F5, F7
// Compute how much underlying has accrued since the last time this user collected, in units of Target.
// The scale is the amount of underlying per Target. `underlying = shares * scale`.
// Hackmd: F6
// Reminder: _lscale is the scale of the last time the user collected their yield.
// If the scale (price) of Target has increased since then (_maxscale > _lscale), the user has accrued some interest.
// The balance of YT `_yBal` represents the underlying amount a user has deposited into the yield source at the last collection.
// At the last collection, `_yBal` underlying was worth `_yBal / _lscale` in units of Target.
// Now, `_yBal` underlying is worth `_yBal / effMaxscale` in units of Target.
// The difference is the amount of interest accrued in units of Target.
// NOTE: The `yBal / maxscale` should be rounded up, which lets the `accrued` value round up, i.e., toward the protocol (against a user).
// This is to prevent a user from withdrawing more shares than this contract has.
uint256 sharesNow = _yBal.divWadUp(_maxscale); // rounded up to prevent a user from withdrawing more shares than this contract has.
uint256 sharesDeposited = _yBal.divWadDown(_lscale);
if (sharesDeposited <= sharesNow) {
return 0;
}
return sharesDeposited - sharesNow; // rounded down
}
}
BaseToken.sol 19 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.19;
import {IBaseToken} from "./interfaces/IBaseToken.sol";
import {DateTime} from "./utils/DateTime.sol";
import {ERC20Permit} from "@openzeppelin/[email protected]/token/ERC20/extensions/ERC20Permit.sol";
abstract contract BaseToken is ERC20Permit, IBaseToken {
/// @inheritdoc IBaseToken
function maturity() external view virtual returns (uint256);
/// @inheritdoc IBaseToken
function target() external view virtual returns (address);
function _toDateString(uint256 _maturity) internal pure returns (string memory) {
(string memory d, string memory m, string memory y) = DateTime.toDateString(_maturity);
return string.concat(d, "-", m, "-", y);
}
}
Constants.sol 87 lines
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.19; uint256 constant WAD = 1e18; // @notice 100% in basis points. 10_000 = 100%s uint256 constant MAX_BPS = 10_000; /* =============== ADDRESSES ================ */ // @notice WETH address on mainnet address constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // @notice stETH address on mainnet address constant STETH = 0xae7ab96520DE3A18E5e111B5EaAb095312D7fE84; // @notice wstETH address on mainnet address constant WSTETH = 0x7f39C581F595B53c5cb19bD0b3f8dA6c935E2Ca0; // @notice WithdrawalQueueERC721 of LIDO address on mainnet address constant LIDO_WITHDRAWAL_QUEUE = 0x889edC2eDab5f40e902b864aD4d7AdE8E412F9B1; // @notice rETH address on mainnet address constant RETH = 0xae78736Cd615f374D3085123A210448E74Fc6393; // @notice eETH address on mainnet address constant EETH = 0x35fA164735182de50811E8e2E824cFb9B6118ac2; // @notice cETH address on mainnet address constant CETH = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; // @notice CDAI address on mainnet address constant CDAI = 0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643; // @notice DAI address on mainnet address constant DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // @notice COMPTROLLER address on mainnet address constant COMPTROLLER = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; // @notice COMP address on mainnet address constant COMP = 0xc00e94Cb662C3520282E6f5717214004A7f26888; // @notice AWETH address on mainnet address constant AWETH = 0x4d5F47FA6A74757f35C14fD3a6Ef8E3C9BC514E8; // @notice LendingAAVEV3_POOL_ADDRESSES_PROVIDER address on mainnet address constant AAVEV3_POOL_ADDRESSES_PROVIDER = 0x2f39d218133AFaB8F2B819B1066c7E434Ad94E9e; // @notice ma3WETH ERC 4626 Vault address on mainnet address constant MA3WETH = 0x39Dd7790e75C6F663731f7E1FdC0f35007D3879b; // @notice Morpho Aave v3 optimizer contract address on mainnet address constant MORPHO_AAVE_V3 = 0x33333aea097c193e66081E930c33020272b33333; // @notice MORPHO token address on mainnet address constant MORPHO = 0x9994E35Db50125E0DF82e4c2dde62496CE330999; // @notice Frax Ether address on mainnet address constant FRXETH = 0x5E8422345238F34275888049021821E8E08CAa1f; // @notice Staked Frax Ether address on mainnet address constant STAKED_FRXETH = 0xac3E018457B222d93114458476f3E3416Abbe38F; // @notice EtherFi LiquidityPool address constant ETHERFI_LP = 0x308861A430be4cce5502d0A12724771Fc6DaF216; // @notice EtherFi WETH address constant ETHERFI_WEETH = 0xCd5fE23C85820F7B72D0926FC9b05b43E359b7ee; // @notice EtherFi WithdrawRequestNFT address constant ETHERFI_WITHDRAW_REQUEST = 0x7d5706f6ef3F89B3951E23e557CDFBC3239D4E2c; // @notice BedRock uniETH address on mainnet address constant UNIETH = 0xF1376bceF0f78459C0Ed0ba5ddce976F1ddF51F4; // @notice BedRock Staking address on mainnet address constant BEDROCK_STAKING = 0x4beFa2aA9c305238AA3E0b5D17eB20C045269E9d; // @notice Inception inETH address on mainnet address constant INETH = 0xf073bAC22DAb7FaF4a3Dd6c6189a70D54110525C; // @notice Origin Protocol OETH address address constant OETH = 0x856c4Efb76C1D1AE02e20CEB03A2A6a08b0b8dC3; // @notice Origin Protocol Vault address address constant OETH_VAULT = 0x39254033945AA2E4809Cc2977E7087BEE48bd7Ab;
DateTime.sol 131 lines
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
// Taken from: https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
library DateTime {
uint256 constant SECONDS_PER_DAY = 24 * 60 * 60;
uint256 constant SECONDS_PER_HOUR = 60 * 60;
uint256 constant SECONDS_PER_MINUTE = 60;
int256 constant OFFSET19700101 = 2440588;
function timestampToDate(uint256 timestamp) internal pure returns (uint256 year, uint256 month, uint256 day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(
uint256 timestamp
) internal pure returns (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute, uint256 second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint256 secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function toDateString(
uint256 _timestamp
) internal pure returns (string memory d, string memory m, string memory y) {
(uint256 year, uint256 month, uint256 day) = timestampToDate(_timestamp);
d = uintToString(day);
m = uintToString(month);
y = uintToString(year);
}
function getDayOfWeek(uint256 timestamp) internal pure returns (uint256 dayOfWeek) {
uint256 _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = ((_days + 3) % 7) + 1;
}
/// Taken from https://stackoverflow.com/questions/47129173/how-to-convert-uint-to-string-in-solidity
function uintToString(uint256 _i) internal pure returns (string memory _uintAsString) {
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint256 year, uint256 month, uint256 day) internal pure returns (uint256 _days) {
require(year >= 1970);
int256 _year = int256(year);
int256 _month = int256(month);
int256 _day = int256(day);
int256 __days = _day -
32075 +
(1461 * (_year + 4800 + (_month - 14) / 12)) /
4 +
(367 * (_month - 2 - ((_month - 14) / 12) * 12)) /
12 -
(3 * ((_year + 4900 + (_month - 14) / 12) / 100)) /
4 -
OFFSET19700101;
_days = uint256(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint256 _days) internal pure returns (uint256 year, uint256 month, uint256 day) {
int256 __days = int256(_days);
int256 L = __days + 68569 + OFFSET19700101;
int256 N = (4 * L) / 146097;
L = L - (146097 * N + 3) / 4;
int256 _year = (4000 * (L + 1)) / 1461001;
L = L - (1461 * _year) / 4 + 31;
int256 _month = (80 * L) / 2447;
int256 _day = L - (2447 * _month) / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint256(_year);
month = uint256(_month);
day = uint256(_day);
}
}
IERC5095.sol 40 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
/// @notice Principal tokens (zero-coupon tokens) are redeemable for a single underlying EIP-20 token at a future timestamp.
/// https://eips.ethereum.org/EIPS/eip-5095
interface IERC5095 is IERC20 {
event Redeem(address indexed from, address indexed to, uint256 underlyingAmount);
/// @dev Asset that is returned on redemption.
function underlying() external view returns (address underlyingAddress);
/// @dev Unix time at which redemption of fyToken for underlying are possible
function maturity() external view returns (uint256 timestamp);
/// @dev Converts a specified amount of principal to underlying
function convertToUnderlying(uint256 principalAmount) external view returns (uint256 underlyingAmount);
/// @dev Converts a specified amount of underlying to principal
function convertToPrincipal(uint256 underlyingAmount) external view returns (uint256 principalAmount);
/// @dev Gives the maximum amount an address holder can redeem in terms of the principal
function maxRedeem(address holder) external view returns (uint256 maxPrincipalAmount);
/// @dev Gives the amount in terms of underlying that the princiapl amount can be redeemed for plus accrual
function previewRedeem(uint256 principalAmount) external view returns (uint256 underlyingAmount);
/// @dev Burn fyToken after maturity for an amount of principal.
function redeem(uint256 principalAmount, address to, address from) external returns (uint256 underlyingAmount);
/// @dev Gives the maximum amount an address holder can withdraw in terms of the underlying
function maxWithdraw(address holder) external view returns (uint256 maxUnderlyingAmount);
/// @dev Gives the amount in terms of principal that the underlying amount can be withdrawn for plus accrual
function previewWithdraw(uint256 underlyingAmount) external view returns (uint256 principalAmount);
/// @dev Burn fyToken after maturity for an amount of underlying.
function withdraw(uint256 underlyingAmount, address to, address from) external returns (uint256 principalAmount);
}
ITranche.sol 124 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {IERC5095} from "./IERC5095.sol";
/// @notice Tranche interface
/// @dev Tranche divides a yield-bearing token into two tokens: Principal and Yield tokens
/// Unspecific types: Simply avoiding dependencies on other interfaces from our interfaces
interface ITranche is IERC5095 {
/* ==================== ERRORS ===================== */
error TimestampBeforeMaturity();
error TimestampAfterMaturity();
error ProtectedToken();
error Unauthorized();
error OnlyYT();
error ReentrancyGuarded();
error ZeroAddress();
error NoAccruedYield();
/* ==================== EVENTS ===================== */
/// @param adapter the address of the adapter
/// @param maturity timestamp of maturity (seconds since Unix epoch)
/// @param issuanceFee fee for issuing PT and YT
event SeriesCreated(address indexed adapter, uint256 indexed maturity, uint256 issuanceFee);
/// @param from the sender of the underlying token
/// @param to the recipient of the PT and YT
/// @param underlyingUsed the amount of underlying token used to issue PT and YT
/// @param sharesUsed the amount of target token used to issue PT and YT (before deducting issuance fee)
event Issue(address indexed from, address indexed to, uint256 underlyingUsed, uint256 sharesUsed);
/// @param owner the address of the owner of the PT and YT (address that called collect())
/// @param shares the amount of Target token collected
event Collect(address indexed owner, uint256 shares);
/// @param owner the address of the owner of the PT and YT
/// @param to the recipient of the underlying token redeemed
/// @param underlyingRedeemed the amount of underlying token redeemed
event RedeemWithYT(address indexed owner, address indexed to, uint256 underlyingRedeemed);
/* ==================== STRUCTS ===================== */
/// @notice Series is a struct that contains all the information about a series.
/// @param underlying the address of the underlying token
/// @param target the address of the target token
/// @param yt the address of the Yield Token
/// @param adapter the address of the adapter
/// @param mscale scale value at maturity
/// @param maxscale max scale value from this series' lifetime
/// @param issuanceFee fee for issuing PT and YT
/// @param maturity timestamp of maturity (seconds since Unix epoch)
struct Series {
address underlying;
address target;
address yt;
address adapter;
uint256 mscale;
uint256 maxscale;
uint64 issuanceFee;
uint64 maturity;
}
/// @notice GlobalScales is a struct that contains scale values that are used in multiple functions throughout the Tranche contract.
/// @param mscale scale value at maturity. before maturity and settlement, this value is 0.
/// @param maxscale max scale value from this series' lifetime.
struct GlobalScales {
uint128 mscale;
uint128 maxscale;
}
/* ================== MUTATIVE METHODS =================== */
/// @notice deposit an `underlyingAmount` of underlying token into the yield source, receiving PT and YT.
/// amount of PT and YT issued are the same.
/// @param to the address to receive PT and YT
/// @param underlyingAmount the amount of underlying token to deposit
/// @return principalAmount the amount of PT and YT issued
function issue(address to, uint256 underlyingAmount) external returns (uint256 principalAmount);
/// @notice redeem an `principalAmount` of PT and YT for underlying token.
/// @param from the address to burn PT and YT from
/// @param to the address to receive underlying token
/// @param pyAmount the amount of PT and YT to redeem
/// @return underlyingAmount the amount of underlying token redeemed
function redeemWithYT(address from, address to, uint256 pyAmount) external returns (uint256 underlyingAmount);
/// @notice collect interest for `msg.sender` and transfer accrued interest to `msg.sender`
/// NOTE: if the maturity has passed, all the YT balance of `msg.sender` is burned.
/// @dev anyone can call this function to collect interest for themselves
/// @return collected collected interest in Underlying token
function collect() external returns (uint256 collected);
/* ================== PERMISSIONED METHODS =================== */
/// @notice collect interest from the yield source and distribute it
/// every YT transfer, this function is triggered by the Yield Token contract.
/// only the Yield Token contract can call this function.
/// NOTE: YT is not burned in this function even if the maturity has passed.
/// @param from address to transfer the Yield Token from. i.e. the user who collects the interest.
/// @param to address to transfer the Yield Token to (MUST NOT be zero address, CAN be the same as `from`)
/// @param value amount of Yield Token transferred to `to` (CAN be 0)
function updateUnclaimedYield(address from, address to, uint256 value) external;
/* ================== VIEW METHODS =================== */
/// @notice get the address of Yield Token associated with this Tranche.
function yieldToken() external view returns (address);
/// @notice get Series struct
function getSeries() external view returns (Series memory);
/// @notice get an accrued yield that can be claimed by `account` (in unis of Target token)
/// @dev this is reset to 0 when `account` claims the yield.
/// @param account the address to check
/// @return accruedInTarget
function unclaimedYields(address account) external view returns (uint256 accruedInTarget);
/// @notice get an accrued yield that can be claimed by `account` (in unis of Underlying token)
/// @param account the address to check
/// @return accruedInUnderlying accrued yield in underlying token
function previewCollect(address account) external view returns (uint256 accruedInUnderlying);
}
SafeERC20Namer.sol 99 lines
// SPDX-License-Identifier: GPL-3.0-or-later
// Modified from: Uniswap Library
// Use OpenZepplin's Strings library instead of the one from Uniswap
// https://github.com/Uniswap/solidity-lib/blob/c01640b0f0f1d8a85cba8de378cc48469fcfd9a6/contracts/libraries/SafeERC20Namer.sol
// https://github.com/yieldprotocol/yield-utils-v2/blob/dbeb85ac94befc477bf8cdff9f178fdf331eb83d/src/token/SafeERC20Namer.sol
pragma solidity ^0.8.0;
import {Strings} from "@openzeppelin/[email protected]/utils/Strings.sol";
// produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32
// this library will always produce a string symbol to represent the token
library SafeERC20Namer {
function bytes32ToString(bytes32 x) private pure returns (string memory) {
bytes memory bytesString = new bytes(32);
uint256 charCount = 0;
for (uint256 j; j < 32; j++) {
bytes1 char = x[j];
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint256 j; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
// assumes the data is in position 2
function parseStringData(bytes memory b) private pure returns (string memory) {
uint256 charCount = 0;
// first parse the charCount out of the data
for (uint256 i = 32; i < 64; i++) {
charCount <<= 8;
charCount += uint8(b[i]);
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint256 i; i < charCount; i++) {
bytesStringTrimmed[i] = b[i + 64];
}
return string(bytesStringTrimmed);
}
// uses a heuristic to produce a token name from the address
// the heuristic returns the full hex of the address string in upper case
function addressToName(address token) private pure returns (string memory) {
return Strings.toHexString(token);
}
// uses a heuristic to produce a token symbol from the address
// the heuristic returns the first 6 hex of the address string in upper case
function addressToSymbol(address token) private pure returns (string memory) {
return Strings.toHexString(token);
}
// calls an external view token contract method that returns a symbol or name, and parses the output into a string
function callAndParseStringReturn(address token, bytes4 selector) private view returns (string memory) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector));
// if not implemented, or returns empty data, return empty string
if (!success || data.length == 0) {
return "";
}
// bytes32 data always has length 32
if (data.length == 32) {
bytes32 decoded = abi.decode(data, (bytes32));
return bytes32ToString(decoded);
} else if (data.length > 64) {
return abi.decode(data, (string));
}
return "";
}
// attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address
function tokenSymbol(address token) internal view returns (string memory) {
// 0x95d89b41 = bytes4(keccak256("symbol()"))
string memory symbol = callAndParseStringReturn(token, 0x95d89b41);
if (bytes(symbol).length == 0) {
// fallback to 6 uppercase hex of address
return addressToSymbol(token);
}
return symbol;
}
// attempts to extract the token name. if it does not implement name, returns a name derived from the address
function tokenName(address token) internal view returns (string memory) {
// 0x06fdde03 = bytes4(keccak256("name()"))
string memory name = callAndParseStringReturn(token, 0x06fdde03);
if (bytes(name).length == 0) {
// fallback to full hex of address
return addressToName(token);
}
return name;
}
}
IBaseToken.sol 14 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {IERC20} from "@openzeppelin/[email protected]/token/ERC20/IERC20.sol";
/// @title IBaseToken
/// @notice token interface for Principal and Yield tokens
interface IBaseToken is IERC20 {
/// @notice maturity date of the token
function maturity() external view returns (uint256);
/// @notice target address of the token
function target() external view returns (address);
}
IYieldToken.sol 30 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {IBaseToken} from "./IBaseToken.sol";
interface IYieldToken is IBaseToken {
error OnlyTranche();
function tranche() external view returns (address);
/// @notice mint yield token
/// @dev only tranche can mint yield token
/// @param to recipient of yield token
/// @param amount amount of yield token to mint
function mint(address to, uint256 amount) external;
/// @notice burn yield token of owner
/// @dev only tranche can burn yield token
/// @param owner owner of yield token
/// @param amount amount of yield token to burn
function burn(address owner, uint256 amount) external;
/// @notice spender burn yield token on behalf of owner
/// @notice owner must approve spender prior to calling this function
/// @dev only tranche can burn yield token
/// @param owner owner of yield token
/// @param spender address to burn yield token on behalf of owner
/// @param amount amount of yield token to burn
function burnFrom(address owner, address spender, uint256 amount) external;
}
IBaseAdapter.sol 37 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
interface IBaseAdapter {
/* ============== MUTATIVE METHODS =============== */
/// @notice update adapter's scale value and return it
/// Underlying decimals: `u`, Target decimals: `t`, Target conversion rate: 10^u / 10^t
/// => Scale = 10^(u-t) * 10^18 = 10^(u-t+18)
/// e.g. WstETH (t=18,u=18) price: 1.2 WETH => scale = 1.2*10^18
/// eUSDC (t=18,u=6) price: 1.01 USDC => scale = 1.01*10^(6-18+18) = 1.01*10^6
/// @dev For interest-bearing token, such as cTokens, this is simply the conversion rate
/// @dev For other Targets, such as AMM LP shares, specialized logic will be required
/// @return scale in units of underlying token
function scale() external view returns (uint256);
/// @notice deposit Underlying in return for Target.
function deposit(uint256 underlyingUsed) external returns (uint256 shares);
/// @notice redeem Target and receive Underlying in return.
/// @dev no funds should be left in the contract after this call
/// the caller must transfer Target to this contract before calling this function.
/// @param to recipient of Underlying
/// @return underlyingWithdrawn amount of Underlying returned
/// @return sharesRedeemed amount of Target redeemed
function prefundedRedeem(address to) external returns (uint256 underlyingWithdrawn, uint256 sharesRedeemed);
/* =============== VIEW METHODS ================ */
/// @notice return Underlying token address (eg USDC, DAI)
/// @return Underlying address
function underlying() external view returns (address);
/// @notice return yield-bearing token address (eg cUSDC, wstETH, AMM LP shares)
/// @return Target address (yield-bearing token)
function target() external view returns (address);
}
FixedPointMathLib.sol 245 lines
// SPDX-License-Identifier: AGPL-3.0-only
/// @notice Taken from: https://github.com/transmissions11/solmate/blob/2001af43aedb46fdc2335d2a7714fb2dae7cfcd1/src/utils/FixedPointMathLib.sol
pragma solidity >=0.8.0;
/// @notice Arithmetic library with operations for fixed-point numbers.
/// @author Solmate (https://github.com/transmissions11/solmate/blob/main/src/utils/FixedPointMathLib.sol)
/// @author Inspired by USM (https://github.com/usmfum/USM/blob/master/contracts/WadMath.sol)
library FixedPointMathLib {
/*//////////////////////////////////////////////////////////////
SIMPLIFIED FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
uint256 internal constant MAX_UINT256 = 2 ** 256 - 1;
uint256 internal constant WAD = 1e18; // The scalar of ETH and most ERC20s.
function mulWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, y, WAD); // Equivalent to (x * y) / WAD rounded down.
}
function mulWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, y, WAD); // Equivalent to (x * y) / WAD rounded up.
}
function divWadDown(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivDown(x, WAD, y); // Equivalent to (x * WAD) / y rounded down.
}
function divWadUp(uint256 x, uint256 y) internal pure returns (uint256) {
return mulDivUp(x, WAD, y); // Equivalent to (x * WAD) / y rounded up.
}
/*//////////////////////////////////////////////////////////////
LOW LEVEL FIXED POINT OPERATIONS
//////////////////////////////////////////////////////////////*/
function mulDivDown(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// Divide x * y by the denominator.
z := div(mul(x, y), denominator)
}
}
function mulDivUp(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Equivalent to require(denominator != 0 && (y == 0 || x <= type(uint256).max / y))
if iszero(mul(denominator, iszero(mul(y, gt(x, div(MAX_UINT256, y)))))) {
revert(0, 0)
}
// If x * y modulo the denominator is strictly greater than 0,
// 1 is added to round up the division of x * y by the denominator.
z := add(gt(mod(mul(x, y), denominator), 0), div(mul(x, y), denominator))
}
}
function rpow(uint256 x, uint256 n, uint256 scalar) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
switch x
case 0 {
switch n
case 0 {
// 0 ** 0 = 1
z := scalar
}
default {
// 0 ** n = 0
z := 0
}
}
default {
switch mod(n, 2)
case 0 {
// If n is even, store scalar in z for now.
z := scalar
}
default {
// If n is odd, store x in z for now.
z := x
}
// Shifting right by 1 is like dividing by 2.
let half := shr(1, scalar)
for {
// Shift n right by 1 before looping to halve it.
n := shr(1, n)
} n {
// Shift n right by 1 each iteration to halve it.
n := shr(1, n)
} {
// Revert immediately if x ** 2 would overflow.
// Equivalent to iszero(eq(div(xx, x), x)) here.
if shr(128, x) {
revert(0, 0)
}
// Store x squared.
let xx := mul(x, x)
// Round to the nearest number.
let xxRound := add(xx, half)
// Revert if xx + half overflowed.
if lt(xxRound, xx) {
revert(0, 0)
}
// Set x to scaled xxRound.
x := div(xxRound, scalar)
// If n is even:
if mod(n, 2) {
// Compute z * x.
let zx := mul(z, x)
// If z * x overflowed:
if iszero(eq(div(zx, x), z)) {
// Revert if x is non-zero.
if iszero(iszero(x)) {
revert(0, 0)
}
}
// Round to the nearest number.
let zxRound := add(zx, half)
// Revert if zx + half overflowed.
if lt(zxRound, zx) {
revert(0, 0)
}
// Return properly scaled zxRound.
z := div(zxRound, scalar)
}
}
}
}
}
/*//////////////////////////////////////////////////////////////
GENERAL NUMBER UTILITIES
//////////////////////////////////////////////////////////////*/
function sqrt(uint256 x) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
let y := x // We start y at x, which will help us make our initial estimate.
z := 181 // The "correct" value is 1, but this saves a multiplication later.
// This segment is to get a reasonable initial estimate for the Babylonian method. With a bad
// start, the correct # of bits increases ~linearly each iteration instead of ~quadratically.
// We check y >= 2^(k + 8) but shift right by k bits
// each branch to ensure that if x >= 256, then y >= 256.
if iszero(lt(y, 0x10000000000000000000000000000000000)) {
y := shr(128, y)
z := shl(64, z)
}
if iszero(lt(y, 0x1000000000000000000)) {
y := shr(64, y)
z := shl(32, z)
}
if iszero(lt(y, 0x10000000000)) {
y := shr(32, y)
z := shl(16, z)
}
if iszero(lt(y, 0x1000000)) {
y := shr(16, y)
z := shl(8, z)
}
// Goal was to get z*z*y within a small factor of x. More iterations could
// get y in a tighter range. Currently, we will have y in [256, 256*2^16).
// We ensured y >= 256 so that the relative difference between y and y+1 is small.
// That's not possible if x < 256 but we can just verify those cases exhaustively.
// Now, z*z*y <= x < z*z*(y+1), and y <= 2^(16+8), and either y >= 256, or x < 256.
// Correctness can be checked exhaustively for x < 256, so we assume y >= 256.
// Then z*sqrt(y) is within sqrt(257)/sqrt(256) of sqrt(x), or about 20bps.
// For s in the range [1/256, 256], the estimate f(s) = (181/1024) * (s+1) is in the range
// (1/2.84 * sqrt(s), 2.84 * sqrt(s)), with largest error when s = 1 and when s = 256 or 1/256.
// Since y is in [256, 256*2^16), let a = y/65536, so that a is in [1/256, 256). Then we can estimate
// sqrt(y) using sqrt(65536) * 181/1024 * (a + 1) = 181/4 * (y + 65536)/65536 = 181 * (y + 65536)/2^18.
// There is no overflow risk here since y < 2^136 after the first branch above.
z := shr(18, mul(z, add(y, 65536))) // A mul() is saved from starting z at 181.
// Given the worst case multiplicative error of 2.84 above, 7 iterations should be enough.
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
z := shr(1, add(z, div(x, z)))
// If x+1 is a perfect square, the Babylonian method cycles between
// floor(sqrt(x)) and ceil(sqrt(x)). This statement ensures we return floor.
// See: https://en.wikipedia.org/wiki/Integer_square_root#Using_only_integer_division
// Since the ceil is rare, we save gas on the assignment and repeat division in the rare case.
// If you don't care whether the floor or ceil square root is returned, you can remove this statement.
z := sub(z, lt(div(x, z), z))
}
}
function unsafeMod(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Mod x by y. Note this will return
// 0 instead of reverting if y is zero.
z := mod(x, y)
}
}
function unsafeDiv(uint256 x, uint256 y) internal pure returns (uint256 r) {
/// @solidity memory-safe-assembly
assembly {
// Divide x by y. Note this will return
// 0 instead of reverting if y is zero.
r := div(x, y)
}
}
function unsafeDivUp(uint256 x, uint256 y) internal pure returns (uint256 z) {
/// @solidity memory-safe-assembly
assembly {
// Add 1 to x * y if x % y > 0. Note this will
// return 0 instead of reverting if y is zero.
z := add(gt(mod(x, y), 0), div(x, y))
}
}
}
ITrancheFactory.sol 45 lines
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
/// @title ITrancheFactory
/// @notice interface for TrancheFactory
interface ITrancheFactory {
error ZeroAddress();
error TrancheAlreadyExists();
error MaturityInvalid();
error OnlyManagement();
error IssueanceFeeTooHigh();
error TrancheAddressMismatch();
event TrancheDeployed(uint256 indexed maturity, address indexed principalToken, address indexed yieldToken);
/// @notice init args for a tranche
/// @param adapter address of the adapter
/// @param maturity UNIX timestamp of maturity
/// @param issuanceFee fee for issuing PT and YT
/// @param yt address of the Yield Token
/// @param management management address of the deployed tranche
struct TrancheInitArgs {
address adapter; // 20 bytes
uint32 maturity; // 4 bytes
uint16 issuanceFee; // 2 bytes (1th-slot)
address yt; // 20 bytes (2nd-slot)
address management; // 20 bytes (3rd-slot)
}
/// @notice deploy a new Tranche instance with the given maturity and adapter
/// @dev only the management address can call this function
/// @param adapter the adapter to use for this series
/// @param maturity the maturity of this series (in seconds)
/// @param issuanceFee the issueance fee of this series (in basis points 10_000=100%)
/// @return the address of the new tranche
function deployTranche(address adapter, uint256 maturity, uint256 issuanceFee) external returns (address);
/// @notice calculate the address of a tranche with CREATE2 using the adapter and maturity as salt
function trancheFor(address adapter, uint256 maturity) external view returns (address tranche);
/// @notice return init args for a tranche
function args() external view returns (TrancheInitArgs memory);
function TRANCHE_CREATION_HASH() external view returns (bytes32);
}
Address.sol 244 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library 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
*
* Furthermore, `isContract` will also return true if the target contract within
* the same transaction is already scheduled for destruction by `SELFDESTRUCT`,
* which only has an effect at the end of a transaction.
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://consensys.net/diligence/blog/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.8.0/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResultFromTarget(target, success, returndata, errorMessage);
}
/**
* @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling
* the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.
*
* _Available since v4.8._
*/
function verifyCallResultFromTarget(
address target,
bool success,
bytes memory returndata,
string memory errorMessage
) internal view returns (bytes memory) {
if (success) {
if (returndata.length == 0) {
// only check isContract if the call was successful and the return data is empty
// otherwise we already know that it was a contract
require(isContract(target), "Address: call to non-contract");
}
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
/**
* @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason or using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
_revert(returndata, errorMessage);
}
}
function _revert(bytes memory returndata, string memory errorMessage) private pure {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
/// @solidity memory-safe-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
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;
}
}
Strings.sol 85 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)
pragma solidity ^0.8.0;
import "./math/Math.sol";
import "./math/SignedMath.sol";
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _SYMBOLS = "0123456789abcdef";
uint8 private constant _ADDRESS_LENGTH = 20;
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
unchecked {
uint256 length = Math.log10(value) + 1;
string memory buffer = new string(length);
uint256 ptr;
/// @solidity memory-safe-assembly
assembly {
ptr := add(buffer, add(32, length))
}
while (true) {
ptr--;
/// @solidity memory-safe-assembly
assembly {
mstore8(ptr, byte(mod(value, 10), _SYMBOLS))
}
value /= 10;
if (value == 0) break;
}
return buffer;
}
}
/**
* @dev Converts a `int256` to its ASCII `string` decimal representation.
*/
function toString(int256 value) internal pure returns (string memory) {
return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value))));
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
unchecked {
return toHexString(value, Math.log256(value) + 1);
}
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
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] = _SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
/**
* @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
*/
function toHexString(address addr) internal pure returns (string memory) {
return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
}
/**
* @dev Returns true if the two strings are equal.
*/
function equal(string memory a, string memory b) internal pure returns (bool) {
return keccak256(bytes(a)) == keccak256(bytes(b));
}
}
Counters.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
Math.sol 339 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
enum Rounding {
Down, // Toward negative infinity
Up, // Toward infinity
Zero // Toward zero
}
/**
* @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 == 0 ? 0 : (a - 1) / b + 1;
}
/**
* @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
* @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
* with further edits by Uniswap Labs also under MIT license.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {
unchecked {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2^256 + prod0.
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
// Solidity will revert if denominator == 0, unlike the div opcode on its own.
// The surrounding unchecked block does not change this fact.
// See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.
return prod0 / denominator;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
require(denominator > prod1, "Math: mulDiv overflow");
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 twos = denominator & (~denominator + 1);
assembly {
// Divide denominator by twos.
denominator := div(denominator, twos)
// Divide [prod1 prod0] by twos.
prod0 := div(prod0, twos)
// Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
twos := add(div(sub(0, twos), twos), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * twos;
// Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
// that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
// in modular arithmetic, doubling the correct bits in each step.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // inverse mod 2^256
// Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
// This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
// less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inverse;
return result;
}
}
/**
* @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
*/
function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {
uint256 result = mulDiv(x, y, denominator);
if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
result += 1;
}
return result;
}
/**
* @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.
*
* Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
*/
function sqrt(uint256 a) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
// For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
//
// We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
// `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.
//
// This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`
// → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`
// → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`
//
// Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.
uint256 result = 1 << (log2(a) >> 1);
// At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
// since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
// every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
// into the expected uint128 result.
unchecked {
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
result = (result + a / result) >> 1;
return min(result, a / result);
}
}
/**
* @notice Calculates sqrt(a), following the selected rounding direction.
*/
function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = sqrt(a);
return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);
}
}
/**
* @dev Return the log in base 2, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 128;
}
if (value >> 64 > 0) {
value >>= 64;
result += 64;
}
if (value >> 32 > 0) {
value >>= 32;
result += 32;
}
if (value >> 16 > 0) {
value >>= 16;
result += 16;
}
if (value >> 8 > 0) {
value >>= 8;
result += 8;
}
if (value >> 4 > 0) {
value >>= 4;
result += 4;
}
if (value >> 2 > 0) {
value >>= 2;
result += 2;
}
if (value >> 1 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 2, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log2(value);
return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 10, rounded down, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >= 10 ** 64) {
value /= 10 ** 64;
result += 64;
}
if (value >= 10 ** 32) {
value /= 10 ** 32;
result += 32;
}
if (value >= 10 ** 16) {
value /= 10 ** 16;
result += 16;
}
if (value >= 10 ** 8) {
value /= 10 ** 8;
result += 8;
}
if (value >= 10 ** 4) {
value /= 10 ** 4;
result += 4;
}
if (value >= 10 ** 2) {
value /= 10 ** 2;
result += 2;
}
if (value >= 10 ** 1) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 10, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log10(value);
return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);
}
}
/**
* @dev Return the log in base 256, rounded down, of a positive value.
* Returns 0 if given 0.
*
* Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.
*/
function log256(uint256 value) internal pure returns (uint256) {
uint256 result = 0;
unchecked {
if (value >> 128 > 0) {
value >>= 128;
result += 16;
}
if (value >> 64 > 0) {
value >>= 64;
result += 8;
}
if (value >> 32 > 0) {
value >>= 32;
result += 4;
}
if (value >> 16 > 0) {
value >>= 16;
result += 2;
}
if (value >> 8 > 0) {
result += 1;
}
}
return result;
}
/**
* @dev Return the log in base 256, following the selected rounding direction, of a positive value.
* Returns 0 if given 0.
*/
function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {
unchecked {
uint256 result = log256(value);
return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);
}
}
}
Pausable.sol 105 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @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.
*/
constructor() {
_paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
_requireNotPaused();
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
_requirePaused();
_;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Throws if the contract is paused.
*/
function _requireNotPaused() internal view virtual {
require(!paused(), "Pausable: paused");
}
/**
* @dev Throws if the contract is not paused.
*/
function _requirePaused() internal view virtual {
require(paused(), "Pausable: not paused");
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
ERC20.sol 365 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* The default value of {decimals} is 18. To change this, you should override
* this function so it returns a different value.
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the default value returned by this function, unless
* it's overridden.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(address from, address to, uint256 amount) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `from` to `to`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(address from, address to, uint256 amount) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
// Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by
// decrementing then incrementing.
_balances[to] += amount;
}
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
unchecked {
// Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.
_balances[account] += amount;
}
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
// Overflow not possible: amount <= accountBalance <= totalSupply.
_totalSupply -= amount;
}
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(address owner, address spender, uint256 amount) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(address from, address to, uint256 amount) internal virtual {}
}
StorageSlot.sol 138 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/StorageSlot.sol)
// This file was procedurally generated from scripts/generate/templates/StorageSlot.js.
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```solidity
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, `uint256`._
* _Available since v4.9 for `string`, `bytes`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
struct StringSlot {
string value;
}
struct BytesSlot {
bytes value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` with member `value` located at `slot`.
*/
function getStringSlot(bytes32 slot) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `StringSlot` representation of the string storage pointer `store`.
*/
function getStringSlot(string storage store) internal pure returns (StringSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
/**
* @dev Returns an `BytesSlot` with member `value` located at `slot`.
*/
function getBytesSlot(bytes32 slot) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BytesSlot` representation of the bytes storage pointer `store`.
*/
function getBytesSlot(bytes storage store) internal pure returns (BytesSlot storage r) {
/// @solidity memory-safe-assembly
assembly {
r.slot := store.slot
}
}
}
IERC20.sol 78 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 amount) external returns (bool);
}
ShortStrings.sol 122 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/ShortStrings.sol)
pragma solidity ^0.8.8;
import "./StorageSlot.sol";
// | string | 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA |
// | length | 0x BB |
type ShortString is bytes32;
/**
* @dev This library provides functions to convert short memory strings
* into a `ShortString` type that can be used as an immutable variable.
*
* Strings of arbitrary length can be optimized using this library if
* they are short enough (up to 31 bytes) by packing them with their
* length (1 byte) in a single EVM word (32 bytes). Additionally, a
* fallback mechanism can be used for every other case.
*
* Usage example:
*
* ```solidity
* contract Named {
* using ShortStrings for *;
*
* ShortString private immutable _name;
* string private _nameFallback;
*
* constructor(string memory contractName) {
* _name = contractName.toShortStringWithFallback(_nameFallback);
* }
*
* function name() external view returns (string memory) {
* return _name.toStringWithFallback(_nameFallback);
* }
* }
* ```
*/
library ShortStrings {
// Used as an identifier for strings longer than 31 bytes.
bytes32 private constant _FALLBACK_SENTINEL = 0x00000000000000000000000000000000000000000000000000000000000000FF;
error StringTooLong(string str);
error InvalidShortString();
/**
* @dev Encode a string of at most 31 chars into a `ShortString`.
*
* This will trigger a `StringTooLong` error is the input string is too long.
*/
function toShortString(string memory str) internal pure returns (ShortString) {
bytes memory bstr = bytes(str);
if (bstr.length > 31) {
revert StringTooLong(str);
}
return ShortString.wrap(bytes32(uint256(bytes32(bstr)) | bstr.length));
}
/**
* @dev Decode a `ShortString` back to a "normal" string.
*/
function toString(ShortString sstr) internal pure returns (string memory) {
uint256 len = byteLength(sstr);
// using `new string(len)` would work locally but is not memory safe.
string memory str = new string(32);
/// @solidity memory-safe-assembly
assembly {
mstore(str, len)
mstore(add(str, 0x20), sstr)
}
return str;
}
/**
* @dev Return the length of a `ShortString`.
*/
function byteLength(ShortString sstr) internal pure returns (uint256) {
uint256 result = uint256(ShortString.unwrap(sstr)) & 0xFF;
if (result > 31) {
revert InvalidShortString();
}
return result;
}
/**
* @dev Encode a string into a `ShortString`, or write it to storage if it is too long.
*/
function toShortStringWithFallback(string memory value, string storage store) internal returns (ShortString) {
if (bytes(value).length < 32) {
return toShortString(value);
} else {
StorageSlot.getStringSlot(store).value = value;
return ShortString.wrap(_FALLBACK_SENTINEL);
}
}
/**
* @dev Decode a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*/
function toStringWithFallback(ShortString value, string storage store) internal pure returns (string memory) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return toString(value);
} else {
return store;
}
}
/**
* @dev Return the length of a string that was encoded to `ShortString` or written to storage using {setWithFallback}.
*
* WARNING: This will return the "byte length" of the string. This may not reflect the actual length in terms of
* actual characters as the UTF-8 encoding of a single character can span over multiple bytes.
*/
function byteLengthWithFallback(ShortString value, string storage store) internal view returns (uint256) {
if (ShortString.unwrap(value) != _FALLBACK_SENTINEL) {
return byteLength(value);
} else {
return bytes(store).length;
}
}
}
IERC5267.sol 28 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (interfaces/IERC5267.sol)
pragma solidity ^0.8.0;
interface IERC5267 {
/**
* @dev MAY be emitted to signal that the domain could have changed.
*/
event EIP712DomainChanged();
/**
* @dev returns the fields and values that describe the domain separator used by this contract for EIP-712
* signature.
*/
function eip712Domain()
external
view
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
);
}
SafeCast.sol 1136 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SafeCast.sol)
// This file was procedurally generated from scripts/generate/templates/SafeCast.js.
pragma solidity ^0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint248 from uint256, reverting on
* overflow (when the input is greater than largest uint248).
*
* Counterpart to Solidity's `uint248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toUint248(uint256 value) internal pure returns (uint248) {
require(value <= type(uint248).max, "SafeCast: value doesn't fit in 248 bits");
return uint248(value);
}
/**
* @dev Returns the downcasted uint240 from uint256, reverting on
* overflow (when the input is greater than largest uint240).
*
* Counterpart to Solidity's `uint240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toUint240(uint256 value) internal pure returns (uint240) {
require(value <= type(uint240).max, "SafeCast: value doesn't fit in 240 bits");
return uint240(value);
}
/**
* @dev Returns the downcasted uint232 from uint256, reverting on
* overflow (when the input is greater than largest uint232).
*
* Counterpart to Solidity's `uint232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toUint232(uint256 value) internal pure returns (uint232) {
require(value <= type(uint232).max, "SafeCast: value doesn't fit in 232 bits");
return uint232(value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.2._
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint216 from uint256, reverting on
* overflow (when the input is greater than largest uint216).
*
* Counterpart to Solidity's `uint216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toUint216(uint256 value) internal pure returns (uint216) {
require(value <= type(uint216).max, "SafeCast: value doesn't fit in 216 bits");
return uint216(value);
}
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toUint208(uint256 value) internal pure returns (uint208) {
require(value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(value);
}
/**
* @dev Returns the downcasted uint200 from uint256, reverting on
* overflow (when the input is greater than largest uint200).
*
* Counterpart to Solidity's `uint200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toUint200(uint256 value) internal pure returns (uint200) {
require(value <= type(uint200).max, "SafeCast: value doesn't fit in 200 bits");
return uint200(value);
}
/**
* @dev Returns the downcasted uint192 from uint256, reverting on
* overflow (when the input is greater than largest uint192).
*
* Counterpart to Solidity's `uint192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toUint192(uint256 value) internal pure returns (uint192) {
require(value <= type(uint192).max, "SafeCast: value doesn't fit in 192 bits");
return uint192(value);
}
/**
* @dev Returns the downcasted uint184 from uint256, reverting on
* overflow (when the input is greater than largest uint184).
*
* Counterpart to Solidity's `uint184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toUint184(uint256 value) internal pure returns (uint184) {
require(value <= type(uint184).max, "SafeCast: value doesn't fit in 184 bits");
return uint184(value);
}
/**
* @dev Returns the downcasted uint176 from uint256, reverting on
* overflow (when the input is greater than largest uint176).
*
* Counterpart to Solidity's `uint176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toUint176(uint256 value) internal pure returns (uint176) {
require(value <= type(uint176).max, "SafeCast: value doesn't fit in 176 bits");
return uint176(value);
}
/**
* @dev Returns the downcasted uint168 from uint256, reverting on
* overflow (when the input is greater than largest uint168).
*
* Counterpart to Solidity's `uint168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toUint168(uint256 value) internal pure returns (uint168) {
require(value <= type(uint168).max, "SafeCast: value doesn't fit in 168 bits");
return uint168(value);
}
/**
* @dev Returns the downcasted uint160 from uint256, reverting on
* overflow (when the input is greater than largest uint160).
*
* Counterpart to Solidity's `uint160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toUint160(uint256 value) internal pure returns (uint160) {
require(value <= type(uint160).max, "SafeCast: value doesn't fit in 160 bits");
return uint160(value);
}
/**
* @dev Returns the downcasted uint152 from uint256, reverting on
* overflow (when the input is greater than largest uint152).
*
* Counterpart to Solidity's `uint152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toUint152(uint256 value) internal pure returns (uint152) {
require(value <= type(uint152).max, "SafeCast: value doesn't fit in 152 bits");
return uint152(value);
}
/**
* @dev Returns the downcasted uint144 from uint256, reverting on
* overflow (when the input is greater than largest uint144).
*
* Counterpart to Solidity's `uint144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toUint144(uint256 value) internal pure returns (uint144) {
require(value <= type(uint144).max, "SafeCast: value doesn't fit in 144 bits");
return uint144(value);
}
/**
* @dev Returns the downcasted uint136 from uint256, reverting on
* overflow (when the input is greater than largest uint136).
*
* Counterpart to Solidity's `uint136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toUint136(uint256 value) internal pure returns (uint136) {
require(value <= type(uint136).max, "SafeCast: value doesn't fit in 136 bits");
return uint136(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v2.5._
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint120 from uint256, reverting on
* overflow (when the input is greater than largest uint120).
*
* Counterpart to Solidity's `uint120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toUint120(uint256 value) internal pure returns (uint120) {
require(value <= type(uint120).max, "SafeCast: value doesn't fit in 120 bits");
return uint120(value);
}
/**
* @dev Returns the downcasted uint112 from uint256, reverting on
* overflow (when the input is greater than largest uint112).
*
* Counterpart to Solidity's `uint112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toUint112(uint256 value) internal pure returns (uint112) {
require(value <= type(uint112).max, "SafeCast: value doesn't fit in 112 bits");
return uint112(value);
}
/**
* @dev Returns the downcasted uint104 from uint256, reverting on
* overflow (when the input is greater than largest uint104).
*
* Counterpart to Solidity's `uint104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toUint104(uint256 value) internal pure returns (uint104) {
require(value <= type(uint104).max, "SafeCast: value doesn't fit in 104 bits");
return uint104(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.2._
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint88 from uint256, reverting on
* overflow (when the input is greater than largest uint88).
*
* Counterpart to Solidity's `uint88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toUint88(uint256 value) internal pure returns (uint88) {
require(value <= type(uint88).max, "SafeCast: value doesn't fit in 88 bits");
return uint88(value);
}
/**
* @dev Returns the downcasted uint80 from uint256, reverting on
* overflow (when the input is greater than largest uint80).
*
* Counterpart to Solidity's `uint80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toUint80(uint256 value) internal pure returns (uint80) {
require(value <= type(uint80).max, "SafeCast: value doesn't fit in 80 bits");
return uint80(value);
}
/**
* @dev Returns the downcasted uint72 from uint256, reverting on
* overflow (when the input is greater than largest uint72).
*
* Counterpart to Solidity's `uint72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toUint72(uint256 value) internal pure returns (uint72) {
require(value <= type(uint72).max, "SafeCast: value doesn't fit in 72 bits");
return uint72(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v2.5._
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint56 from uint256, reverting on
* overflow (when the input is greater than largest uint56).
*
* Counterpart to Solidity's `uint56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toUint56(uint256 value) internal pure returns (uint56) {
require(value <= type(uint56).max, "SafeCast: value doesn't fit in 56 bits");
return uint56(value);
}
/**
* @dev Returns the downcasted uint48 from uint256, reverting on
* overflow (when the input is greater than largest uint48).
*
* Counterpart to Solidity's `uint48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toUint48(uint256 value) internal pure returns (uint48) {
require(value <= type(uint48).max, "SafeCast: value doesn't fit in 48 bits");
return uint48(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value <= type(uint40).max, "SafeCast: value doesn't fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v2.5._
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint24 from uint256, reverting on
* overflow (when the input is greater than largest uint24).
*
* Counterpart to Solidity's `uint24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toUint24(uint256 value) internal pure returns (uint24) {
require(value <= type(uint24).max, "SafeCast: value doesn't fit in 24 bits");
return uint24(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v2.5._
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v2.5._
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*
* _Available since v3.0._
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int248 from int256, reverting on
* overflow (when the input is less than smallest int248 or
* greater than largest int248).
*
* Counterpart to Solidity's `int248` operator.
*
* Requirements:
*
* - input must fit into 248 bits
*
* _Available since v4.7._
*/
function toInt248(int256 value) internal pure returns (int248 downcasted) {
downcasted = int248(value);
require(downcasted == value, "SafeCast: value doesn't fit in 248 bits");
}
/**
* @dev Returns the downcasted int240 from int256, reverting on
* overflow (when the input is less than smallest int240 or
* greater than largest int240).
*
* Counterpart to Solidity's `int240` operator.
*
* Requirements:
*
* - input must fit into 240 bits
*
* _Available since v4.7._
*/
function toInt240(int256 value) internal pure returns (int240 downcasted) {
downcasted = int240(value);
require(downcasted == value, "SafeCast: value doesn't fit in 240 bits");
}
/**
* @dev Returns the downcasted int232 from int256, reverting on
* overflow (when the input is less than smallest int232 or
* greater than largest int232).
*
* Counterpart to Solidity's `int232` operator.
*
* Requirements:
*
* - input must fit into 232 bits
*
* _Available since v4.7._
*/
function toInt232(int256 value) internal pure returns (int232 downcasted) {
downcasted = int232(value);
require(downcasted == value, "SafeCast: value doesn't fit in 232 bits");
}
/**
* @dev Returns the downcasted int224 from int256, reverting on
* overflow (when the input is less than smallest int224 or
* greater than largest int224).
*
* Counterpart to Solidity's `int224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*
* _Available since v4.7._
*/
function toInt224(int256 value) internal pure returns (int224 downcasted) {
downcasted = int224(value);
require(downcasted == value, "SafeCast: value doesn't fit in 224 bits");
}
/**
* @dev Returns the downcasted int216 from int256, reverting on
* overflow (when the input is less than smallest int216 or
* greater than largest int216).
*
* Counterpart to Solidity's `int216` operator.
*
* Requirements:
*
* - input must fit into 216 bits
*
* _Available since v4.7._
*/
function toInt216(int256 value) internal pure returns (int216 downcasted) {
downcasted = int216(value);
require(downcasted == value, "SafeCast: value doesn't fit in 216 bits");
}
/**
* @dev Returns the downcasted int208 from int256, reverting on
* overflow (when the input is less than smallest int208 or
* greater than largest int208).
*
* Counterpart to Solidity's `int208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*
* _Available since v4.7._
*/
function toInt208(int256 value) internal pure returns (int208 downcasted) {
downcasted = int208(value);
require(downcasted == value, "SafeCast: value doesn't fit in 208 bits");
}
/**
* @dev Returns the downcasted int200 from int256, reverting on
* overflow (when the input is less than smallest int200 or
* greater than largest int200).
*
* Counterpart to Solidity's `int200` operator.
*
* Requirements:
*
* - input must fit into 200 bits
*
* _Available since v4.7._
*/
function toInt200(int256 value) internal pure returns (int200 downcasted) {
downcasted = int200(value);
require(downcasted == value, "SafeCast: value doesn't fit in 200 bits");
}
/**
* @dev Returns the downcasted int192 from int256, reverting on
* overflow (when the input is less than smallest int192 or
* greater than largest int192).
*
* Counterpart to Solidity's `int192` operator.
*
* Requirements:
*
* - input must fit into 192 bits
*
* _Available since v4.7._
*/
function toInt192(int256 value) internal pure returns (int192 downcasted) {
downcasted = int192(value);
require(downcasted == value, "SafeCast: value doesn't fit in 192 bits");
}
/**
* @dev Returns the downcasted int184 from int256, reverting on
* overflow (when the input is less than smallest int184 or
* greater than largest int184).
*
* Counterpart to Solidity's `int184` operator.
*
* Requirements:
*
* - input must fit into 184 bits
*
* _Available since v4.7._
*/
function toInt184(int256 value) internal pure returns (int184 downcasted) {
downcasted = int184(value);
require(downcasted == value, "SafeCast: value doesn't fit in 184 bits");
}
/**
* @dev Returns the downcasted int176 from int256, reverting on
* overflow (when the input is less than smallest int176 or
* greater than largest int176).
*
* Counterpart to Solidity's `int176` operator.
*
* Requirements:
*
* - input must fit into 176 bits
*
* _Available since v4.7._
*/
function toInt176(int256 value) internal pure returns (int176 downcasted) {
downcasted = int176(value);
require(downcasted == value, "SafeCast: value doesn't fit in 176 bits");
}
/**
* @dev Returns the downcasted int168 from int256, reverting on
* overflow (when the input is less than smallest int168 or
* greater than largest int168).
*
* Counterpart to Solidity's `int168` operator.
*
* Requirements:
*
* - input must fit into 168 bits
*
* _Available since v4.7._
*/
function toInt168(int256 value) internal pure returns (int168 downcasted) {
downcasted = int168(value);
require(downcasted == value, "SafeCast: value doesn't fit in 168 bits");
}
/**
* @dev Returns the downcasted int160 from int256, reverting on
* overflow (when the input is less than smallest int160 or
* greater than largest int160).
*
* Counterpart to Solidity's `int160` operator.
*
* Requirements:
*
* - input must fit into 160 bits
*
* _Available since v4.7._
*/
function toInt160(int256 value) internal pure returns (int160 downcasted) {
downcasted = int160(value);
require(downcasted == value, "SafeCast: value doesn't fit in 160 bits");
}
/**
* @dev Returns the downcasted int152 from int256, reverting on
* overflow (when the input is less than smallest int152 or
* greater than largest int152).
*
* Counterpart to Solidity's `int152` operator.
*
* Requirements:
*
* - input must fit into 152 bits
*
* _Available since v4.7._
*/
function toInt152(int256 value) internal pure returns (int152 downcasted) {
downcasted = int152(value);
require(downcasted == value, "SafeCast: value doesn't fit in 152 bits");
}
/**
* @dev Returns the downcasted int144 from int256, reverting on
* overflow (when the input is less than smallest int144 or
* greater than largest int144).
*
* Counterpart to Solidity's `int144` operator.
*
* Requirements:
*
* - input must fit into 144 bits
*
* _Available since v4.7._
*/
function toInt144(int256 value) internal pure returns (int144 downcasted) {
downcasted = int144(value);
require(downcasted == value, "SafeCast: value doesn't fit in 144 bits");
}
/**
* @dev Returns the downcasted int136 from int256, reverting on
* overflow (when the input is less than smallest int136 or
* greater than largest int136).
*
* Counterpart to Solidity's `int136` operator.
*
* Requirements:
*
* - input must fit into 136 bits
*
* _Available since v4.7._
*/
function toInt136(int256 value) internal pure returns (int136 downcasted) {
downcasted = int136(value);
require(downcasted == value, "SafeCast: value doesn't fit in 136 bits");
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128 downcasted) {
downcasted = int128(value);
require(downcasted == value, "SafeCast: value doesn't fit in 128 bits");
}
/**
* @dev Returns the downcasted int120 from int256, reverting on
* overflow (when the input is less than smallest int120 or
* greater than largest int120).
*
* Counterpart to Solidity's `int120` operator.
*
* Requirements:
*
* - input must fit into 120 bits
*
* _Available since v4.7._
*/
function toInt120(int256 value) internal pure returns (int120 downcasted) {
downcasted = int120(value);
require(downcasted == value, "SafeCast: value doesn't fit in 120 bits");
}
/**
* @dev Returns the downcasted int112 from int256, reverting on
* overflow (when the input is less than smallest int112 or
* greater than largest int112).
*
* Counterpart to Solidity's `int112` operator.
*
* Requirements:
*
* - input must fit into 112 bits
*
* _Available since v4.7._
*/
function toInt112(int256 value) internal pure returns (int112 downcasted) {
downcasted = int112(value);
require(downcasted == value, "SafeCast: value doesn't fit in 112 bits");
}
/**
* @dev Returns the downcasted int104 from int256, reverting on
* overflow (when the input is less than smallest int104 or
* greater than largest int104).
*
* Counterpart to Solidity's `int104` operator.
*
* Requirements:
*
* - input must fit into 104 bits
*
* _Available since v4.7._
*/
function toInt104(int256 value) internal pure returns (int104 downcasted) {
downcasted = int104(value);
require(downcasted == value, "SafeCast: value doesn't fit in 104 bits");
}
/**
* @dev Returns the downcasted int96 from int256, reverting on
* overflow (when the input is less than smallest int96 or
* greater than largest int96).
*
* Counterpart to Solidity's `int96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*
* _Available since v4.7._
*/
function toInt96(int256 value) internal pure returns (int96 downcasted) {
downcasted = int96(value);
require(downcasted == value, "SafeCast: value doesn't fit in 96 bits");
}
/**
* @dev Returns the downcasted int88 from int256, reverting on
* overflow (when the input is less than smallest int88 or
* greater than largest int88).
*
* Counterpart to Solidity's `int88` operator.
*
* Requirements:
*
* - input must fit into 88 bits
*
* _Available since v4.7._
*/
function toInt88(int256 value) internal pure returns (int88 downcasted) {
downcasted = int88(value);
require(downcasted == value, "SafeCast: value doesn't fit in 88 bits");
}
/**
* @dev Returns the downcasted int80 from int256, reverting on
* overflow (when the input is less than smallest int80 or
* greater than largest int80).
*
* Counterpart to Solidity's `int80` operator.
*
* Requirements:
*
* - input must fit into 80 bits
*
* _Available since v4.7._
*/
function toInt80(int256 value) internal pure returns (int80 downcasted) {
downcasted = int80(value);
require(downcasted == value, "SafeCast: value doesn't fit in 80 bits");
}
/**
* @dev Returns the downcasted int72 from int256, reverting on
* overflow (when the input is less than smallest int72 or
* greater than largest int72).
*
* Counterpart to Solidity's `int72` operator.
*
* Requirements:
*
* - input must fit into 72 bits
*
* _Available since v4.7._
*/
function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64 downcasted) {
downcasted = int64(value);
require(downcasted == value, "SafeCast: value doesn't fit in 64 bits");
}
/**
* @dev Returns the downcasted int56 from int256, reverting on
* overflow (when the input is less than smallest int56 or
* greater than largest int56).
*
* Counterpart to Solidity's `int56` operator.
*
* Requirements:
*
* - input must fit into 56 bits
*
* _Available since v4.7._
*/
function toInt56(int256 value) internal pure returns (int56 downcasted) {
downcasted = int56(value);
require(downcasted == value, "SafeCast: value doesn't fit in 56 bits");
}
/**
* @dev Returns the downcasted int48 from int256, reverting on
* overflow (when the input is less than smallest int48 or
* greater than largest int48).
*
* Counterpart to Solidity's `int48` operator.
*
* Requirements:
*
* - input must fit into 48 bits
*
* _Available since v4.7._
*/
function toInt48(int256 value) internal pure returns (int48 downcasted) {
downcasted = int48(value);
require(downcasted == value, "SafeCast: value doesn't fit in 48 bits");
}
/**
* @dev Returns the downcasted int40 from int256, reverting on
* overflow (when the input is less than smallest int40 or
* greater than largest int40).
*
* Counterpart to Solidity's `int40` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*
* _Available since v4.7._
*/
function toInt40(int256 value) internal pure returns (int40 downcasted) {
downcasted = int40(value);
require(downcasted == value, "SafeCast: value doesn't fit in 40 bits");
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32 downcasted) {
downcasted = int32(value);
require(downcasted == value, "SafeCast: value doesn't fit in 32 bits");
}
/**
* @dev Returns the downcasted int24 from int256, reverting on
* overflow (when the input is less than smallest int24 or
* greater than largest int24).
*
* Counterpart to Solidity's `int24` operator.
*
* Requirements:
*
* - input must fit into 24 bits
*
* _Available since v4.7._
*/
function toInt24(int256 value) internal pure returns (int24 downcasted) {
downcasted = int24(value);
require(downcasted == value, "SafeCast: value doesn't fit in 24 bits");
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16 downcasted) {
downcasted = int16(value);
require(downcasted == value, "SafeCast: value doesn't fit in 16 bits");
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8 downcasted) {
downcasted = int8(value);
require(downcasted == value, "SafeCast: value doesn't fit in 8 bits");
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*
* _Available since v3.0._
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
SignedMath.sol 43 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)
pragma solidity ^0.8.0;
/**
* @dev Standard signed math utilities missing in the Solidity language.
*/
library SignedMath {
/**
* @dev Returns the largest of two signed numbers.
*/
function max(int256 a, int256 b) internal pure returns (int256) {
return a > b ? a : b;
}
/**
* @dev Returns the smallest of two signed numbers.
*/
function min(int256 a, int256 b) internal pure returns (int256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two signed numbers without overflow.
* The result is rounded towards zero.
*/
function average(int256 a, int256 b) internal pure returns (int256) {
// Formula from the book "Hacker's Delight"
int256 x = (a & b) + ((a ^ b) >> 1);
return x + (int256(uint256(x) >> 255) & (a ^ b));
}
/**
* @dev Returns the absolute unsigned value of a signed value.
*/
function abs(int256 n) internal pure returns (uint256) {
unchecked {
// must be unchecked in order to support `n = type(int256).min`
return uint256(n >= 0 ? n : -n);
}
}
}
ReentrancyGuard.sol 77 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @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 ReentrancyGuard {
// 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;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_nonReentrantBefore();
_;
_nonReentrantAfter();
}
function _nonReentrantBefore() private {
// On the first call to nonReentrant, _status will be _NOT_ENTERED
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
}
function _nonReentrantAfter() private {
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
/**
* @dev Returns true if the reentrancy guard is currently set to "entered", which indicates there is a
* `nonReentrant` function in the call stack.
*/
function _reentrancyGuardEntered() internal view returns (bool) {
return _status == _ENTERED;
}
}
ECDSA.sol 217 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV // Deprecated in v4.8
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
/// @solidity memory-safe-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
/// @solidity memory-safe-assembly
assembly {
mstore(0x00, "\x19Ethereum Signed Message:\n32")
mstore(0x1c, hash)
message := keccak256(0x00, 0x3c)
}
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {
/// @solidity memory-safe-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, "\x19\x01")
mstore(add(ptr, 0x02), domainSeparator)
mstore(add(ptr, 0x22), structHash)
data := keccak256(ptr, 0x42)
}
}
/**
* @dev Returns an Ethereum Signed Data with intended validator, created from a
* `validator` and `data` according to the version 0 of EIP-191.
*
* See {recover}.
*/
function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x00", validator, data));
}
}
EIP712.sol 142 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/EIP712.sol)
pragma solidity ^0.8.8;
import "./ECDSA.sol";
import "../ShortStrings.sol";
import "../../interfaces/IERC5267.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* NOTE: In the upgradeable version of this contract, the cached values will correspond to the address, and the domain
* separator of the implementation contract. This will cause the `_domainSeparatorV4` function to always rebuild the
* separator from the immutable values, which is cheaper than accessing a cached version in cold storage.
*
* _Available since v3.4._
*
* @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment
*/
abstract contract EIP712 is IERC5267 {
using ShortStrings for *;
bytes32 private constant _TYPE_HASH =
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _cachedDomainSeparator;
uint256 private immutable _cachedChainId;
address private immutable _cachedThis;
bytes32 private immutable _hashedName;
bytes32 private immutable _hashedVersion;
ShortString private immutable _name;
ShortString private immutable _version;
string private _nameFallback;
string private _versionFallback;
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
_name = name.toShortStringWithFallback(_nameFallback);
_version = version.toShortStringWithFallback(_versionFallback);
_hashedName = keccak256(bytes(name));
_hashedVersion = keccak256(bytes(version));
_cachedChainId = block.chainid;
_cachedDomainSeparator = _buildDomainSeparator();
_cachedThis = address(this);
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (address(this) == _cachedThis && block.chainid == _cachedChainId) {
return _cachedDomainSeparator;
} else {
return _buildDomainSeparator();
}
}
function _buildDomainSeparator() private view returns (bytes32) {
return keccak256(abi.encode(_TYPE_HASH, _hashedName, _hashedVersion, block.chainid, address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
/**
* @dev See {EIP-5267}.
*
* _Available since v4.9._
*/
function eip712Domain()
public
view
virtual
override
returns (
bytes1 fields,
string memory name,
string memory version,
uint256 chainId,
address verifyingContract,
bytes32 salt,
uint256[] memory extensions
)
{
return (
hex"0f", // 01111
_name.toStringWithFallback(_nameFallback),
_version.toStringWithFallback(_versionFallback),
block.chainid,
address(this),
bytes32(0),
new uint256[](0)
);
}
}
SafeERC20.sol 143 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.3) (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../extensions/IERC20Permit.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;
/**
* @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
/**
* @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the
* calling contract. If `token` returns no value, non-reverting calls are assumed to be successful.
*/
function safeTransferFrom(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));
}
/**
* @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 oldAllowance = token.allowance(address(this), spender);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value));
}
/**
* @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful.
*/
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value));
}
}
/**
* @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value,
* non-reverting calls are assumed to be successful. Meant to be used with tokens that require the approval
* to be set to zero before setting it to a non-zero value, such as USDT.
*/
function forceApprove(IERC20 token, address spender, uint256 value) internal {
bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value);
if (!_callOptionalReturnBool(token, approvalCall)) {
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0));
_callOptionalReturn(token, approvalCall);
}
}
/**
* @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`.
* Revert on invalid signature.
*/
function safePermit(
IERC20Permit token,
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) internal {
uint256 nonceBefore = token.nonces(owner);
token.permit(owner, spender, value, deadline, v, r, s);
uint256 nonceAfter = token.nonces(owner);
require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(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");
require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*
* This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead.
*/
function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false
// and not revert is the subcall reverts.
(bool success, bytes memory returndata) = address(token).call(data);
return
success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token));
}
}
ERC20Permit.sol 95 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/ERC20Permit.sol)
pragma solidity ^0.8.0;
import "./IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/cryptography/EIP712.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation 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.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping(address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private constant _PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev In previous versions `_PERMIT_TYPEHASH` was declared as `immutable`.
* However, to ensure consistency with the upgradeable transpiler, we will continue
* to reserve a slot.
* @custom:oz-renamed-from _PERMIT_TYPEHASH
*/
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH_DEPRECATED_SLOT;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline));
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
IERC20Permit.sol 60 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
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);
}
Read Contract
DOMAIN_SEPARATOR 0x3644e515 → bytes32
adapter 0x03eadcfc → address
allowance 0xdd62ed3e → uint256
balanceOf 0x70a08231 → uint256
convertToPrincipal 0x25a8d87d → uint256
convertToUnderlying 0x1dc7f521 → uint256
decimals 0x313ce567 → uint8
eip712Domain 0x84b0196e → bytes1, string, string, uint256, address, bytes32, uint256[]
feeRecipient 0x46904840 → address
getGlobalScales 0x0835dda7 → tuple
getSeries 0xe6432a34 → tuple
lscales 0x840e493f → uint256
management 0x88a8d602 → address
maturity 0x204f83f9 → uint256
maxRedeem 0xd905777e → uint256
maxWithdraw 0xce96cb77 → uint256
name 0x06fdde03 → string
nonces 0x7ecebe00 → uint256
paused 0x5c975abb → bool
previewCollect 0xfafe6cad → uint256
previewRedeem 0x4cdad506 → uint256
previewWithdraw 0x0a28a477 → uint256
protocolFees 0x1ad8b03b → uint256
symbol 0x95d89b41 → string
target 0xd4b83992 → address
totalSupply 0x18160ddd → uint256
unclaimedYields 0xe2230f60 → uint256
underlying 0x6f307dc3 → address
yieldToken 0x76d5de85 → address
Write Contract 17 functions
These functions modify contract state and require a wallet transaction to execute.
approve 0x095ea7b3
address spender
uint256 amount
returns: bool
claimProtocolFees 0x4a7d0369
No parameters
collect 0xe5225381
No parameters
returns: uint256
decreaseAllowance 0xa457c2d7
address spender
uint256 subtractedValue
returns: bool
increaseAllowance 0x39509351
address spender
uint256 addedValue
returns: bool
issue 0x867904b4
address to
uint256 underlyingAmount
returns: uint256
pause 0x8456cb59
No parameters
permit 0xd505accf
address owner
address spender
uint256 value
uint256 deadline
uint8 v
bytes32 r
bytes32 s
recoverERC20 0x886f039a
address token
address recipient
redeem 0xba087652
uint256 principalAmount
address to
address from
returns: uint256
redeemWithYT 0x927d7953
address from
address to
uint256 pyAmount
returns: uint256
setFeeRecipient 0xe74b981b
address _feeRecipient
transfer 0xa9059cbb
address to
uint256 amount
returns: bool
transferFrom 0x23b872dd
address from
address to
uint256 amount
returns: bool
unpause 0x3f4ba83a
No parameters
updateUnclaimedYield 0xefb2873c
address from
address to
uint256 value
withdraw 0xb460af94
uint256 underlyingAmount
address to
address from
returns: uint256
Token Balances (1)
View Transfers →Recent Transactions
No transactions found for this address