Address Contract Verified
Address
0x797B173A2C31fd34b0BeBf5f0C64ec70372b2d2f
Balance
0 ETH
Nonce
28
Code Size
8177 bytes
Creator
0x2532C3D3...8154 at tx 0x7a976798...579d04
Indexed Transactions
0
Contract Bytecode
8177 bytes
0x6080604052600436101561001257600080fd5b60003560e01c8062774360146101a657806306c75b6a146101a157806331c315df1461019c57806336683100146101975780634793221d14610192578063492924271461018d5780634bc66f32146101885780635399212a1461018357806354fd4d501461017e578063607b6d161461017957806368bde41f14610174578063692857271461016f5780636c191eee1461016a578063715018a61461016557806371ad727c146101605780637bc028061461015b5780637ec9e1561461015657806382beee8914610151578063854cff2f1461014c5780638bad38dd146101475780638da5cb5b14610142578063a1f31aa41461013d578063a91ee0dc14610138578063bdacb303146101335763f2fde38b1461012e57600080fd5b610fea565b610f6a565b610eea565b610ec3565b610e9c565b610e1c565b610d9c565b610d1c565b610cf5565b610cce565b610ca7565b610c4a565b610b62565b610b0e565b610ae7565b610a57565b610a2d565b6109d0565b610961565b61093a565b610811565b6106fd565b61069e565b610557565b610270565b634e487b7160e01b600052604160045260246000fd5b67ffffffffffffffff81116101d557604052565b6101ab565b6040810190811067ffffffffffffffff8211176101d557604052565b90601f8019910116810190811067ffffffffffffffff8211176101d557604052565b67ffffffffffffffff81116101d557601f01601f191660200190565b92919261024082610218565b9161024e60405193846101f6565b82948184528183011161026b578281602093846000960137010152565b600080fd5b3461026b5760208060031936011261026b576004803567ffffffffffffffff811161026b573660238201121561026b576102b39036906024818501359101610234565b906102d86102cc6102cc6007546001600160a01b031690565b6001600160a01b031690565b9060409184835180927fdb8c056a0000000000000000000000000000000000000000000000000000000082528180610322338883019190916001600160a01b036020820193169052565b03915afa9081156104fe5760009161052a575b501561050357825161034d90840185018486016116d5565b50505050505050906001600160a01b038080921692169261036e848461120a565b969092600354610384906001600160a01b031690565b988354610397906001600160a01b031690565b6005546001600160a01b031689516001600160a01b039c8d16848201908152928d1660208401529b1660408201528a906060010390601f19918281018c526103df908c6101f6565b856103e988611d8a565b8a519b8c938401926103fa93611758565b03908101895261040a90896101f6565b610415888a84611898565b97600654610429906001600160a01b031690565b6001600160a01b0316803b1561026b5788517fc2b7bbb60000000000000000000000000000000000000000000000000000000081526001600160a01b038b1695810195865294600091869182908490829060200103925af19081156104fe576104e19a7f9303649990c462969a3c46d4e2c758166e92f5a4b18c67f26d3e58d2b0660e67956104c6936104e5575b5089519485948c16978561178b565b0390a4516001600160a01b0390911681529081906020820190565b0390f35b806104f26104f8926101c1565b806106f2565b386104b7565b6111a5565b90517f93afd589000000000000000000000000000000000000000000000000000000008152fd5b61054a9150853d8711610550575b61054281836101f6565b8101906116bd565b38610335565b503d610538565b3461026b5760208060031936011261026b5760043567ffffffffffffffff80821161026b573660238301121561026b57816004013590811161026b576024820191602482369201011161026b5782906105ae6110c6565b6105b9368285610234565b926132c8926105cb8486511015611ee4565b60405190600882019560086132d084019101905b80881061066557505050839461060b948252601f80199101166040526001600160a01b039384916115db565b16936001600160a01b031994856001541617600155821161062857005b6132c71982018281116106605761064761064c92610651943691610234565b611f2f565b6115db565b16906002541617600255600080f35b6111b1565b8151885296820196908201906105df565b602090600319011261026b5760043590565b634e487b7160e01b600052603260045260246000fd5b3461026b576106ac36610676565b60095481101561026b576001600160a01b0360209160096000527f6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af015416604051908152f35b600091031261026b57565b3461026b57600036600319011261026b576020600954604051908152f35b67ffffffffffffffff81116101d55760051b60200190565b6001600160a01b0381160361026b57565b60208060031983011261026b576004359167ffffffffffffffff831161026b578060238401121561026b57826004013561077d8161071b565b9361078b60405195866101f6565b81855260248486019260051b82010192831161026b57602401905b8282106107b4575050505090565b83809183356107c281610733565b8152019101906107a6565b6020908160408183019282815285518094520193019160005b8281106107f4575050505090565b83516001600160a01b0316855293810193928101926001016107e6565b3461026b5761081f36610744565b6108346102cc6003546001600160a01b031690565b330361091057805161084581611a86565b9060005b81811061085e57604051806104e185826107cd565b6001600160a01b036108806108738387611884565b516001600160a01b031690565b1690813b1561026b576000806001936004604051809481937f8456cb590000000000000000000000000000000000000000000000000000000083525af190816108fd575b506108d0575b01610849565b6108f86108e06108738388611884565b6108ea8387611884565b906001600160a01b03169052565b6108ca565b806104f261090a926101c1565b386108c4565b60046040517fd8ebffc4000000000000000000000000000000000000000000000000000000008152fd5b3461026b57600036600319011261026b5760206001600160a01b0360035416604051908152f35b3461026b57600036600319011261026b5760206001600160a01b0360055416604051908152f35b60005b83811061099b5750506000910152565b818101518382015260200161098b565b906020916109c481518092818552858086019101610988565b601f01601f1916010190565b3461026b57604036600319011261026b57610a1f6104e1610a086004356109f681610733565b60243590610a0382610733565b61120a565b6040929192519384936040855260408501906109ab565b9083820360208501526109ab565b3461026b57600036600319011261026b576060604051600481526001602082015260006040820152f35b3461026b57600036600319011261026b57604051806009549182815260208091019260096000527f6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af916000905b828210610ac7576104e185610abb818903826101f6565b604051918291826107cd565b83546001600160a01b031686529485019460019384019390910190610aa4565b3461026b57600036600319011261026b5760206001600160a01b0360045416604051908152f35b3461026b57610b1c36610676565b60085481101561026b576001600160a01b0360209160086000527ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee3015416604051908152f35b3461026b57610b7036610744565b610b786110c6565b805167ffffffffffffffff81116101d5576801000000000000000081116101d55760085481600855808210610c03575b50600860005260209182017ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee39260005b838110610be157005b60019082610bf685516001600160a01b031690565b9401938187015501610bd8565b600060088152827ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee392830192015b828110610c3f575050610ba8565b818155600101610c31565b3461026b57600080600319360112610ca457610c646110c6565b806001600160a01b0381546001600160a01b031981168355167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08280a380f35b80fd5b3461026b57600036600319011261026b5760206001600160a01b0360065416604051908152f35b3461026b57600036600319011261026b5760206001600160a01b0360015416604051908152f35b3461026b57600036600319011261026b5760206001600160a01b0360025416604051908152f35b3461026b57602036600319011261026b57600435610d3981610733565b610d416110c6565b600354604080516001600160a01b038084168252848116602083015292936001600160a01b0319939290917f4cb8c9e37efb94c6cdbd2a80fe36cee1957b5584d1a1986fa2bae115180af59a9190a116911617600355600080f35b3461026b57602036600319011261026b57600435610db981610733565b610dc16110c6565b600754604080516001600160a01b038084168252848116602083015292936001600160a01b0319939290917fe8664b925e623f88e598288ed83ff0a0c9b17d50f56ec07db74f075ca4c1d57b9190a116911617600755600080f35b3461026b57602036600319011261026b57600435610e3981610733565b610e416110c6565b600454604080516001600160a01b038084168252848116602083015292936001600160a01b0319939290917ff45d882a72fce9d8d7a7e2e196a338d4d9d4057510b4b9ddf91a7066104d2eaf9190a116911617600455600080f35b3461026b57600036600319011261026b5760206001600160a01b0360005416604051908152f35b3461026b57600036600319011261026b5760206001600160a01b0360075416604051908152f35b3461026b57602036600319011261026b57600435610f0781610733565b610f0f6110c6565b600654604080516001600160a01b038084168252848116602083015292936001600160a01b0319939290917fa6cdf06494ab3c79fae6cca5316f6324ff80979c2a51d8f239aee07a4aecd35b9190a116911617600655600080f35b3461026b57602036600319011261026b57600435610f8781610733565b610f8f6110c6565b600554604080516001600160a01b038084168252848116602083015292936001600160a01b0319939290917f91aa98337922135c1d3ae8654f8d0b938c01a35c402eb21e568af3755e4dcd799190a116911617600555600080f35b3461026b57602036600319011261026b5760043561100781610733565b61100f6110c6565b6001600160a01b03809116801561105c576000918254826001600160a01b03198216178455167f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e08380a380f35b608460405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201527f64647265737300000000000000000000000000000000000000000000000000006064820152fd5b6001600160a01b036000541633036110da57565b606460405162461bcd60e51b815260206004820152602060248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e65726044820152fd5b60405190600854808352826020918282019060086000527ff3f7a9fe364faab93b216da50a3214154f22a0a2b415b23a84c8169e8b636ee3936000905b82821061117357505050611171925003836101f6565b565b85546001600160a01b03168452600195860195889550938101939091019061115b565b9081602091031261026b575190565b6040513d6000823e3d90fd5b634e487b7160e01b600052601160045260246000fd5b906001820180921161066057565b90601f820180921161066057565b906132c891820180921161066057565b9061120660209282815194859201610988565b0190565b919060049060206112296102cc6102cc6006546001600160a01b031690565b604051938480927f366831000000000000000000000000000000000000000000000000000000000082525afa9182156104fe57600092611429575b506001600160a01b038094169361127a85611b17565b911661128581611d46565b9161128f846111c7565b6112989061148b565b6040517f53747572647920496e7465726573742042656172696e672000000000000000006020820152938492603884016112d1916111f3565b7f20280000000000000000000000000000000000000000000000000000000000008152600201611300916111f3565b602960f81b81526001017f202d2000000000000000000000000000000000000000000000000000000000008152600301611339916111f3565b0391601f1992838101825261134e90826101f6565b9461135890611b17565b9061136290611b17565b9261136c906111c7565b6113759061148b565b6040517f66000000000000000000000000000000000000000000000000000000000000006020820152938492602184016113ae916111f3565b7f280000000000000000000000000000000000000000000000000000000000000081526001016113dd916111f3565b602960f81b81526001017f2d000000000000000000000000000000000000000000000000000000000000008152600101611416916111f3565b03908101825261142690826101f6565b90565b61144b91925060203d8111611452575b61144381836101f6565b810190611196565b9038611264565b503d611439565b9061146382610218565b61147060405191826101f6565b8281528092611481601f1991610218565b0190602036910137565b806000917a184f03e93ff9f4daa797ed6e38ed64bf6a1f010000000000000000808210156115cd575b506d04ee2d6d415b85acef8100000000808310156115be575b50662386f26fc10000808310156115af575b506305f5e100808310156115a0575b5061271080831015611591575b506064821015611581575b600a80921015611577575b600190816021611522828701611459565b95860101905b611534575b5050505090565b600019019083907f30313233343536373839616263646566000000000000000000000000000000008282061a83530491821561157257919082611528565b61152d565b9160010191611511565b9190606460029104910191611506565b600491939204910191386114fb565b600891939204910191386114ee565b601091939204910191386114df565b602091939204910191386114cd565b6040935081049150386114b4565b604051906116116021836020810193600085526116018151809260208686019101610988565b81010360018101855201836101f6565b611662602b604051809361165260208301967f600b5981380380925939f3000000000000000000000000000000000000000000885251809285850190610988565b810103600b8101845201826101f6565b51906000f0906001600160a01b0382161561167957565b606460405162461bcd60e51b815260206004820152601160248201527f4445504c4f594d454e545f4641494c45440000000000000000000000000000006044820152fd5b9081602091031261026b5751801515810361026b5790565b908161012091031261026b5780516116ec81610733565b9160208201516116fb81610733565b91604081015161170a81610733565b91606082015163ffffffff8116810361026b5791608081015161172c81610733565b9160a082015167ffffffffffffffff8116810361026b579160c08101519161010060e083015192015190565b9161178460ff916117766040949796976060875260608701906109ab565b9085820360208701526109ab565b9416910152565b926117b761142695936117a96117c5946080885260808801906109ab565b9086820360208801526109ab565b9084820360408601526109ab565b9160608184039101526109ab565b916117fc906117ee61142695936060865260608601906109ab565b9084820360208601526109ab565b9160408184039101526109ab565b600954680100000000000000008110156101d5576001810180600955811015611870576001600160a01b039060096000527f6e1540171b6c0c960b71a7020d9f60077f6af931a8bbf590da0223dacf75c7af0191166001600160a01b0319825416179055565b610688565b60001981146106605760010190565b80518210156118705760209160051b010190565b9190916119296001916119236119546118de6118c36118be87546001600160a01b031690565b611a56565b6118d86118be6002546001600160a01b031690565b90611e20565b95604097611948895192611935846118fb83868b602085016117d3565b039461190f601f19968781018352826101f6565b8c51998a91611923602084019e8f906111f3565b906111f3565b038581018a52896101f6565b8a5195869361192360208601809a6111f3565b039081018352826101f6565b519020905160009384f5926001600160a01b0384168015611a2d576119788561180a565b61198061111e565b84845b611991575b50505050505090565b8151811015611a28576119a76108738284611884565b833b15611a245784517f3f2617cb0000000000000000000000000000000000000000000000000000000081526001600160a01b039190911660048201526001602482015290868260448183885af19182156104fe57611a0b92611a11575b50611875565b84611983565b806104f2611a1e926101c1565b38611a05565b8680fd5b611988565b600482517f04a5b3ee000000000000000000000000000000000000000000000000000000008152fd5b803b906000198201908282116106605760019060405193603e601f19910116840160405282845260208401903c90565b90611a908261071b565b611a9d60405191826101f6565b8281528092611481601f199161071b565b3d15611ad9573d90611abf82610218565b91611acd60405193846101f6565b82523d6000602084013e565b606090565b60405190611aeb826101da565b600382527f3f3f3f00000000000000000000000000000000000000000000000000000000006020830152565b600080916040516001600160a01b0360208201917f95d89b4100000000000000000000000000000000000000000000000000000000835260048152611b5b816101da565b5192165afa611b68611aae565b9015611b775761142690611c01565b50611426611ade565b908151811015611870570160200190565b60ff1660ff81146106605760010190565b60208183031261026b5780519067ffffffffffffffff821161026b570181601f8201121561026b578051611bd581610218565b92611be360405194856101f6565b8184526020828401011161026b576114269160208085019101610988565b805160408110611c1f57508060208061142693518301019101611ba2565b602092908303611d3b576000805b60ff81168581109081611d02575b5015611c4f57611c4a90611b91565b611c2d565b92611c5d60ff809516611459565b92825b85811687811080611ccb575b15611cc0579081611cb5611cac611c86611cbb9588611b80565b517fff000000000000000000000000000000000000000000000000000000000000001690565b871a9188611b80565b53611b91565b611c60565b505094505050905090565b507fff00000000000000000000000000000000000000000000000000000000000000611cfa611c868387611b80565b161515611c6c565b7fff000000000000000000000000000000000000000000000000000000000000009150611c86611d329187611b80565b16151538611c3b565b915050611426611ade565b600080916040516001600160a01b0360208201917f06fdde0300000000000000000000000000000000000000000000000000000000835260048152611b5b816101da565b6001600160a01b0360405160208101927f313ce56700000000000000000000000000000000000000000000000000000000845260048252611dca826101da565b600093849384935192165afa611dde611aae565b9080611e15575b15611e0e57602081805181010312611e0a57602001519060ff82168203610ca4575090565b5080fd5b5050601290565b506020815114611de5565b6040519181518084526020808501918501928184019282808701915b858110611e895750505080518093875182018852940193828086019201905b828110611e7a575050505090603f91601f199351011501011660405290565b81518152908301908301611e5b565b8251815291810191849101611e3c565b15611ea057565b606460405162461bcd60e51b815260206004820152600e60248201527f736c6963655f6f766572666c6f770000000000000000000000000000000000006044820152fd5b15611eeb57565b606460405162461bcd60e51b815260206004820152601160248201527f736c6963655f6f75744f66426f756e64730000000000000000000000000000006044820152fd5b611f4382611f3c816111d5565b1015611e99565b611f588151611f51846111e3565b1115611ee4565b81611f70575050604051600081526020810160405290565b60405191601f8116916132c8831560051b80858701019484860193010101905b808410611fa85750508252601f01601f191660405290565b9092835181526020809101930190611f9056fea2646970667358221220d0f9f659a5c6121c4992559e7e9f442d617dd2f691782bc93ca88172ffbda4d564736f6c63430008150033
Verified Source Code Full Match
Compiler: v0.8.21+commit.d9974bed
EVM: paris
Optimization: Yes (1660 runs)
SturdyPairDeployer.sol 314 lines
// SPDX-License-Identifier: ISC
pragma solidity ^0.8.21;
// ====================== SturdyPairDeployer ========================
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { Strings } from "@openzeppelin/contracts/utils/Strings.sol";
import { SSTORE2 } from "@rari-capital/solmate/src/utils/SSTORE2.sol";
import { BytesLib } from "solidity-bytes-utils/contracts/BytesLib.sol";
import { ISturdyWhitelist } from "./interfaces/ISturdyWhitelist.sol";
import { ISturdyPair } from "./interfaces/ISturdyPair.sol";
import { ISturdyPairRegistry } from "./interfaces/ISturdyPairRegistry.sol";
import { SafeERC20 } from "./libraries/SafeERC20.sol";
// solhint-disable no-inline-assembly
struct ConstructorParams {
address circuitBreaker;
address comptroller;
address timelock;
address sturdyWhitelist;
address sturdyPairRegistry;
}
/// @title SturdyPairDeployer
/// @author Drake Evans (Frax Finance) https://github.com/drakeevans
/// @notice Deploys and initializes new SturdyPairs
/// @dev Uses create2 to deploy the pairs, logs an event, and records a list of all deployed pairs
contract SturdyPairDeployer is Ownable {
using Strings for uint256;
using SafeERC20 for IERC20;
// Storage
address public contractAddress1;
address public contractAddress2;
// Admin contracts
address public circuitBreakerAddress;
address public comptrollerAddress;
address public timelockAddress;
address public sturdyPairRegistryAddress;
address public sturdyWhitelistAddress;
// Default swappers
address[] public defaultSwappers;
/// @notice Emits when a new pair is deployed
/// @notice The ```LogDeploy``` event is emitted when a new Pair is deployed
/// @param address_ The address of the pair
/// @param asset The address of the Asset Token contract
/// @param collateral The address of the Collateral Token contract
/// @param name The name of the Pair
/// @param configData The config data of the Pair
/// @param immutables The immutables of the Pair
/// @param customConfigData The custom config data of the Pair
event LogDeploy(
address indexed address_,
address indexed asset,
address indexed collateral,
string name,
bytes configData,
bytes immutables,
bytes customConfigData
);
/// @notice List of the names of all deployed Pairs
address[] public deployedPairsArray;
constructor(ConstructorParams memory _params) Ownable() {
circuitBreakerAddress = _params.circuitBreaker;
comptrollerAddress = _params.comptroller;
timelockAddress = _params.timelock;
sturdyWhitelistAddress = _params.sturdyWhitelist;
sturdyPairRegistryAddress = _params.sturdyPairRegistry;
}
function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch) {
return (4, 1, 0);
}
// ============================================================================================
// Functions: View Functions
// ============================================================================================
/// @notice The ```deployedPairsLength``` function returns the length of the deployedPairsArray
/// @return length of array
function deployedPairsLength() external view returns (uint256) {
return deployedPairsArray.length;
}
/// @notice The ```getAllPairAddresses``` function returns all pair addresses in deployedPairsArray
/// @return _deployedPairs memory All deployed pair addresses
function getAllPairAddresses() external view returns (address[] memory _deployedPairs) {
_deployedPairs = deployedPairsArray;
}
function getNextNameSymbol(
address _asset,
address _collateral
) public view returns (string memory _name, string memory _symbol) {
uint256 _length = ISturdyPairRegistry(sturdyPairRegistryAddress).deployedPairsLength();
_name = string(
abi.encodePacked(
"Sturdy Interest Bearing ",
IERC20(_asset).safeSymbol(),
" (",
IERC20(_collateral).safeName(),
")",
" - ",
(_length + 1).toString()
)
);
_symbol = string(
abi.encodePacked(
"f",
IERC20(_asset).safeSymbol(),
"(",
IERC20(_collateral).safeSymbol(),
")",
"-",
(_length + 1).toString()
)
);
}
// ============================================================================================
// Functions: Setters
// ============================================================================================
/// @notice The ```setCreationCode``` function sets the bytecode for the sturdyPair
/// @dev splits the data if necessary to accommodate creation code that is slightly larger than 24kb
/// @param _creationCode The creationCode for the Sturdy Pair
function setCreationCode(bytes calldata _creationCode) external onlyOwner {
bytes memory _firstHalf = BytesLib.slice(_creationCode, 0, 13_000);
contractAddress1 = SSTORE2.write(_firstHalf);
if (_creationCode.length > 13_000) {
bytes memory _secondHalf = BytesLib.slice(_creationCode, 13_000, _creationCode.length - 13_000);
contractAddress2 = SSTORE2.write(_secondHalf);
}
}
/// @notice The ```setDefaultSwappers``` function is used to set default list of approved swappers
/// @param _swappers The list of swappers to set as default allowed
function setDefaultSwappers(address[] memory _swappers) external onlyOwner {
defaultSwappers = _swappers;
}
/// @notice The ```SetTimelock``` event is emitted when the timelockAddress is set
/// @param oldAddress The original address
/// @param newAddress The new address
event SetTimelock(address oldAddress, address newAddress);
/// @notice The ```setTimelock``` function sets the timelockAddress
/// @param _newAddress the new time lock address
function setTimelock(address _newAddress) external onlyOwner {
emit SetTimelock(timelockAddress, _newAddress);
timelockAddress = _newAddress;
}
/// @notice The ```SetRegistry``` event is emitted when the sturdyPairRegistryAddress is set
/// @param oldAddress The old address
/// @param newAddress The new address
event SetRegistry(address oldAddress, address newAddress);
/// @notice The ```setRegistry``` function sets the sturdyPairRegistryAddress
/// @param _newAddress The new address
function setRegistry(address _newAddress) external onlyOwner {
emit SetRegistry(sturdyPairRegistryAddress, _newAddress);
sturdyPairRegistryAddress = _newAddress;
}
/// @notice The ```SetComptroller``` event is emitted when the comptrollerAddress is set
/// @param oldAddress The old address
/// @param newAddress The new address
event SetComptroller(address oldAddress, address newAddress);
/// @notice The ```setComptroller``` function sets the comptrollerAddress
/// @param _newAddress The new address
function setComptroller(address _newAddress) external onlyOwner {
emit SetComptroller(comptrollerAddress, _newAddress);
comptrollerAddress = _newAddress;
}
/// @notice The ```SetWhitelist``` event is emitted when the sturdyWhitelistAddress is set
/// @param oldAddress The old address
/// @param newAddress The new address
event SetWhitelist(address oldAddress, address newAddress);
/// @notice The ```setWhitelist``` function sets the sturdyWhitelistAddress
/// @param _newAddress The new address
function setWhitelist(address _newAddress) external onlyOwner {
emit SetWhitelist(sturdyWhitelistAddress, _newAddress);
sturdyWhitelistAddress = _newAddress;
}
/// @notice The ```SetCircuitBreaker``` event is emitted when the circuitBreakerAddress is set
/// @param oldAddress The old address
/// @param newAddress The new address
event SetCircuitBreaker(address oldAddress, address newAddress);
/// @notice The ```setCircuitBreaker``` function sets the circuitBreakerAddress
/// @param _newAddress The new address
function setCircuitBreaker(address _newAddress) external onlyOwner {
emit SetCircuitBreaker(circuitBreakerAddress, _newAddress);
circuitBreakerAddress = _newAddress;
}
// ============================================================================================
// Functions: Internal Methods
// ============================================================================================
/// @notice The ```_deploy``` function is an internal function with deploys the pair
/// @param _configData abi.encode(address _asset, address _collateral, address _oracle, uint32 _maxOracleDeviation, address _rateContract, uint64 _fullUtilizationRate, uint256 _maxLTV, uint256 _cleanLiquidationFee, uint256 _dirtyLiquidationFee, uint256 _protocolLiquidationFee)
/// @param _immutables abi.encode(address _circuitBreakerAddress, address _comptrollerAddress, address _timelockAddress)
/// @param _customConfigData abi.encode(string memory _nameOfContract, string memory _symbolOfContract, uint8 _decimalsOfContract)
/// @return _pairAddress The address to which the Pair was deployed
function _deploy(
bytes memory _configData,
bytes memory _immutables,
bytes memory _customConfigData
) private returns (address _pairAddress) {
// Get creation code
bytes memory _creationCode = BytesLib.concat(SSTORE2.read(contractAddress1), SSTORE2.read(contractAddress2));
// Get bytecode
bytes memory bytecode = abi.encodePacked(
_creationCode,
abi.encode(_configData, _immutables, _customConfigData)
);
// Generate salt using constructor params
bytes32 salt = keccak256(abi.encodePacked(_configData, _immutables, _customConfigData));
/// @solidity memory-safe-assembly
assembly {
_pairAddress := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
if (_pairAddress == address(0)) revert Create2Failed();
deployedPairsArray.push(_pairAddress);
// Set additional values for SturdyPair
ISturdyPair _sturdyPair = ISturdyPair(_pairAddress);
address[] memory _defaultSwappers = defaultSwappers;
for (uint256 i = 0; i < _defaultSwappers.length; i++) {
_sturdyPair.setSwapper(_defaultSwappers[i], true);
}
return _pairAddress;
}
// ============================================================================================
// Functions: External Deploy Methods
// ============================================================================================
/// @notice The ```deploy``` function allows the deployment of a SturdyPair with default values
/// @param _configData abi.encode(address _asset, address _collateral, address _oracle, uint32 _maxOracleDeviation, address _rateContract, uint64 _fullUtilizationRate, uint256 _maxLTV, uint256 _cleanLiquidationFee, uint256 _dirtyLiquidationFee, uint256 _protocolLiquidationFee)
/// @return _pairAddress The address to which the Pair was deployed
function deploy(bytes memory _configData) external returns (address _pairAddress) {
if (!ISturdyWhitelist(sturdyWhitelistAddress).sturdyDeployerWhitelist(msg.sender)) {
revert WhitelistedDeployersOnly();
}
(address _asset, address _collateral, , , , , , , ) = abi.decode(
_configData,
(address, address, address, uint32, address, uint64, uint256, uint256, uint256)
);
(string memory _name, string memory _symbol) = getNextNameSymbol(_asset, _collateral);
bytes memory _immutables = abi.encode(circuitBreakerAddress, comptrollerAddress, timelockAddress);
bytes memory _customConfigData = abi.encode(_name, _symbol, IERC20(_asset).safeDecimals());
_pairAddress = _deploy(_configData, _immutables, _customConfigData);
ISturdyPairRegistry(sturdyPairRegistryAddress).addPair(_pairAddress);
emit LogDeploy(_pairAddress, _asset, _collateral, _name, _configData, _immutables, _customConfigData);
}
// ============================================================================================
// Functions: Admin
// ============================================================================================
/// @notice The ```globalPause``` function calls the pause() function on a given set of pair addresses
/// @dev Ignores reverts when calling pause()
/// @param _addresses Addresses to attempt to pause()
/// @return _updatedAddresses Addresses for which pause() was successful
function globalPause(address[] memory _addresses) external returns (address[] memory _updatedAddresses) {
if (msg.sender != circuitBreakerAddress) revert CircuitBreakerOnly();
address _pairAddress;
uint256 _lengthOfArray = _addresses.length;
_updatedAddresses = new address[](_lengthOfArray);
for (uint256 i = 0; i < _lengthOfArray; ) {
_pairAddress = _addresses[i];
try ISturdyPair(_pairAddress).pause() {
_updatedAddresses[i] = _addresses[i];
} catch {}
unchecked {
i = i + 1;
}
}
}
// ============================================================================================
// Errors
// ============================================================================================
error CircuitBreakerOnly();
error WhitelistedDeployersOnly();
error Create2Failed();
}
SafeERC20.sol 67 lines
// SPDX-License-Identifier: ISC
pragma solidity ^0.8.21;
import { IERC20 } from "@openzeppelin/contracts/interfaces/IERC20.sol";
import { SafeERC20 as OZSafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
// solhint-disable avoid-low-level-calls
// solhint-disable max-line-length
/// @title SafeERC20 provides helper functions for safe transfers as well as safe metadata access
/// @author Library originally written by @Boring_Crypto github.com/boring_crypto, modified by Drake Evans (Frax Finance) github.com/drakeevans
/// @dev original: https://github.com/boringcrypto/BoringSolidity/blob/fed25c5d43cb7ce20764cd0b838e21a02ea162e9/contracts/libraries/BoringERC20.sol
library SafeERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
function returnDataToString(bytes memory data) internal pure returns (string memory) {
if (data.length >= 64) {
return abi.decode(data, (string));
} else if (data.length == 32) {
uint8 i = 0;
while (i < 32 && data[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && data[i] != 0; i++) {
bytesArray[i] = data[i];
}
return string(bytesArray);
} else {
return "???";
}
}
/// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token symbol.
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token name.
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
/// @param token The address of the ERC-20 token contract.
/// @return (uint8) Token decimals.
function safeDecimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
function safeTransfer(IERC20 token, address to, uint256 value) internal {
OZSafeERC20.safeTransfer(token, to, value);
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
OZSafeERC20.safeTransferFrom(token, from, to, value);
}
}
ISturdyPair.sol 282 lines
// SPDX-License-Identifier: AGPL-3.0
pragma solidity ^0.8.21;
import { VaultAccount } from "../libraries/VaultAccount.sol";
interface ISturdyPair {
struct CurrentRateInfo {
uint32 lastBlock;
uint32 feeToProtocolRate; // Fee amount 1e5 precision
uint64 lastTimestamp;
uint64 ratePerSec;
uint64 fullUtilizationRate;
}
function CIRCUIT_BREAKER_ADDRESS() external view returns (address);
function COMPTROLLER_ADDRESS() external view returns (address);
function DEPLOYER_ADDRESS() external view returns (address);
function FRAXLEND_WHITELIST_ADDRESS() external view returns (address);
function timelockAddress() external view returns (address);
function addCollateral(uint256 _collateralAmount, address _borrower) external;
function addInterest(
bool _returnAccounting
)
external
returns (
uint256 _interestEarned,
uint256 _feesAmount,
uint256 _feesShare,
CurrentRateInfo memory _currentRateInfo,
VaultAccount memory _totalAsset,
VaultAccount memory _totalBorrow
);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function approvedBorrowers(address) external view returns (bool);
function approvedLenders(address) external view returns (bool);
function approveBorrowDelegation(address _delegatee, uint256 _amount) external;
function asset() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function borrowAsset(
uint256 _borrowAmount,
uint256 _collateralAmount,
address _receiver
) external returns (uint256 _shares);
function borrowAssetOnBehalfOf(
uint256 _borrowAmount,
address _onBehalfOf
) external returns (uint256 _shares);
function borrowerWhitelistActive() external view returns (bool);
function changeFee(uint32 _newFee) external;
function cleanLiquidationFee() external view returns (uint256);
function collateralContract() external view returns (address);
function currentRateInfo()
external
view
returns (
uint32 lastBlock,
uint32 feeToProtocolRate,
uint64 lastTimestamp,
uint64 ratePerSec,
uint64 fullUtilizationRate
);
function decimals() external view returns (uint8);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function deposit(uint256 _amount, address _receiver) external returns (uint256 _sharesReceived);
function dirtyLiquidationFee() external view returns (uint256);
function exchangeRateInfo() external view returns (address oracle, uint32 maxOracleDeviation, uint184 lastTimestamp, uint256 lowExchangeRate, uint256 highExchangeRate);
function getConstants()
external
pure
returns (
uint256 _LTV_PRECISION,
uint256 _LIQ_PRECISION,
uint256 _UTIL_PREC,
uint256 _FEE_PRECISION,
uint256 _EXCHANGE_PRECISION,
uint256 _DEVIATION_PRECISION,
uint256 _RATE_PRECISION,
uint256 _MAX_PROTOCOL_FEE
);
function getImmutableAddressBool()
external
view
returns (
address _assetContract,
address _collateralContract,
address _oracleMultiply,
address _oracleDivide,
address _rateContract,
address _DEPLOYER_CONTRACT,
address _COMPTROLLER_ADDRESS,
address _FRAXLEND_WHITELIST,
bool _borrowerWhitelistActive,
bool _lenderWhitelistActive
);
function getImmutableUint256()
external
view
returns (
uint256 _oracleNormalization,
uint256 _maxLTV,
uint256 _cleanLiquidationFee,
uint256 _maturityDate,
uint256 _penaltyRate
);
function getPairAccounting()
external
view
returns (
uint128 _totalAssetAmount,
uint128 _totalAssetShares,
uint128 _totalBorrowAmount,
uint128 _totalBorrowShares,
uint256 _totalCollateral
);
function getUserSnapshot(
address _address
) external view returns (uint256 _userAssetShares, uint256 _userBorrowShares, uint256 _userCollateralBalance);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function lenderWhitelistActive() external view returns (bool);
function leveragedPosition(
address _swapperAddress,
uint256 _borrowAmount,
uint256 _initialCollateralAmount,
uint256 _amountCollateralOutMin,
address[] memory _path
) external returns (uint256 _totalCollateralBalance);
function liquidate(
uint128 _sharesToLiquidate,
uint256 _deadline,
address _borrower
) external returns (uint256 _collateralForLiquidator);
function maturityDate() external view returns (uint256);
function maxLTV() external view returns (uint256);
function maxOracleDelay() external view returns (uint256);
function name() external view returns (string memory);
function oracleDivide() external view returns (address);
function oracleMultiply() external view returns (address);
function oracleNormalization() external view returns (uint256);
function owner() external view returns (address);
function pause() external;
function paused() external view returns (bool);
function penaltyRate() external view returns (uint256);
function rateContract() external view returns (address);
function redeem(uint256 _shares, address _receiver, address _owner) external returns (uint256 _amountToReturn);
function removeCollateral(uint256 _collateralAmount, address _receiver) external;
function removeCollateralFrom(
uint256 _collateralAmount,
address _receiver,
address _borrower
) external;
function setWhitelistedDelegators(address _delegator, bool _enabled) external;
function renounceOwnership() external;
function repayAsset(uint256 _shares, address _borrower) external returns (uint256 _amountToRepay);
function repayAssetWithCollateral(
address _swapperAddress,
uint256 _collateralToSwap,
uint256 _amountAssetOutMin,
address[] memory _path
) external returns (uint256 _amountAssetOut);
function setApprovedBorrowers(address[] memory _borrowers, bool _approval) external;
function setApprovedLenders(address[] memory _lenders, bool _approval) external;
function setMaxOracleDelay(uint256 _newDelay) external;
function setSwapper(address _swapper, bool _approval) external;
function setTimelock(address _newAddress) external;
function swappers(address) external view returns (bool);
function symbol() external view returns (string memory);
function toAssetAmount(
uint256 _shares,
bool _roundUp,
bool _previewInterest
) external view returns (uint256);
function toAssetShares(
uint256 _amount,
bool _roundUp,
bool _previewInterest
) external view returns (uint256);
function toBorrowAmount(
uint256 _shares,
bool _roundUp,
bool _previewInterest
) external view returns (uint256 _amount);
function toBorrowShares(
uint256 _amount,
bool _roundUp,
bool _previewInterest
) external view returns (uint256 _shares);
function totalAsset() external view returns (uint128 amount, uint128 shares);
function totalBorrow() external view returns (uint128 amount, uint128 shares);
function totalCollateral() external view returns (uint256);
function totalSupply() external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function transferFrom(address from, address to, uint256 amount) external returns (bool);
function transferOwnership(address newOwner) external;
function unpause() external;
function updateExchangeRate()
external
returns (bool _isBorrowAllowed, uint256 _lowExchangeRate, uint256 _highExchangeRate);
function userBorrowShares(address) external view returns (uint256);
function userCollateralBalance(address) external view returns (uint256);
function version() external pure returns (uint256 _major, uint256 _minor, uint256 _patch);
function withdrawFees(uint128 _shares, address _recipient) external returns (uint256 _amountToTransfer);
function isInterestPaused() external view returns (bool);
}
VaultAccount.sol 39 lines
// SPDX-License-Identifier: ISC
pragma solidity ^0.8.21;
struct VaultAccount {
uint128 amount; // Total amount, analogous to market cap
uint128 shares; // Total shares, analogous to shares outstanding
}
/// @title VaultAccount Library
/// @author Drake Evans (Frax Finance) github.com/drakeevans, modified from work by @Boring_Crypto github.com/boring_crypto
/// @notice Provides a library for use with the VaultAccount struct, provides convenient math implementations
/// @dev Uses uint128 to save on storage
library VaultAccountingLibrary {
/// @notice Calculates the shares value in relationship to `amount` and `total`
/// @dev Given an amount, return the appropriate number of shares
function toShares(VaultAccount memory total, uint256 amount, bool roundUp) internal pure returns (uint256 shares) {
if (total.amount == 0) {
shares = amount;
} else {
shares = (amount * total.shares) / total.amount;
if (roundUp && (shares * total.amount) / total.shares < amount) {
shares = shares + 1;
}
}
}
/// @notice Calculates the amount value in relationship to `shares` and `total`
/// @dev Given a number of shares, returns the appropriate amount
function toAmount(VaultAccount memory total, uint256 shares, bool roundUp) internal pure returns (uint256 amount) {
if (total.shares == 0) {
amount = shares;
} else {
amount = (shares * total.amount) / total.shares;
if (roundUp && (amount * total.shares) / total.amount < shares) {
amount = amount + 1;
}
}
}
}
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));
}
}
Ownable.sol 83 lines
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.9.0) (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
_checkOwner();
_;
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if the sender is not the owner.
*/
function _checkOwner() internal view virtual {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby disabling any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
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);
}
}
}
SSTORE2.sol 99 lines
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity >=0.8.0;
/// @notice Read and write to persistent storage at a fraction of the cost.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/utils/SSTORE2.sol)
/// @author Modified from 0xSequence (https://github.com/0xSequence/sstore2/blob/master/contracts/SSTORE2.sol)
library SSTORE2 {
uint256 internal constant DATA_OFFSET = 1; // We skip the first byte as it's a STOP opcode to ensure the contract can't be called.
/*//////////////////////////////////////////////////////////////
WRITE LOGIC
//////////////////////////////////////////////////////////////*/
function write(bytes memory data) internal returns (address pointer) {
// Prefix the bytecode with a STOP opcode to ensure it cannot be called.
bytes memory runtimeCode = abi.encodePacked(hex"00", data);
bytes memory creationCode = abi.encodePacked(
//---------------------------------------------------------------------------------------------------------------//
// Opcode | Opcode + Arguments | Description | Stack View //
//---------------------------------------------------------------------------------------------------------------//
// 0x60 | 0x600B | PUSH1 11 | codeOffset //
// 0x59 | 0x59 | MSIZE | 0 codeOffset //
// 0x81 | 0x81 | DUP2 | codeOffset 0 codeOffset //
// 0x38 | 0x38 | CODESIZE | codeSize codeOffset 0 codeOffset //
// 0x03 | 0x03 | SUB | (codeSize - codeOffset) 0 codeOffset //
// 0x80 | 0x80 | DUP | (codeSize - codeOffset) (codeSize - codeOffset) 0 codeOffset //
// 0x92 | 0x92 | SWAP3 | codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
// 0x59 | 0x59 | MSIZE | 0 codeOffset (codeSize - codeOffset) 0 (codeSize - codeOffset) //
// 0x39 | 0x39 | CODECOPY | 0 (codeSize - codeOffset) //
// 0xf3 | 0xf3 | RETURN | //
//---------------------------------------------------------------------------------------------------------------//
hex"60_0B_59_81_38_03_80_92_59_39_F3", // Returns all code in the contract except for the first 11 (0B in hex) bytes.
runtimeCode // The bytecode we want the contract to have after deployment. Capped at 1 byte less than the code size limit.
);
assembly {
// Deploy a new contract with the generated creation code.
// We start 32 bytes into the code to avoid copying the byte length.
pointer := create(0, add(creationCode, 32), mload(creationCode))
}
require(pointer != address(0), "DEPLOYMENT_FAILED");
}
/*//////////////////////////////////////////////////////////////
READ LOGIC
//////////////////////////////////////////////////////////////*/
function read(address pointer) internal view returns (bytes memory) {
return readBytecode(pointer, DATA_OFFSET, pointer.code.length - DATA_OFFSET);
}
function read(address pointer, uint256 start) internal view returns (bytes memory) {
start += DATA_OFFSET;
return readBytecode(pointer, start, pointer.code.length - start);
}
function read(
address pointer,
uint256 start,
uint256 end
) internal view returns (bytes memory) {
start += DATA_OFFSET;
end += DATA_OFFSET;
require(pointer.code.length >= end, "OUT_OF_BOUNDS");
return readBytecode(pointer, start, end - start);
}
/*//////////////////////////////////////////////////////////////
INTERNAL HELPER LOGIC
//////////////////////////////////////////////////////////////*/
function readBytecode(
address pointer,
uint256 start,
uint256 size
) private view returns (bytes memory data) {
assembly {
// Get a pointer to some free memory.
data := mload(0x40)
// Update the free memory pointer to prevent overriding our data.
// We use and(x, not(31)) as a cheaper equivalent to sub(x, mod(x, 32)).
// Adding 31 to size and running the result through the logic above ensures
// the memory pointer remains word-aligned, following the Solidity convention.
mstore(0x40, add(data, and(add(add(size, 32), 31), not(31))))
// Store the size of the data in the first 32 byte chunk of free memory.
mstore(data, size)
// Copy the code into memory right after the 32 bytes we used to store the size.
extcodecopy(pointer, add(data, 32), start, size)
}
}
}
BytesLib.sol 510 lines
// SPDX-License-Identifier: Unlicense /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.8.0 <0.9.0; library BytesLib { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function concatStorage(bytes storage _preBytes, bytes memory _postBytes) internal { assembly { // Read the first 32 bytes of _preBytes storage, which is the length // of the array. (We don't need to use the offset into the slot // because arrays use the entire slot.) let fslot := sload(_preBytes.slot) // Arrays of 31 bytes or less have an even value in their slot, // while longer arrays have an odd value. The actual length is // the slot divided by two for odd values, and the lowest order // byte divided by two for even values. // If the slot is even, bitwise and the slot with 255 and divide by // two to get the length. If the slot is odd, bitwise and the slot // with -1 and divide by two. let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) let newlength := add(slength, mlength) // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage switch add(lt(slength, 32), lt(newlength, 32)) case 2 { // Since the new array still fits in the slot, we just need to // update the contents of the slot. // uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length sstore( _preBytes.slot, // all the modifications to the slot are inside this // next block add( // we can just add to the slot contents because the // bytes we want to change are the LSBs fslot, add( mul( div( // load the bytes from memory mload(add(_postBytes, 0x20)), // zero all bytes to the right exp(0x100, sub(32, mlength)) ), // and now shift left the number of bytes to // leave space for the length in the slot exp(0x100, sub(32, newlength)) ), // increase length by the double of the memory // bytes length mul(mlength, 2) ) ) ) } case 1 { // The stored value fits in the slot, but the combined value // will exceed it. // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes.slot, add(mul(newlength, 2), 1)) // The contents of the _postBytes array start 32 bytes into // the structure. Our first read should obtain the `submod` // bytes that can fit into the unused space in the last word // of the stored array. To get this, we read 32 bytes starting // from `submod`, so the data we read overlaps with the array // contents by `submod` bytes. Masking the lowest-order // `submod` bytes allows us to add that value directly to the // stored value. let submod := sub(32, slength) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore( sc, add( and( fslot, 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00 ), and(mload(mc), mask) ) ) for { mc := add(mc, 0x20) sc := add(sc, 1) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } default { // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) // Start copying to the last used word of the stored array. let sc := add(keccak256(0x0, 0x20), div(slength, 32)) // save new length sstore(_preBytes.slot, add(mul(newlength, 2), 1)) // Copy over the first `submod` bytes of the new data as in // case 1 above. let slengthmod := mod(slength, 32) let mlengthmod := mod(mlength, 32) let submod := sub(32, slengthmod) let mc := add(_postBytes, submod) let end := add(_postBytes, mlength) let mask := sub(exp(0x100, submod), 1) sstore(sc, add(sload(sc), and(mload(mc), mask))) for { sc := add(sc, 1) mc := add(mc, 0x20) } lt(mc, end) { sc := add(sc, 1) mc := add(mc, 0x20) } { sstore(sc, mload(mc)) } mask := exp(0x100, sub(mc, end)) sstore(sc, mul(div(mload(mc), mask), mask)) } } } function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, "slice_overflow"); require(_bytes.length >= _start + _length, "slice_outOfBounds"); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_bytes.length >= _start + 20, "toAddress_outOfBounds"); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint256 _start) internal pure returns (uint8) { require(_bytes.length >= _start + 1 , "toUint8_outOfBounds"); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint256 _start) internal pure returns (uint16) { require(_bytes.length >= _start + 2, "toUint16_outOfBounds"); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint256 _start) internal pure returns (uint32) { require(_bytes.length >= _start + 4, "toUint32_outOfBounds"); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint256 _start) internal pure returns (uint64) { require(_bytes.length >= _start + 8, "toUint64_outOfBounds"); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint256 _start) internal pure returns (uint96) { require(_bytes.length >= _start + 12, "toUint96_outOfBounds"); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint256 _start) internal pure returns (uint128) { require(_bytes.length >= _start + 16, "toUint128_outOfBounds"); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint256(bytes memory _bytes, uint256 _start) internal pure returns (uint256) { require(_bytes.length >= _start + 32, "toUint256_outOfBounds"); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32) { require(_bytes.length >= _start + 32, "toBytes32_outOfBounds"); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function equal(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { bool success = true; assembly { let length := mload(_preBytes) // if lengths don't match the arrays are not equal switch eq(length, mload(_postBytes)) case 1 { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 let mc := add(_preBytes, 0x20) let end := add(mc, length) for { let cc := add(_postBytes, 0x20) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) } eq(add(lt(mc, end), cb), 2) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { // if any of these checks fails then arrays are not equal if iszero(eq(mload(mc), mload(cc))) { // unsuccess: success := 0 cb := 0 } } } default { // unsuccess: success := 0 } } return success; } function equalStorage( bytes storage _preBytes, bytes memory _postBytes ) internal view returns (bool) { bool success = true; assembly { // we know _preBytes_offset is 0 let fslot := sload(_preBytes.slot) // Decode the length of the stored array like in concatStorage(). let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2) let mlength := mload(_postBytes) // if lengths don't match the arrays are not equal switch eq(slength, mlength) case 1 { // slength can contain both the length and contents of the array // if length < 32 bytes so let's prepare for that // v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage if iszero(iszero(slength)) { switch lt(slength, 32) case 1 { // blank the last byte which is the length fslot := mul(div(fslot, 0x100), 0x100) if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) { // unsuccess: success := 0 } } default { // cb is a circuit breaker in the for loop since there's // no said feature for inline assembly loops // cb = 1 - don't breaker // cb = 0 - break let cb := 1 // get the keccak hash to get the contents of the array mstore(0x0, _preBytes.slot) let sc := keccak256(0x0, 0x20) let mc := add(_postBytes, 0x20) let end := add(mc, mlength) // the next line is the loop condition: // while(uint256(mc < end) + cb == 2) for {} eq(add(lt(mc, end), cb), 2) { sc := add(sc, 1) mc := add(mc, 0x20) } { if iszero(eq(sload(sc), mload(mc))) { // unsuccess: success := 0 cb := 0 } } } } } default { // unsuccess: success := 0 } } return success; } }
IERC20.sol 6 lines
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC20.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol";
ISturdyWhitelist.sol 22 lines
// SPDX-License-Identifier: ISC
pragma solidity >=0.8.21;
interface ISturdyWhitelist {
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event SetSturdyDeployerWhitelist(address indexed _address, bool _bool);
function acceptOwnership() external;
function sturdyDeployerWhitelist(address) external view returns (bool);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function renounceOwnership() external;
function setSturdyDeployerWhitelist(address[] memory _addresses, bool _bool) external;
function transferOwnership(address newOwner) external;
}
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);
}
ISturdyPairRegistry.sol 33 lines
// SPDX-License-Identifier: ISC
pragma solidity ^0.8.21;
interface ISturdyPairRegistry {
event AddPair(address pairAddress);
event OwnershipTransferStarted(address indexed previousOwner, address indexed newOwner);
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event SetDeployer(address deployer, bool _bool);
function acceptOwnership() external;
function addPair(address _pairAddress) external;
function deployedPairsArray(uint256) external view returns (address);
function deployedPairsByName(string memory) external view returns (address);
function deployedPairsLength() external view returns (uint256);
function deployers(address) external view returns (bool);
function getAllPairAddresses() external view returns (address[] memory _deployedPairsArray);
function owner() external view returns (address);
function pendingOwner() external view returns (address);
function renounceOwnership() external;
function setDeployers(address[] memory _deployers, bool _bool) external;
function transferOwnership(address newOwner) external;
}
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);
}
}
}
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));
}
}
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);
}
Read Contract
circuitBreakerAddress 0x49292427 → address
comptrollerAddress 0x68bde41f → address
contractAddress1 0x7bc02806 → address
contractAddress2 0x7ec9e156 → address
defaultSwappers 0x69285727 → address
deployedPairsArray 0x31c315df → address
deployedPairsLength 0x36683100 → uint256
getAllPairAddresses 0x607b6d16 → address[]
getNextNameSymbol 0x5399212a → string, string
owner 0x8da5cb5b → address
sturdyPairRegistryAddress 0x71ad727c → address
sturdyWhitelistAddress 0xa1f31aa4 → address
timelockAddress 0x4bc66f32 → address
version 0x54fd4d50 → uint256, uint256, uint256
Write Contract 11 functions
These functions modify contract state and require a wallet transaction to execute.
deploy 0x00774360
bytes _configData
returns: address
globalPause 0x4793221d
address[] _addresses
returns: address[]
renounceOwnership 0x715018a6
No parameters
setCircuitBreaker 0x82beee89
address _newAddress
setComptroller 0x8bad38dd
address _newAddress
setCreationCode 0x06c75b6a
bytes _creationCode
setDefaultSwappers 0x6c191eee
address[] _swappers
setRegistry 0xa91ee0dc
address _newAddress
setTimelock 0xbdacb303
address _newAddress
setWhitelist 0x854cff2f
address _newAddress
transferOwnership 0xf2fde38b
address newOwner
Recent Transactions
No transactions found for this address