Contract Overview
[ Download CSV Export ]
Latest 1 internal transaction
Parent Txn Hash | Block | From | To | Value | |||
---|---|---|---|---|---|---|---|
0x75b7612ee1c2bab6313d5da19e4ded67fe8c1c30355b2c06ec0039778ab7deb1 | 1711623 | 279 days 20 hrs ago | 0x079710316b06bbb2c0ff4befb7d2dac206c716a0 | Contract Creation | 0 GLMR |
[ Download CSV Export ]
Similar Match Source Code
Note: This contract matches the deployed ByteCode of the Source Code for Contract 0xb822EEf11C9478f6155A4161a9ED847e89759aa3
Contract Name:
Pair
Compiler Version
v0.8.7+commit.e28d00a7
Contract Source Code (Solidity Standard Json-Input format)
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./interfaces/IFactory.sol"; import "./Pair.sol"; import "../libraries/AdminUpgradeable.sol"; contract Factory is AdminUpgradeable, IFactory { address public override feeto; uint8 public override feeBasePoint; bool public override lockForPairCreate; mapping(address => mapping(address => address)) public override getPair; mapping(address => mapping(address => address)) public override getBootstrap; address[] public override allPairs; constructor(address _admin) { _initializeAdmin(_admin); feeto = _admin; } function allPairsLength() external view override returns (uint256) { return allPairs.length; } function pairCodeHash() external pure returns (bytes32) { return keccak256(type(Pair).creationCode); } function createPair(address tokenA, address tokenB) external override returns (address pair) { require( !lockForPairCreate || (lockForPairCreate && msg.sender == admin), "CREATE_PAIR_LOCKED" ); require(tokenA != tokenB, "IDENTICAL_ADDRESSES"); (address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "ZERO_ADDRESS"); require(getPair[token0][token1] == address(0), "Factory: PAIR_EXISTS"); if (getBootstrap[token0][token1] != address(0)) { require(getBootstrap[token0][token1] == msg.sender, 'NOT_BOOTSTRAP_OWNER'); } bytes memory bytecode = type(Pair).creationCode; bytes32 salt = keccak256(abi.encodePacked(token0, token1)); assembly { pair := create2(0, add(bytecode, 32), mload(bytecode), salt) } IPair(pair).initialize(token0, token1); getPair[token0][token1] = pair; getPair[token1][token0] = pair; allPairs.push(pair); emit PairCreated(token0, token1, pair, allPairs.length); } function setBootstrap(address tokenA, address tokenB, address bootstrap) external onlyAdmin { require(getPair[tokenA][tokenB] == address(0), "Factory: PAIR_EXISTS"); getBootstrap[tokenA][tokenB] = bootstrap; getBootstrap[tokenB][tokenA] = bootstrap; emit BootstrapSetted(tokenA, tokenB, bootstrap); } function lockPairCreate() external onlyAdmin { lockForPairCreate = true; emit PairCreateLocked(msg.sender); } function unlockPairCreate() external onlyAdmin { lockForPairCreate = false; emit PairCreateUnlocked(msg.sender); } function setFeeto(address _feeto) external onlyAdmin { feeto = _feeto; emit FeetoUpdated(_feeto); } function setFeeBasePoint(uint8 _basePoint) external onlyAdmin { require(_basePoint <= 30, "FORBIDDEN"); feeBasePoint = _basePoint; emit FeeBasePointUpdated(_basePoint); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IFactory { event PairCreated( address indexed token0, address indexed token1, address pair, uint256 ); event PairCreateLocked( address indexed caller ); event PairCreateUnlocked( address indexed caller ); event BootstrapSetted( address indexed tokenA, address indexed tokenB, address indexed bootstrap ); event FeetoUpdated( address indexed feeto ); event FeeBasePointUpdated( uint8 basePoint ); function feeto() external view returns (address); function feeBasePoint() external view returns (uint8); function lockForPairCreate() external view returns (bool); function getPair(address tokenA, address tokenB) external view returns (address pair); function getBootstrap(address tokenA, address tokenB) external view returns (address bootstrap); function allPairs(uint256) external view returns (address pair); function allPairsLength() external view returns (uint256); function createPair(address tokenA, address tokenB) external returns (address pair); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./ZenlinkERC20.sol"; import "./interfaces/IPair.sol"; import "./interfaces/IFactory.sol"; import './interfaces/IZenlinkCallee.sol'; import "../libraries/Math.sol"; import "../libraries/UQ112x112.sol"; contract Pair is IPair, ZenlinkERC20 { using Math for uint256; using UQ112x112 for uint224; uint256 public constant override MINIMUM_LIQUIDITY = 10**3; bytes4 private constant SELECTOR = bytes4(keccak256(bytes("transfer(address,uint256)"))); address public override factory; address public override token0; address public override token1; uint112 private reserve0; // uses single storage slot, accessible via getReserves uint112 private reserve1; // uses single storage slot, accessible via getReserves uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves uint256 public override price0CumulativeLast; uint256 public override price1CumulativeLast; uint256 public override kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event uint8 private unlocked = 1; modifier lock() { require(unlocked == 1, "LOCKED"); unlocked = 0; _; unlocked = 1; } function _safeTransfer( address token, address to, uint256 value ) private { (bool success, bytes memory data) = token.call( abi.encodeWithSelector(SELECTOR, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TRANSFER_FAILED" ); } function getReserves() public view override returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) { _reserve0 = reserve0; _reserve1 = reserve1; _blockTimestampLast = blockTimestampLast; } constructor() { factory = msg.sender; } function initialize(address _token0, address _token1) external override { require(msg.sender == factory, "Only called by factory"); token0 = _token0; token1 = _token1; } function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (uint8 feeBasePoint) { address feeTo = IFactory(factory).feeto(); feeBasePoint = IFactory(factory).feeBasePoint(); uint256 _kLast = kLast; // gas savings if (feeBasePoint > 0) { if (_kLast != 0) { uint256 rootK = Math.sqrt( uint256(_reserve0).mul(uint256(_reserve1)) ); uint256 rootKLast = Math.sqrt(_kLast); if (rootK > rootKLast) { uint256 numerator = totalSupply().mul(rootK.sub(rootKLast)); uint256 denominator = (rootK.mul(30 - feeBasePoint) / feeBasePoint).add(rootKLast); uint256 liquidity = numerator / denominator; if (liquidity > 0) _mint(feeTo, liquidity); } } } else if (_kLast != 0) { kLast = 0; } } function mint(address to) external override lock returns (uint256 liquidity) { (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); uint256 balance0 = IERC20(token0).balanceOf(address(this)); uint256 balance1 = IERC20(token1).balanceOf(address(this)); uint256 amount0 = balance0.sub(_reserve0); uint256 amount1 = balance1.sub(_reserve1); uint8 feeBasePoint = _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply(); if (_totalSupply == 0) { address feeTo = IFactory(factory).feeto(); liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY); _mint(feeTo, MINIMUM_LIQUIDITY); } else { liquidity = Math.min( amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1 ); } require(liquidity > 0, "INSUFFICIENT_LIQUIDITY_MINTED"); _mint(to, liquidity); _update(balance0, balance1, _reserve0, _reserve1); if (feeBasePoint > 0) kLast = uint256(reserve0).mul(reserve1); emit Mint(msg.sender, amount0, amount1); } function burn(address to) external override lock returns (uint256 amount0, uint256 amount1) { (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); address _token0 = token0; address _token1 = token1; uint256 balance0 = IERC20(_token0).balanceOf(address(this)); uint256 balance1 = IERC20(_token1).balanceOf(address(this)); uint256 liquidity = balanceOf(address(this)); uint8 feeBasePoint = _mintFee(_reserve0, _reserve1); uint256 _totalSupply = totalSupply(); amount0 = liquidity.mul(balance0) / _totalSupply; amount1 = liquidity.mul(balance1) / _totalSupply; require(amount0 > 0 && amount1 > 0, "INSUFFICIENT_LIQUIDITY_BURNED"); _burn(address(this), liquidity); _safeTransfer(_token0, to, amount0); _safeTransfer(_token1, to, amount1); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); _update(balance0, balance1, _reserve0, _reserve1); if (feeBasePoint > 0) kLast = uint256(reserve0).mul(reserve1); emit Burn(msg.sender, amount0, amount1, to); } function swap( uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data ) external override lock { require(amount0Out > 0 || amount1Out > 0, "INSUFFICIENT_OUTPUT_AMOUNT"); (uint112 _reserve0, uint112 _reserve1, ) = getReserves(); require( amount0Out < _reserve0 && amount1Out < _reserve1, "INSUFFICIENT_LIQUIDITY" ); uint256 balance0; uint256 balance1; { address _token0 = token0; address _token1 = token1; require(to != _token0 && to != _token1, "INVALID_TO"); if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); if (data.length > 0) IZenlinkCallee(to).zenlinkCall(msg.sender, amount0Out, amount1Out, data); balance0 = IERC20(_token0).balanceOf(address(this)); balance1 = IERC20(_token1).balanceOf(address(this)); } uint256 amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0; uint256 amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0; require(amount0In > 0 || amount1In > 0, " INSUFFICIENT_INPUT_AMOUNT"); { uint256 balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3)); uint256 balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3)); require( balance0Adjusted.mul(balance1Adjusted) >= uint256(_reserve0).mul(_reserve1).mul(1000**2), "Pair: K" ); } _update(balance0, balance1, _reserve0, _reserve1); emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to); } function _update(uint256 balance0, uint256 balance1, uint112 _reserve0, uint112 _reserve1) private { require( balance0 <= type(uint112).max && balance1 <= type(uint112).max, "OVERFLOW" ); uint32 blockTimestamp = uint32(block.timestamp % 2**32); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) { // * never overflows, and + overflow is desired price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed; price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed; } reserve0 = uint112(balance0); reserve1 = uint112(balance1); blockTimestampLast = blockTimestamp; emit Sync(reserve0, reserve1); } // force balances to match reserves function skim(address to) external override lock { address _token0 = token0; // gas savings address _token1 = token1; // gas savings _safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0)); _safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1)); } // force reserves to match balances function sync() external override lock { _update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; abstract contract AdminUpgradeable { address public admin; address public adminCandidate; function _initializeAdmin(address _admin) internal { require(admin == address(0), "admin already set"); admin = _admin; } function candidateConfirm() external { require(msg.sender == adminCandidate, "not Candidate"); emit AdminChanged(admin, adminCandidate); admin = adminCandidate; adminCandidate = address(0); } function setAdminCandidate(address _candidate) external onlyAdmin { adminCandidate = _candidate; emit Candidate(_candidate); } modifier onlyAdmin { require(msg.sender == admin, "not admin"); _; } event Candidate(address indexed newAdmin); event AdminChanged(address indexed oldAdmin, address indexed newAdmin); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./interfaces/IZenlinkERC20.sol"; contract ZenlinkERC20 is IZenlinkERC20, ERC20 { bytes32 public override DOMAIN_SEPARATOR; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant override PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; mapping(address => uint256) public override nonces; constructor() ERC20('Zenlink LP Token', 'ZLK-LP') { uint chainId; assembly { chainId := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'), keccak256(bytes(name())), keccak256(bytes('1')), chainId, address(this) ) ); } function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external override { require(deadline >= block.timestamp, 'EXPIRED'); bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', DOMAIN_SEPARATOR, keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline)) ) ); address recoveredAddress = ecrecover(digest, v, r, s); require(recoveredAddress != address(0) && recoveredAddress == owner, 'INVALID_SIGNATURE'); _approve(owner, spender, value); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IPair { event Mint(address indexed sender, uint256 amount0, uint256 amount1); event Burn( address indexed sender, uint256 amount0, uint256 amount1, address indexed to ); event Swap( address indexed sender, uint256 amount0In, uint256 amount1In, uint256 amount0Out, uint256 amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint256); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint256); function price1CumulativeLast() external view returns (uint256); function kLast() external view returns (uint256); function mint(address to) external returns (uint256 liquidity); function burn(address to) external returns (uint256 amount0, uint256 amount1); function swap(uint256 amount0Out, uint256 amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IZenlinkCallee { function zenlinkCall(address sender, uint256 amount0, uint256 amount1, bytes calldata data) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; // a library for performing various math operations library Math { function min(uint256 x, uint256 y) internal pure returns (uint256 z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } function add(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint256 x, uint256 y) internal pure returns (uint256 z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint256 x, uint256 y) internal pure returns (uint256 z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) // range: [0, 2**112 - 1] // resolution: 1 / 2**112 library UQ112x112 { uint224 constant Q112 = 2**112; // encode a uint112 as a UQ112x112 function encode(uint112 y) internal pure returns (uint224 z) { z = uint224(y) * Q112; // never overflows } // divide a UQ112x112 by a uint112, returning a UQ112x112 function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) { z = x / uint224(y); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IZenlinkERC20 is IERC20 { function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `to` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address to, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _transfer(owner, to, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on * `transferFrom`. This is semantically equivalent to an infinite approval. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { address owner = _msgSender(); _approve(owner, spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * NOTE: Does not update the allowance if the current allowance * is the maximum `uint256`. * * Requirements: * * - `from` and `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. * - the caller must have allowance for ``from``'s tokens of at least * `amount`. */ function transferFrom( address from, address to, uint256 amount ) public virtual override returns (bool) { address spender = _msgSender(); _spendAllowance(from, spender, amount); _transfer(from, to, amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { address owner = _msgSender(); _approve(owner, spender, allowance(owner, spender) + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { address owner = _msgSender(); uint256 currentAllowance = allowance(owner, spender); require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(owner, spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `from` to `to`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `from` must have a balance of at least `amount`. */ function _transfer( address from, address to, uint256 amount ) internal virtual { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(from, to, amount); uint256 fromBalance = _balances[from]; require(fromBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[from] = fromBalance - amount; } _balances[to] += amount; emit Transfer(from, to, amount); _afterTokenTransfer(from, to, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Updates `owner` s allowance for `spender` based on spent `amount`. * * Does not update the allowance amount in case of infinite allowance. * Revert if not enough allowance is available. * * Might emit an {Approval} event. */ function _spendAllowance( address owner, address spender, uint256 amount ) internal virtual { uint256 currentAllowance = allowance(owner, spender); if (currentAllowance != type(uint256).max) { require(currentAllowance >= amount, "ERC20: insufficient allowance"); unchecked { _approve(owner, spender, currentAllowance - amount); } } } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.6.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); }
// 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; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {AdminUpgradeable} from "../libraries/AdminUpgradeable.sol"; import {IFactory} from "../core/interfaces/IFactory.sol"; import {IPair} from "../core/interfaces/IPair.sol"; import {IStableSwap} from "../stableswap/interfaces/IStableSwap.sol"; contract ZenlinkMaker is AdminUpgradeable { using SafeERC20 for IERC20; IFactory public immutable factory; address public immutable vxzlk; address private immutable zlk; address private immutable wnative; uint256 public constant PRECISION = 10**3; address public feeDistributor; uint256 public fee; mapping(address => address) internal _bridges; mapping(address => uint8) internal _stableSwapFeeTokenIndex; event LogBridgeSet(address indexed token, address indexed bridge); event LogStableSwapFeeTokenIndexSet(address indexed pool, uint8 indexed feeTokenIndex); event FeeDistributorChanged(address newController); event FeeChanged(uint256 newFee); event LogConvertPair( address indexed sender, address indexed token0, address indexed token1, uint256 amount0, uint256 amount1, uint256 amountZLK ); event LogConvertStableSwap( address indexed sender, address indexed pool, address indexed token, uint256 amount, uint256 amountZLK ); error NotEOA(address account); error BridgeTokenInvalid(address token); error TokenIndexInvalid(uint8 feeTokenIndex); error ZeroAddress(); error FeeExceedsMaximum(uint256 newFee, uint256 max); error ArrayMismatch(); constructor( IFactory _factory, address _vxzlk, address _zlk, address _wnative, address _feeDistributor ) { factory = _factory; vxzlk = _vxzlk; zlk = _zlk; wnative = _wnative; feeDistributor = _feeDistributor; _initializeAdmin(msg.sender); } modifier onlyEOA() { if (msg.sender != tx.origin) revert NotEOA(msg.sender); _; } function bridgeFor(address token) public view returns (address bridge) { bridge = _bridges[token]; if (bridge == address(0)) { bridge = wnative; } } function feeTokenIndexFor(address pool) public view returns (uint8 feeTokenIndex) { feeTokenIndex = _stableSwapFeeTokenIndex[pool]; } function setBridge(address token, address bridge) external onlyAdmin { if (token == zlk || token == wnative || token == bridge) revert BridgeTokenInvalid(token); _bridges[token] = bridge; emit LogBridgeSet(token, bridge); } function setFeeTokenIndex(address pool, uint8 feeTokenIndex) external onlyAdmin { if (feeTokenIndex >= IStableSwap(pool).getNumberOfTokens()) revert TokenIndexInvalid(feeTokenIndex); _stableSwapFeeTokenIndex[pool] = feeTokenIndex; emit LogStableSwapFeeTokenIndexSet(pool, feeTokenIndex); } function setFeeDistributor(address _feeDistributor) external onlyAdmin { if (_feeDistributor == address(0)) revert ZeroAddress(); feeDistributor = _feeDistributor; emit FeeDistributorChanged(_feeDistributor); } function setFee(uint256 newFee) external onlyAdmin { if (newFee > PRECISION) revert FeeExceedsMaximum(newFee, PRECISION); fee = newFee; emit FeeChanged(newFee); } function convertPair(address token0, address token1) external onlyEOA() { _convertPair(token0, token1); } function convertStableSwap(IStableSwap pool) external onlyEOA() { _convertStableSwap(pool); } function convertPairMultiple( address[] calldata tokens0, address[] calldata tokens1 ) external onlyEOA() { uint256 len = tokens0.length; if (len != tokens1.length) revert ArrayMismatch(); for (uint256 i = 0; i < len; i++) { _convertPair(tokens0[i], tokens1[i]); } } function convertStableSwapMultiple(IStableSwap[] calldata pools) external onlyEOA() { for (uint256 i = 0; i < pools.length; i++) { _convertStableSwap(pools[i]); } } function _convertPair(address token0, address token1) internal { IPair pair = IPair(factory.getPair(token0, token1)); if (address(pair) == address(0)) revert ZeroAddress(); uint256 amount = IERC20(address(pair)).balanceOf(address(this)); IERC20(address(pair)).safeTransfer(address(pair), amount); (uint256 amount0, uint256 amount1) = pair.burn(address(this)); if (token0 != pair.token0()) { (amount0, amount1) = (amount1, amount0); } uint256 amount0Fee = (amount0 * fee) / PRECISION; uint256 amount1Fee = (amount1 * fee) / PRECISION; if (amount0Fee > 0) { IERC20(token0).safeTransfer(feeDistributor, amount0Fee); } if (amount1Fee > 0) { IERC20(token1).safeTransfer(feeDistributor, amount1Fee); } emit LogConvertPair( msg.sender, token0, token1, amount0 - amount0Fee, amount1 - amount1Fee, _convertStep(token0, token1, amount0 - amount0Fee, amount1 - amount1Fee) ); } function _convertStableSwap(IStableSwap pool) internal { pool.withdrawAdminFee(); IERC20[] memory tokens = pool.getTokens(); uint8 feeTokenIndex = _stableSwapFeeTokenIndex[address(pool)]; IERC20 feeToken = pool.getToken(feeTokenIndex); for (uint8 i = 0; i < tokens.length; i++) { if (i == feeTokenIndex) continue; uint256 balance = tokens[i].balanceOf(address(this)); tokens[i].safeIncreaseAllowance(address(pool), balance); pool.swap(i, feeTokenIndex, balance, 0, block.timestamp); } uint256 amount = feeToken.balanceOf(address(this)); uint256 feeAmount = (amount * fee) / PRECISION; if (feeAmount > 0) { feeToken.safeTransfer(feeDistributor, feeAmount); } emit LogConvertStableSwap( msg.sender, address(pool), address(feeToken), amount - feeAmount, _convertStep(address(feeToken), address(feeToken), amount - feeAmount, 0) ); } function _convertStep( address token0, address token1, uint256 amount0, uint256 amount1 ) internal returns(uint256 zlkOut) { if (token0 == token1) { uint256 amount = amount0 + amount1; if (token0 == zlk) { IERC20(zlk).safeTransfer(vxzlk, amount); zlkOut = amount; } else if (token0 == wnative) { zlkOut = _toZLK(wnative, amount); } else { address bridge = bridgeFor(token0); amount = _swap(token0, bridge, amount, address(this)); zlkOut = _convertStep(bridge, bridge, amount, 0); } } else if (token0 == zlk) { IERC20(zlk).safeTransfer(vxzlk, amount0); zlkOut = _toZLK(token1, amount1) + amount0; } else if (token1 == zlk) { IERC20(zlk).safeTransfer(vxzlk, amount1); zlkOut = _toZLK(token0, amount0) + amount1; } else if (token0 == wnative) { zlkOut = _toZLK(wnative, _swap(token1, wnative, amount1, address(this)) + amount0); } else if (token1 == wnative) { zlkOut = _toZLK(wnative, _swap(token0, wnative, amount0, address(this)) + amount1); } else { address bridge0 = bridgeFor(token0); address bridge1 = bridgeFor(token1); if (bridge0 == token1) { zlkOut = _convertStep( bridge0, token1, _swap(token0, bridge0, amount0, address(this)), amount1 ); } else if (bridge1 == token0) { zlkOut = _convertStep( token0, bridge1, amount0, _swap(token1, bridge1, amount1, address(this)) ); } else { zlkOut = _convertStep( bridge0, bridge1, _swap(token0, bridge0, amount0, address(this)), _swap(token1, bridge1, amount1, address(this)) ); } } } function _swap( address fromToken, address toToken, uint256 amountIn, address to ) internal returns(uint256 amountOut) { IPair pair = IPair(factory.getPair(fromToken, toToken)); if (address(pair) == address(0)) revert ZeroAddress(); (uint256 reserve0, uint256 reserve1, ) = pair.getReserves(); uint256 amountInWithFee = amountIn * 997; if (fromToken == pair.token0()) { amountOut = (amountInWithFee * reserve1) / (reserve0 * 1000 + amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(0, amountOut, to, new bytes(0)); } else { amountOut = (amountInWithFee * reserve0) / (reserve1 * 1000 + amountInWithFee); IERC20(fromToken).safeTransfer(address(pair), amountIn); pair.swap(amountOut, 0, to, new bytes(0)); } } function _toZLK(address token, uint256 amountIn) internal returns(uint256 amountOut) { amountOut = _swap(token, zlk, amountIn, vxzlk); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../LPToken.sol"; interface IStableSwap { /// EVENTS event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 tokenSupply ); event FlashLoan( address indexed caller, address indexed receiver, uint256[] amounts_out ); event TokenExchange( address indexed buyer, uint256 soldId, uint256 tokensSold, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidity(address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 tokenSupply); event RemoveLiquidityOne(address indexed provider, uint256 tokenIndex, uint256 tokenAmount, uint256 coinAmount); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 tokenSupply ); event RampA(uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime); event StopRampA(uint256 A, uint256 timestamp); event NewFee(uint256 fee, uint256 adminFee); event CollectProtocolFee(address token, uint256 amount); event FeeControllerChanged(address newController); event FeeDistributorChanged(address newController); // pool data view functions function getLpToken() external view returns (IERC20 lpToken); function getA() external view returns (uint256); function getAPrecise() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokens() external view returns (IERC20[] memory); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getTokenBalances() external view returns (uint256[] memory); function getNumberOfTokens() external view returns (uint256); function getVirtualPrice() external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex) external view returns (uint256 availableTokenAmount); function getAdminBalances() external view returns (uint256[] memory adminBalances); function getAdminBalance(uint8 index) external view returns (uint256); function swapStorage() external view returns ( LPToken, uint256, uint256, uint256, uint256, uint256, uint256 ); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function flashLoan( uint256[] memory amountsOut, address to, bytes calldata data, uint256 deadline ) external; function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); function withdrawAdminFee() external; }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/draft-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; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } 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"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/extensions/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./interfaces/IStableSwap.sol"; contract LPToken is Ownable, ERC20Burnable { IStableSwap public swap; constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) { swap = IStableSwap(msg.sender); } function mint(address _to, uint256 _amount) external onlyOwner { require(_amount > 0, "zeroMintAmount"); _mint(_to, _amount); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.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 anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing 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); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../../../utils/Context.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { _spendAllowance(account, _msgSender(), amount); _burn(account, amount); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/extensions/ERC4626.sol) pragma solidity ^0.8.0; import "../ERC20.sol"; import "../utils/SafeERC20.sol"; import "../../../interfaces/IERC4626.sol"; import "../../../utils/math/Math.sol"; /** * @dev Implementation of the ERC4626 "Tokenized Vault Standard" as defined in * https://eips.ethereum.org/EIPS/eip-4626[EIP-4626]. * * This extension allows the minting and burning of "shares" (represented using the ERC20 inheritance) in exchange for * underlying "assets" through standardized {deposit}, {mint}, {redeem} and {burn} workflows. This contract extends * the ERC20 standard. Any additional extensions included along it would affect the "shares" token represented by this * contract and not the "assets" token which is an independent contract. * * CAUTION: Deposits and withdrawals may incur unexpected slippage. Users should verify that the amount received of * shares or assets is as expected. EOAs should operate through a wrapper that performs these checks such as * https://github.com/fei-protocol/ERC4626#erc4626router-and-base[ERC4626Router]. * * _Available since v4.7._ */ abstract contract ERC4626 is ERC20, IERC4626 { using Math for uint256; IERC20Metadata private immutable _asset; /** * @dev Set the underlying asset contract. This must be an ERC20-compatible contract (ERC20 or ERC777). */ constructor(IERC20Metadata asset_) { _asset = asset_; } /** @dev See {IERC4262-asset}. */ function asset() public view virtual override returns (address) { return address(_asset); } /** @dev See {IERC4262-totalAssets}. */ function totalAssets() public view virtual override returns (uint256) { return _asset.balanceOf(address(this)); } /** @dev See {IERC4262-convertToShares}. */ function convertToShares(uint256 assets) public view virtual override returns (uint256 shares) { return _convertToShares(assets, Math.Rounding.Down); } /** @dev See {IERC4262-convertToAssets}. */ function convertToAssets(uint256 shares) public view virtual override returns (uint256 assets) { return _convertToAssets(shares, Math.Rounding.Down); } /** @dev See {IERC4262-maxDeposit}. */ function maxDeposit(address) public view virtual override returns (uint256) { return _isVaultCollateralized() ? type(uint256).max : 0; } /** @dev See {IERC4262-maxMint}. */ function maxMint(address) public view virtual override returns (uint256) { return type(uint256).max; } /** @dev See {IERC4262-maxWithdraw}. */ function maxWithdraw(address owner) public view virtual override returns (uint256) { return _convertToAssets(balanceOf(owner), Math.Rounding.Down); } /** @dev See {IERC4262-maxRedeem}. */ function maxRedeem(address owner) public view virtual override returns (uint256) { return balanceOf(owner); } /** @dev See {IERC4262-previewDeposit}. */ function previewDeposit(uint256 assets) public view virtual override returns (uint256) { return _convertToShares(assets, Math.Rounding.Down); } /** @dev See {IERC4262-previewMint}. */ function previewMint(uint256 shares) public view virtual override returns (uint256) { return _convertToAssets(shares, Math.Rounding.Up); } /** @dev See {IERC4262-previewWithdraw}. */ function previewWithdraw(uint256 assets) public view virtual override returns (uint256) { return _convertToShares(assets, Math.Rounding.Up); } /** @dev See {IERC4262-previewRedeem}. */ function previewRedeem(uint256 shares) public view virtual override returns (uint256) { return _convertToAssets(shares, Math.Rounding.Down); } /** @dev See {IERC4262-deposit}. */ function deposit(uint256 assets, address receiver) public virtual override returns (uint256) { require(assets <= maxDeposit(receiver), "ERC4626: deposit more than max"); uint256 shares = previewDeposit(assets); _deposit(_msgSender(), receiver, assets, shares); return shares; } /** @dev See {IERC4262-mint}. */ function mint(uint256 shares, address receiver) public virtual override returns (uint256) { require(shares <= maxMint(receiver), "ERC4626: mint more than max"); uint256 assets = previewMint(shares); _deposit(_msgSender(), receiver, assets, shares); return assets; } /** @dev See {IERC4262-withdraw}. */ function withdraw( uint256 assets, address receiver, address owner ) public virtual override returns (uint256) { require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max"); uint256 shares = previewWithdraw(assets); _withdraw(_msgSender(), receiver, owner, assets, shares); return shares; } /** @dev See {IERC4262-redeem}. */ function redeem( uint256 shares, address receiver, address owner ) public virtual override returns (uint256) { require(shares <= maxRedeem(owner), "ERC4626: redeem more than max"); uint256 assets = previewRedeem(shares); _withdraw(_msgSender(), receiver, owner, assets, shares); return assets; } /** * @dev Internal conversion function (from assets to shares) with support for rounding direction. * * Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset * would represent an infinite amout of shares. */ function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256 shares) { uint256 supply = totalSupply(); return (assets == 0 || supply == 0) ? assets.mulDiv(10**decimals(), 10**_asset.decimals(), rounding) : assets.mulDiv(supply, totalAssets(), rounding); } /** * @dev Internal conversion function (from shares to assets) with support for rounding direction. */ function _convertToAssets(uint256 shares, Math.Rounding rounding) internal view virtual returns (uint256 assets) { uint256 supply = totalSupply(); return (supply == 0) ? shares.mulDiv(10**_asset.decimals(), 10**decimals(), rounding) : shares.mulDiv(totalAssets(), supply, rounding); } /** * @dev Deposit/mint common workflow. */ function _deposit( address caller, address receiver, uint256 assets, uint256 shares ) internal virtual { // If _asset is ERC777, `transferFrom` can trigger a reenterancy BEFORE the transfer happens through the // `tokensToSend` hook. On the other hand, the `tokenReceived` hook, that is triggered after the transfer, // calls the vault, which is assumed not malicious. // // Conclusion: we need to do the transfer before we mint so that any reentrancy would happen before the // assets are transfered and before the shares are minted, which is a valid state. // slither-disable-next-line reentrancy-no-eth SafeERC20.safeTransferFrom(_asset, caller, address(this), assets); _mint(receiver, shares); emit Deposit(caller, receiver, assets, shares); } /** * @dev Withdraw/redeem common workflow. */ function _withdraw( address caller, address receiver, address owner, uint256 assets, uint256 shares ) internal virtual { if (caller != owner) { _spendAllowance(owner, caller, shares); } // If _asset is ERC777, `transfer` can trigger a reentrancy AFTER the transfer happens through the // `tokensReceived` hook. On the other hand, the `tokensToSend` hook, that is triggered before the transfer, // calls the vault, which is assumed not malicious. // // Conclusion: we need to do the transfer after the burn so that any reentrancy would happen after the // shares are burned and after the assets are transfered, which is a valid state. _burn(owner, shares); SafeERC20.safeTransfer(_asset, receiver, assets); emit Withdraw(caller, receiver, owner, assets, shares); } function _isVaultCollateralized() private view returns (bool) { return totalAssets() > 0 || totalSupply() == 0; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.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) { return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1); /////////////////////////////////////////////// // 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. It 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)`. // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`. // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`. // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a // good first aproximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1; uint256 x = a; if (x >> 128 > 0) { x >>= 128; result <<= 64; } if (x >> 64 > 0) { x >>= 64; result <<= 32; } if (x >> 32 > 0) { x >>= 32; result <<= 16; } if (x >> 16 > 0) { x >>= 16; result <<= 8; } if (x >> 8 > 0) { x >>= 8; result <<= 4; } if (x >> 4 > 0) { x >>= 4; result <<= 2; } if (x >> 2 > 0) { result <<= 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) { uint256 result = sqrt(a); if (rounding == Rounding.Up && result * result < a) { result += 1; } return result; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (interfaces/IERC4626.sol) pragma solidity ^0.8.0; import "../token/ERC20/IERC20.sol"; import "../token/ERC20/extensions/IERC20Metadata.sol"; /** * @dev Interface of the ERC4626 "Tokenized Vault Standard", as defined in * https://eips.ethereum.org/EIPS/eip-4626[ERC-4626]. * * _Available since v4.7._ */ interface IERC4626 is IERC20, IERC20Metadata { event Deposit(address indexed caller, address indexed owner, uint256 assets, uint256 shares); event Withdraw( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 shares ); /** * @dev Returns the address of the underlying token used for the Vault for accounting, depositing, and withdrawing. * * - MUST be an ERC-20 token contract. * - MUST NOT revert. */ function asset() external view returns (address assetTokenAddress); /** * @dev Returns the total amount of the underlying asset that is “managed” by Vault. * * - SHOULD include any compounding that occurs from yield. * - MUST be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT revert. */ function totalAssets() external view returns (uint256 totalManagedAssets); /** * @dev Returns the amount of shares that the Vault would exchange for the amount of assets provided, in an ideal * scenario where all the conditions are met. * * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT show any variations depending on the caller. * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. * - MUST NOT revert. * * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and * from. */ function convertToShares(uint256 assets) external view returns (uint256 shares); /** * @dev Returns the amount of assets that the Vault would exchange for the amount of shares provided, in an ideal * scenario where all the conditions are met. * * - MUST NOT be inclusive of any fees that are charged against assets in the Vault. * - MUST NOT show any variations depending on the caller. * - MUST NOT reflect slippage or other on-chain conditions, when performing the actual exchange. * - MUST NOT revert. * * NOTE: This calculation MAY NOT reflect the “per-user” price-per-share, and instead should reflect the * “average-user’s” price-per-share, meaning what the average user should expect to see when exchanging to and * from. */ function convertToAssets(uint256 shares) external view returns (uint256 assets); /** * @dev Returns the maximum amount of the underlying asset that can be deposited into the Vault for the receiver, * through a deposit call. * * - MUST return a limited value if receiver is subject to some deposit limit. * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of assets that may be deposited. * - MUST NOT revert. */ function maxDeposit(address receiver) external view returns (uint256 maxAssets); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their deposit at the current block, given * current on-chain conditions. * * - MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit * call in the same transaction. I.e. deposit should return the same or more shares as previewDeposit if called * in the same transaction. * - MUST NOT account for deposit limits like those returned from maxDeposit and should always act as though the * deposit would be accepted, regardless if the user has enough tokens approved, etc. * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToShares and previewDeposit SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by depositing. */ function previewDeposit(uint256 assets) external view returns (uint256 shares); /** * @dev Mints shares Vault shares to receiver by depositing exactly amount of underlying tokens. * * - MUST emit the Deposit event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * deposit execution, and are accounted for during deposit. * - MUST revert if all of assets cannot be deposited (due to deposit limit being reached, slippage, the user not * approving enough underlying tokens to the Vault contract, etc). * * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. */ function deposit(uint256 assets, address receiver) external returns (uint256 shares); /** * @dev Returns the maximum amount of the Vault shares that can be minted for the receiver, through a mint call. * - MUST return a limited value if receiver is subject to some mint limit. * - MUST return 2 ** 256 - 1 if there is no limit on the maximum amount of shares that may be minted. * - MUST NOT revert. */ function maxMint(address receiver) external view returns (uint256 maxShares); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their mint at the current block, given * current on-chain conditions. * * - MUST return as close to and no fewer than the exact amount of assets that would be deposited in a mint call * in the same transaction. I.e. mint should return the same or fewer assets as previewMint if called in the * same transaction. * - MUST NOT account for mint limits like those returned from maxMint and should always act as though the mint * would be accepted, regardless if the user has enough tokens approved, etc. * - MUST be inclusive of deposit fees. Integrators should be aware of the existence of deposit fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToAssets and previewMint SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by minting. */ function previewMint(uint256 shares) external view returns (uint256 assets); /** * @dev Mints exactly shares Vault shares to receiver by depositing amount of underlying tokens. * * - MUST emit the Deposit event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the mint * execution, and are accounted for during mint. * - MUST revert if all of shares cannot be minted (due to deposit limit being reached, slippage, the user not * approving enough underlying tokens to the Vault contract, etc). * * NOTE: most implementations will require pre-approval of the Vault with the Vault’s underlying asset token. */ function mint(uint256 shares, address receiver) external returns (uint256 assets); /** * @dev Returns the maximum amount of the underlying asset that can be withdrawn from the owner balance in the * Vault, through a withdraw call. * * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. * - MUST NOT revert. */ function maxWithdraw(address owner) external view returns (uint256 maxAssets); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their withdrawal at the current block, * given current on-chain conditions. * * - MUST return as close to and no fewer than the exact amount of Vault shares that would be burned in a withdraw * call in the same transaction. I.e. withdraw should return the same or fewer shares as previewWithdraw if * called * in the same transaction. * - MUST NOT account for withdrawal limits like those returned from maxWithdraw and should always act as though * the withdrawal would be accepted, regardless if the user has enough shares, etc. * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToShares and previewWithdraw SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by depositing. */ function previewWithdraw(uint256 assets) external view returns (uint256 shares); /** * @dev Burns shares from owner and sends exactly assets of underlying tokens to receiver. * * - MUST emit the Withdraw event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * withdraw execution, and are accounted for during withdraw. * - MUST revert if all of assets cannot be withdrawn (due to withdrawal limit being reached, slippage, the owner * not having enough shares, etc). * * Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. * Those methods should be performed separately. */ function withdraw( uint256 assets, address receiver, address owner ) external returns (uint256 shares); /** * @dev Returns the maximum amount of Vault shares that can be redeemed from the owner balance in the Vault, * through a redeem call. * * - MUST return a limited value if owner is subject to some withdrawal limit or timelock. * - MUST return balanceOf(owner) if owner is not subject to any withdrawal limit or timelock. * - MUST NOT revert. */ function maxRedeem(address owner) external view returns (uint256 maxShares); /** * @dev Allows an on-chain or off-chain user to simulate the effects of their redeemption at the current block, * given current on-chain conditions. * * - MUST return as close to and no more than the exact amount of assets that would be withdrawn in a redeem call * in the same transaction. I.e. redeem should return the same or more assets as previewRedeem if called in the * same transaction. * - MUST NOT account for redemption limits like those returned from maxRedeem and should always act as though the * redemption would be accepted, regardless if the user has enough shares, etc. * - MUST be inclusive of withdrawal fees. Integrators should be aware of the existence of withdrawal fees. * - MUST NOT revert. * * NOTE: any unfavorable discrepancy between convertToAssets and previewRedeem SHOULD be considered slippage in * share price or some other type of condition, meaning the depositor will lose assets by redeeming. */ function previewRedeem(uint256 shares) external view returns (uint256 assets); /** * @dev Burns exactly shares from owner and sends assets of underlying tokens to receiver. * * - MUST emit the Withdraw event. * - MAY support an additional flow in which the underlying tokens are owned by the Vault contract before the * redeem execution, and are accounted for during redeem. * - MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner * not having enough shares, etc). * * NOTE: some implementations will require pre-requesting to the Vault before a withdrawal may be performed. * Those methods should be performed separately. */ function redeem( uint256 shares, address receiver, address owner ) external returns (uint256 assets); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/security/Pausable.sol"; import "../libraries/AdminUpgradeable.sol"; abstract contract OwnerPausable is Pausable, AdminUpgradeable { function pause() external onlyAdmin { _pause(); } function unpause() external onlyAdmin { _unpause(); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./OwnerPausable.sol"; import "./StableSwapStorage.sol"; import "./interfaces/IStableSwap.sol"; contract StableSwap is OwnerPausable, ReentrancyGuard, Initializable, IStableSwap { using StableSwapStorage for StableSwapStorage.SwapStorage; using SafeERC20 for IERC20; /// constants uint256 public constant MIN_RAMP_TIME = 1 days; uint256 public constant MAX_A = 1e6; // max_a with precision uint256 public constant MAX_A_CHANGE = 10; uint256 public constant MAX_ADMIN_FEE = 1e10; // 100% uint256 public constant MAX_SWAP_FEE = 1e8; // 1% /// STATE VARS StableSwapStorage.SwapStorage public override swapStorage; address public feeDistributor; address public feeController; mapping(address => uint8) public tokenIndexes; modifier deadlineCheck(uint256 _deadline) { require(block.timestamp <= _deadline, "timeout"); _; } modifier onlyFeeControllerOrOwner() { require(msg.sender == feeController || msg.sender == admin, "!feeControllerOrOwner"); _; } constructor () { _initializeAdmin(msg.sender); } function initialize( address[] memory _coins, uint8[] memory _decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _A, uint256 _fee, uint256 _adminFee, address _feeDistributor ) public virtual onlyAdmin initializer { require(_coins.length == _decimals.length, "coinsLength != decimalsLength"); require(_feeDistributor != address(0), "feeDistributor = empty"); uint256 numberOfCoins = _coins.length; uint256[] memory rates = new uint256[](numberOfCoins); IERC20[] memory coins = new IERC20[](numberOfCoins); for (uint256 i = 0; i < numberOfCoins; i++) { require(_coins[i] != address(0), "invalidTokenAddress"); require(_decimals[i] <= StableSwapStorage.POOL_TOKEN_COMMON_DECIMALS, "invalidDecimals"); rates[i] = 10**(StableSwapStorage.POOL_TOKEN_COMMON_DECIMALS - _decimals[i]); coins[i] = IERC20(_coins[i]); tokenIndexes[address(coins[i])] = uint8(i); } require(_A < MAX_A, "> maxA"); require(_fee <= MAX_SWAP_FEE, "> maxSwapFee"); require(_adminFee <= MAX_ADMIN_FEE, "> maxAdminFee"); swapStorage.lpToken = new LPToken(lpTokenName, lpTokenSymbol); swapStorage.balances = new uint256[](numberOfCoins); swapStorage.tokenMultipliers = rates; swapStorage.pooledTokens = coins; swapStorage.initialA = _A * StableSwapStorage.A_PRECISION; swapStorage.futureA = _A * StableSwapStorage.A_PRECISION; swapStorage.fee = _fee; swapStorage.adminFee = _adminFee; feeDistributor = _feeDistributor; } /// PUBLIC FUNCTIONS function addLiquidity( uint256[] memory amounts, uint256 minMintAmount, uint256 deadline ) external virtual override whenNotPaused nonReentrant deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minMintAmount); } function flashLoan( uint256[] memory amountsOut, address to, bytes calldata data, uint256 deadline ) external virtual override whenNotPaused nonReentrant deadlineCheck(deadline) { swapStorage.flashLoan(amountsOut, to, data); } function swap( uint8 fromIndex, uint8 toIndex, uint256 inAmount, uint256 minOutAmount, uint256 deadline ) external virtual override whenNotPaused nonReentrant deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(fromIndex, toIndex, inAmount, minOutAmount); } function removeLiquidity( uint256 lpAmount, uint256[] memory minAmounts, uint256 deadline ) external virtual override nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(lpAmount, minAmounts); } function removeLiquidityOneToken( uint256 lpAmount, uint8 index, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken(lpAmount, index, minAmount); } function removeLiquidityImbalance( uint256[] memory amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /// VIEW FUNCTIONS function getVirtualPrice() external virtual view override returns (uint256) { return swapStorage.getVirtualPrice(); } function getA() external virtual view override returns (uint256) { return swapStorage.getA(); } function getAPrecise() external virtual view override returns (uint256) { return swapStorage.getAPrecise(); } function getTokens() external virtual view override returns (IERC20[] memory) { return swapStorage.pooledTokens; } function getToken(uint8 index) external virtual view override returns (IERC20) { return swapStorage.pooledTokens[index]; } function getLpToken() external virtual view override returns (IERC20) { return swapStorage.lpToken; } function getTokenIndex(address token) external virtual view override returns (uint8 index) { index = tokenIndexes[token]; require(address(swapStorage.pooledTokens[index]) == token, "tokenNotFound"); } function getTokenPrecisionMultipliers() external virtual view returns (uint256[] memory) { return swapStorage.tokenMultipliers; } function getTokenBalances() external virtual view override returns (uint256[] memory) { return swapStorage.balances; } function getTokenBalance(uint8 index) external virtual view override returns (uint256) { return swapStorage.balances[index]; } function getNumberOfTokens() external virtual view override returns (uint256) { return swapStorage.pooledTokens.length; } function getAdminBalances() external virtual view override returns (uint256[] memory adminBalances) { uint256 length = swapStorage.pooledTokens.length; adminBalances = new uint256[](length); for (uint256 i = 0; i < length; i++) { adminBalances[i] = swapStorage.getAdminBalance(i); } } function getAdminBalance(uint8 index) external virtual view override returns (uint256) { return swapStorage.getAdminBalance((index)); } function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external virtual view override returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } function calculateSwap( uint8 inIndex, uint8 outIndex, uint256 inAmount ) external virtual view override returns (uint256) { return swapStorage.calculateSwap(inIndex, outIndex, inAmount); } function calculateRemoveLiquidity(uint256 amount) external virtual view override returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } function calculateRemoveLiquidityOneToken(uint256 amount, uint8 index) external virtual view override returns (uint256) { return swapStorage.calculateRemoveLiquidityOneToken(amount, index); } /// RESTRICTED FUNCTION /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * swap fee cannot be higher than 1% of each swap * @param newSwapFee new swap fee to be applied on future transactions * @param newAdminFee new admin fee to be applied on future transactions */ function setFee(uint256 newSwapFee, uint256 newAdminFee) external onlyAdmin { require(newSwapFee <= MAX_SWAP_FEE, "> maxSwapFee"); require(newAdminFee <= MAX_ADMIN_FEE, "> maxAdminFee"); swapStorage.adminFee = newAdminFee; swapStorage.fee = newSwapFee; emit NewFee(newSwapFee, newAdminFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureATime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureATime) external onlyAdmin { require(block.timestamp >= swapStorage.initialATime + (1 days), "< rampDelay"); // please wait 1 days before start a new ramping require(futureATime >= block.timestamp + (MIN_RAMP_TIME), "< minRampTime"); require(0 < futureA && futureA < MAX_A, "outOfRange"); uint256 initialAPrecise = swapStorage.getAPrecise(); uint256 futureAPrecise = futureA * StableSwapStorage.A_PRECISION; if (futureAPrecise < initialAPrecise) { require(futureAPrecise * (MAX_A_CHANGE) >= initialAPrecise, "> maxChange"); } else { require(futureAPrecise <= initialAPrecise * (MAX_A_CHANGE), "> maxChange"); } swapStorage.initialA = initialAPrecise; swapStorage.futureA = futureAPrecise; swapStorage.initialATime = block.timestamp; swapStorage.futureATime = futureATime; emit RampA(initialAPrecise, futureAPrecise, block.timestamp, futureATime); } function stopRampA() external onlyAdmin { require(swapStorage.futureATime > block.timestamp, "alreadyStopped"); uint256 currentA = swapStorage.getAPrecise(); swapStorage.initialA = currentA; swapStorage.futureA = currentA; swapStorage.initialATime = block.timestamp; swapStorage.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } function setFeeController(address _feeController) external onlyAdmin { require(_feeController != address(0), "zeroAddress"); feeController = _feeController; emit FeeControllerChanged(_feeController); } function setFeeDistributor(address _feeDistributor) external onlyAdmin { require(_feeDistributor != address(0), "zeroAddress"); feeDistributor = _feeDistributor; emit FeeDistributorChanged(_feeDistributor); } function withdrawAdminFee() external override onlyFeeControllerOrOwner { for (uint256 i = 0; i < swapStorage.pooledTokens.length; i++) { IERC20 token = swapStorage.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)) - (swapStorage.balances[i]); if (balance != 0) { token.safeTransfer(feeDistributor, balance); emit CollectProtocolFee(address(token), balance); } } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IStableSwapCallee.sol"; import "./LPToken.sol"; /** * StableSwap main algorithm */ library StableSwapStorage { using SafeERC20 for IERC20; event AddLiquidity( address indexed provider, uint256[] token_amounts, uint256[] fees, uint256 invariant, uint256 token_supply ); event FlashLoan( address indexed caller, address indexed receiver, uint256[] amounts_out ); event TokenExchange( address indexed buyer, uint256 sold_id, uint256 tokens_sold, uint256 bought_id, uint256 tokens_bought ); event RemoveLiquidity(address indexed provider, uint256[] token_amounts, uint256[] fees, uint256 token_supply); event RemoveLiquidityOne(address indexed provider, uint256 index, uint256 token_amount, uint256 coin_amount); event RemoveLiquidityImbalance( address indexed provider, uint256[] token_amounts, uint256[] fees, uint256 invariant, uint256 token_supply ); uint256 public constant FEE_DENOMINATOR = 1e10; /// @dev protect from division loss when run approximation loop. We cannot divide at the end because of overflow, /// so we add some (small) PRECISION when divide in each iteration uint256 public constant A_PRECISION = 100; /// @dev max iteration of converge calculate uint256 internal constant MAX_ITERATION = 256; uint256 public constant POOL_TOKEN_COMMON_DECIMALS = 18; struct SwapStorage { IERC20[] pooledTokens; LPToken lpToken; uint256[] tokenMultipliers; // token i multiplier to reach POOL_TOKEN_COMMON_DECIMALS uint256[] balances; // effective balance which might different from token balance of the contract 'cause it hold admin fee as well uint256 fee; // swap fee ratio. Charge on any action which move balance state far from the ideal state uint256 adminFee; // admin fee in ratio of swap fee. uint256 initialA; // observation of A, multiplied with A_PRECISION uint256 futureA; uint256 initialATime; uint256 futureATime; } /** * @notice Deposit coins into the pool * @param amounts List of amounts of coins to deposit * @param minMintAmount Minimum amount of LP tokens to mint from the deposit * @return mintAmount Amount of LP tokens received by depositing */ function addLiquidity( SwapStorage storage self, uint256[] memory amounts, uint256 minMintAmount ) external returns (uint256 mintAmount) { uint256 nCoins = self.pooledTokens.length; require(amounts.length == nCoins, "invalidAmountsLength"); uint256[] memory fees = new uint256[](nCoins); uint256 _fee = _feePerToken(self); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 amp = _getAPrecise(self); uint256 D0 = 0; if (tokenSupply > 0) { D0 = _getD(_xp(self.balances, self.tokenMultipliers), amp); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < nCoins; i++) { if (tokenSupply == 0) { require(amounts[i] > 0, "initialDepositRequireAllTokens"); } // get real transfer in amount if (amounts[i] > 0) { newBalances[i] += _doTransferIn(self.pooledTokens[i], amounts[i]); } } uint256 D1 = _getD(_xp(newBalances, self.tokenMultipliers), amp); assert(D1 > D0); // double check if (tokenSupply == 0) { self.balances = newBalances; mintAmount = D1; } else { uint256 diff = 0; for (uint256 i = 0; i < nCoins; i++) { diff = _distance((D1 * self.balances[i]) / D0, newBalances[i]); fees[i] = (_fee * diff) / FEE_DENOMINATOR; self.balances[i] = newBalances[i] - ((fees[i] * self.adminFee) / FEE_DENOMINATOR); newBalances[i] -= fees[i]; } D1 = _getD(_xp(newBalances, self.tokenMultipliers), amp); mintAmount = (tokenSupply * (D1 - D0)) / D0; } require(mintAmount >= minMintAmount, "> slippage"); self.lpToken.mint(msg.sender, mintAmount); emit AddLiquidity(msg.sender, amounts, fees, D1, mintAmount); } function flashLoan( SwapStorage storage self, uint256[] memory amountsOut, address to, bytes calldata data ) external { uint256 nCoins = self.pooledTokens.length; require(amountsOut.length == nCoins, "invalidAmountsLength"); { uint256 tokenSupply = self.lpToken.totalSupply(); require(tokenSupply > 0, "insufficientLiquidity"); } uint256[] memory fees = new uint256[](nCoins); uint256 _fee = _feePerToken(self); uint256 amp = _getAPrecise(self); uint256 D0 = _getD(_xp(self.balances, self.tokenMultipliers), amp); for (uint256 i = 0; i < nCoins; i++) { if (amountsOut[i] > 0) { require(amountsOut[i] < self.balances[i], "insufficientBalance"); fees[i] = (_fee * amountsOut[i]) / FEE_DENOMINATOR; self.pooledTokens[i].safeTransfer(to, amountsOut[i]); } } if (data.length > 0) { IStableSwapCallee(to).zenlinkStableSwapCall( msg.sender, self.pooledTokens, amountsOut, fees, data ); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < nCoins; i++) { if (amountsOut[i] > 0) { newBalances[i] += (_doTransferIn(self.pooledTokens[i], amountsOut[i] + fees[i]) - amountsOut[i]); } } uint256 D1 = _getD(_xp(newBalances, self.tokenMultipliers), amp); assert(D1 > D0); uint256 diff = 0; for (uint256 i = 0; i < nCoins; i++) { diff = _distance((D1 * self.balances[i]) / D0, newBalances[i]); fees[i] = (_fee * diff) / FEE_DENOMINATOR; self.balances[i] = newBalances[i] - ((fees[i] * self.adminFee) / FEE_DENOMINATOR); } emit FlashLoan(msg.sender, to, amountsOut); } function swap( SwapStorage storage self, uint256 i, uint256 j, uint256 inAmount, uint256 minOutAmount ) external returns (uint256) { IERC20 inCoin = self.pooledTokens[i]; uint256[] memory normalizedBalances = _xp(self); inAmount = _doTransferIn(inCoin, inAmount); uint256 x = normalizedBalances[i] + (inAmount * self.tokenMultipliers[i]); uint256 y = _getY(self, i, j, x, normalizedBalances); uint256 dy = normalizedBalances[j] - y - 1; // just in case there were some rounding errors uint256 dy_fee = (dy * self.fee) / FEE_DENOMINATOR; dy = (dy - dy_fee) / self.tokenMultipliers[j]; // denormalize require(dy >= minOutAmount, "> slippage"); uint256 _adminFee = (dy_fee * self.adminFee) / FEE_DENOMINATOR / self.tokenMultipliers[j]; // update balances self.balances[i] += inAmount; self.balances[j] -= dy + _adminFee; self.pooledTokens[j].safeTransfer(msg.sender, dy); emit TokenExchange(msg.sender, i, inAmount, j, dy); return dy; } function removeLiquidity( SwapStorage storage self, uint256 lpAmount, uint256[] memory minAmounts ) external returns (uint256[] memory amounts) { uint256 totalSupply = self.lpToken.totalSupply(); require(lpAmount <= totalSupply); uint256 nCoins = self.pooledTokens.length; uint256[] memory fees = new uint256[](nCoins); amounts = _calculateRemoveLiquidity(self, lpAmount); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "> slippage"); self.balances[i] = self.balances[i] - amounts[i]; self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, lpAmount); emit RemoveLiquidity(msg.sender, amounts, fees, totalSupply - lpAmount); } function removeLiquidityOneToken( SwapStorage storage self, uint256 lpAmount, uint256 index, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); require(totalSupply > 0, "totalSupply = 0"); uint256 numTokens = self.pooledTokens.length; require(lpAmount <= self.lpToken.balanceOf(msg.sender), "> balance"); require(lpAmount <= totalSupply, "> totalSupply"); require(index < numTokens, "tokenNotFound"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateRemoveLiquidityOneToken(self, lpAmount, index); require(dy >= minAmount, "> slippage"); self.balances[index] -= (dy + (dyFee * self.adminFee) / FEE_DENOMINATOR); self.lpToken.burnFrom(msg.sender, lpAmount); self.pooledTokens[index].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne(msg.sender, index, lpAmount, dy); return dy; } function removeLiquidityImbalance( SwapStorage storage self, uint256[] memory amounts, uint256 maxBurnAmount ) external returns (uint256 burnAmount) { uint256 nCoins = self.pooledTokens.length; require(amounts.length == nCoins, "invalidAmountsLength"); uint256 totalSupply = self.lpToken.totalSupply(); require(totalSupply != 0, "totalSupply = 0"); uint256 _fee = _feePerToken(self); uint256 amp = _getAPrecise(self); uint256[] memory newBalances = self.balances; uint256 D0 = _getD(_xp(self), amp); for (uint256 i = 0; i < nCoins; i++) { newBalances[i] -= amounts[i]; } uint256 D1 = _getD(_xp(newBalances, self.tokenMultipliers), amp); uint256[] memory fees = new uint256[](nCoins); for (uint256 i = 0; i < nCoins; i++) { uint256 idealBalance = (D1 * self.balances[i]) / D0; uint256 diff = _distance(newBalances[i], idealBalance); fees[i] = (_fee * diff) / FEE_DENOMINATOR; self.balances[i] = newBalances[i] - ((fees[i] * self.adminFee) / FEE_DENOMINATOR); newBalances[i] -= fees[i]; } // recalculate invariant with fee charged balances D1 = _getD(_xp(newBalances, self.tokenMultipliers), amp); burnAmount = ((D0 - D1) * totalSupply) / D0; assert(burnAmount > 0); burnAmount += 1; // in case of rounding errors require(burnAmount <= maxBurnAmount, "> slippage"); self.lpToken.burnFrom(msg.sender, burnAmount); for (uint256 i = 0; i < nCoins; i++) { if (amounts[i] != 0) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } } emit RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, totalSupply - burnAmount); } /// VIEW FUNCTIONS function getAPrecise(SwapStorage storage self) external view returns (uint256) { return _getAPrecise(self); } /** * Returns portfolio virtual price (for calculating profit) * scaled up by 1e18 */ function getVirtualPrice(SwapStorage storage self) external view returns (uint256) { uint256 D = _getD(_xp(self), _getAPrecise(self)); uint256 tokenSupply = self.lpToken.totalSupply(); if (tokenSupply > 0) { return (D * 10**POOL_TOKEN_COMMON_DECIMALS) / tokenSupply; } return 0; } function getAdminBalance(SwapStorage storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "indexOutOfRange"); return self.pooledTokens[index].balanceOf(address(this)) - (self.balances[index]); } /** * Estimate amount of LP token minted or burned at deposit or withdrawal * without taking fees into account */ function calculateTokenAmount( SwapStorage storage self, uint256[] memory amounts, bool deposit ) external view returns (uint256) { uint256 nCoins = self.pooledTokens.length; require(amounts.length == nCoins, "invalidAmountsLength"); uint256 amp = _getAPrecise(self); uint256 D0 = _getD(_xp(self), amp); uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < nCoins; i++) { if (deposit) { newBalances[i] += amounts[i]; } else { newBalances[i] -= amounts[i]; } } uint256 D1 = _getD(_xp(newBalances, self.tokenMultipliers), amp); uint256 totalSupply = self.lpToken.totalSupply(); if (totalSupply == 0) { return D1; // first depositor take it all } uint256 diff = deposit ? D1 - D0 : D0 - D1; return (diff * self.lpToken.totalSupply()) / D0; } function getA(SwapStorage storage self) external view returns (uint256) { return _getAPrecise(self) / A_PRECISION; } function calculateSwap( SwapStorage storage self, uint256 inIndex, uint256 outIndex, uint256 inAmount ) external view returns (uint256) { uint256[] memory normalizedBalances = _xp(self); uint256 newInBalance = normalizedBalances[inIndex] + (inAmount * self.tokenMultipliers[inIndex]); uint256 outBalance = _getY(self, inIndex, outIndex, newInBalance, normalizedBalances); uint256 outAmount = (normalizedBalances[outIndex] - outBalance - 1) / self.tokenMultipliers[outIndex]; uint256 _fee = (self.fee * outAmount) / FEE_DENOMINATOR; return outAmount - _fee; } function calculateRemoveLiquidity(SwapStorage storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, amount); } function calculateRemoveLiquidityOneToken( SwapStorage storage self, uint256 lpAmount, uint256 tokenIndex ) external view returns (uint256 amount) { (amount, ) = _calculateRemoveLiquidityOneToken(self, lpAmount, tokenIndex); } /// INTERNAL FUNCTIONS /** * Ramping A up or down, return A with precision of A_PRECISION */ function _getAPrecise(SwapStorage storage self) internal view returns (uint256) { if (block.timestamp >= self.futureATime) { return self.futureA; } if (self.futureA > self.initialA) { return self.initialA + ((self.futureA - self.initialA) * (block.timestamp - self.initialATime)) / (self.futureATime - self.initialATime); } return self.initialA - ((self.initialA - self.futureA) * (block.timestamp - self.initialATime)) / (self.futureATime - self.initialATime); } /** * normalized balances of each tokens. */ function _xp(uint256[] memory balances, uint256[] memory rates) internal pure returns (uint256[] memory) { for (uint256 i = 0; i < balances.length; i++) { rates[i] = (rates[i] * balances[i]); } return rates; } function _xp(SwapStorage storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenMultipliers); } /** * Calculate D for *NORMALIZED* balances of each tokens * @param xp normalized balances of token */ function _getD(uint256[] memory xp, uint256 amp) internal pure returns (uint256) { uint256 nCoins = xp.length; uint256 sum = _sumOf(xp); if (sum == 0) { return 0; } uint256 Dprev = 0; uint256 D = sum; uint256 Ann = amp * nCoins; for (uint256 i = 0; i < MAX_ITERATION; i++) { uint256 D_P = D; for (uint256 j = 0; j < xp.length; j++) { D_P = (D_P * D) / (xp[j] * nCoins); } Dprev = D; D = (((Ann * sum) / A_PRECISION + D_P * nCoins) * D) / (((Ann - A_PRECISION) * D) / A_PRECISION + (nCoins + 1) * D_P); if (_distance(D, Dprev) <= 1) { return D; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("invariantCalculationFailed"); } /** * calculate new balance of when swap * Done by solving quadratic equation iteratively. * x_1**2 + x_1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * @param inIndex index of token to swap in * @param outIndex index of token to swap out * @param inBalance new balance (normalized) of input token if the swap success * @return NORMALIZED balance of output token if the swap success */ function _getY( SwapStorage storage self, uint256 inIndex, uint256 outIndex, uint256 inBalance, uint256[] memory normalizedBalances ) internal view returns (uint256) { require(inIndex != outIndex, "sameToken"); uint256 nCoins = self.pooledTokens.length; require(inIndex < nCoins && outIndex < nCoins, "indexOutOfRange"); uint256 amp = _getAPrecise(self); uint256 Ann = amp * nCoins; uint256 D = _getD(normalizedBalances, amp); uint256 sum = 0; // sum of new balances except output token uint256 c = D; for (uint256 i = 0; i < nCoins; i++) { if (i == outIndex) { continue; } uint256 x = i == inIndex ? inBalance : normalizedBalances[i]; sum += x; c = (c * D) / (x * nCoins); } c = (c * D * A_PRECISION) / (Ann * nCoins); uint256 b = sum + (D * A_PRECISION) / Ann; uint256 lastY = 0; uint256 y = D; for (uint256 index = 0; index < MAX_ITERATION; index++) { lastY = y; y = (y * y + c) / (2 * y + b - D); if (_distance(lastY, y) <= 1) { return y; } } revert("yCalculationFailed"); } function _calculateRemoveLiquidity(SwapStorage storage self, uint256 amount) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = (self.balances[i] * (amount)) / (totalSupply); } return amounts; } function _calculateRemoveLiquidityOneToken( SwapStorage storage self, uint256 tokenAmount, uint256 index ) internal view returns (uint256 dy, uint256 fee) { require(index < self.pooledTokens.length, "indexOutOfRange"); uint256 amp = _getAPrecise(self); uint256[] memory xp = _xp(self); uint256 D0 = _getD(xp, amp); uint256 D1 = D0 - (tokenAmount * D0) / self.lpToken.totalSupply(); uint256 newY = _getYD(self, amp, index, xp, D1); uint256[] memory reducedXP = xp; uint256 _fee = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 expectedDx = 0; if (i == index) { expectedDx = (xp[i] * D1) / D0 - newY; } else { expectedDx = xp[i] - (xp[i] * D1) / D0; } reducedXP[i] -= (_fee * expectedDx) / FEE_DENOMINATOR; } dy = reducedXP[index] - _getYD(self, amp, index, reducedXP, D1); dy = (dy - 1) / self.tokenMultipliers[index]; fee = ((xp[index] - newY) / self.tokenMultipliers[index]) - dy; } function _feePerToken(SwapStorage storage self) internal view returns (uint256) { uint256 nCoins = self.pooledTokens.length; return (self.fee * nCoins) / (4 * (nCoins - 1)); } function _getYD( SwapStorage storage self, uint256 A, uint256 index, uint256[] memory xp, uint256 D ) internal view returns (uint256) { uint256 nCoins = self.pooledTokens.length; assert(index < nCoins); uint256 Ann = A * nCoins; uint256 c = D; uint256 s = 0; uint256 _x = 0; uint256 yPrev = 0; for (uint256 i = 0; i < nCoins; i++) { if (i == index) { continue; } _x = xp[i]; s += _x; c = (c * D) / (_x * nCoins); } c = (c * D * A_PRECISION) / (Ann * nCoins); uint256 b = s + (D * A_PRECISION) / Ann; uint256 y = D; for (uint256 i = 0; i < MAX_ITERATION; i++) { yPrev = y; y = (y * y + c) / (2 * y + b - D); if (_distance(yPrev, y) <= 1) { return y; } } revert("invariantCalculationFailed"); } function _doTransferIn(IERC20 token, uint256 amount) internal returns (uint256) { uint256 priorBalance = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), amount); return token.balanceOf(address(this)) - priorBalance; } function _sumOf(uint256[] memory x) internal pure returns (uint256 sum) { sum = 0; for (uint256 i = 0; i < x.length; i++) { sum += x[i]; } } function _distance(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x - y : y - x; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/Address.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!Address.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IStableSwapCallee { function zenlinkStableSwapCall( address sender, IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory fees, bytes calldata data ) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {InputStream} from './InputStream.sol'; import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import {IPair} from "../core/interfaces/IPair.sol"; import {IWETH} from "./interfaces/IWETH.sol"; import {IStableSwapDispatcher} from "./interfaces/IStableSwapDispatcher.sol"; address constant NATIVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; contract UniversalRouter is ReentrancyGuard { using SafeERC20 for IERC20; using InputStream for uint256; error InvalidCommandCode(uint8 code); error WrongAmountInValue(uint256 accAmount, uint256 amountIn); error InsufficientOutAmount(); error InvalidPool(address pool); IStableSwapDispatcher public immutable stableSwapDispatcher; constructor(IStableSwapDispatcher _stableSwapDispatcher) { stableSwapDispatcher = _stableSwapDispatcher; } /// @notice To receive ETH from WETH receive() external payable {} /// @notice Decodes and executes the given route /// @param tokenIn Address of the input token /// @param amountIn Amount of the input token /// @param tokenOut Address of the output token /// @param amountOutMin Minimum amount of the output token /// @param to Receiver address /// @param route The encoded route to execute with /// @return amountOut Actual amount of the output token function processRoute( address tokenIn, uint256 amountIn, address tokenOut, uint256 amountOutMin, address to, bytes memory route ) external payable nonReentrant returns (uint256 amountOut) { return processRouteInternal(tokenIn, amountIn, tokenOut, amountOutMin, to, route); } /// @notice Decodes and executes the given route /// @param tokenIn Address of the input token /// @param amountIn Amount of the input token /// @param tokenOut Address of the output token /// @param amountOutMin Minimum amount of the output token /// @param to Receiver address /// @param route The encoded route to execute with /// @return amountOut Actual amount of the output token function processRouteInternal( address tokenIn, uint256 amountIn, address tokenOut, uint256 amountOutMin, address to, bytes memory route ) private returns (uint256 amountOut) { uint256 amountInAcc = 0; uint256 balanceInitial = tokenOut == NATIVE_ADDRESS ? address(to).balance : IERC20(tokenOut).balanceOf(to); uint256 stream = InputStream.createStream(route); while (stream.isNotEmpty()) { uint8 commandCode = stream.readUint8(); if (commandCode < 20) { if (commandCode == 10) { // UniswapV2 pool swap swapUniswapV2Pool(stream); } else if (commandCode == 4) { // distribute ERC20 tokens from this router to pools distributeERC20Shares(stream); } else if (commandCode == 3) { // initial distribution amountInAcc += distributeERC20Amounts(stream, tokenIn); } else if (commandCode == 5) { // wrap natives and initial distribution amountInAcc += wrapAndDistributeERC20Amounts(stream, amountIn); } else if (commandCode == 6) { // unwrap natives unwrapNative(to, stream); } else { revert InvalidCommandCode(commandCode); } } else if (commandCode < 24) { if (commandCode == 20) { // Zenlink stable pool swap swapZenlinkStableSwap(stream); } else { revert InvalidCommandCode(commandCode); } } else { revert InvalidCommandCode(commandCode); } } if (amountInAcc != amountIn) revert WrongAmountInValue(amountInAcc, amountIn); uint256 balanceFinal = tokenOut == NATIVE_ADDRESS ? address(to).balance : IERC20(tokenOut).balanceOf(to); if (balanceFinal < balanceInitial + amountOutMin) revert InsufficientOutAmount(); amountOut = balanceFinal - balanceInitial; } /// @notice Performs a UniswapV2 pool swap /// @param stream [Pool, TokenIn, Direction, To] /// @return amountOut Amount of the output token function swapUniswapV2Pool(uint256 stream) private returns (uint256 amountOut) { address pool = stream.readAddress(); address tokenIn = stream.readAddress(); uint8 direction = stream.readUint8(); address to = stream.readAddress(); (uint256 reserve0, uint256 reserve1, ) = IPair(pool).getReserves(); if (reserve0 == 0 || reserve1 == 0) revert InvalidPool(pool); (uint256 reserveIn, uint256 reserveOut) = direction == 1 ? (reserve0, reserve1) : (reserve1, reserve0); uint256 amountIn = IERC20(tokenIn).balanceOf(pool) - reserveIn; uint256 amountInWithFee = amountIn * 997; amountOut = (amountInWithFee * reserveOut) / (reserveIn * 1000 + amountInWithFee); (uint256 amount0Out, uint256 amount1Out) = direction == 1 ? (uint256(0), amountOut) : (amountOut, uint256(0)); IPair(pool).swap(amount0Out, amount1Out, to, new bytes(0)); } /// @notice Performs a Zenlink stable pool swap /// @param stream [Pool, To, [TokenIn, TokenOut]] function swapZenlinkStableSwap(uint256 stream) private { address pool = stream.readAddress(); address to = stream.readAddress(); bytes memory swapData = stream.readBytes(); (address tokenIn, address tokenOut) = abi.decode(swapData, (address, address)); stableSwapDispatcher.swap(pool, tokenIn, tokenOut, to); } /// @notice Distributes input ERC20 tokens from msg.sender to addresses. Tokens should be approved /// @param stream [ArrayLength, ...[To, Amount][]]. An array of destinations and token amounts /// @param token Token to distribute /// @return amountTotal Total amount distributed function distributeERC20Amounts(uint256 stream, address token) private returns (uint256 amountTotal) { uint8 num = stream.readUint8(); amountTotal = 0; for (uint256 i = 0; i < num; ++i) { address to = stream.readAddress(); uint256 amount = stream.readUint(); amountTotal += amount; IERC20(token).safeTransferFrom(msg.sender, to, amount); } } /// @notice Wraps all native inputs and distributes wrapped ERC20 tokens from router to addresses /// @param stream [WrapToken, ArrayLength, ...[To, Amount][]]. An array of destinations and token amounts /// @return amountTotal Total amount distributed function wrapAndDistributeERC20Amounts(uint256 stream, uint256 amountIn) private returns (uint256 amountTotal) { address token = stream.readAddress(); IWETH(token).deposit{value: amountIn}(); uint8 num = stream.readUint8(); amountTotal = 0; for (uint256 i = 0; i < num; ++i) { address to = stream.readAddress(); uint256 amount = stream.readUint(); amountTotal += amount; IERC20(token).safeTransfer(to, amount); } } /// @notice Distributes ERC20 tokens from router to addresses /// @notice Quantity for sending is determined by share in 1/65535 /// @notice During routing we can't predict in advance the actual value of internal swaps because of slippage, /// @notice so we have to work with shares - not fixed amounts /// @param stream [Token, ArrayLength, ...[To, ShareAmount][]]. Token to distribute. An array of destinations and token share amounts function distributeERC20Shares(uint256 stream) private { address token = stream.readAddress(); uint8 num = stream.readUint8(); // slot undrain protection uint256 amountTotal = IERC20(token).balanceOf(address(this)) - 1; for (uint256 i = 0; i < num; ++i) { address to = stream.readAddress(); uint16 share = stream.readUint16(); uint256 amount = (amountTotal * share) / 65535; amountTotal -= amount; IERC20(token).safeTransfer(to, amount); } } /// @notice Unwraps the Native Token /// @param receiver Destination of the unwrapped token /// @param stream [Token]. Token to unwrap native function unwrapNative(address receiver, uint256 stream) private { address token = stream.readAddress(); uint256 amount = IERC20(token).balanceOf(address(this)) - 1; // slot undrain protection IWETH(token).withdraw(amount); payable(receiver).transfer(amount); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; library InputStream { function createStream( bytes memory data ) internal pure returns (uint256 stream) { assembly { stream := mload(0x40) mstore(0x40, add(stream, 64)) mstore(stream, data) let length := mload(data) mstore(add(stream, 32), add(data, length)) } } function isNotEmpty(uint256 stream) internal pure returns (bool) { uint256 pos; uint256 finish; assembly { pos := mload(stream) finish := mload(add(stream, 32)) } return pos < finish; } function readUint8(uint256 stream) internal pure returns (uint8 res) { assembly { let pos := mload(stream) pos := add(pos, 1) res := mload(pos) mstore(stream, pos) } } function readUint16(uint256 stream) internal pure returns (uint16 res) { assembly { let pos := mload(stream) pos := add(pos, 2) res := mload(pos) mstore(stream, pos) } } function readUint32(uint256 stream) internal pure returns (uint32 res) { assembly { let pos := mload(stream) pos := add(pos, 4) res := mload(pos) mstore(stream, pos) } } function readUint(uint256 stream) internal pure returns (uint256 res) { assembly { let pos := mload(stream) pos := add(pos, 32) res := mload(pos) mstore(stream, pos) } } function readAddress(uint256 stream) internal pure returns (address res) { assembly { let pos := mload(stream) pos := add(pos, 20) res := mload(pos) mstore(stream, pos) } } function readBytes( uint256 stream ) internal pure returns (bytes memory res) { assembly { let pos := mload(stream) res := add(pos, 32) let length := mload(res) mstore(stream, add(res, length)) } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IStableSwapDispatcher { function swap(address pool, address tokenIn, address tokenOut, address to) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { IPair } from "../../core/interfaces/IPair.sol"; interface IMigrator { function migrate(IPair pair, uint256 amount0Min, uint256 amount1Min, address to, uint256 deadline) external; function migrateMany(IPair[] memory pairs, uint256[] memory amounts0Min, uint256[] memory amounts1Min, address to, uint256 deadline) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { IMigrator } from "./interfaces/IMigrator.sol"; import { IRouter } from "./interfaces/IRouter.sol"; import { IFactory } from "../core/interfaces/IFactory.sol"; import { IPair } from "../core/interfaces/IPair.sol"; import { IWNativeCurrency } from "./interfaces/IWNativeCurrency.sol"; import { Helper } from "../libraries/Helper.sol"; contract Migrator is IMigrator { using SafeERC20 for IERC20; IFactory immutable factoryV1; IRouter immutable router; address immutable wnative; error InvalidMinAmountsParams(); constructor(IFactory _factoryV1, IRouter _router, address _wnative) { factoryV1 = _factoryV1; router = _router; wnative = _wnative; } receive() external payable { require(msg.sender == wnative); } function _migrate(IPair pair, uint256 amount0Min, uint256 amount1Min, address to, uint256 deadline) internal { { uint256 liquidity = IERC20(address(pair)).balanceOf(msg.sender); IERC20(address(pair)).safeTransferFrom(msg.sender, address(pair), liquidity); } address token0 = pair.token0(); address token1 = pair.token1(); (uint256 amount0V1, uint256 amount1V1) = pair.burn(address(this)); IERC20(token0).safeApprove(address(router), amount0V1); IERC20(token1).safeApprove(address(router), amount1V1); (uint256 amount0V2, uint256 amount1V2, ) = router.addLiquidity( token0, token1, amount0V1, amount1V1, amount0Min, amount1Min, to, deadline ); if (amount0V1 > amount0V2) { IERC20(token0).safeApprove(address(router), 0); _transferBack(token0, amount0V1 - amount0V2, to); } else if (amount1V1 > amount1V2) { IERC20(token1).safeApprove(address(router), 0); _transferBack(token1, amount1V1 - amount1V2, to); } } function _transferBack(address token, uint256 amount, address to) internal { if (token == wnative) { IWNativeCurrency(wnative).withdraw(amount); Helper.safeTransferNativeCurrency(to, amount); } else { IERC20(token).safeTransfer(to, amount); } } function migrate( IPair pair, uint256 amount0Min, uint256 amount1Min, address to, uint256 deadline ) override external { _migrate(pair, amount0Min, amount1Min, to, deadline); } function migrateMany( IPair[] memory pairs, uint256[] memory amounts0Min, uint256[] memory amounts1Min, address to, uint256 deadline ) override external { uint256 commonLength = pairs.length; if (amounts0Min.length != commonLength || amounts1Min.length != commonLength) revert InvalidMinAmountsParams(); for (uint256 i; i < commonLength; i++) { _migrate(pairs[i], amounts0Min[i], amounts1Min[i], to, deadline); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IRouter { function factory() external view returns (address); function WNativeCurrency() external view returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquiditySingleToken( address[] calldata path, uint256 amountIn, uint256 amountSwapIn, uint256 amountSwapOutMin, uint256 amountInReserveMin, address to, uint256 deadline ) external returns ( uint256 liquidity ); function addLiquidityNativeCurrency( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountNativeCurrencyMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountNativeCurrency, uint256 liquidity ); function addLiquiditySingleNativeCurrency( address[] calldata path, uint256 amountSwapOut, uint256 nativeCurrencySwapInMax, uint256 nativeCurrencyReserveMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountNativeCurrency, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityNativeCurrency( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountNativeCurrencyMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountNativeCurrency); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactNativeCurrencyForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactNativeCurrency( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForNativeCurrency( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapNativeCurrencyForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IWNativeCurrency { function deposit() external payable; function withdraw(uint256) external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "./Math.sol"; import "../core/interfaces/IPair.sol"; import "../core/interfaces/IFactory.sol"; library Helper { using Math for uint256; function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, "Helper: IDENTICAL_ADDRESSES"); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), "Helper: ZERO_ADDRESS"); } function pairFor( address factory, address tokenA, address tokenB ) internal view returns (address pair) { return IFactory(factory).getPair(tokenA, tokenB); } function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) internal pure returns (uint256 amountB) { require(amountA > 0, "INSUFFICIENT_AMOUNT"); require(reserveA > 0 && reserveB > 0, "INSUFFICIENT_LIQUIDITY"); amountB = amountA.mul(reserveB) / reserveA; } function getReserves( address factory, address tokenA, address tokenB ) internal view returns (uint256 reserveA, uint256 reserveB) { (address token0, ) = sortTokens(tokenA, tokenB); (uint256 reserve0, uint256 reserve1, ) = IPair( pairFor(factory, tokenA, tokenB) ).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } function safeTransferFrom( address token, address from, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0x23b872dd, from, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::transferFrom: transferFrom failed" ); } function safeTransfer( address token, address to, uint256 value ) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call( abi.encodeWithSelector(0xa9059cbb, to, value) ); require( success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeTransfer: transfer failed" ); } function safeTransferNativeCurrency(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require( success, "TransferHelper::safeTransferNativeCurrency: NativeCurrency transfer failed" ); } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountOut) { require(amountIn > 0, "Helper: INSUFFICIENT_INPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "Helper: INSUFFICIENT_LIQUIDITY" ); uint256 amountInWithFee = amountIn.mul(997); uint256 numerator = amountInWithFee.mul(reserveOut); uint256 denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) internal pure returns (uint256 amountIn) { require(amountOut > 0, "Helper: INSUFFICIENT_OUTPUT_AMOUNT"); require( reserveIn > 0 && reserveOut > 0, "Helper: INSUFFICIENT_LIQUIDITY" ); uint256 numerator = reserveIn.mul(amountOut).mul(1000); uint256 denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut( address factory, uint256 amountIn, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "Helper: INVALID_PATH"); amounts = new uint256[](path.length); amounts[0] = amountIn; for (uint256 i; i < path.length - 1; i++) { (uint256 reserveIn, uint256 reserveOut) = getReserves( factory, path[i], path[i + 1] ); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } function getAmountsIn( address factory, uint256 amountOut, address[] memory path ) internal view returns (uint256[] memory amounts) { require(path.length >= 2, "Helper: INVALID_PATH"); amounts = new uint256[](path.length); amounts[amounts.length - 1] = amountOut; for (uint256 i = path.length - 1; i > 0; i--) { (uint256 reserveIn, uint256 reserveOut) = getReserves( factory, path[i - 1], path[i] ); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IWNativeCurrency.sol"; import "./interfaces/ISwapRouterV1.sol"; import "../stableswap/interfaces/IStableSwap.sol"; import "../libraries/Math.sol"; import "../libraries/Helper.sol"; contract SwapRouterV1 is ISwapRouterV1 { using SafeERC20 for IERC20; using Math for uint256; struct StablePath { IStableSwap pool; IStableSwap basePool; address fromToken; address toToken; bool fromBase; } address public override factory; address public override WNativeCurrency; constructor(address _factory, address _WNativeCurrency) { factory = _factory; WNativeCurrency = _WNativeCurrency; } modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "SwapRouterV1: EXPIRED"); _; } receive() external payable { require(msg.sender == WNativeCurrency); } function _swap( uint256[] memory amounts, address[] memory path, address _to ) private { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = Helper.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? Helper.pairFor(factory, output, path[i + 2]) : _to; IPair(Helper.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external override ensure(deadline) returns (uint256[] memory amounts) { amounts = Helper.getAmountsOut(factory, amountIn, path); require( amounts[amounts.length - 1] >= amountOutMin, "SwapRouterV1: INSUFFICIENT_OUTPUT_AMOUNT" ); Helper.safeTransferFrom( path[0], msg.sender, Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external override ensure(deadline) returns (uint256[] memory amounts) { amounts = Helper.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, "SwapRouterV1: EXCESSIVE_INPUT_AMOUNT"); Helper.safeTransferFrom( path[0], msg.sender, Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactNativeCurrencyForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external override payable ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WNativeCurrency, "SwapRouterV1: INVALID_PATH"); amounts = Helper.getAmountsOut(factory, msg.value, path); require( amounts[amounts.length - 1] >= amountOutMin, "SwapRouterV1: INSUFFICIENT_OUTPUT_AMOUNT" ); IWNativeCurrency(WNativeCurrency).deposit{value: amounts[0]}(); require( IERC20(WNativeCurrency).transfer( Helper.pairFor(factory, path[0], path[1]), amounts[0] ) ); _swap(amounts, path, to); } function swapTokensForExactNativeCurrency( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external override ensure(deadline) returns (uint256[] memory amounts) { require( path[path.length - 1] == WNativeCurrency, "SwapRouterV1: INVALID_PATH" ); amounts = Helper.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, "SwapRouterV1: EXCESSIVE_INPUT_AMOUNT"); Helper.safeTransferFrom( path[0], msg.sender, Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWNativeCurrency(WNativeCurrency).withdraw(amounts[amounts.length - 1]); Helper.safeTransferNativeCurrency(to, amounts[amounts.length - 1]); } function swapExactTokensForNativeCurrency( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external override ensure(deadline) returns (uint256[] memory amounts) { require( path[path.length - 1] == WNativeCurrency, "SwapRouterV1: INVALID_PATH" ); amounts = Helper.getAmountsOut(factory, amountIn, path); require( amounts[amounts.length - 1] >= amountOutMin, "SwapRouterV1: INSUFFICIENT_OUTPUT_AMOUNT" ); Helper.safeTransferFrom( path[0], msg.sender, Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWNativeCurrency(WNativeCurrency).withdraw(amounts[amounts.length - 1]); Helper.safeTransferNativeCurrency(to, amounts[amounts.length - 1]); } function swapNativeCurrencyForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external override payable ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WNativeCurrency, "SwapRouterV1: INVALID_PATH"); amounts = Helper.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, "SwapRouterV1: EXCESSIVE_INPUT_AMOUNT"); IWNativeCurrency(WNativeCurrency).deposit{value: amounts[0]}(); require( IERC20(WNativeCurrency).transfer( Helper.pairFor(factory, path[0], path[1]), amounts[0] ) ); _swap(amounts, path, to); if (msg.value > amounts[0]) { Helper.safeTransferNativeCurrency( msg.sender, msg.value - amounts[0] ); } } function _swapPool( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount, uint256 minOutAmount, uint256 deadline ) private returns (uint256 amountOut) { IERC20 coin = pool.getToken(fromIndex); coin.safeIncreaseAllowance(address(pool), inAmount); amountOut = pool.swap(fromIndex, toIndex, inAmount, minOutAmount, deadline); } function _swapPoolFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) private returns (uint256 amountOut) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256[] memory base_amounts = new uint256[](basePool.getNumberOfTokens()); base_amounts[tokenIndexFrom] = dx; IERC20 coin = basePool.getToken(tokenIndexFrom); coin.safeIncreaseAllowance(address(basePool), dx); uint256 baseLpAmount = basePool.addLiquidity(base_amounts, 0, deadline); if (baseTokenIndex != tokenIndexTo) { amountOut = _swapPool(pool, baseTokenIndex, tokenIndexTo, baseLpAmount, minDy, deadline); } else { amountOut = baseLpAmount; } } function _swapPoolToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) private returns (uint256 amountOut) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256 tokenLPAmount = dx; if (baseTokenIndex != tokenIndexFrom) { tokenLPAmount = _swapPool(pool, tokenIndexFrom, baseTokenIndex, dx, 0, deadline); } baseToken.safeIncreaseAllowance(address(basePool), tokenLPAmount); amountOut = basePool.removeLiquidityOneToken(tokenLPAmount, tokenIndexTo, minDy, deadline); } function swapPool( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount, uint256 minOutAmount, address to, uint256 deadline ) external override ensure(deadline) returns (uint256 amountOut) { IERC20 coin = pool.getToken(fromIndex); coin.safeTransferFrom(msg.sender, address(this), inAmount); amountOut = _swapPool(pool, fromIndex, toIndex, inAmount, minOutAmount, deadline); IERC20 coinTo = pool.getToken(toIndex); coinTo.safeTransfer(to, amountOut); } function swapPoolFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, address to, uint256 deadline ) external override ensure(deadline) returns (uint256 amountOut) { IERC20 coin = basePool.getToken(tokenIndexFrom); coin.safeTransferFrom(msg.sender, address(this), dx); amountOut = _swapPoolFromBase(pool, basePool, tokenIndexFrom, tokenIndexTo, dx, minDy, deadline); IERC20 coinTo = pool.getToken(tokenIndexTo); coinTo.safeTransfer(to, amountOut); } function swapPoolToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, address to, uint256 deadline ) external override ensure(deadline) returns (uint256 amountOut) { IERC20 coin = pool.getToken(tokenIndexFrom); coin.safeTransferFrom(msg.sender, address(this), dx); amountOut = _swapPoolToBase(pool, basePool, tokenIndexFrom, tokenIndexTo, dx, minDy, deadline); IERC20 coinTo = basePool.getToken(tokenIndexTo); coinTo.safeTransfer(to, amountOut); } function _anyStableSwap( uint256 amountIn, Route calldata route, uint256 deadline ) private returns (address tokenOut, uint256 amountOut) { StablePath memory path = _decodeStableSwapCallData(route.callData); tokenOut = path.toToken; if (address(path.basePool) == address(0)) { amountOut = _swapPool( path.pool, path.pool.getTokenIndex(path.fromToken), path.pool.getTokenIndex(path.toToken), amountIn, 0, deadline ); } else if (path.fromBase) { amountOut = _swapPoolFromBase( path.pool, path.basePool, path.basePool.getTokenIndex(path.fromToken), path.pool.getTokenIndex(path.toToken), amountIn, 0, deadline ); } else { amountOut = _swapPoolToBase( path.pool, path.basePool, path.pool.getTokenIndex(path.fromToken), path.basePool.getTokenIndex(path.toToken), amountIn, 0, deadline ); } } function _swapThroughStablePool( address tokenIn, uint256 amountIn, Route[] calldata routes, uint256 deadline ) private returns (address tokenOut, uint256 amountOut) { tokenOut = tokenIn; amountOut = amountIn; for (uint256 i = 0; i < routes.length; i++) { if (routes[i].stable) { (tokenOut, amountOut) = _anyStableSwap(amountOut, routes[i], deadline); } else { address[] memory path = _decodeAmmCalldata(routes[i].callData); tokenOut = path[path.length - 1]; uint256[] memory amounts = Helper.getAmountsOut(factory, amountOut, path); Helper.safeTransfer( path[0], Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); amountOut = amounts[amounts.length - 1]; } } } function swapExactTokensForTokensThroughStablePool( uint256 amountIn, uint256 amountOutMin, Route[] calldata routes, address to, uint256 deadline ) external override ensure(deadline) returns (uint256 amountOut) { address tokenIn; if (routes[0].stable) { tokenIn = _decodeStableSwapCallData(routes[0].callData).fromToken; } else { tokenIn = _decodeAmmCalldata(routes[0].callData)[0]; } Helper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address tokenOut; (tokenOut, amountOut) = _swapThroughStablePool(tokenIn, amountIn, routes, deadline); require( amountOut >= amountOutMin, "SwapRouterV1: INSUFFICIENT_OUTPUT_AMOUNT" ); IERC20(tokenOut).safeTransfer(to, amountOut); } function swapExactNativeCurrencyForTokensThroughStablePool( uint256 amountOutMin, Route[] calldata routes, address to, uint256 deadline ) external override payable ensure(deadline) returns (uint256 amountOut) { require(!routes[0].stable, "SwapRouterV1: INVALID_ROUTES"); address tokenIn = _decodeAmmCalldata(routes[0].callData)[0]; require(tokenIn == WNativeCurrency, "SwapRouterV1: INVALID_ROUTES"); IWNativeCurrency(WNativeCurrency).deposit{value: msg.value}(); address tokenOut; (tokenOut, amountOut) = _swapThroughStablePool(tokenIn, msg.value, routes, deadline); require( amountOut >= amountOutMin, "SwapRouterV1: INSUFFICIENT_OUTPUT_AMOUNT" ); IERC20(tokenOut).safeTransfer(to, amountOut); } function swapExactTokensForNativeCurrencyThroughStablePool( uint256 amountIn, uint256 amountOutMin, Route[] calldata routes, address to, uint256 deadline ) external override ensure(deadline) returns (uint256 amountOut) { require(!routes[routes.length - 1].stable, "SwapRouterV1: INVALID_ROUTES"); address[] memory tokenOutPath = _decodeAmmCalldata(routes[routes.length - 1].callData); require(tokenOutPath[tokenOutPath.length - 1] == WNativeCurrency, "SwapRouterV1: INVALID_ROUTES"); address tokenIn; if (routes[0].stable) { tokenIn = _decodeStableSwapCallData(routes[0].callData).fromToken; } else { tokenIn = _decodeAmmCalldata(routes[0].callData)[0]; } Helper.safeTransferFrom(tokenIn, msg.sender, address(this), amountIn); address tokenOut; (tokenOut, amountOut) = _swapThroughStablePool(tokenIn, amountIn, routes, deadline); require( amountOut >= amountOutMin, "SwapRouterV1: INSUFFICIENT_OUTPUT_AMOUNT" ); IWNativeCurrency(WNativeCurrency).withdraw(amountOut); Helper.safeTransferNativeCurrency(to, amountOut); } function _decodeAmmCalldata(bytes memory data) private pure returns (address[] memory path) { path = abi.decode(data, (address[])); } function _decodeStableSwapCallData(bytes memory data) private pure returns (StablePath memory path) { ( IStableSwap pool, IStableSwap basePool, address fromToken, address toToken, bool fromBase ) = abi.decode(data, (IStableSwap, IStableSwap, address, address, bool)); return StablePath(pool, basePool, fromToken, toToken, fromBase); } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external override pure returns (uint256 amountOut) { return Helper.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external override pure returns (uint256 amountIn) { return Helper.getAmountOut(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint256 amountIn, address[] memory path) external override view returns (uint256[] memory amounts) { return Helper.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) external override view returns (uint256[] memory amounts) { return Helper.getAmountsIn(factory, amountOut, path); } function calculateSwap( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount ) external override view returns (uint256) { return pool.calculateSwap(fromIndex, toIndex, inAmount); } function calculateSwapFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external override view returns (uint256) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256[] memory base_amounts = new uint256[](basePool.getNumberOfTokens()); base_amounts[tokenIndexFrom] = dx; uint256 baseLpAmount = basePool.calculateTokenAmount(base_amounts, true); if (baseTokenIndex == tokenIndexTo) { return baseLpAmount; } return pool.calculateSwap(baseTokenIndex, tokenIndexTo, baseLpAmount); } function calculateSwapToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external override view returns (uint256) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256 tokenLPAmount = dx; if (baseTokenIndex != tokenIndexFrom) { tokenLPAmount = pool.calculateSwap(tokenIndexFrom, baseTokenIndex, dx); } return basePool.calculateRemoveLiquidityOneToken(tokenLPAmount, tokenIndexTo); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../../stableswap/interfaces/IStableSwap.sol"; interface ISwapRouterV1 { struct Route { bool stable; bytes callData; } function factory() external view returns (address); function WNativeCurrency() external view returns (address); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactNativeCurrencyForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactNativeCurrency( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForNativeCurrency( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapNativeCurrencyForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapPool( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount, uint256 minOutAmount, address to, uint256 deadline ) external returns (uint256 amountOut); function swapPoolFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, address to, uint256 deadline ) external returns (uint256 amountOut); function swapPoolToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, address to, uint256 deadline ) external returns (uint256 amountOut); function swapExactTokensForTokensThroughStablePool( uint256 amountIn, uint256 amountOutMin, Route[] calldata routes, address to, uint256 deadline ) external returns (uint256 amountOut); function swapExactNativeCurrencyForTokensThroughStablePool( uint256 amountOutMin, Route[] calldata routes, address to, uint256 deadline ) external payable returns (uint256 amountOut); function swapExactTokensForNativeCurrencyThroughStablePool( uint256 amountIn, uint256 amountOutMin, Route[] calldata routes, address to, uint256 deadline ) external returns (uint256 amountOut); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut( uint256 amountIn, address[] memory path ) external view returns (uint256[] memory amounts); function getAmountsIn( uint256 amountOut, address[] memory path ) external view returns (uint256[] memory amounts); function calculateSwap( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount ) external view returns (uint256); function calculateSwapFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "../libraries/AdminUpgradeable.sol"; import "../libraries/Math.sol"; contract ZenlinkToken is ERC20, AdminUpgradeable { using Math for uint256; // global transfer switch bool public transferable; uint8 private decimal; uint256 public maxTotalSupply; // address map that can be transferred at any time. mapping(address => bool) public whitelistMap; modifier canTransfer() { require( transferable == true || whitelistMap[msg.sender] == true, "can't transfer" ); _; } constructor( string memory setSymbol, string memory setName, uint8 setDecimal, uint256 initialBalance, uint256 maxMint ) ERC20(setName, setSymbol) { require(maxMint >= initialBalance, "initialBalance bigger than max"); _initializeAdmin(msg.sender); _mint(msg.sender, initialBalance); whitelistMap[msg.sender] = true; decimal = setDecimal; maxTotalSupply = maxMint; } function decimals() public view virtual override returns (uint8) { return decimal; } function addWhitelist(address user) external onlyAdmin { whitelistMap[user] = true; } function removeWhitelist(address user) external onlyAdmin { delete whitelistMap[user]; } function enableTransfer() external onlyAdmin { transferable = true; } function disableTransfer() external onlyAdmin { transferable = false; } function mint(uint256 mintAmount) external onlyAdmin { require(totalSupply().add(mintAmount) <= maxTotalSupply, "can't mint"); _mint(msg.sender, mintAmount); } function transfer(address recipient, uint256 amount) public virtual override canTransfer returns (bool) { return ERC20.transfer(recipient, amount); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override canTransfer returns (bool) { return ERC20.transferFrom(sender, recipient, amount); } function burn(uint256 amount) public virtual canTransfer{ ERC20._burn(msg.sender, amount); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../libraries/Helper.sol"; import "../libraries/Math.sol"; import "../libraries/AdminUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract Stake is ReentrancyGuard, AdminUpgradeable { using Math for uint256; // Info of each staker struct StakerInfo { uint256 stakedAmount; // How many stake tokens the user has provided uint256 lastUpdatedBlock; // Last block number that user behavior occurs uint256 accInterest; // Accumulated interest the user has owned } // The STAKED TOKEN address public immutable STAKED_TOKEN; // The REWARD TOKEN address public immutable REWARD_TOKEN; // The block when stake starts uint256 public immutable START_BLOCK; // The block when stake ends uint256 public immutable END_BLOCK; // The total interest of whole stake uint256 public totalInterest; // The total staked amount of whole stake uint256 public totalStakedAmount; // The total reward amount of whole stake uint256 public totalRewardAmount; // Is stake paused bool private _stakePaused; // Info of each staker that stakes token mapping(address => StakerInfo) private _stakerInfos; event Staked(address indexed user, uint256 amount, uint256 interest); event Redeem(address indexed user, uint256 redeemAmount, uint256 interest); event RewardsClaimed(address indexed to, uint256 amount); event WithdrawExtraFunds(address indexed token, address indexed to, uint256 amount); event StakePaused(address indexed caller); event StakeUnpaused(address indexed caller); constructor( address _stakeToken, address _rewardToken, uint256 _startBlock, uint256 _endBlock ) { require(_startBlock >= block.number, 'INVALID_START_BLOCK'); require(_endBlock > _startBlock, 'INVALID_STAKE_PERIOD'); _initializeAdmin(msg.sender); STAKED_TOKEN = _stakeToken; REWARD_TOKEN = _rewardToken; START_BLOCK = _startBlock; END_BLOCK = _endBlock; totalRewardAmount = IERC20(_rewardToken).balanceOf(address(this)); _stakePaused = false; } modifier beforeEndPeriod() { require(block.number < END_BLOCK, "OVER_PERIOD"); _; } modifier whenStakeNotPaused() { require(!_stakePaused, "STAKE_PAUSED"); _; } /** * @dev add reward amount by admin **/ function addReward(uint256 amount) external onlyAdmin beforeEndPeriod { Helper.safeTransferFrom( REWARD_TOKEN, msg.sender, address(this), amount ); totalRewardAmount = totalRewardAmount.add(amount); } /** * @dev remove reward amount by admin **/ function removeReward(uint256 amount) external onlyAdmin beforeEndPeriod { require(amount <= totalRewardAmount, 'INSUFFICIENT_REWARD_AMOUNT'); Helper.safeTransfer(REWARD_TOKEN, msg.sender, amount); totalRewardAmount = totalRewardAmount.sub(amount); } /** * @dev Return funds directly transfered to this contract, will not affect the portion of the amount * that participated in stake using `stake` function **/ function withdrawExtraFunds(address token, address to, uint256 amount) external onlyAdmin { if (token == STAKED_TOKEN) { uint256 stakedBalance = IERC20(STAKED_TOKEN).balanceOf(address(this)); require(stakedBalance.sub(amount) >= totalStakedAmount, 'INSUFFICIENT_STAKED_BALANCE'); } if (token == REWARD_TOKEN) { uint256 rewardBalance = IERC20(REWARD_TOKEN).balanceOf(address(this)); require(rewardBalance.sub(amount) >= totalRewardAmount, 'INSUFFICIENT_REWARD_BALANCE'); } Helper.safeTransfer(token, to, amount); emit WithdrawExtraFunds(token, to, amount); } function getStakerInfo(address staker) external view returns (uint256 stakedAmount, uint256 accInterest) { StakerInfo memory stakerInfo = _stakerInfos[staker]; stakedAmount = stakerInfo.stakedAmount; accInterest = stakerInfo.accInterest; } function pauseStake() external onlyAdmin { require(!_stakePaused, 'STAKE_PAUSED'); _stakePaused = true; emit StakePaused(msg.sender); } function unpauseStake() external onlyAdmin { require(_stakePaused, 'STAKE_UNPAUSED'); _stakePaused = false; emit StakeUnpaused(msg.sender); } /** * @dev Stakes tokens * @param amount Amount to stake **/ function stake(uint256 amount) external beforeEndPeriod nonReentrant whenStakeNotPaused { require(amount > 0, 'INVALID_ZERO_AMOUNT'); StakerInfo storage stakerInfo = _stakerInfos[msg.sender]; Helper.safeTransferFrom( STAKED_TOKEN, msg.sender, address(this), amount ); stakerInfo.lastUpdatedBlock = block.number < START_BLOCK ? START_BLOCK : block.number; uint256 addedInterest = amount.mul(END_BLOCK.sub(stakerInfo.lastUpdatedBlock)); totalInterest = totalInterest.add(addedInterest); totalStakedAmount = totalStakedAmount.add(amount); stakerInfo.stakedAmount = stakerInfo.stakedAmount.add(amount); stakerInfo.accInterest = stakerInfo.accInterest.add(addedInterest); emit Staked(msg.sender, amount, addedInterest); } /** * @dev Redeems staked tokens * @param amount Amount to redeem **/ function redeem(uint256 amount) external nonReentrant { require(amount > 0, 'INVALID_ZERO_AMOUNT'); require(block.number > START_BLOCK, "STAKE_NOT_STARTED"); StakerInfo storage stakerInfo = _stakerInfos[msg.sender]; require(amount <= totalStakedAmount, 'INSUFFICIENT_TOTAL_STAKED_AMOUNT'); require(amount <= stakerInfo.stakedAmount, 'INSUFFICIENT_STAKED_AMOUNT'); stakerInfo.lastUpdatedBlock = block.number < END_BLOCK ? block.number : END_BLOCK; uint256 removedInterest = amount.mul(END_BLOCK.sub(stakerInfo.lastUpdatedBlock)); totalInterest = totalInterest.sub(removedInterest); totalStakedAmount = totalStakedAmount.sub(amount); stakerInfo.stakedAmount = stakerInfo.stakedAmount.sub(amount); stakerInfo.accInterest = stakerInfo.accInterest.sub(removedInterest); Helper.safeTransfer(STAKED_TOKEN, msg.sender, amount); emit Redeem(msg.sender, amount, removedInterest); } /** * @dev Return the total amount of estimated rewards from an staker * @param staker The staker address * @return The rewards */ function getEstimatedRewardsBalance(address staker) external view returns (uint256) { StakerInfo memory stakerInfo = _stakerInfos[staker]; if (totalInterest != 0) { return totalRewardAmount.mul(stakerInfo.accInterest) / totalInterest; } return 0; } /** * @dev Claims all amount of `REWARD_TOKEN` calculated from staker interest **/ function claim() external nonReentrant { require(block.number > END_BLOCK, "STAKE_NOT_FINISHED"); require(totalInterest > 0, 'INVALID_ZERO_TOTAL_INTEREST'); StakerInfo storage stakerInfo = _stakerInfos[msg.sender]; require(stakerInfo.accInterest > 0, "INSUFFICIENT_ACCUMULATED_INTEREST"); uint256 claimRewardAmount = totalRewardAmount.mul(stakerInfo.accInterest) / totalInterest; stakerInfo.accInterest = 0; stakerInfo.lastUpdatedBlock = block.number; Helper.safeTransfer(REWARD_TOKEN, msg.sender, claimRewardAmount); emit RewardsClaimed(msg.sender, claimRewardAmount); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "./interfaces/IRouter.sol"; import "./interfaces/IWNativeCurrency.sol"; import "../libraries/Helper.sol"; import "../libraries/Math.sol"; contract Router is IRouter { using Math for uint256; address public override factory; address public override WNativeCurrency; constructor(address _factory, address _WNativeCurrency) { factory = _factory; WNativeCurrency = _WNativeCurrency; } modifier ensure(uint256 deadline) { require(deadline >= block.timestamp, "Router: EXPIRED"); _; } receive() external payable { require(msg.sender == WNativeCurrency); // only accept Native Currency via fallback from the WNativeCurrency contract } function addLiquidity( address token0, address token1, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min, address to, uint256 deadline ) public override ensure(deadline) returns ( uint256 amount0, uint256 amount1, uint256 liquidity ) { (amount0, amount1) = _addLiquidity( token0, token1, amount0Desired, amount1Desired, amount0Min, amount1Min ); address pair = Helper.pairFor(factory, token0, token1); Helper.safeTransferFrom(token0, msg.sender, pair, amount0); Helper.safeTransferFrom(token1, msg.sender, pair, amount1); liquidity = IPair(pair).mint(to); } function addLiquiditySingleToken( address[] calldata path, uint256 amountIn, uint256 amountSwapOut, uint256 amountSwapInMax, uint256 amountInReserveMin, address to, uint256 deadline ) external override ensure(deadline) returns (uint256 liquidity) { address token0 = path[0]; address token1 = path[path.length - 1]; uint256[] memory amounts = swapTokensForExactTokens( amountSwapOut, amountSwapInMax, path, to, deadline ); uint256 amountInReserve = amountIn - amounts[0]; (, , liquidity) = addLiquidity( token1, token0, amounts[amounts.length - 1], amountInReserve, amounts[amounts.length - 1], amountInReserveMin, to, deadline ); } function addLiquidityNativeCurrency( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountNativeCurrencyMin, address to, uint256 deadline ) external payable override ensure(deadline) returns ( uint256 amountToken, uint256 amountNativeCurrency, uint256 liquidity ) { (amountToken, amountNativeCurrency) = _addLiquidity( token, WNativeCurrency, amountTokenDesired, msg.value, amountTokenMin, amountNativeCurrencyMin ); address pair = Helper.pairFor(factory, token, WNativeCurrency); Helper.safeTransferFrom(token, msg.sender, pair, amountToken); IWNativeCurrency(WNativeCurrency).deposit{ value: amountNativeCurrency }(); require(IERC20(WNativeCurrency).transfer(pair, amountNativeCurrency)); liquidity = IPair(pair).mint(to); if (msg.value > amountNativeCurrency) Helper.safeTransferNativeCurrency( msg.sender, msg.value - amountNativeCurrency ); // refund dust native currency, if any } function addLiquiditySingleNativeCurrency( address[] memory path, uint256 amountSwapOut, uint256 nativeCurrencySwapInMax, uint256 nativeCurrencyReserveMin, address to, uint256 deadline ) external payable override ensure(deadline) returns ( uint256 amountToken, uint256 amountNativeCurrency, uint256 liquidity ) { // Swap require(path[0] == WNativeCurrency, "Router: INVALID_PATH"); uint256[] memory amounts = Helper.getAmountsIn( factory, amountSwapOut, path ); require(amounts[0] <= msg.value, "Router: EXCESSIVE_INPUT_AMOUNT"); IWNativeCurrency(WNativeCurrency).deposit{value: amounts[0]}(); require( IERC20(WNativeCurrency).transfer( Helper.pairFor(factory, path[0], path[1]), amounts[0] ) ); _swap(amounts, path, to); require( amounts[0] <= nativeCurrencySwapInMax, "not allow bigger than nativeCurrencySwapInMax" ); // Addliquidity address token = path[path.length - 1]; uint256 nativeCurrencyReserve = msg.value - amounts[0]; (amountToken, amountNativeCurrency) = _addLiquidity( token, WNativeCurrency, amounts[amounts.length - 1], nativeCurrencyReserve, amounts[amounts.length - 1], nativeCurrencyReserveMin ); address pair = Helper.pairFor(factory, token, WNativeCurrency); Helper.safeTransferFrom(token, msg.sender, pair, amountToken); IWNativeCurrency(WNativeCurrency).deposit{ value: amountNativeCurrency }(); require(IERC20(WNativeCurrency).transfer(pair, amountNativeCurrency)); liquidity = IPair(pair).mint(to); if (msg.value > (amountNativeCurrency + amounts[0])) Helper.safeTransferNativeCurrency( msg.sender, msg.value - (amountNativeCurrency + amounts[0]) ); // refund dust native currency, if any } function _addLiquidity( address token0, address token1, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) private returns (uint256 amount0, uint256 amount1) { if (IFactory(factory).getPair(token0, token1) == address(0)) { IFactory(factory).createPair(token0, token1); } (uint256 reserve0, uint256 reserve1) = Helper.getReserves( factory, token0, token1 ); if (reserve0 == 0 && reserve1 == 0) { (amount0, amount1) = (amount0Desired, amount1Desired); } else { uint256 amount1Optimal = Helper.quote( amount0Desired, reserve0, reserve1 ); if (amount1Optimal <= amount1Desired) { require( amount1Optimal >= amount1Min, "Router: INSUFFICIENT_1_AMOUNT" ); (amount0, amount1) = (amount0Desired, amount1Optimal); } else { uint256 amount0Optimal = Helper.quote( amount1Desired, reserve1, reserve0 ); require(amount0Optimal <= amount0Desired); require( amount0Optimal >= amount0Min, "Router: INSUFFICIENT_0_AMOUNT" ); (amount0, amount1) = (amount0Optimal, amount1Desired); } } } function removeLiquidity( address token0, address token1, uint256 liquidity, uint256 amount0Min, uint256 amount1Min, address to, uint256 deadline ) public override ensure(deadline) returns (uint256 amount0, uint256 amount1) { address pair = Helper.pairFor(factory, token0, token1); IERC20(pair).transferFrom(msg.sender, pair, liquidity); (uint256 amountA, uint256 amountB) = IPair(pair).burn(to); (address tokenA, ) = Helper.sortTokens(token0, token1); (amount0, amount1) = tokenA == token0 ? (amountA, amountB) : (amountB, amountA); require(amount0 >= amount0Min, "Router: INSUFFICIENT_0_AMOUNT"); require(amount1 >= amount1Min, "Router: INSUFFICIENT_1_AMOUNT"); } function removeLiquidityNativeCurrency( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountNativeCurrencyMin, address to, uint256 deadline ) public override ensure(deadline) returns (uint256 amountToken, uint256 amountNativeCurrency) { (amountToken, amountNativeCurrency) = removeLiquidity( token, WNativeCurrency, liquidity, amountTokenMin, amountNativeCurrencyMin, address(this), deadline ); Helper.safeTransfer(token, to, amountToken); IWNativeCurrency(WNativeCurrency).withdraw(amountNativeCurrency); Helper.safeTransferNativeCurrency(to, amountNativeCurrency); } function _swap( uint256[] memory amounts, address[] memory path, address _to ) private { for (uint256 i; i < path.length - 1; i++) { (address input, address output) = (path[i], path[i + 1]); (address token0, ) = Helper.sortTokens(input, output); uint256 amountOut = amounts[i + 1]; (uint256 amount0Out, uint256 amount1Out) = input == token0 ? (uint256(0), amountOut) : (amountOut, uint256(0)); address to = i < path.length - 2 ? Helper.pairFor(factory, output, path[i + 2]) : _to; IPair(Helper.pairFor(factory, input, output)).swap( amount0Out, amount1Out, to, new bytes(0) ); } } function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) public override ensure(deadline) returns (uint256[] memory amounts) { amounts = Helper.getAmountsOut(factory, amountIn, path); require( amounts[amounts.length - 1] >= amountOutMin, "Router: INSUFFICIENT_OUTPUT_AMOUNT" ); Helper.safeTransferFrom( path[0], msg.sender, Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) public override ensure(deadline) returns (uint256[] memory amounts) { amounts = Helper.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, "Router: EXCESSIVE_INPUT_AMOUNT"); Helper.safeTransferFrom( path[0], msg.sender, Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, to); } function swapExactNativeCurrencyForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WNativeCurrency, "Router: INVALID_PATH"); amounts = Helper.getAmountsOut(factory, msg.value, path); require( amounts[amounts.length - 1] >= amountOutMin, "Router: INSUFFICIENT_OUTPUT_AMOUNT" ); IWNativeCurrency(WNativeCurrency).deposit{value: amounts[0]}(); require( IERC20(WNativeCurrency).transfer( Helper.pairFor(factory, path[0], path[1]), amounts[0] ) ); _swap(amounts, path, to); } function swapTokensForExactNativeCurrency( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external override ensure(deadline) returns (uint256[] memory amounts) { require( path[path.length - 1] == WNativeCurrency, "Router: INVALID_PATH" ); amounts = Helper.getAmountsIn(factory, amountOut, path); require(amounts[0] <= amountInMax, "Router: EXCESSIVE_INPUT_AMOUNT"); Helper.safeTransferFrom( path[0], msg.sender, Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWNativeCurrency(WNativeCurrency).withdraw(amounts[amounts.length - 1]); Helper.safeTransferNativeCurrency(to, amounts[amounts.length - 1]); } function swapExactTokensForNativeCurrency( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external override ensure(deadline) returns (uint256[] memory amounts) { require( path[path.length - 1] == WNativeCurrency, "Router: INVALID_PATH" ); amounts = Helper.getAmountsOut(factory, amountIn, path); require( amounts[amounts.length - 1] >= amountOutMin, "Router: INSUFFICIENT_OUTPUT_AMOUNT" ); Helper.safeTransferFrom( path[0], msg.sender, Helper.pairFor(factory, path[0], path[1]), amounts[0] ); _swap(amounts, path, address(this)); IWNativeCurrency(WNativeCurrency).withdraw(amounts[amounts.length - 1]); Helper.safeTransferNativeCurrency(to, amounts[amounts.length - 1]); } function swapNativeCurrencyForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable override ensure(deadline) returns (uint256[] memory amounts) { require(path[0] == WNativeCurrency, "Router: INVALID_PATH"); amounts = Helper.getAmountsIn(factory, amountOut, path); require(amounts[0] <= msg.value, "Router: EXCESSIVE_INPUT_AMOUNT"); IWNativeCurrency(WNativeCurrency).deposit{value: amounts[0]}(); require( IERC20(WNativeCurrency).transfer( Helper.pairFor(factory, path[0], path[1]), amounts[0] ) ); _swap(amounts, path, to); if (msg.value > amounts[0]) Helper.safeTransferNativeCurrency( msg.sender, msg.value - amounts[0] ); // refund dust eth, if any } function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) public pure override returns (uint256 amountOut) { return Helper.getAmountOut(amountIn, reserveIn, reserveOut); } function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) public pure override returns (uint256 amountIn) { return Helper.getAmountOut(amountOut, reserveIn, reserveOut); } function getAmountsOut(uint256 amountIn, address[] memory path) public view override returns (uint256[] memory amounts) { return Helper.getAmountsOut(factory, amountIn, path); } function getAmountsIn(uint256 amountOut, address[] memory path) public view override returns (uint256[] memory amounts) { return Helper.getAmountsIn(factory, amountOut, path); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../periphery/interfaces/IWNativeCurrency.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; contract NativeCurrency is IWNativeCurrency, ERC20 { constructor(string memory setName, string memory setSymbol) ERC20(setName, setSymbol) {} function deposit() public payable override { _mint(msg.sender, msg.value); } function withdraw(uint256 wad) public override { require(balanceOf(msg.sender) >= wad, ""); _burn(msg.sender, wad); payable(msg.sender).transfer(wad); } function totalSupply() public view override returns (uint256) { return address(this).balance; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../libraries/Math.sol"; import "../libraries/Helper.sol"; import "../libraries/AdminUpgradeable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract Farming is AdminUpgradeable { using Math for uint256; // Info of each user. struct UserInfo { uint256 amount; // How many farming tokens that user has provided. uint256[] rewardDebt; // Reward debt. See explanation below. // pending reward = (user.amount * pool.accRewardPerShare) - user.rewardDebt // Whenever a user stakes or redeems farming tokens to a pool. Here's what happens: // 1. The pool's `accRewardPerShare` (and `lastRewardBlock`) gets updated. // 2. User add pending reward to his/her info. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. uint256[] pending; // Pending rewards. uint256 nextClaimableBlock; // Next Block user can claim rewards. } // Info of each pool. struct PoolInfo { address farmingToken; // Address of farming token contract. address[] rewardTokens; // Reward tokens. uint256[] rewardPerBlock; // Reward tokens created per block. uint256[] accRewardPerShare; // Accumulated rewards per share, times 1e12. uint256[] remainingRewards; // remaining rewards in the pool. uint256 amount; // amount of farming token. uint256 lastRewardBlock; // Last block number that pools updated. uint256 startBlock; // Start block of pools. uint256 claimableInterval; // How many blocks of rewards can be claimed. } // Info of each pool. PoolInfo[] private poolInfo; // Info of each user that stakes farming tokens. mapping(uint256 => mapping(address => UserInfo)) private userInfo; event PoolAdded(address indexed farmingToken); event ClaimableBlockUpdated(uint256 indexed pid, uint256 interval); event Charged(uint256 indexed pid, address[] rewards, uint256[] amounts); event WithdrawRewards(uint256 indexed pid, address[] rewards, uint256[] amounts); event Stake(address indexed user, uint256 indexed pid, uint256 amount); event Redeem(address indexed user, uint256 indexed pid, uint256 amount); event Claim( address indexed user, uint256 indexed pid, address[] rewards, uint256[] amounts ); event EmergencyWithdraw( address indexed user, uint256 indexed pid, uint256 amount ); constructor() { _initializeAdmin(msg.sender); } function poolLength() external view returns (uint256) { return poolInfo.length; } // Add a new farming token to the pool. Can only be called by the admin. // XXX DO NOT add the same farming token more than once. Rewards will be messed up if you do. function add( address _farmingToken, address[] memory _rewardTokens, uint256[] memory _rewardPerBlock, uint256 _startBlock, uint256 _claimableInterval ) external onlyAdmin { require(_rewardTokens.length == _rewardPerBlock.length, 'INVALID_REWARDS'); uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock; uint256[] memory accRewardPerShare = new uint256[](_rewardTokens.length); uint256[] memory remainingRewards = new uint256[](_rewardTokens.length); poolInfo.push( PoolInfo({ farmingToken: _farmingToken, rewardTokens: _rewardTokens, rewardPerBlock: _rewardPerBlock, accRewardPerShare: accRewardPerShare, remainingRewards: remainingRewards, amount: 0, lastRewardBlock: lastRewardBlock, startBlock: _startBlock, claimableInterval: _claimableInterval }) ); emit PoolAdded(_farmingToken); } // Update the given pool's rewardPerBlock. Can only be called by the admin. function set( uint256 _pid, uint256[] memory _rewardPerBlock, bool _withUpdate ) external onlyAdmin { if (_withUpdate) { updatePool(_pid); } PoolInfo storage pool = poolInfo[_pid]; require(_rewardPerBlock.length == pool.rewardPerBlock.length, 'INVALID_REWARDS'); pool.rewardPerBlock = _rewardPerBlock; } function setClaimableBlock( uint256 _pid, uint256 _interval ) external onlyAdmin { PoolInfo storage pool = poolInfo[_pid]; pool.claimableInterval = _interval; emit ClaimableBlockUpdated(_pid, _interval); } // Charge the given pool's rewards. Can only be called by the admin. function charge( uint256 _pid, uint256[] memory _amounts ) external onlyAdmin { PoolInfo storage pool = poolInfo[_pid]; require(_amounts.length == pool.rewardTokens.length, 'INVALID_AMOUNTS'); for (uint256 i = 0; i < _amounts.length; i++) { if (_amounts[i] > 0) { Helper.safeTransferFrom( pool.rewardTokens[i], msg.sender, address(this), _amounts[i] ); pool.remainingRewards[i] = pool.remainingRewards[i].add(_amounts[i]); } } emit Charged(_pid, pool.rewardTokens, _amounts); } // Withdraw the given pool's rewards. Can only be called by the admin. function withdrawRewards( uint256 _pid, uint256[] memory _amounts ) external onlyAdmin { PoolInfo storage pool = poolInfo[_pid]; require(_amounts.length == pool.rewardTokens.length, 'INVALID_AMOUNTS'); for (uint256 i = 0; i < _amounts.length; i++) { require(_amounts[i] <= pool.remainingRewards[i], 'INVALID_AMOUNT'); if (_amounts[i] > 0) { Helper.safeTransfer( pool.rewardTokens[i], msg.sender, _amounts[i] ); pool.remainingRewards[i] = pool.remainingRewards[i].sub(_amounts[i]); } } emit WithdrawRewards(_pid, pool.rewardTokens, _amounts); } // View function to see the given pool's info. function getPoolInfo(uint256 _pid) external view returns( address farmingToken, uint256 amount, address[] memory rewardTokens, uint256[] memory rewardPerBlock, uint256[] memory accRewardPerShare, uint256 lastRewardBlock, uint256 startBlock, uint256 claimableInterval ) { PoolInfo memory pool = poolInfo[_pid]; farmingToken = pool.farmingToken; amount = pool.amount; rewardTokens = pool.rewardTokens; rewardPerBlock = pool.rewardPerBlock; accRewardPerShare = pool.accRewardPerShare; lastRewardBlock = pool.lastRewardBlock; startBlock = pool.startBlock; claimableInterval = pool.claimableInterval; } // View function to see the remaing rewards of the given pool. function getRemaingRewards(uint256 _pid) external view returns(uint256[] memory remainingRewards) { PoolInfo memory pool = poolInfo[_pid]; remainingRewards = pool.remainingRewards; } // View function to see the given pool's info of user. function getUserInfo(uint256 _pid, address _user) external view returns( uint256 amount, uint256[] memory pending, uint256[] memory rewardDebt, uint256 nextClaimableBlock ) { UserInfo memory user = userInfo[_pid][_user]; amount = user.amount; pending = user.pending; rewardDebt= user.rewardDebt; nextClaimableBlock = user.nextClaimableBlock; } // View function to see pending rewards. function pendingRewards(uint256 _pid, address _user) public view returns(uint256[] memory rewards, uint256 nextClaimableBlock) { PoolInfo memory pool = poolInfo[_pid]; UserInfo memory user = userInfo[_pid][_user]; uint256 farmingTokenSupply = pool.amount; rewards = user.pending; if (block.number >= pool.lastRewardBlock && user.pending.length > 0 && farmingTokenSupply != 0) { for (uint256 i = 0; i < pool.accRewardPerShare.length; i++) { uint256 reward = pool.rewardPerBlock[i].mul( block.number.sub(pool.lastRewardBlock) ); uint256 accRewardPerShare = pool.accRewardPerShare[i].add( reward.mul(1e12) / farmingTokenSupply ); rewards[i] = user.pending[i].add( (user.amount.mul(accRewardPerShare) / 1e12).sub(user.rewardDebt[i]) ); } } nextClaimableBlock = user.nextClaimableBlock; } // View function to see current periods. function getPeriodsSinceStart(uint256 _pid) public view returns(uint256 periods) { PoolInfo memory pool = poolInfo[_pid]; if (block.number <= pool.startBlock || pool.claimableInterval == 0) return 0; uint256 blocksSinceStart = block.number.sub(pool.startBlock); periods = (blocksSinceStart / pool.claimableInterval).add(1); if (blocksSinceStart % pool.claimableInterval == 0) { periods = periods - 1; } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 farmingTokenSupply = pool.amount; if (farmingTokenSupply == 0) { pool.lastRewardBlock = block.number; return; } for (uint256 i = 0; i < pool.accRewardPerShare.length; i++) { uint256 reward = pool.rewardPerBlock[i].mul( block.number.sub(pool.lastRewardBlock) ); if (pool.remainingRewards[i] >= reward) { pool.remainingRewards[i] = pool.remainingRewards[i].sub(reward); } else { pool.remainingRewards[i] = 0; } pool.accRewardPerShare[i] = pool.accRewardPerShare[i].add( reward.mul(1e12) / farmingTokenSupply ); } pool.lastRewardBlock = block.number; } // Stake farming tokens to the given pool. function stake( uint256 _pid, address _farmingToken, uint256 _amount ) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(pool.farmingToken == _farmingToken, 'FARMING_TOKEN_SAFETY_CHECK'); updatePool(_pid); if (user.amount > 0) { for (uint256 i = 0; i < pool.accRewardPerShare.length; i++) { uint256 pending = ( user.amount.mul(pool.accRewardPerShare[i]) / 1e12 ).sub(user.rewardDebt[i]); user.pending[i] = user.pending[i].add(pending); } } if (user.nextClaimableBlock == 0 && user.amount == 0) { if (block.number <= pool.startBlock) { user.nextClaimableBlock = pool.startBlock.add(pool.claimableInterval); } else { uint256 periods = getPeriodsSinceStart(_pid); user.nextClaimableBlock = pool.startBlock.add( periods.mul(pool.claimableInterval) ); } user.rewardDebt = new uint256[](pool.rewardTokens.length); user.pending = new uint256[](pool.rewardTokens.length); } Helper.safeTransferFrom( pool.farmingToken, msg.sender, address(this), _amount ); user.amount = user.amount.add(_amount); pool.amount = pool.amount.add(_amount); for (uint256 i = 0; i < pool.accRewardPerShare.length; i++) { user.rewardDebt[i] = user.amount.mul(pool.accRewardPerShare[i]) / 1e12; } emit Stake(msg.sender, _pid, _amount); } // Redeem farming tokens from the given pool. function redeem( uint256 _pid, address _farmingToken, uint256 _amount ) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(pool.farmingToken == _farmingToken, 'FARMING_TOKEN_SAFETY_CHECK'); require(user.amount >= _amount, 'INSUFFICIENT_AMOUNT'); updatePool(_pid); for (uint256 i = 0; i < pool.accRewardPerShare.length; i++) { uint256 pending = ( user.amount.mul(pool.accRewardPerShare[i]) / 1e12 ).sub(user.rewardDebt[i]); user.pending[i] = user.pending[i].add(pending); user.rewardDebt[i] = user.amount.sub(_amount).mul(pool.accRewardPerShare[i]) / 1e12; } Helper.safeTransfer(pool.farmingToken, msg.sender, _amount); user.amount = user.amount.sub(_amount); pool.amount = pool.amount.sub(_amount); emit Redeem(msg.sender, _pid, _amount); } // Claim rewards when block number larger than user's nextClaimableBlock. function claim(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(block.number > user.nextClaimableBlock, 'NOT_CLAIMABLE'); (uint256[] memory rewards, ) = pendingRewards(_pid, msg.sender); updatePool(_pid); for (uint256 i = 0; i < pool.accRewardPerShare.length; i++) { user.pending[i] = 0; user.rewardDebt[i] = user.amount.mul(pool.accRewardPerShare[i]) / 1e12; if (rewards[i] > 0) { Helper.safeTransfer(pool.rewardTokens[i], msg.sender, rewards[i]); } } uint256 periods = getPeriodsSinceStart(_pid); user.nextClaimableBlock = pool.startBlock.add( periods.mul(pool.claimableInterval) ); emit Claim(msg.sender, _pid, pool.rewardTokens, rewards); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; pool.amount = pool.amount.sub(amount); user.amount = 0; user.pending = new uint256[](pool.accRewardPerShare.length); user.rewardDebt = new uint256[](pool.accRewardPerShare.length); user.nextClaimableBlock = 0; Helper.safeTransfer(pool.farmingToken, msg.sender, amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {AdminUpgradeable} from "../libraries/AdminUpgradeable.sol"; import {Farming} from "../periphery/Farming.sol"; contract Gauge is AdminUpgradeable { using SafeERC20 for IERC20; /// @notice The address of framing contract address public farming; /// @notice The address of the token used to vote. address public voteToken; /// @notice The duration between tow vote period. uint256 public voteSetWindow; /// @notice The duration of a vote period. uint256 public voteDuration; /// @notice The next vote period id. uint256 public nextVotePeriodID; struct PoolPeriodState { /// @notice Flag marking whether the pool inherit the last period token. bool inherit; /// @notice Flag marking whether the pool votalbe has been reset by admin. bool resetVotable; /// @notice Flag marking whether the pool is votalbe in this period. bool votable; /// @notice score this pool get in this period. uint256 score; /// @notice The Amount of token this pool get in this period. uint256 totalAmount; } struct VotePeriod { /// @notice The start timestmap of this vote period uint256 start; /// @notice The end timestmap of this vote period uint256 end; } /// @notice (periodId => VotePeriod) mapping(uint256 => VotePeriod) public votePeriods; /// @notice (userAddress => pooId => amount) mapping(address => mapping(uint256 => uint256)) public userInfos; /// @notice periodId => (poolId => PoolPeriodState) mapping(uint256 => mapping(uint256 => PoolPeriodState)) public allPoolState; /// @notice pool last update period mapping(uint256 => uint256) public poolLastUpdatePeriod; ///@notice poolId => bool, flag mark whether the trading pool is consist of stablecoins mapping(uint256 => bool) public stablePools; event UpdatePoolHistory( uint256 indexed poolId, uint256 curPeriod, uint256 lastPeriod, uint256 needUpdatePool, uint256 lastPeriodAmount ); event Vote( address indexed voter, uint256 indexed period, uint256 poolId, uint256 amount, uint256 poolPeriodScore, uint256 poolPeriodAmount ); event CancelVote( address indexed voter, uint256 indexed period, uint256 poolId, uint256 amount, uint256 poolPeriodScore, uint256 poolPeriodAmount ); event InheritPool( uint256 poolId, uint256 curPeriod, uint256 lastPeriod, uint256 amount, bool votable ); event UpdateVotePeriod(uint256 curPeriod, uint256 start, uint256 end); event SetNonVotablePools(uint256 period, uint256[] pools); event SetVotablePools(uint256 period, uint256[] pools); event UpdateVoteSetWindow(uint256 curPeriod, uint256 voteSetWindow); event UpdateVoteDuration(uint256 curPeriod, uint256 voteDuration); event UpdateStablePools(uint256[] pids); event MigrateVote( address indexed voter, uint256 indexed period, uint256[] fromPoolIds, uint256[] fromAmounts, uint256[] toPoolIds, uint256[] toAmounts ); error InvalidBlock(uint256 block); error PoolNotAllowedToVote(uint256 poolId); error InsuffientAmount(uint256 amount); error ArrayMismatch(); error AmountNotEqual(uint256 amount0, uint256 amount1); error NoNeedToUpdate(uint256 curPeriod, uint256 period); constructor( address _farming, address _voteToken, uint256 _voteDuration, uint256 _voteSetWindow, uint256 _firstPeriodStart ) { if (block.timestamp >= _firstPeriodStart) revert InvalidBlock(_firstPeriodStart); nextVotePeriodID = 1; voteToken = _voteToken; farming = _farming; voteSetWindow = _voteSetWindow; voteDuration = _voteDuration; votePeriods[0] = VotePeriod( _firstPeriodStart, _firstPeriodStart + voteDuration ); _initializeAdmin(msg.sender); } function updateVoteSetWindow(uint256 _voteSetWindow) external onlyAdmin { uint256 curPeriodId = getCurrentPeriodId(); voteSetWindow = _voteSetWindow; emit UpdateVoteSetWindow(curPeriodId, voteSetWindow); } function updateVoteDuration(uint256 _voteDuration) external onlyAdmin { uint256 curPeriodId = getCurrentPeriodId(); voteDuration = _voteDuration; emit UpdateVoteDuration(curPeriodId, voteDuration); } function updateVotePeriod() public { uint256 curTimestamp = block.timestamp; uint256 curPeriodId = getCurrentPeriodId(); VotePeriod storage curPeriod = votePeriods[curPeriodId]; if (curPeriod.end > curTimestamp) { return; } VotePeriod storage nextPeriod = votePeriods[nextVotePeriodID]; if (curPeriod.end + voteSetWindow >= curTimestamp) { nextPeriod.start = curPeriod.end + voteSetWindow; nextPeriod.end = nextPeriod.start + voteDuration; } else { nextPeriod.start = curTimestamp; nextPeriod.end = curTimestamp + voteDuration; } emit UpdateVotePeriod( nextVotePeriodID, nextPeriod.start, nextPeriod.end ); nextVotePeriodID++; } function setVotablePools(uint256[] memory poolIds) external onlyAdmin { uint256 periodId = getCurrentPeriodId(); VotePeriod memory curPeriod = votePeriods[periodId]; if (curPeriod.end < block.timestamp) { periodId = nextVotePeriodID; } for (uint256 i; i < poolIds.length; i++) { PoolPeriodState storage poolPeriodState = allPoolState[periodId][poolIds[i]]; poolPeriodState.votable = true; poolPeriodState.resetVotable = true; } emit SetVotablePools(periodId, poolIds); } function setNonVotablePools(uint256[] memory poolIds) external onlyAdmin { uint256 periodId = getCurrentPeriodId(); VotePeriod memory curPeriod = votePeriods[periodId]; if (curPeriod.end < block.timestamp) { periodId = nextVotePeriodID; } for (uint256 i; i < poolIds.length; i++) { PoolPeriodState storage poolPeriodState = allPoolState[periodId][poolIds[i]]; poolPeriodState.votable = false; poolPeriodState.resetVotable = true; } emit SetNonVotablePools(periodId, poolIds); } function vote(uint256 poolId, uint256 amount) external { updateVotePeriod(); uint256 curPeriodId = getCurrentPeriodId(); VotePeriod memory currentPeriod = votePeriods[curPeriodId]; if (block.timestamp >= currentPeriod.end) revert InvalidBlock(currentPeriod.end); PoolPeriodState storage curPoolState = _inheritExpiredPool(poolId); _vote(poolId, amount, curPoolState, currentPeriod); } function _vote( uint256 poolId, uint256 amount, PoolPeriodState storage curPoolState, VotePeriod memory currentPeriod ) internal { uint256 curTimestamp = block.timestamp; if (!curPoolState.votable) revert PoolNotAllowedToVote(poolId); uint256 curPeriodId = getCurrentPeriodId(); if (curTimestamp < currentPeriod.start) { curTimestamp = currentPeriod.start; } uint256 score = ((currentPeriod.end - curTimestamp) * amount) / (currentPeriod.end - currentPeriod.start); curPoolState.score += score; curPoolState.totalAmount += amount; userInfos[msg.sender][poolId] += amount; IERC20(voteToken).safeTransferFrom(msg.sender, address(this), amount); emit Vote( msg.sender, curPeriodId, poolId, amount, curPoolState.score, curPoolState.totalAmount ); } function cancelVote(uint256 poolId, uint256 amount) external { updateVotePeriod(); PoolPeriodState storage poolState = _inheritExpiredPool(poolId); uint256 curPeriodId = getCurrentPeriodId(); _cancelVote(poolId, curPeriodId, poolState, amount); } function _cancelVote( uint256 poolId, uint256 curPeriodId, PoolPeriodState storage poolState, uint256 amount ) internal { uint256 userBalance = userInfos[msg.sender][poolId]; if (userBalance < amount) revert InsuffientAmount(userBalance); userInfos[msg.sender][poolId] -= amount; VotePeriod memory curPeriod = votePeriods[curPeriodId]; uint256 curTimestamp = block.timestamp; if (curTimestamp < curPeriod.start) { poolState.score -= amount; } else if (curTimestamp <= curPeriod.end) { poolState.score -= (amount * (curPeriod.end - curTimestamp)) / (curPeriod.end - curPeriod.start); } poolState.totalAmount -= amount; IERC20(voteToken).safeTransfer(msg.sender, amount); emit CancelVote( msg.sender, curPeriodId, poolId, amount, poolState.score, poolState.totalAmount ); } function batchVote(uint256[] memory poolIds, uint256[] memory amounts) public { if (poolIds.length != amounts.length) revert ArrayMismatch(); updateVotePeriod(); uint256 curPeriodId = getCurrentPeriodId(); VotePeriod memory currentPeriod = votePeriods[curPeriodId]; if (block.timestamp >= currentPeriod.end) revert InvalidBlock(currentPeriod.end); for (uint256 i = 0; i < poolIds.length; i++) { PoolPeriodState storage poolState = _inheritExpiredPool(poolIds[i]); _vote(poolIds[i], amounts[i], poolState, currentPeriod); } } function batchCancelVote(uint256[] memory poolIds, uint256[] memory amounts) public { if (poolIds.length != amounts.length) revert ArrayMismatch(); updateVotePeriod(); uint256 curPeriodId = getCurrentPeriodId(); for (uint256 i = 0; i < poolIds.length; i++) { PoolPeriodState storage poolState = _inheritExpiredPool(poolIds[i]); _cancelVote(poolIds[i], curPeriodId, poolState, amounts[i]); } } function migrateVote( uint256[] memory fromPoolIds, uint256[] memory fromAmounts, uint256[] memory toPoolIds, uint256[] memory toAmounts ) external { if ( fromPoolIds.length != fromAmounts.length || toPoolIds.length != toAmounts.length ) revert ArrayMismatch(); uint256 fromTotalAmount; uint256 toTotalAmount; for (uint256 i = 0; i < fromPoolIds.length; i++) { fromTotalAmount += fromAmounts[i]; } for (uint256 i = 0; i < toPoolIds.length; i++) { toTotalAmount += toAmounts[i]; } if (fromTotalAmount != toTotalAmount) revert AmountNotEqual(fromTotalAmount, toTotalAmount); batchCancelVote(fromPoolIds, fromAmounts); batchVote(toPoolIds, toAmounts); emit MigrateVote( msg.sender, getCurrentPeriodId(), fromPoolIds, fromAmounts, toPoolIds, toAmounts ); } function _inheritExpiredPool(uint256 poolId) internal returns (PoolPeriodState storage curPoolState) { uint256 curPeriodId = getCurrentPeriodId(); curPoolState = allPoolState[curPeriodId][poolId]; if (curPeriodId == 0 || curPoolState.inherit) { return curPoolState; } uint256 lastUpdatePeriod = poolLastUpdatePeriod[poolId]; PoolPeriodState memory lastPoolState = allPoolState[lastUpdatePeriod][poolId]; curPoolState.inherit = true; curPoolState.score = lastPoolState.totalAmount; // Reset votable by admin, can't inherit last pool votable. if (!curPoolState.resetVotable) { curPoolState.votable = lastPoolState.votable; } curPoolState.totalAmount = lastPoolState.totalAmount; poolLastUpdatePeriod[poolId] = curPeriodId; emit InheritPool( poolId, curPeriodId, lastUpdatePeriod, lastPoolState.totalAmount, lastPoolState.votable ); } function updatePoolHistory(uint256 poolId, uint256 needUpdatePeriodId) public { uint256 curPeriodId = getCurrentPeriodId(); if (needUpdatePeriodId == 0 || needUpdatePeriodId > curPeriodId) revert NoNeedToUpdate(curPeriodId, needUpdatePeriodId); uint256 findedPeriodId = needUpdatePeriodId - 1; PoolPeriodState memory findedPeriodState; for (; findedPeriodId >= 0; findedPeriodId--) { findedPeriodState = allPoolState[findedPeriodId][poolId]; if (findedPeriodState.inherit || findedPeriodId == 0) { break; } } for (uint256 i = needUpdatePeriodId; i > findedPeriodId; i--) { PoolPeriodState storage poolState = allPoolState[i][poolId]; if (poolState.inherit) { continue; } poolState.inherit = true; poolState.score = findedPeriodState.totalAmount; poolState.totalAmount = findedPeriodState.totalAmount; if (!poolState.resetVotable) { poolState.votable = findedPeriodState.votable; } } uint256 lastUpdatePeriodId = poolLastUpdatePeriod[poolId]; if (needUpdatePeriodId > lastUpdatePeriodId) { poolLastUpdatePeriod[poolId] = needUpdatePeriodId; } emit UpdatePoolHistory( poolId, curPeriodId, findedPeriodId, needUpdatePeriodId, findedPeriodState.totalAmount ); } function setStablePools(uint256[] memory poolIds) external onlyAdmin{ for (uint256 i = 0; i < poolIds.length; i++) { stablePools[poolIds[i]] = true; } emit UpdateStablePools(poolIds); } function setNonStablePools(uint256[] memory poolIds) external onlyAdmin { for (uint256 i = 0; i < poolIds.length; i++) { stablePools[poolIds[i]] = false; } emit UpdateStablePools(poolIds); } function getPoolInfo(uint256 poolId) external view returns ( uint256 score, bool stable, address farmingToken, uint256 amount, address[] memory rewardTokens, uint256[] memory rewardPerBlock, uint256[] memory accRewardPerShare, uint256 lastRewardBlock, uint256 startBlock, uint256 claimableInterval ) { ( farmingToken, amount, rewardTokens, rewardPerBlock, accRewardPerShare, lastRewardBlock, startBlock, claimableInterval ) = Farming(farming).getPoolInfo(poolId); stable = stablePools[poolId]; uint256 lastUpdatePeriod = poolLastUpdatePeriod[poolId]; uint256 curPeriodId = getCurrentPeriodId(); if (lastUpdatePeriod == curPeriodId) { score = allPoolState[curPeriodId][poolId].score; } else { score = allPoolState[lastUpdatePeriod][poolId].totalAmount; } } function getCurrentPeriodId() public view returns (uint256) { return nextVotePeriodID - 1; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../libraries/Math.sol"; import "../libraries/Helper.sol"; import "../libraries/AdminUpgradeable.sol"; import "../core/interfaces/IFactory.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; contract Bootstrap is ReentrancyGuard, AdminUpgradeable { using Math for uint256; struct UserInfo { uint256 amount0; uint256 amount1; } address public factory; address public token0; address public token1; uint256 public constant MINIMUM_LIQUIDITY = 10**3; uint256 public MINUM_AMOUNT0; uint256 public MINUM_AMOUNT1; uint256 public HARD_CAP_AMOUNT0; uint256 public HARD_CAP_AMOUNT1; uint256 public END_BLOCK; uint256 public totalAmount0; uint256 public totalAmount1; address[] private rewardTokens; address[] private limitTokens; uint256[] private limitTokenAmounts; uint256[] private rewardTokenAmounts; mapping(address => UserInfo) private _userInfos; event Provided(address indexed user, uint256 amount0, uint256 amount1); event LiquidityClaimed(address indexed to, uint256 amount); event Refund(address indexed to, uint256 amount0, uint256 amount1); event WithdrawExtraFunds(address indexed token, address indexed to, uint256 amount); event MinumAmountUpdated(uint256 amount0, uint256 amount1); event HardCapAmountUpdated(uint256 amount0, uint256 amount1); event EndBlockUpdated(uint256 endBlock); event DistributeReward(address indexed provider, address[] rewardTokens, uint256[] rewardAmount); event ChargeReward(address indexed sender, address[] rewardTokens, uint256[] totalAmount); event SetRewardAndLimit(address[] rewards, address[] limits, uint256[] limitAmounts); constructor( address _factory, address _tokenA, address _tokenB, uint256 _minumAmountA, uint256 _minumAmountB, uint256 _hardCapAmountA, uint256 _hardCapAmountB, uint256 _endBlock ) { require(_endBlock > block.number, 'INVALID_END_BLOCK'); require(_hardCapAmountA > _minumAmountA && _hardCapAmountB > _minumAmountB, 'INVALID_HARD_CAP_AMOUNT'); (address _token0, address _token1) = Helper.sortTokens(_tokenA, _tokenB); require( IFactory(_factory).getPair(_token0, _token1) == address(0), 'PAIR_EXISTS' ); require( IFactory(_factory).getBootstrap(_token0, _token1) != address(0), 'BOOTSTRAP_NOT_EXISTS' ); factory = _factory; token0 = _token0; token1 = _token1; MINUM_AMOUNT0 = _token0 == _tokenA ? _minumAmountA : _minumAmountB; MINUM_AMOUNT1 = _token0 == _tokenA ? _minumAmountB : _minumAmountA; HARD_CAP_AMOUNT0 = _token0 == _tokenA ? _hardCapAmountA : _hardCapAmountB; HARD_CAP_AMOUNT1 = _token0 == _tokenA ? _hardCapAmountB : _hardCapAmountA; END_BLOCK = _endBlock; _initializeAdmin(msg.sender); } modifier whenNotEnded() { require(block.number < END_BLOCK, 'BOOTSTRAP_ENDED'); _; } modifier whenEndedAndCapped { require( block.number >= END_BLOCK && totalAmount0 >= MINUM_AMOUNT0 && totalAmount1 >= MINUM_AMOUNT1, 'NOT_ENDED_AND_CAPPED' ); _; } modifier whenEndedAndFailed { require( block.number >= END_BLOCK && (totalAmount0 < MINUM_AMOUNT0 || totalAmount1 < MINUM_AMOUNT1), 'NOT_ENDED_AND_FAILED' ); _; } modifier whenLiquidityMinted { address pair = Helper.pairFor(factory, token0, token1); require(pair != address(0), 'PAIR_NOT_CREATED'); require( IERC20(pair).balanceOf(address(this)) > 0, 'LIQUIDITY_NOT_MINTED' ); _; } function setMinumAmount0(uint256 amount0) external whenNotEnded onlyAdmin { MINUM_AMOUNT0 = amount0; emit MinumAmountUpdated(amount0, MINUM_AMOUNT1); } function setMinumAmount1(uint256 amount1) external whenNotEnded onlyAdmin { MINUM_AMOUNT1 = amount1; emit MinumAmountUpdated(MINUM_AMOUNT0, amount1); } function setHardCapAmount0(uint256 amount0) external whenNotEnded onlyAdmin { require(amount0 > MINUM_AMOUNT0, 'INVALID_AMOUNT0'); HARD_CAP_AMOUNT0 = amount0; emit HardCapAmountUpdated(amount0, HARD_CAP_AMOUNT1); } function setHardCapAmount1(uint256 amount1) external whenNotEnded onlyAdmin { require(amount1 > MINUM_AMOUNT1, 'INVALID_AMOUNT1'); HARD_CAP_AMOUNT1 = amount1; emit HardCapAmountUpdated(HARD_CAP_AMOUNT0, amount1); } function setEndBlock(uint256 endBlock) external whenNotEnded onlyAdmin { require(endBlock > block.number, 'INVALID_END_BLOCK'); END_BLOCK = endBlock; emit EndBlockUpdated(endBlock); } function getUserInfo(address user) external view returns (uint256 amount0, uint256 amount1) { UserInfo memory userInfo = _userInfos[user]; amount0 = userInfo.amount0; amount1 = userInfo.amount1; } function getTotalLiquidity() public view returns (uint256 totalLiquidity) { if (totalAmount0 == 0 || totalAmount1 == 0) return 0; totalLiquidity = Math.sqrt(totalAmount0.mul(totalAmount1)); } function getExactLiquidity(address user) public view returns (uint256 exactLiquidity) { if (totalAmount0 == 0 || totalAmount1 == 0) return 0; UserInfo memory userInfo = _userInfos[user]; uint256 _amount0 = userInfo.amount0; uint256 _amount1 = userInfo.amount1; uint256 exactAmount0 = _amount0.mul(totalAmount1).add(_amount1.mul(totalAmount0)) / totalAmount1.mul(2); uint256 exactAmount1 = _amount1.mul(totalAmount0).add(_amount0.mul(totalAmount1)) / totalAmount0.mul(2); uint256 calculatedLiquidity = Math.sqrt(exactAmount0.mul(exactAmount1)); uint256 totalLiquidity = getTotalLiquidity(); exactLiquidity = calculatedLiquidity.mul(totalLiquidity.sub(MINIMUM_LIQUIDITY)) / totalLiquidity; } function getLiquidityBalance() external view returns (uint256 balance) { address pair = Helper.pairFor(factory, token0, token1); if (pair == address(0)) return 0; balance = IERC20(pair).balanceOf(address(this)); } function addProvision( address tokenA, address tokenB, uint256 amountA, uint256 amountB ) external whenNotEnded nonReentrant { require(checkProviderLimit(msg.sender), 'CheckLimitFailed'); (address _token0, address _token1) = Helper.sortTokens(tokenA, tokenB); require(_token0 == token0 && _token1 == token1, 'INVALID_TOKEN'); uint256 _amount0 = _token0 == tokenA ? amountA : amountB; uint256 _amount1 = _token0 == tokenA ? amountB : amountA; require(_amount0 > 0 || _amount1 > 0, 'INVALID_ZERO_AMOUNT'); UserInfo storage userInfo = _userInfos[msg.sender]; if (_amount0 > 0) { require(totalAmount0 < HARD_CAP_AMOUNT0, 'AMOUNT0_CAPPED'); uint256 remainingAmount0 = HARD_CAP_AMOUNT0.sub(totalAmount0); _amount0 = _amount0 < remainingAmount0 ? _amount0 : remainingAmount0; totalAmount0 = totalAmount0.add(_amount0); userInfo.amount0 = userInfo.amount0.add(_amount0); Helper.safeTransferFrom( _token0, msg.sender, address(this), _amount0 ); } if (_amount1 > 0) { require(totalAmount1 < HARD_CAP_AMOUNT1, 'AMOUNT1_CAPPED'); uint256 remainingAmount1 = HARD_CAP_AMOUNT1.sub(totalAmount1); _amount1 = _amount1 < remainingAmount1 ? _amount1 : remainingAmount1; totalAmount1 = totalAmount1.add(_amount1); userInfo.amount1 = userInfo.amount1.add(_amount1); Helper.safeTransferFrom( _token1, msg.sender, address(this), _amount1 ); } emit Provided(msg.sender, _amount0, _amount1); } function mintLiquidity() external whenEndedAndCapped nonReentrant onlyAdmin { require( IFactory(factory).getPair(token0, token1) == address(0), 'PAIR_EXISTS' ); IFactory(factory).createPair(token0, token1); address pair = Helper.pairFor(factory, token0, token1); Helper.safeTransfer(token0, pair, totalAmount0); Helper.safeTransfer(token1, pair, totalAmount1); IPair(pair).mint(address(this)); } function claim() external whenEndedAndCapped whenLiquidityMinted nonReentrant { UserInfo storage userInfo = _userInfos[msg.sender]; require( userInfo.amount0 > 0 || userInfo.amount1 > 0, 'INSUFFICIENT_AMOUNT' ); uint256 exactLiquidity = getExactLiquidity(msg.sender); require(exactLiquidity > 0, 'INSUFFICIENT_LIQUIDITY'); userInfo.amount0 = 0; userInfo.amount1 = 0; address pair = Helper.pairFor(factory, token0, token1); Helper.safeTransfer(pair, msg.sender, exactLiquidity); if (rewardTokens.length > 0){ distributeReward(msg.sender, exactLiquidity, getTotalLiquidity()); } emit LiquidityClaimed(msg.sender, exactLiquidity); } function refund() external whenEndedAndFailed nonReentrant { UserInfo storage userInfo = _userInfos[msg.sender]; require( userInfo.amount0 > 0 || userInfo.amount1 > 0, 'INSUFFICIENT_AMOUNT' ); uint256 _amount0 = userInfo.amount0; uint256 _amount1 = userInfo.amount1; if (_amount0 > 0) { totalAmount0 = totalAmount0.sub(_amount0); userInfo.amount0 = 0; Helper.safeTransfer(token0, msg.sender, _amount0); } if (_amount1 > 0) { totalAmount1 = totalAmount1.sub(_amount1); userInfo.amount1 = 0; Helper.safeTransfer(token1, msg.sender, _amount1); } emit Refund(msg.sender, _amount0, _amount1); } /** * @dev Return funds directly transfered to this contract, will not affect the portion of the amount * that participated in bootstrap using `addProvision` function **/ function withdrawExtraFunds( address token, address to, uint256 amount ) external onlyAdmin { if (token == token0) { uint256 token0Balance = IERC20(token0).balanceOf(address(this)); require(token0Balance.sub(amount) >= totalAmount0, 'INSUFFICIENT_TOKEN_BALANCE'); } if (token == token1) { uint256 token1Balance = IERC20(token1).balanceOf(address(this)); require(token1Balance.sub(amount) >= totalAmount1, 'INSUFFICIENT_TOKEN_BALANCE'); } Helper.safeTransfer(token, to, amount); emit WithdrawExtraFunds(token, to, amount); } function setRewardAndLimit( address[] memory _rewardTokens, address[] memory _limitTokens, uint256[] memory _limitAmounts ) external onlyAdmin{ rewardTokens = _rewardTokens; limitTokens = _limitTokens; limitTokenAmounts = _limitAmounts; emit SetRewardAndLimit(_rewardTokens, _limitTokens, _limitAmounts); } function charge( uint256[] memory _amounts ) external onlyAdmin { require(_amounts.length == rewardTokens.length, 'INVALID_AMOUNTS'); for (uint256 i = 0; i < _amounts.length; i++) { if ( _amounts[i] > 0 ){ Helper.safeTransferFrom( rewardTokens[i], msg.sender, address(this), _amounts[i] ); } } if (rewardTokenAmounts.length == 0){ rewardTokenAmounts = _amounts; }else{ for(uint256 i = 0; i < _amounts.length; i++){ rewardTokenAmounts[i] = rewardTokenAmounts[i].add(_amounts[i]); } } emit ChargeReward(msg.sender, rewardTokens, _amounts); } function withdrawReward(address recipient) external onlyAdmin{ for (uint256 i = 0; i < rewardTokens.length; i++) { if (rewardTokenAmounts[i] == 0){ continue; } Helper.safeTransfer( rewardTokens[i], recipient, rewardTokenAmounts[i] ); rewardTokenAmounts[i] = 0; } } function checkProviderLimit(address provider) public view returns(bool success){ success = true; for (uint256 i = 0; i < limitTokenAmounts.length; i++){ uint256 balance = IERC20(limitTokens[i]).balanceOf(provider); if (balance < limitTokenAmounts[i]){ success = false; break; } } } function distributeReward(address provider, uint256 providerLiquidity, uint256 totalLiquidity) private{ uint256[] memory rewardAmounts = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardTokens.length; i++){ uint256 distributeRewardAmount = providerLiquidity.mul(rewardTokenAmounts[i]) / totalLiquidity; if (distributeRewardAmount > 0) { Helper.safeTransfer( rewardTokens[i], provider, distributeRewardAmount ); } rewardAmounts[i] = distributeRewardAmount; } emit DistributeReward(provider, rewardTokens, rewardAmounts); } function getRewardTokens() external view returns(address[] memory tokens){ tokens = rewardTokens; } function getLimitTokens() external view returns(address[] memory tokens){ tokens = limitTokens; } function getLimitAmounts() external view returns(uint256[] memory amounts){ amounts = limitTokenAmounts; } function getRewardTokenAmounts() external view returns(uint256[] memory amounts){ amounts = rewardTokenAmounts; } function estimateRewardTokenAmounts(address who) external view returns(uint256[] memory amounts){ uint256 whoLiquidity = getExactLiquidity(who); uint256 totalLiquidity = getTotalLiquidity(); amounts = new uint256[](rewardTokens.length); for (uint256 i = 0; i < rewardTokens.length; i++){ amounts[i] = whoLiquidity.mul(rewardTokenAmounts[i]) / totalLiquidity; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { IPair } from '../core/interfaces/IPair.sol'; import { IFactory } from '../core/interfaces/IFactory.sol'; import { Helper } from './Helper.sol'; import { Math } from '@openzeppelin/contracts/utils/math/Math.sol'; import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; library LiquidityMathLibrary { error ZeroPairReserves(); error InvalidLiquidityAmount(); // computes the direction and magnitude of the profit-maximizing trade function computeProfitMaximizingTrade( uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 reserveA, uint256 reserveB ) pure internal returns (bool aToB, uint256 amountIn) { aToB = Math.mulDiv(reserveA, truePriceTokenB, reserveB) < truePriceTokenA; uint256 invariant = reserveA * reserveB; uint256 leftSide = Math.sqrt( Math.mulDiv( invariant * 1000, aToB ? truePriceTokenA : truePriceTokenB, (aToB ? truePriceTokenB : truePriceTokenA) * 997 ) ); uint256 rightSide = (aToB ? reserveA * 1000 : reserveB * 1000) / 997; if (leftSide < rightSide) return (false, 0); // compute the amount that must be sent to move the price to the profit-maximizing price amountIn = leftSide - rightSide; } // gets the reserves after an arbitrage moves the price to the profit-maximizing ratio given an externally observed true price function getReservesAfterArbitrage( address factory, address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB ) view internal returns (uint256 reserveA, uint256 reserveB) { // first get reserves before the swap (reserveA, reserveB) = Helper.getReserves(factory, tokenA, tokenB); if (reserveA == 0 || reserveB == 0) revert ZeroPairReserves(); // then compute how much to swap to arb to the true price (bool aToB, uint256 amountIn) = computeProfitMaximizingTrade(truePriceTokenA, truePriceTokenB, reserveA, reserveB); if (amountIn == 0) { return (reserveA, reserveB); } // now affect the trade to the reserves if (aToB) { uint256 amountOut = Helper.getAmountOut(amountIn, reserveA, reserveB); reserveA += amountIn; reserveB -= amountOut; } else { uint256 amountOut = Helper.getAmountOut(amountIn, reserveB, reserveA); reserveB += amountIn; reserveA -= amountOut; } } // computes liquidity value given all the parameters of the pair function computeLiquidityValue( uint256 reservesA, uint256 reservesB, uint256 totalSupply, uint256 liquidityAmount, uint8 feeBasePoint, uint256 kLast ) internal pure returns (uint256 tokenAAmount, uint256 tokenBAmount) { if (feeBasePoint > 0 && kLast > 0) { uint256 rootK = Math.sqrt(reservesA * reservesB); uint256 rootKLast = Math.sqrt(kLast); if (rootK > rootKLast) { uint256 numerator1 = totalSupply; uint256 numerator2 = rootK - rootKLast; uint256 denominator = (rootK * (30 - feeBasePoint)) / feeBasePoint + rootKLast; uint256 feeLiquidity = Math.mulDiv(numerator1, numerator2, denominator); totalSupply = totalSupply + feeLiquidity; } } return (reservesA * liquidityAmount / totalSupply, reservesB * liquidityAmount / totalSupply); } // get all current parameters from the pair and compute value of a liquidity amount // **note this is subject to manipulation, e.g. sandwich attacks**. prefer passing a manipulation resistant price to // #getLiquidityValueAfterArbitrageToPrice function getLiquidityValue( address factory, address tokenA, address tokenB, uint256 liquidityAmount ) internal view returns (uint256 tokenAAmount, uint256 tokenBAmount) { (uint256 reservesA, uint256 reservesB) = Helper.getReserves(factory, tokenA, tokenB); IPair pair = IPair(Helper.pairFor(factory, tokenA, tokenB)); uint8 feeBasePoint = IFactory(factory).feeBasePoint(); uint256 kLast = feeBasePoint > 0 ? pair.kLast() : 0; uint256 totalSupply = IERC20(address(pair)).totalSupply(); return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeBasePoint, kLast); } // given two tokens, tokenA and tokenB, and their "true price", i.e. the observed ratio of value of token A to token B, // and a liquidity amount, returns the value of the liquidity in terms of tokenA and tokenB function getLiquidityValueAfterArbitrageToPrice( address factory, address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 liquidityAmount ) internal view returns (uint256 tokenAAmount, uint256 tokenBAmount) { uint8 feeBasePoint = IFactory(factory).feeBasePoint(); IPair pair = IPair(Helper.pairFor(factory, tokenA, tokenB)); uint256 kLast = feeBasePoint > 0 ? pair.kLast() : 0; uint256 totalSupply = IERC20(address(pair)).totalSupply(); // this also checks that totalSupply > 0 if (totalSupply < liquidityAmount || liquidityAmount == 0) revert InvalidLiquidityAmount(); (uint256 reservesA, uint256 reservesB) = getReservesAfterArbitrage(factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB); return computeLiquidityValue(reservesA, reservesB, totalSupply, liquidityAmount, feeBasePoint, kLast); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {AdminUpgradeable} from "./AdminUpgradeable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {Math} from "@openzeppelin/contracts/utils/math/Math.sol"; import {EnumerableSet} from "@openzeppelin/contracts/utils/structs/EnumerableSet.sol"; contract ZenlinkTokenLoyaltyCalculator is AdminUpgradeable { using EnumerableSet for EnumerableSet.AddressSet; address immutable vxZenlinkToken; address immutable zenlinkToken; uint256 public minPenaltyRatio; uint256 public maxPenaltyRatio; EnumerableSet.AddressSet private _lockedContracts; error ZeroAddress(); error CannotExceedMaxPenaltyRatio(uint256 maxPenaltyRatio); error InvalidPenaltyRatio(uint256 min, uint256 max); constructor( address _vxZenlinkToken, address _zenlinkToken, uint256 _minPenaltyRatio, uint256 _maxPenaltyRatio ) { vxZenlinkToken = _vxZenlinkToken; zenlinkToken = _zenlinkToken; _updatePenaltyRatio(_minPenaltyRatio, _maxPenaltyRatio); _initializeAdmin(msg.sender); } function updatePenaltyRatio( uint256 _minPenaltyRatio, uint256 _maxPenaltyRatio ) external onlyAdmin { _updatePenaltyRatio(_minPenaltyRatio, _maxPenaltyRatio); } function _updatePenaltyRatio( uint256 _minPenaltyRatio, uint256 _maxPenaltyRatio ) private { if (_maxPenaltyRatio > 5e17) revert CannotExceedMaxPenaltyRatio(5e17); if (_minPenaltyRatio > _maxPenaltyRatio) revert InvalidPenaltyRatio(_minPenaltyRatio, _maxPenaltyRatio); minPenaltyRatio = _minPenaltyRatio; maxPenaltyRatio = _maxPenaltyRatio; } function lockedContracts() external view returns (address[] memory) { return _lockedContracts.values(); } function addLockedContract(address lockedContract) external onlyAdmin { if (lockedContract == address(0)) revert ZeroAddress(); if (!_lockedContracts.contains(lockedContract)) { _lockedContracts.add(lockedContract); } } function removeLockedContract(address lockedContract) external onlyAdmin { if (lockedContract == address(0)) revert ZeroAddress(); if (_lockedContracts.contains(lockedContract)) { _lockedContracts.remove(lockedContract); } } function getCirculation() public view returns (uint256 circulation) { circulation = IERC20(zenlinkToken).totalSupply(); address[] memory contracts = _lockedContracts.values(); for (uint256 i = 0; i < contracts.length; i++) { circulation -= IERC20(zenlinkToken).balanceOf(contracts[i]); } } function getZenlinkTokenWithdrawFeeRatio() external view returns (uint256 ratio) { uint256 zenlinkCirculation = getCirculation(); uint256 x = Math.mulDiv( IERC20(zenlinkToken).balanceOf(vxZenlinkToken), 1e18, zenlinkCirculation ); ratio = getRatioValue(x); } function getRatioValue(uint256 input) public view returns (uint256) { // y = maxPenaltyRatio (x < 0.1) // y = minPenaltyRatio (x > 0.5) // y = maxPenaltyRatio - (input - 0.1) * step if (input < 1e17) { return maxPenaltyRatio; } else if (input > 5e17) { return minPenaltyRatio; } else { uint256 step = Math.mulDiv( maxPenaltyRatio - minPenaltyRatio, 1e18, 4e17 ); return maxPenaltyRatio - Math.mulDiv(input - 1e17, step, 1e18); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol) pragma solidity ^0.8.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) * and `uint256` (`UintSet`) are supported. * * [WARNING] * ==== * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable. * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info. * * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet. * ==== */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping(bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; if (lastIndex != toDeleteIndex) { bytes32 lastValue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastValue; // Update the index for the moved value set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex } // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // Bytes32Set struct Bytes32Set { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, value); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, index); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(uint160(value)))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint160(uint256(_at(set._inner, index)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; /// @solidity memory-safe-assembly assembly { result := store } return result; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import { LiquidityMathLibrary } from '../libraries/LiquidityMathLibrary.sol'; contract ExampleComputeLiquidityValue { address public immutable factory; constructor(address factory_) { factory = factory_; } function getReservesAfterArbitrage( address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB ) external view returns (uint256 reserveA, uint256 reserveB) { return LiquidityMathLibrary.getReservesAfterArbitrage( factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB ); } function getLiquidityValue( address tokenA, address tokenB, uint256 liquidityAmount ) external view returns (uint256 tokenAAmount, uint256 tokenBAmount) { return LiquidityMathLibrary.getLiquidityValue( factory, tokenA, tokenB, liquidityAmount ); } function getLiquidityValueAfterArbitrageToPrice( address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 liquidityAmount ) external view returns (uint256 tokenAAmount, uint256 tokenBAmount) { return LiquidityMathLibrary.getLiquidityValueAfterArbitrageToPrice( factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB, liquidityAmount ); } function getGasCostOfGetLiquidityValueAfterArbitrageToPrice( address tokenA, address tokenB, uint256 truePriceTokenA, uint256 truePriceTokenB, uint256 liquidityAmount ) external view returns (uint256) { uint gasBefore = gasleft(); LiquidityMathLibrary.getLiquidityValueAfterArbitrageToPrice( factory, tokenA, tokenB, truePriceTokenA, truePriceTokenB, liquidityAmount ); uint gasAfter = gasleft(); return gasBefore - gasAfter; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import '../core/ZenlinkERC20.sol'; contract MockZenlinkERC20 is ZenlinkERC20 { constructor(uint256 _totalSupply) { _mint(msg.sender, _totalSupply); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {IStableSwap} from "../../stableswap/interfaces/IStableSwap.sol"; contract StableSwapDispatcher { using SafeERC20 for IERC20; error InsufficientAmountIn(); function swap(address pool, address tokenIn, address tokenOut, address to) external { uint8 tokenInIndex = IStableSwap(pool).getTokenIndex(tokenIn); uint8 tokenOutIndex = IStableSwap(pool).getTokenIndex(tokenOut); uint256 amountIn = IERC20(tokenIn).balanceOf(address(this)); uint256 prevBalanceOut = IERC20(tokenOut).balanceOf(address(this)); if (amountIn == 0) revert InsufficientAmountIn(); IERC20(tokenIn).safeIncreaseAllowance(address(pool), amountIn); IStableSwap(pool).swap(tokenInIndex, tokenOutIndex, amountIn, 0, type(uint256).max); IERC20(tokenOut).safeTransfer(to, IERC20(tokenOut).balanceOf(address(this)) - prevBalanceOut); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {IStableSwap} from "./IStableSwap.sol"; interface IMetaSwap { /// EVENTS event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 tokenSupply ); event FlashLoan( address indexed caller, address indexed receiver, uint256[] amounts_out ); event TokenExchange( address indexed buyer, uint256 soldId, uint256 tokensSold, uint256 boughtId, uint256 tokensBought ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event RemoveLiquidity(address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 tokenSupply); event RemoveLiquidityOne(address indexed provider, uint256 tokenIndex, uint256 tokenAmount, uint256 coinAmount); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 tokenSupply ); event RampA(uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime); event StopRampA(uint256 A, uint256 timestamp); event NewFee(uint256 fee, uint256 adminFee); event CollectProtocolFee(address token, uint256 amount); event FeeControllerChanged(address newController); event FeeDistributorChanged(address newController); // pool data view functions function getLpToken() external view returns (IERC20 lpToken); function getA() external view returns (uint256); function getAPrecise() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokens() external view returns (IERC20[] memory); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getTokenBalances() external view returns (uint256[] memory); function getNumberOfTokens() external view returns (uint256); function getVirtualPrice() external view returns (uint256); function metaSwapStorage() external view returns ( address baseSwap, uint256 baseVirtualPrice, uint256 baseCacheLastUpdated ); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex) external view returns (uint256 availableTokenAmount); function getAdminBalances() external view returns (uint256[] memory adminBalances); function getAdminBalance(uint8 index) external view returns (uint256); function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address _feeDistributor ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address _feeDistributor, IStableSwap baseSwap ) external; // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function flashLoan( uint256[] memory amountsOut, address to, bytes calldata data, uint256 deadline ) external; function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); function withdrawAdminFee() external; }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import {LPToken} from "./LPToken.sol"; import {IStableSwap} from "./interfaces/IStableSwap.sol"; import {IStableSwapCallee} from "./interfaces/IStableSwapCallee.sol"; import {StableSwapStorage} from "./StableSwapStorage.sol"; library MetaSwapStorage { using SafeERC20 for IERC20; event AddLiquidity( address indexed provider, uint256[] token_amounts, uint256[] fees, uint256 invariant, uint256 token_supply ); event FlashLoan( address indexed caller, address indexed receiver, uint256[] amounts_out ); event TokenExchange( address indexed buyer, uint256 sold_id, uint256 tokens_sold, uint256 bought_id, uint256 tokens_bought ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event RemoveLiquidity( address indexed provider, uint256[] token_amounts, uint256[] fees, uint256 token_supply ); event RemoveLiquidityOne( address indexed provider, uint256 index, uint256 token_amount, uint256 coin_amount ); event RemoveLiquidityImbalance( address indexed provider, uint256[] token_amounts, uint256[] fees, uint256 invariant, uint256 token_supply ); uint256 public constant FEE_DENOMINATOR = 1e10; /// @dev protect from division loss when run approximation loop. We cannot divide at the end because of overflow, /// so we add some (small) PRECISION when divide in each iteration uint256 public constant A_PRECISION = 100; /// @dev max iteration of converge calculate uint256 internal constant MAX_ITERATION = 256; uint256 public constant POOL_TOKEN_COMMON_DECIMALS = 18; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; struct MetaSwap { // Meta-Swap related parameters IStableSwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateRemoveLiquidityOneTokenInfo function to avoid stack too deep errors struct CalculateRemoveLiquidityOneTokenInfo { uint256 D0; uint256 D1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 D0; uint256 D1; uint256 D2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; IStableSwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint256 tokenIndexFrom, uint256 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); transferredDx = _doTransferIn(tokenFrom, dx); } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = ((dyFee * self.adminFee) / FEE_DENOMINATOR) / self.tokenMultipliers[tokenIndexTo]; self.balances[tokenIndexFrom] += transferredDx; self.balances[tokenIndexTo] -= dy + dyAdminFee; self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenExchange( msg.sender, tokenIndexFrom, transferredDx, tokenIndexTo, dy ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length - 1); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } IStableSwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } v.dx = _doTransferIn(v.tokenFrom, dx); if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom] + (dx * v.tokenPrecisionMultipliers[tokenIndexFrom]); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[](v.baseTokens.length); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = ((v.dx * v.baseVirtualPrice) / BASE_VIRTUAL_PRICE_PRECISION) + xp[baseLPTokenIndex]; } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = _getY( self, v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo] - y - 1; if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = (v.dy * BASE_VIRTUAL_PRICE_PRECISION) / v.baseVirtualPrice; } dyFee = (v.dy * self.fee) / FEE_DENOMINATOR; v.dy = (v.dy - dyFee) / v.tokenPrecisionMultipliers[v.metaIndexTo]; } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = (dyFee * self.adminFee) / FEE_DENOMINATOR; dyAdminFee = dyAdminFee / v.tokenPrecisionMultipliers[v.metaIndexTo]; self.balances[v.metaIndexFrom] = v.oldBalances[v.metaIndexFrom] + v.dx; self.balances[v.metaIndexTo] = v.oldBalances[v.metaIndexTo] - v.dy - dyAdminFee; } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - v.dy; } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } function flashLoan( StableSwapStorage.SwapStorage storage self, uint256[] memory amountsOut, address to, bytes calldata data ) external { uint256 nCoins = self.pooledTokens.length; require(amountsOut.length == nCoins, "invalidAmountsLength"); { uint256 tokenSupply = self.lpToken.totalSupply(); require(tokenSupply > 0, "insufficientLiquidity"); } uint256[] memory fees = new uint256[](nCoins); uint256 _fee = _feePerToken(self); uint256 amp = _getAPrecise(self); uint256 D0 = _getD(_xp(self.balances, self.tokenMultipliers), amp); for (uint256 i = 0; i < nCoins; i++) { if (amountsOut[i] > 0) { require(amountsOut[i] < self.balances[i], "insufficientBalance"); fees[i] = (_fee * amountsOut[i]) / FEE_DENOMINATOR; self.pooledTokens[i].safeTransfer(to, amountsOut[i]); } } if (data.length > 0) { IStableSwapCallee(to).zenlinkStableSwapCall( msg.sender, self.pooledTokens, amountsOut, fees, data ); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < nCoins; i++) { if (amountsOut[i] > 0) { newBalances[i] += (_doTransferIn(self.pooledTokens[i], amountsOut[i] + fees[i]) - amountsOut[i]); } } uint256 D1 = _getD(_xp(newBalances, self.tokenMultipliers), amp); assert(D1 > D0); uint256 diff = 0; for (uint256 i = 0; i < nCoins; i++) { diff = _distance((D1 * self.balances[i]) / D0, newBalances[i]); fees[i] = (_fee * diff) / FEE_DENOMINATOR; self.balances[i] = newBalances[i] - ((fees[i] * self.adminFee) / FEE_DENOMINATOR); } emit FlashLoan(msg.sender, to, amountsOut); } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, _getAPrecise(self), _updateBaseVirtualPrice(metaSwapStorage), self.tokenMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.D0 = _getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); if (amounts[i] > 0) { v.newBalances[i] += _doTransferIn(pooledTokens[i], amounts[i]); } } v.D1 = _getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.D1 > v.D0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.D2 = v.D1; uint256 toMint; if (v.totalSupply > 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = (v.D1 * self.balances[i]) / v.D0; fees[i] = (feePerToken * _distance(idealBalance, v.newBalances[i])) / FEE_DENOMINATOR; self.balances[i] = v.newBalances[i] - ((fees[i] * self.adminFee) / FEE_DENOMINATOR); v.newBalances[i] -= fees[i]; } v.D2 = _getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); toMint = ((v.D2 - v.D0) * v.totalSupply) / v.D0; } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.D1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity(msg.sender, amounts, fees, v.D1, toMint); return toMint; } function removeLiquidity( StableSwapStorage.SwapStorage storage self, uint256 lpAmount, uint256[] memory minAmounts ) external returns (uint256[] memory amounts) { uint256 totalSupply = self.lpToken.totalSupply(); require(lpAmount <= totalSupply); uint256 nCoins = self.pooledTokens.length; uint256[] memory fees = new uint256[](nCoins); amounts = _calculateRemoveLiquidity(self, lpAmount); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "> slippage"); self.balances[i] = self.balances[i] - amounts[i]; self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, lpAmount); emit RemoveLiquidity(msg.sender, amounts, fees, totalSupply - lpAmount); } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateRemoveLiquidityOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] -= (dy + (dyFee * self.adminFee) / FEE_DENOMINATOR); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne(msg.sender, tokenIndex, tokenAmount, dy); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) external returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, _getAPrecise(self), _updateBaseVirtualPrice(metaSwapStorage), self.tokenMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = _feePerToken(self); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.D0 = _getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i] - amounts[i]; } v.D1 = _getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = (v.D1 * v.newBalances[i]) / v.D0; uint256 difference = _distance(idealBalance, balances1[i]); fees[i] = (feePerToken * difference) / FEE_DENOMINATOR; self.balances[i] = balances1[i] - ((fees[i] * self.adminFee) / FEE_DENOMINATOR); balances1[i] -= fees[i]; } v.D2 = _getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = ((v.D0 - v.D2) * v.totalSupply) / v.D0; require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount += 1; // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { if (amounts[i] > 0) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } } emit RemoveLiquidityImbalance(msg.sender, amounts, fees, v.D1, v.totalSupply - tokenAmount); return tokenAmount; } /// VIEW FUNCTIONS /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 D = _getD(_xp(self, _getBaseVirtualPrice(metaSwapStorage)), _getAPrecise(self)); uint256 tokenSupply = self.lpToken.totalSupply(); if (tokenSupply != 0) { return (D * BASE_VIRTUAL_PRICE_PRECISION) / tokenSupply; } return 0; } function calculateRemoveLiquidityOneToken( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint256 inAmount, uint256 inIndex ) external view returns (uint256 amount) { (amount, ) = _calculateRemoveLiquidityOneToken( self, inAmount, inIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function calculateSwap( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint256 inIndex, uint256 outIndex, uint256 inAmount ) external view returns (uint256 outAmount) { (outAmount, ) = _calculateSwap( self, inIndex, outIndex, inAmount, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length - 1); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom] + (dx * self.tokenMultipliers[tokenIndexFrom]); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = ( v.baseSwap.calculateTokenAmount(baseInputs, true) * v.baseVirtualPrice ) / BASE_VIRTUAL_PRICE_PRECISION; // when adding to the base pool,you pay approx 50% of the swap fee v.x = v.x - ((v.x * _getBaseSwapFee(metaSwapStorage.baseSwap)) / (FEE_DENOMINATOR * 2)) + xp[v.baseLPTokenIndex]; } else { return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = _getY( self, tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo] - y - 1; uint256 dyFee = (v.dy * self.fee) / FEE_DENOMINATOR; v.dy = v.dy - dyFee; } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy / self.tokenMultipliers[v.metaIndexTo]; } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( (v.dy * BASE_VIRTUAL_PRICE_PRECISION) / v.baseVirtualPrice, tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } function calculateRemoveLiquidity(StableSwapStorage.SwapStorage storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, amount); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( StableSwapStorage.SwapStorage storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 amp = _getAPrecise(self); uint256 D0; uint256 D1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self.tokenMultipliers; uint256 numTokens = balances1.length; D0 = _getD(_xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), amp); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] += amounts[i]; } else { balances1[i] -= amounts[i]; } } D1 = _getD(_xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), amp); } uint256 totalSupply = self.lpToken.totalSupply(); if (totalSupply == 0) { return D1; // first depositor take it all } if (deposit) { return ((D1 - D0) * totalSupply) / D0; } else { return ((D0 - D1) * totalSupply) / D0; } } /// INTERNAL FUNCTIONS /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if (block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(IStableSwap baseSwap) internal view returns (uint256 fee) { (, fee, , , , , ) = baseSwap.swapStorage(); } function _calculateRemoveLiquidity(StableSwapStorage.SwapStorage storage self, uint256 amount) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = (self.balances[i] * (amount)) / (totalSupply); } return amounts; } function _calculateRemoveLiquidityOneToken( StableSwapStorage.SwapStorage storage self, uint256 inAmount, uint256 inIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns(uint256, uint256) { uint256 dy; uint256 swapFee; { uint256 currentY; uint256 newY; (dy, newY, currentY) = _calculateRemoveLiquidityOneTokenDY( self, inIndex, inAmount, baseVirtualPrice, totalSupply ); swapFee = ((currentY - newY) / self.tokenMultipliers[inIndex]) - dy; } return (dy, swapFee); } function _calculateRemoveLiquidityOneTokenDY( StableSwapStorage.SwapStorage storage self, uint256 inIndex, uint256 inAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256, uint256) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(inIndex < xp.length, "Token index out of range"); CalculateRemoveLiquidityOneTokenInfo memory v = CalculateRemoveLiquidityOneTokenInfo( 0, 0, 0, 0, _getAPrecise(self), 0 ); v.D0 = _getD(xp, v.preciseA); v.D1 = v.D0 - ((inAmount * v.D0) / totalSupply); require(inAmount <= xp[inIndex], "Withdraw exceeds available"); v.newY = _getYD(self, v.preciseA, inIndex, xp, v.D1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi - ( ( (i == inIndex) ? ((v.xpi * v.D1) / v.D0) - v.newY : v.xpi - ((v.xpi * v.D1) / v.D0) ) * v.feePerToken / FEE_DENOMINATOR ); } uint256 dy = xpReduced[inIndex] - ( _getYD(self, v.preciseA, inIndex, xpReduced, v.D1) ); if (inIndex == xp.length - 1) { dy = (dy * BASE_VIRTUAL_PRICE_PRECISION) / baseVirtualPrice; v.newY = (v.newY * BASE_VIRTUAL_PRICE_PRECISION) / baseVirtualPrice; xp[inIndex] = (xp[inIndex] * BASE_VIRTUAL_PRICE_PRECISION) / baseVirtualPrice; } dy = (dy - 1) * self.tokenMultipliers[inIndex]; return (dy, v.newY, xp[inIndex]); } function _calculateSwap( StableSwapStorage.SwapStorage storage self, uint256 inIndex, uint256 outIndex, uint256 inAmount, uint256 baseVirtualPrice ) internal view returns (uint256 outAmount, uint256 fee) { uint256[] memory normalizedBalances = _xp(self, baseVirtualPrice); require( inIndex < normalizedBalances.length && outIndex < normalizedBalances.length, "Token index out of range" ); uint256 baseLPTokenIndex = normalizedBalances.length - 1; uint256 newInBalance = inAmount * self.tokenMultipliers[inIndex]; if (inIndex == baseLPTokenIndex) { newInBalance = (newInBalance * baseVirtualPrice) / BASE_VIRTUAL_PRICE_PRECISION; } newInBalance = newInBalance + normalizedBalances[inIndex]; uint256 outBalance = _getY(self, inIndex, outIndex, newInBalance, normalizedBalances); outAmount = normalizedBalances[outIndex] - outBalance - 1; if (outIndex == baseLPTokenIndex) { outAmount = (outAmount * BASE_VIRTUAL_PRICE_PRECISION) / baseVirtualPrice; } fee = (outAmount * self.fee) / FEE_DENOMINATOR; outAmount = outAmount - fee; outAmount = outAmount / self.tokenMultipliers[outIndex]; } /** * Ramping A up or down, return A with precision of A_PRECISION */ function _getAPrecise(StableSwapStorage.SwapStorage storage self) internal view returns (uint256) { if (block.timestamp >= self.futureATime) { return self.futureA; } if (self.futureA > self.initialA) { return self.initialA + ((self.futureA - self.initialA) * (block.timestamp - self.initialATime)) / (self.futureATime - self.initialATime); } return self.initialA - ((self.initialA - self.futureA) * (block.timestamp - self.initialATime)) / (self.futureATime - self.initialATime); } /** * normalized balances of each tokens. */ function _xp( uint256[] memory balances, uint256[] memory rates ) internal pure returns (uint256[] memory) { require( balances.length == rates.length, "Balances must match rates" ); uint256[] memory xp = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { xp[i] = (rates[i] * balances[i]); } return xp; } function _xp( uint256[] memory balances, uint256[] memory rates, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = _xp(balances, rates); uint256 baseLPTokenIndex = balances.length - 1; xp[baseLPTokenIndex] = (xp[baseLPTokenIndex] * baseVirtualPrice) / BASE_VIRTUAL_PRICE_PRECISION; return xp; } function _xp( StableSwapStorage.SwapStorage storage self, uint256 baseVirtualPrice ) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenMultipliers, baseVirtualPrice ); } /** * Calculate D for *NORMALIZED* balances of each tokens * @param xp normalized balances of token */ function _getD(uint256[] memory xp, uint256 amp) internal pure returns (uint256) { uint256 nCoins = xp.length; uint256 sum = _sumOf(xp); if (sum == 0) { return 0; } uint256 Dprev = 0; uint256 D = sum; uint256 Ann = amp * nCoins; for (uint256 i = 0; i < MAX_ITERATION; i++) { uint256 D_P = D; for (uint256 j = 0; j < xp.length; j++) { D_P = (D_P * D) / (xp[j] * nCoins); } Dprev = D; D = (((Ann * sum) / A_PRECISION + D_P * nCoins) * D) / (((Ann - A_PRECISION) * D) / A_PRECISION + (nCoins + 1) * D_P); if (_distance(D, Dprev) <= 1) { return D; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("invariantCalculationFailed"); } /** * calculate new balance of when swap * Done by solving quadratic equation iteratively. * x_1**2 + x_1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * @param inIndex index of token to swap in * @param outIndex index of token to swap out * @param inBalance new balance (normalized) of input token if the swap success * @return NORMALIZED balance of output token if the swap success */ function _getY( StableSwapStorage.SwapStorage storage self, uint256 inIndex, uint256 outIndex, uint256 inBalance, uint256[] memory normalizedBalances ) internal view returns (uint256) { require(inIndex != outIndex, "sameToken"); uint256 nCoins = self.pooledTokens.length; require(inIndex < nCoins && outIndex < nCoins, "indexOutOfRange"); uint256 amp = _getAPrecise(self); uint256 Ann = amp * nCoins; uint256 D = _getD(normalizedBalances, amp); uint256 sum = 0; // sum of new balances except output token uint256 c = D; for (uint256 i = 0; i < nCoins; i++) { if (i == outIndex) { continue; } uint256 x = i == inIndex ? inBalance : normalizedBalances[i]; sum += x; c = (c * D) / (x * nCoins); } c = (c * D * A_PRECISION) / (Ann * nCoins); uint256 b = sum + (D * A_PRECISION) / Ann; uint256 lastY = 0; uint256 y = D; for (uint256 index = 0; index < MAX_ITERATION; index++) { lastY = y; y = (y * y + c) / (2 * y + b - D); if (_distance(lastY, y) <= 1) { return y; } } revert("yCalculationFailed"); } function _getYD( StableSwapStorage.SwapStorage storage self, uint256 A, uint256 index, uint256[] memory xp, uint256 D ) internal view returns (uint256) { uint256 nCoins = self.pooledTokens.length; assert(index < nCoins); uint256 Ann = A * nCoins; uint256 c = D; uint256 s = 0; uint256 _x = 0; uint256 yPrev = 0; for (uint256 i = 0; i < nCoins; i++) { if (i == index) { continue; } _x = xp[i]; s += _x; c = (c * D) / (_x * nCoins); } c = (c * D * A_PRECISION) / (Ann * nCoins); uint256 b = s + (D * A_PRECISION) / Ann; uint256 y = D; for (uint256 i = 0; i < MAX_ITERATION; i++) { yPrev = y; y = (y * y + c) / (2 * y + b - D); if (_distance(yPrev, y) <= 1) { return y; } } revert("invariantCalculationFailed"); } function _feePerToken(StableSwapStorage.SwapStorage storage self) internal view returns (uint256) { uint256 nCoins = self.pooledTokens.length; return (self.fee * nCoins) / (4 * (nCoins - 1)); } function _doTransferIn(IERC20 token, uint256 amount) internal returns (uint256) { uint256 priorBalance = token.balanceOf(address(this)); token.safeTransferFrom(msg.sender, address(this), amount); return token.balanceOf(address(this)) - priorBalance; } function _sumOf(uint256[] memory x) internal pure returns (uint256 sum) { sum = 0; for (uint256 i = 0; i < x.length; i++) { sum += x[i]; } } function _distance(uint256 x, uint256 y) internal pure returns (uint256) { return x > y ? x - y : y - x; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = IStableSwap(metaSwapStorage.baseSwap).getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {IStableSwapCallee} from "../stableswap/interfaces/IStableSwapCallee.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract MockStableSwapBorrower { using SafeERC20 for IERC20; function zenlinkStableSwapCall( address sender, IERC20[] memory tokens, uint256[] memory amounts, uint256[] memory fees, bytes calldata data ) external { require(data.length > 0); for (uint256 i = 0; i < amounts.length; i++) { if (amounts[i] > 0) { tokens[i].safeTransferFrom(sender, address(this), fees[i]); tokens[i].safeIncreaseAllowance(msg.sender, amounts[i] + fees[i]); } } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {StableSwap, StableSwapStorage, SafeERC20, IERC20, IStableSwap, LPToken} from "./StableSwap.sol"; import {MetaSwapStorage} from "./MetaSwapStorage.sol"; contract MetaSwap is StableSwap { using MetaSwapStorage for StableSwapStorage.SwapStorage; using SafeERC20 for IERC20; MetaSwapStorage.MetaSwap public metaSwapStorage; // events replicated from SwapStorage to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapStorage.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) virtual external view override returns (uint256) { return MetaSwapStorage.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapStorage.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) virtual external view override returns (uint256) { return MetaSwapStorage.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } function calculateRemoveLiquidity(uint256 amount) virtual external view override returns (uint256[] memory) { return MetaSwapStorage.calculateRemoveLiquidity(swapStorage, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) virtual external view override returns (uint256) { return MetaSwapStorage.calculateRemoveLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } function initialize( address[] memory, uint8[] memory, string memory, string memory, uint256, uint256, uint256, address ) public virtual override onlyAdmin { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( address[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address _feeDistributor, IStableSwap baseSwap ) public virtual onlyAdmin { StableSwap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _feeDistributor ); metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), type(uint256).max); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = IERC20(_pooledTokens[_pooledTokens.length - 1]); require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), type(uint256).max); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapStorage.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapStorage.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } function flashLoan( uint256[] memory amountsOut, address to, bytes calldata data, uint256 deadline ) external virtual override whenNotPaused nonReentrant deadlineCheck(deadline) { MetaSwapStorage.flashLoan(swapStorage, amountsOut, to, data); } function addLiquidity( uint256[] memory amounts, uint256 minMintAmount, uint256 deadline ) external virtual override whenNotPaused nonReentrant deadlineCheck(deadline) returns (uint256) { return MetaSwapStorage.addLiquidity( swapStorage, metaSwapStorage, amounts, minMintAmount ); } function removeLiquidity( uint256 lpAmount, uint256[] memory minAmounts, uint256 deadline ) external virtual override nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return MetaSwapStorage.removeLiquidity(swapStorage, lpAmount, minAmounts); } function removeLiquidityOneToken( uint256 lpAmount, uint8 index, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapStorage.removeLiquidityOneToken( swapStorage, metaSwapStorage, lpAmount, index, minAmount ); } function removeLiquidityImbalance( uint256[] memory amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapStorage.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../../stableswap/interfaces/IStableSwap.sol"; interface IStableSwapRouter { function convert( IStableSwap fromPool, IStableSwap toPool, uint256 amount, uint256 minToMint, address to, uint256 deadline ) external returns (uint256); function addPoolLiquidity( IStableSwap pool, uint256[] memory amounts, uint256 minMintAmount, address to, uint256 deadline ) external returns (uint256); function addPoolAndBaseLiquidity( IStableSwap pool, IStableSwap basePool, uint256[] memory meta_amounts, uint256[] memory base_amounts, uint256 minToMint, address to, uint256 deadline ) external returns (uint256); function removePoolLiquidity( IStableSwap pool, uint256 lpAmount, uint256[] memory minAmounts, address to, uint256 deadline ) external returns (uint256[] memory amounts); function removePoolLiquidityOneToken( IStableSwap pool, uint256 lpAmount, uint8 index, uint256 minAmount, address to, uint256 deadline ) external returns (uint256); function removePoolAndBaseLiquidity( IStableSwap pool, IStableSwap basePool, uint256 _amount, uint256[] calldata min_amounts_meta, uint256[] calldata min_amounts_base, address to, uint256 deadline ) external returns (uint256[] memory amounts, uint256[] memory base_amounts); function removePoolAndBaseLiquidityOneToken( IStableSwap pool, IStableSwap basePool, uint256 _token_amount, uint8 i, uint256 _min_amount, address to, uint256 deadline ) external returns (uint256); function swapPool( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount, uint256 minOutAmount, address to, uint256 deadline ) external returns (uint256); function swapPoolFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, address to, uint256 deadline ) external returns (uint256); function swapPoolToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, address to, uint256 deadline ) external returns (uint256); function calculateConvert( IStableSwap fromPool, IStableSwap toPool, uint256 amount ) external view returns (uint256); function calculateTokenAmount( IStableSwap pool, IStableSwap basePool, uint256[] memory meta_amounts, uint256[] memory base_amounts, bool is_deposit ) external view returns (uint256); function calculateRemoveLiquidity( IStableSwap pool, IStableSwap basePool, uint256 amount ) external view returns (uint256[] memory meta_amounts, uint256[] memory base_amounts); function calculateRemoveBaseLiquidityOneToken( IStableSwap pool, IStableSwap basePool, uint256 _token_amount, uint8 iBase ) external view returns (uint256 availableTokenAmount); function calculateSwap( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount ) external view returns (uint256); function calculateSwapFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "../stableswap/interfaces/IStableSwap.sol"; import "./interfaces/IStableSwapRouter.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract StableSwapRouter is IStableSwapRouter { using SafeERC20 for IERC20; function convert( IStableSwap fromPool, IStableSwap toPool, uint256 amount, uint256 minToMint, address to, uint256 deadline ) external override returns (uint256) { uint256 fromPoolLength = fromPool.getNumberOfTokens(); uint256 toPoolLength = toPool.getNumberOfTokens(); require(address(fromPool) != address(toPool), "fromPool = toPool"); require(fromPoolLength == toPoolLength, "poolTokensLengthMissmatch"); IERC20 fromToken = fromPool.getLpToken(); IERC20 toToken = toPool.getLpToken(); uint256[] memory min_amounts = new uint256[](fromPoolLength); // validate token for (uint8 i = 0; i < fromPoolLength; i++) { IERC20 coin = fromPool.getToken(i); toPool.getTokenIndex(address(coin)); } fromToken.safeTransferFrom(msg.sender, address(this), amount); fromToken.safeIncreaseAllowance(address(fromPool), amount); fromPool.removeLiquidity(amount, min_amounts, deadline); uint256[] memory meta_amounts = new uint256[](toPoolLength); for (uint8 i = 0; i < toPoolLength; i++) { IERC20 coin = toPool.getToken(i); uint256 addBalance = coin.balanceOf(address(this)); coin.safeIncreaseAllowance(address(toPool), addBalance); meta_amounts[i] = addBalance; } toPool.addLiquidity(meta_amounts, minToMint, deadline); uint256 lpAmount = toToken.balanceOf(address(this)); toToken.safeTransfer(to, lpAmount); return lpAmount; } function addPoolLiquidity( IStableSwap pool, uint256[] memory amounts, uint256 minMintAmount, address to, uint256 deadline ) external override returns (uint256) { IERC20 token = IERC20(pool.getLpToken()); for (uint8 i = 0; i < amounts.length; i++) { IERC20 coin = pool.getToken(i); uint256 transferred; if (amounts[i] > 0) { transferred = transferIn(coin, msg.sender, amounts[i]); } amounts[i] = transferred; if (transferred > 0) { coin.safeIncreaseAllowance(address(pool), transferred); } } pool.addLiquidity(amounts, minMintAmount, deadline); uint256 lpAmount = token.balanceOf(address(this)); token.safeTransfer(to, lpAmount); return lpAmount; } function addPoolAndBaseLiquidity( IStableSwap pool, IStableSwap basePool, uint256[] memory meta_amounts, uint256[] memory base_amounts, uint256 minToMint, address to, uint256 deadline ) external override returns (uint256) { IERC20 token = IERC20(pool.getLpToken()); IERC20 base_lp = IERC20(basePool.getLpToken()); require(base_amounts.length == basePool.getNumberOfTokens(), "invalidBaseAmountsLength"); require(meta_amounts.length == pool.getNumberOfTokens(), "invalidMetaAmountsLength"); bool deposit_base = false; for (uint8 i = 0; i < base_amounts.length; i++) { uint256 amount = base_amounts[i]; if (amount > 0) { deposit_base = true; IERC20 coin = basePool.getToken(i); uint256 transferred = transferIn(coin, msg.sender, amount); coin.safeIncreaseAllowance(address(basePool), transferred); base_amounts[i] = transferred; } } uint256 base_lp_received; if (deposit_base) { base_lp_received = basePool.addLiquidity(base_amounts, 0, deadline); } for (uint8 i = 0; i < meta_amounts.length; i++) { IERC20 coin = pool.getToken(i); uint256 transferred; if (address(coin) == address(base_lp)) { transferred = base_lp_received; } else if (meta_amounts[i] > 0) { transferred = transferIn(coin, msg.sender, meta_amounts[i]); } meta_amounts[i] = transferred; if (transferred > 0) { coin.safeIncreaseAllowance(address(pool), transferred); } } uint256 base_lp_prior = base_lp.balanceOf(address(this)); pool.addLiquidity(meta_amounts, minToMint, deadline); if (deposit_base) { require((base_lp.balanceOf(address(this)) + base_lp_received) == base_lp_prior, "invalidBasePool"); } uint256 lpAmount = token.balanceOf(address(this)); token.safeTransfer(to, lpAmount); return lpAmount; } function removePoolLiquidity( IStableSwap pool, uint256 lpAmount, uint256[] memory minAmounts, address to, uint256 deadline ) external override returns (uint256[] memory amounts) { IERC20 token = pool.getLpToken(); token.safeTransferFrom(msg.sender, address(this), lpAmount); token.safeIncreaseAllowance(address(pool), lpAmount); pool.removeLiquidity(lpAmount, minAmounts, deadline); amounts = new uint256[](pool.getNumberOfTokens()); for (uint8 i = 0; i < pool.getNumberOfTokens(); i++) { IERC20 coin = pool.getToken(i); amounts[i] = coin.balanceOf(address(this)); if (amounts[i] > 0) { coin.safeTransfer(to, amounts[i]); } } } function removePoolLiquidityOneToken( IStableSwap pool, uint256 lpAmount, uint8 index, uint256 minAmount, address to, uint256 deadline ) external override returns (uint256) { IERC20 token = pool.getLpToken(); token.safeTransferFrom(msg.sender, address(this), lpAmount); token.safeIncreaseAllowance(address(pool), lpAmount); pool.removeLiquidityOneToken(lpAmount, index, minAmount, deadline); IERC20 coin = pool.getToken(index); uint256 coin_amount = coin.balanceOf(address(this)); coin.safeTransfer(to, coin_amount); return coin_amount; } function removePoolAndBaseLiquidity( IStableSwap pool, IStableSwap basePool, uint256 _amount, uint256[] calldata min_amounts_meta, uint256[] calldata min_amounts_base, address to, uint256 deadline ) external override returns (uint256[] memory amounts, uint256[] memory base_amounts) { IERC20 token = pool.getLpToken(); IERC20 baseToken = basePool.getLpToken(); token.safeTransferFrom(msg.sender, address(this), _amount); token.safeIncreaseAllowance(address(pool), _amount); pool.removeLiquidity(_amount, min_amounts_meta, deadline); uint256 _base_amount = baseToken.balanceOf(address(this)); baseToken.safeIncreaseAllowance(address(basePool), _base_amount); basePool.removeLiquidity(_base_amount, min_amounts_base, deadline); // Transfer all coins out amounts = new uint256[](pool.getNumberOfTokens()); for (uint8 i = 0; i < pool.getNumberOfTokens(); i++) { IERC20 coin = pool.getToken(i); amounts[i] = coin.balanceOf(address(this)); if (amounts[i] > 0) { coin.safeTransfer(to, amounts[i]); } } base_amounts = new uint256[](basePool.getNumberOfTokens()); for (uint8 i = 0; i < basePool.getNumberOfTokens(); i++) { IERC20 coin = basePool.getToken(i); base_amounts[i] = coin.balanceOf(address(this)); if (base_amounts[i] > 0) { coin.safeTransfer(to, base_amounts[i]); } } } function removePoolAndBaseLiquidityOneToken( IStableSwap pool, IStableSwap basePool, uint256 _token_amount, uint8 i, uint256 _min_amount, address to, uint256 deadline ) external override returns (uint256) { IERC20 token = pool.getLpToken(); IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); token.safeTransferFrom(msg.sender, address(this), _token_amount); token.safeIncreaseAllowance(address(pool), _token_amount); pool.removeLiquidityOneToken(_token_amount, baseTokenIndex, 0, deadline); uint256 _base_amount = baseToken.balanceOf(address(this)); baseToken.safeIncreaseAllowance(address(basePool), _base_amount); basePool.removeLiquidityOneToken(_base_amount, i, _min_amount, deadline); IERC20 coin = basePool.getToken(i); uint256 coin_amount = coin.balanceOf(address(this)); coin.safeTransfer(to, coin_amount); return coin_amount; } function swapPool( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount, uint256 minOutAmount, address to, uint256 deadline ) external override returns (uint256) { IERC20 coin = pool.getToken(fromIndex); coin.safeTransferFrom(msg.sender, address(this), inAmount); coin.safeIncreaseAllowance(address(pool), inAmount); pool.swap(fromIndex, toIndex, inAmount, minOutAmount, deadline); IERC20 coinTo = pool.getToken(toIndex); uint256 amountOut = coinTo.balanceOf(address(this)); coinTo.safeTransfer(to, amountOut); return amountOut; } function swapPoolFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, address to, uint256 deadline ) external override returns (uint256) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256[] memory base_amounts = new uint256[](basePool.getNumberOfTokens()); base_amounts[tokenIndexFrom] = dx; IERC20 coin = basePool.getToken(tokenIndexFrom); coin.safeTransferFrom(msg.sender, address(this), dx); coin.safeIncreaseAllowance(address(basePool), dx); uint256 baseLpAmount = basePool.addLiquidity(base_amounts, 0, deadline); if (baseTokenIndex != tokenIndexTo) { baseToken.safeIncreaseAllowance(address(pool), baseLpAmount); pool.swap(baseTokenIndex, tokenIndexTo, baseLpAmount, minDy, deadline); } IERC20 coinTo = pool.getToken(tokenIndexTo); uint256 amountOut = coinTo.balanceOf(address(this)); coinTo.safeTransfer(to, amountOut); return amountOut; } function swapPoolToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, address to, uint256 deadline ) external override returns (uint256) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); IERC20 coin = pool.getToken(tokenIndexFrom); coin.safeTransferFrom(msg.sender, address(this), dx); uint256 tokenLPAmount = dx; if (baseTokenIndex != tokenIndexFrom) { coin.safeIncreaseAllowance(address(pool), dx); tokenLPAmount = pool.swap(tokenIndexFrom, baseTokenIndex, dx, 0, deadline); } baseToken.safeIncreaseAllowance(address(basePool), tokenLPAmount); basePool.removeLiquidityOneToken(tokenLPAmount, tokenIndexTo, minDy, deadline); IERC20 coinTo = basePool.getToken(tokenIndexTo); uint256 amountOut = coinTo.balanceOf(address(this)); coinTo.safeTransfer(to, amountOut); return amountOut; } // =========== VIEW =========== function calculateConvert( IStableSwap fromPool, IStableSwap toPool, uint256 amount ) external override view returns (uint256) { uint256 fromPoolLength = fromPool.getNumberOfTokens(); uint256[] memory amounts = fromPool.calculateRemoveLiquidity(amount); uint256[] memory meta_amounts = new uint256[](fromPoolLength); for (uint8 i = 0; i < fromPoolLength; i++) { IERC20 fromCoin = fromPool.getToken(i); uint256 toCoinIndex = toPool.getTokenIndex(address(fromCoin)); meta_amounts[toCoinIndex] = amounts[i]; } return toPool.calculateTokenAmount(meta_amounts, true); } function calculateTokenAmount( IStableSwap pool, IStableSwap basePool, uint256[] memory meta_amounts, uint256[] memory base_amounts, bool is_deposit ) external override view returns (uint256) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256 _base_tokens = basePool.calculateTokenAmount(base_amounts, is_deposit); meta_amounts[baseTokenIndex] = meta_amounts[baseTokenIndex] + _base_tokens; return pool.calculateTokenAmount(meta_amounts, is_deposit); } function calculateRemoveLiquidity( IStableSwap pool, IStableSwap basePool, uint256 amount ) external override view returns (uint256[] memory meta_amounts, uint256[] memory base_amounts) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); meta_amounts = pool.calculateRemoveLiquidity(amount); uint256 lpAmount = meta_amounts[baseTokenIndex]; meta_amounts[baseTokenIndex] = 0; base_amounts = basePool.calculateRemoveLiquidity(lpAmount); } function calculateRemoveBaseLiquidityOneToken( IStableSwap pool, IStableSwap basePool, uint256 _token_amount, uint8 iBase ) external override view returns (uint256 availableTokenAmount) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256 _base_tokens = pool.calculateRemoveLiquidityOneToken(_token_amount, baseTokenIndex); availableTokenAmount = basePool.calculateRemoveLiquidityOneToken(_base_tokens, iBase); } function calculateSwap( IStableSwap pool, uint8 fromIndex, uint8 toIndex, uint256 inAmount ) external override view returns (uint256) { return pool.calculateSwap(fromIndex, toIndex, inAmount); } function calculateSwapFromBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external override view returns (uint256) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256[] memory base_amounts = new uint256[](basePool.getNumberOfTokens()); base_amounts[tokenIndexFrom] = dx; uint256 baseLpAmount = basePool.calculateTokenAmount(base_amounts, true); if (baseTokenIndex == tokenIndexTo) { return baseLpAmount; } return pool.calculateSwap(baseTokenIndex, tokenIndexTo, baseLpAmount); } function calculateSwapToBase( IStableSwap pool, IStableSwap basePool, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external override view returns (uint256) { IERC20 baseToken = basePool.getLpToken(); uint8 baseTokenIndex = pool.getTokenIndex(address(baseToken)); uint256 tokenLPAmount = dx; if (baseTokenIndex != tokenIndexFrom) { tokenLPAmount = pool.calculateSwap(tokenIndexFrom, baseTokenIndex, dx); } return basePool.calculateRemoveLiquidityOneToken(tokenLPAmount, tokenIndexTo); } function transferIn( IERC20 token, address from, uint256 amount ) internal returns (uint256 transferred) { uint256 prior_balance = token.balanceOf(address(this)); token.safeTransferFrom(from, address(this), amount); transferred = token.balanceOf(address(this)) - prior_balance; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; // Example class - a mock class using delivering from ERC20 contract BasicToken is ERC20 { uint8 private _decimals; constructor( string memory setName, string memory setSymbol, uint8 setDecimals, uint256 initialBalance ) ERC20(setName, setSymbol) { _decimals = setDecimals; _mint(msg.sender, initialBalance); } // sets the balance of the address // this mints/burns the amount depending on the current balance function setBalance(address to, uint256 amount) public { uint256 old = balanceOf(to); if (old < amount) { _mint(to, amount - old); } else if (old > amount) { _burn(to, old - amount); } } function decimals() public view virtual override returns (uint8) { return _decimals; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {AdminUpgradeable} from "../libraries/AdminUpgradeable.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import {SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; contract RewardDispatcher is AdminUpgradeable { using SafeERC20 for IERC20; // the token to dispatch IERC20 public immutable token; // the dest address that the token will send to address public immutable dest; uint256 public rewardRate; uint256 public lastRecordBlock; event Charged(address indexed sender, address indexed token, uint256 amount); event WithdrawReward(address indexed sender, address indexed token, uint256 amount); event DispatchReward(address indexed dest, address indexed token, uint256 amount); event UpdateRate(uint256 rate); constructor(IERC20 _token, address _dest) { token = _token; dest = _dest; _initializeAdmin(msg.sender); } function dispatchReward() public { uint256 amount = (block.number - lastRecordBlock) * rewardRate; lastRecordBlock = block.number; token.safeTransfer(dest, amount); emit DispatchReward(msg.sender, address(token), amount); } function updateRate(uint256 rate) external onlyAdmin { dispatchReward(); rewardRate = rate; emit UpdateRate(rate); } function withdrawRewards(uint256 amount) external onlyAdmin { token.safeTransfer(msg.sender, amount); emit WithdrawReward(msg.sender, address(token), amount); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "./interfaces/IMerkleDistributor.sol"; import "../libraries/AdminUpgradeable.sol"; contract MerkleDistributor is IMerkleDistributor, AdminUpgradeable { address public immutable override token; bytes32 public immutable override merkleRoot; // This is a packed array of booleans. mapping(uint256 => uint256) private claimedBitMap; constructor(address token_, bytes32 merkleRoot_) { token = token_; merkleRoot = merkleRoot_; _initializeAdmin(msg.sender); } function isClaimed(uint256 index) public view override returns (bool) { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; uint256 claimedWord = claimedBitMap[claimedWordIndex]; uint256 mask = (1 << claimedBitIndex); return claimedWord & mask == mask; } function _setClaimed(uint256 index) private { uint256 claimedWordIndex = index / 256; uint256 claimedBitIndex = index % 256; claimedBitMap[claimedWordIndex] = claimedBitMap[claimedWordIndex] | (1 << claimedBitIndex); } function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external override { require(!isClaimed(index), 'MerkleDistributor: Drop already claimed.'); // Verify the merkle proof. bytes32 node = keccak256(abi.encodePacked(index, account, amount)); require(MerkleProof.verify(merkleProof, merkleRoot, node), 'MerkleDistributor: Invalid proof.'); // Mark it claimed and send the token. _setClaimed(index); require(IERC20(token).transfer(account, amount), 'MerkleDistributor: Transfer failed.'); emit Claimed(index, account, amount); } function withdraw(uint256 amount) external override onlyAdmin { IERC20(token).transfer(msg.sender, amount); } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; // Allows anyone to claim a token if they exist in a merkle root. interface IMerkleDistributor { // Returns the address of the token distributed by this contract. function token() external view returns (address); // Returns the merkle root of the merkle tree containing account balances available to claim. function merkleRoot() external view returns (bytes32); // Returns true if the index has been marked claimed. function isClaimed(uint256 index) external view returns (bool); // Claim the given amount of the token to the given address. Reverts if the inputs are invalid. function claim(uint256 index, address account, uint256 amount, bytes32[] calldata merkleProof) external; // Withdraw the given amount of the token function withdraw(uint256 amount) external; // This event is triggered whenever a call to #claim succeeds. event Claimed(uint256 index, address account, uint256 amount); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Tree proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Calldata version of {verify} * * _Available since v4.7._ */ function verifyCalldata( bytes32[] calldata proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProofCalldata(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Calldata version of {processProof} * * _Available since v4.7._ */ function processProofCalldata(bytes32[] calldata proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { computedHash = _hashPair(computedHash, proof[i]); } return computedHash; } /** * @dev Returns true if the `leaves` can be proved to be a part of a Merkle tree defined by * `root`, according to `proof` and `proofFlags` as described in {processMultiProof}. * * _Available since v4.7._ */ function multiProofVerify( bytes32[] memory proof, bool[] memory proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProof(proof, proofFlags, leaves) == root; } /** * @dev Calldata version of {multiProofVerify} * * _Available since v4.7._ */ function multiProofVerifyCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32 root, bytes32[] memory leaves ) internal pure returns (bool) { return processMultiProofCalldata(proof, proofFlags, leaves) == root; } /** * @dev Returns the root of a tree reconstructed from `leaves` and the sibling nodes in `proof`, * consuming from one or the other at each step according to the instructions given by * `proofFlags`. * * _Available since v4.7._ */ function processMultiProof( bytes32[] memory proof, bool[] memory proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } /** * @dev Calldata version of {processMultiProof} * * _Available since v4.7._ */ function processMultiProofCalldata( bytes32[] calldata proof, bool[] calldata proofFlags, bytes32[] memory leaves ) internal pure returns (bytes32 merkleRoot) { // This function rebuild the root hash by traversing the tree up from the leaves. The root is rebuilt by // consuming and producing values on a queue. The queue starts with the `leaves` array, then goes onto the // `hashes` array. At the end of the process, the last hash in the `hashes` array should contain the root of // the merkle tree. uint256 leavesLen = leaves.length; uint256 totalHashes = proofFlags.length; // Check proof validity. require(leavesLen + proof.length - 1 == totalHashes, "MerkleProof: invalid multiproof"); // The xxxPos values are "pointers" to the next value to consume in each array. All accesses are done using // `xxx[xxxPos++]`, which return the current value and increment the pointer, thus mimicking a queue's "pop". bytes32[] memory hashes = new bytes32[](totalHashes); uint256 leafPos = 0; uint256 hashPos = 0; uint256 proofPos = 0; // At each step, we compute the next hash using two values: // - a value from the "main queue". If not all leaves have been consumed, we get the next leaf, otherwise we // get the next hash. // - depending on the flag, either another value for the "main queue" (merging branches) or an element from the // `proof` array. for (uint256 i = 0; i < totalHashes; i++) { bytes32 a = leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++]; bytes32 b = proofFlags[i] ? leafPos < leavesLen ? leaves[leafPos++] : hashes[hashPos++] : proof[proofPos++]; hashes[i] = _hashPair(a, b); } if (totalHashes > 0) { return hashes[totalHashes - 1]; } else if (leavesLen > 0) { return leaves[0]; } else { return proof[0]; } } function _hashPair(bytes32 a, bytes32 b) private pure returns (bytes32) { return a < b ? _efficientHash(a, b) : _efficientHash(b, a); } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { /// @solidity memory-safe-assembly assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {ERC4626, IERC20Metadata, ERC20, Math} from "@openzeppelin/contracts/token/ERC20/extensions/ERC4626.sol"; import {AdminUpgradeable} from "../libraries/AdminUpgradeable.sol"; import {IZenlinkTokenLoyaltyCalculator} from "../libraries/interfaces/IZenlinkTokenLoyaltyCalculator.sol"; contract vxZenlinkToken is ERC4626, AdminUpgradeable { address public loyaltyCalculator; event WithdrawVXZLK( address indexed caller, address indexed receiver, address indexed owner, uint256 assets, uint256 fee, uint256 shares ); constructor( IERC20Metadata _zlk, string memory _name, string memory _symbol ) ERC20(_name, _symbol) ERC4626(_zlk) { _initializeAdmin(msg.sender); } function updateLoyaltyCaculator(address calculator) external onlyAdmin { loyaltyCalculator = calculator; } function getZenlinkTokenWithdrawFeeRatio() public view returns (uint256) { return IZenlinkTokenLoyaltyCalculator(loyaltyCalculator).getZenlinkTokenWithdrawFeeRatio(); } function getWithdrawResult(uint256 assets) public view returns (uint256 zlkReceive, uint256 withdrawFeeAmount) { uint256 feeRatio = getZenlinkTokenWithdrawFeeRatio(); withdrawFeeAmount = Math.mulDiv(assets, feeRatio, 1e18); zlkReceive = assets - withdrawFeeAmount; } function withdraw( uint256 assets, address receiver, address owner ) public virtual override returns (uint256) { require(assets <= maxWithdraw(owner), "ERC4626: withdraw more than max"); uint256 shares = previewWithdraw(assets); (uint256 zlkReceive, uint256 withdrawFeeAmount) = getWithdrawResult(assets); _withdraw(_msgSender(), receiver, owner, zlkReceive, shares); emit WithdrawVXZLK(_msgSender(), receiver, owner, zlkReceive, withdrawFeeAmount, shares); return shares; } function redeem( uint256 shares, address receiver, address owner ) public virtual override returns (uint256) { require(shares <= maxRedeem(owner), "ERC4626: redeem more than max"); uint256 assets = previewRedeem(shares); (uint256 zlkReceive, uint256 withdrawFeeAmount) = getWithdrawResult(assets); _withdraw(_msgSender(), receiver, owner, zlkReceive, shares); emit WithdrawVXZLK(_msgSender(), receiver, owner, zlkReceive, withdrawFeeAmount, shares); return assets; } }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; interface IZenlinkTokenLoyaltyCalculator { function getCirculation() external view returns (uint256); function getZenlinkTokenWithdrawFeeRatio() external view returns (uint256); }
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; import {vxZenlinkToken, IERC20Metadata} from "../tokens/vxZenlinkToken.sol"; // mock class using ERC20 contract vxZenlinkTokenMock is vxZenlinkToken { constructor( IERC20Metadata asset, string memory name, string memory symbol ) vxZenlinkToken(asset, name, symbol) {} function mockMint(address account, uint256 amount) public { _mint(account, amount); } function mockBurn(address account, uint256 amount) public { _burn(account, amount); } }
// SPDX-License-Identifier: MIT /** *Submitted for verification at Etherscan.io on 2017-12-12 */ // Copyright (C) 2015, 2016, 2017 Dapphub // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.8.0; contract WETH { string public name = "Wrapped MOVR"; string public symbol = "WMOVR"; uint8 public decimals = 18; event Approval(address indexed src, address indexed guy, uint256 wad); event Transfer(address indexed src, address indexed dst, uint256 wad); event Deposit(address indexed dst, uint256 wad); event Withdrawal(address indexed src, uint256 wad); mapping(address => uint256) public balanceOf; mapping(address => mapping(address => uint256)) public allowance; receive() external payable { deposit(); } function deposit() public payable { balanceOf[msg.sender] += msg.value; emit Deposit(msg.sender, msg.value); } function withdraw(uint256 wad) public { require(balanceOf[msg.sender] >= wad); balanceOf[msg.sender] -= wad; payable(msg.sender).transfer(wad); emit Withdrawal(msg.sender, wad); } function totalSupply() public view returns (uint256) { return address(this).balance; } function approve(address guy, uint256 wad) public returns (bool) { allowance[msg.sender][guy] = wad; emit Approval(msg.sender, guy, wad); return true; } function transfer(address dst, uint256 wad) public returns (bool) { return transferFrom(msg.sender, dst, wad); } function transferFrom( address src, address dst, uint256 wad ) public returns (bool) { require(balanceOf[src] >= wad); if ( src != msg.sender && allowance[src][msg.sender] != type(uint256).max ) { require(allowance[src][msg.sender] >= wad); allowance[src][msg.sender] -= wad; } balanceOf[src] -= wad; balanceOf[dst] += wad; emit Transfer(src, dst, wad); return true; } } /* GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: <program> Copyright (C) <year> <name of author> This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see <http://www.gnu.org/licenses/>. The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read <http://www.gnu.org/philosophy/why-not-lgpl.html>. */
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0; pragma experimental ABIEncoderV2; contract Multicall2 { struct Call { address target; bytes callData; } struct Result { bool success; bytes returnData; } function aggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes[] memory returnData) { blockNumber = block.number; returnData = new bytes[](calls.length); for(uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData); require(success, "Multicall aggregate: call failed"); returnData[i] = ret; } } function blockAndAggregate(Call[] memory calls) public returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) { (blockNumber, blockHash, returnData) = tryBlockAndAggregate(true, calls); } function getBlockHash(uint256 blockNumber) public view returns (bytes32 blockHash) { blockHash = blockhash(blockNumber); } function getBlockNumber() public view returns (uint256 blockNumber) { blockNumber = block.number; } function getCurrentBlockCoinbase() public view returns (address coinbase) { coinbase = block.coinbase; } function getCurrentBlockDifficulty() public view returns (uint256 difficulty) { difficulty = block.difficulty; } function getCurrentBlockGasLimit() public view returns (uint256 gaslimit) { gaslimit = block.gaslimit; } function getCurrentBlockTimestamp() public view returns (uint256 timestamp) { timestamp = block.timestamp; } function getEthBalance(address addr) public view returns (uint256 balance) { balance = addr.balance; } function getLastBlockHash() public view returns (bytes32 blockHash) { blockHash = blockhash(block.number - 1); } function tryAggregate(bool requireSuccess, Call[] memory calls) public returns (Result[] memory returnData) { returnData = new Result[](calls.length); for(uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory ret) = calls[i].target.call(calls[i].callData); if (requireSuccess) { require(success, "Multicall2 aggregate: call failed"); } returnData[i] = Result(success, ret); } } function tryBlockAndAggregate(bool requireSuccess, Call[] memory calls) public returns (uint256 blockNumber, bytes32 blockHash, Result[] memory returnData) { blockNumber = block.number; blockHash = blockhash(block.number); returnData = tryAggregate(requireSuccess, calls); } }
{ "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "abi" ] } }, "metadata": { "useLiteralContent": true } }
[{"inputs":[],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"owner","type":"address"},{"indexed":true,"internalType":"address","name":"spender","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Approval","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Burn","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1","type":"uint256"}],"name":"Mint","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"sender","type":"address"},{"indexed":false,"internalType":"uint256","name":"amount0In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1In","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount0Out","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"amount1Out","type":"uint256"},{"indexed":true,"internalType":"address","name":"to","type":"address"}],"name":"Swap","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint112","name":"reserve0","type":"uint112"},{"indexed":false,"internalType":"uint112","name":"reserve1","type":"uint112"}],"name":"Sync","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"from","type":"address"},{"indexed":true,"internalType":"address","name":"to","type":"address"},{"indexed":false,"internalType":"uint256","name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"inputs":[],"name":"DOMAIN_SEPARATOR","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"MINIMUM_LIQUIDITY","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"PERMIT_TYPEHASH","outputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"}],"name":"allowance","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approve","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"account","type":"address"}],"name":"balanceOf","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"burn","outputs":[{"internalType":"uint256","name":"amount0","type":"uint256"},{"internalType":"uint256","name":"amount1","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"decimals","outputs":[{"internalType":"uint8","name":"","type":"uint8"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"subtractedValue","type":"uint256"}],"name":"decreaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"factory","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"getReserves","outputs":[{"internalType":"uint112","name":"_reserve0","type":"uint112"},{"internalType":"uint112","name":"_reserve1","type":"uint112"},{"internalType":"uint32","name":"_blockTimestampLast","type":"uint32"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"addedValue","type":"uint256"}],"name":"increaseAllowance","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"_token0","type":"address"},{"internalType":"address","name":"_token1","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"kLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"mint","outputs":[{"internalType":"uint256","name":"liquidity","type":"uint256"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"owner","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"value","type":"uint256"},{"internalType":"uint256","name":"deadline","type":"uint256"},{"internalType":"uint8","name":"v","type":"uint8"},{"internalType":"bytes32","name":"r","type":"bytes32"},{"internalType":"bytes32","name":"s","type":"bytes32"}],"name":"permit","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"price0CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"price1CumulativeLast","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"}],"name":"skim","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount0Out","type":"uint256"},{"internalType":"uint256","name":"amount1Out","type":"uint256"},{"internalType":"address","name":"to","type":"address"},{"internalType":"bytes","name":"data","type":"bytes"}],"name":"swap","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"symbol","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"sync","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token0","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"token1","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"totalSupply","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transfer","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"from","type":"address"},{"internalType":"address","name":"to","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"transferFrom","outputs":[{"internalType":"bool","name":"","type":"bool"}],"stateMutability":"nonpayable","type":"function"}]
Contract Creation Code
6080604052600e805460ff191660011790553480156200001e57600080fd5b50604080518082018252601081526f2d32b73634b735902628102a37b5b2b760811b60208083019182528351808501909452600684526505a4c4b2d4c560d41b9084015281519192916200007591600391620001ee565b5080516200008b906004906020840190620001ee565b504691507f8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f9050620000bc62000154565b805160209182012060408051808201825260018152603160f81b90840152805192830193909352918101919091527fc89efdaa54c0f20c7adf612882df0950f5a951637e0307cdcb4c672f298b8bc66060820152608081018290523060a082015260c00160408051601f19818403018152919052805160209091012060055550600780546001600160a01b03191633179055620002d1565b606060038054620001659062000294565b80601f0160208091040260200160405190810160405280929190818152602001828054620001939062000294565b8015620001e45780601f10620001b857610100808354040283529160200191620001e4565b820191906000526020600020905b815481529060010190602001808311620001c657829003601f168201915b5050505050905090565b828054620001fc9062000294565b90600052602060002090601f0160209004810192826200022057600085556200026b565b82601f106200023b57805160ff19168380011785556200026b565b828001600101855582156200026b579182015b828111156200026b5782518255916020019190600101906200024e565b50620002799291506200027d565b5090565b5b808211156200027957600081556001016200027e565b600181811c90821680620002a957607f821691505b60208210811415620002cb57634e487b7160e01b600052602260045260246000fd5b50919050565b6128b680620002e16000396000f3fe608060405234801561001057600080fd5b50600436106101cf5760003560e01c80636a62784211610104578063a9059cbb116100a2578063d21220a711610071578063d21220a71461040f578063d505accf14610422578063dd62ed3e14610435578063fff6cae91461044857600080fd5b8063a9059cbb146103cd578063ba9a7a56146103e0578063bc25cf77146103e9578063c45a0155146103fc57600080fd5b80637ecebe00116100de5780637ecebe001461036a57806389afcb441461038a57806395d89b41146103b2578063a457c2d7146103ba57600080fd5b80636a6278421461032557806370a08231146103385780637464fc3d1461036157600080fd5b806330adf81f11610171578063395093511161014b57806339509351146102ed578063485cc955146103005780635909c0d5146103135780635a3d54931461031c57600080fd5b806330adf81f146102ae578063313ce567146102d55780633644e515146102e457600080fd5b8063095ea7b3116101ad578063095ea7b31461023b5780630dfe16811461025e57806318160ddd1461028957806323b872dd1461029b57600080fd5b8063022c0d9f146101d457806306fdde03146101e95780630902f1ac14610207575b600080fd5b6101e76101e2366004612530565b610450565b005b6101f1610949565b6040516101fe919061264b565b60405180910390f35b61020f6109db565b604080516001600160701b03948516815293909216602084015263ffffffff16908201526060016101fe565b61024e6102493660046124c9565b610a05565b60405190151581526020016101fe565b600854610271906001600160a01b031681565b6040516001600160a01b0390911681526020016101fe565b6002545b6040519081526020016101fe565b61024e6102a9366004612417565b610a1f565b61028d7f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c981565b604051601281526020016101fe565b61028d60055481565b61024e6102fb3660046124c9565b610a43565b6101e761030e3660046123de565b610a65565b61028d600b5481565b61028d600c5481565b61028d6103333660046123a4565b610ae6565b61028d6103463660046123a4565b6001600160a01b031660009081526020819052604090205490565b61028d600d5481565b61028d6103783660046123a4565b60066020526000908152604090205481565b61039d6103983660046123a4565b610e54565b604080519283526020830191909152016101fe565b6101f1611204565b61024e6103c83660046124c9565b611213565b61024e6103db3660046124c9565b61128e565b61028d6103e881565b6101e76103f73660046123a4565b61129c565b600754610271906001600160a01b031681565b600954610271906001600160a01b031681565b6101e7610430366004612458565b6113cf565b61028d6104433660046123de565b6115cc565b6101e76115f7565b600e5460ff1660011461047e5760405162461bcd60e51b81526004016104759061267e565b60405180910390fd5b600e805460ff19169055841515806104965750600084115b6104e25760405162461bcd60e51b815260206004820152601a60248201527f494e53554646494349454e545f4f55545055545f414d4f554e540000000000006044820152606401610475565b6000806104ed6109db565b5091509150816001600160701b0316871080156105125750806001600160701b031686105b6105575760405162461bcd60e51b8152602060048201526016602482015275494e53554646494349454e545f4c495155494449545960501b6044820152606401610475565b60085460095460009182916001600160a01b039182169190811690891682148015906105955750806001600160a01b0316896001600160a01b031614155b6105ce5760405162461bcd60e51b815260206004820152600a602482015269494e56414c49445f544f60b01b6044820152606401610475565b8a156105df576105df828a8d611749565b89156105f0576105f0818a8c611749565b861561065d57604051630c919dcf60e41b81526001600160a01b038a169063c919dcf09061062a9033908f908f908e908e906004016125ff565b600060405180830381600087803b15801561064457600080fd5b505af1158015610658573d6000803e3d6000fd5b505050505b6040516370a0823160e01b81523060048201526001600160a01b038316906370a082319060240160206040518083038186803b15801561069c57600080fd5b505afa1580156106b0573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906106d49190612517565b6040516370a0823160e01b81523060048201529094506001600160a01b038216906370a082319060240160206040518083038186803b15801561071657600080fd5b505afa15801561072a573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061074e9190612517565b92505050600089856001600160701b0316610769919061273e565b8311610776576000610793565b6107898a6001600160701b03871661273e565b610793908461273e565b905060006107aa8a6001600160701b03871661273e565b83116107b75760006107d4565b6107ca8a6001600160701b03871661273e565b6107d4908461273e565b905060008211806107e55750600081115b6108315760405162461bcd60e51b815260206004820152601a60248201527f20494e53554646494349454e545f494e5055545f414d4f554e540000000000006044820152606401610475565b6000610853610841846003611886565b61084d876103e8611886565b906118ed565b90506000610865610841846003611886565b905061088a620f42406108846001600160701b038b8116908b16611886565b90611886565b6108948383611886565b10156108cc5760405162461bcd60e51b8152602060048201526007602482015266506169723a204b60c81b6044820152606401610475565b50506108da84848888611943565b60408051838152602081018390529081018c9052606081018b90526001600160a01b038a169033907fd78ad95fa46c994b6551d0da85fc275fe613ce37657fb8d5e3d130840159d8229060800160405180910390a35050600e805460ff19166001179055505050505050505050565b606060038054610958906127c9565b80601f0160208091040260200160405190810160405280929190818152602001828054610984906127c9565b80156109d15780601f106109a6576101008083540402835291602001916109d1565b820191906000526020600020905b8154815290600101906020018083116109b457829003601f168201915b5050505050905090565b600a546001600160701b0380821692600160701b830490911691600160e01b900463ffffffff1690565b600033610a13818585611b24565b60019150505b92915050565b600033610a2d858285611c49565b610a38858585611cc3565b506001949350505050565b600033610a13818585610a5683836115cc565b610a60919061269e565b611b24565b6007546001600160a01b03163314610ab85760405162461bcd60e51b81526020600482015260166024820152754f6e6c792063616c6c656420627920666163746f727960501b6044820152606401610475565b600880546001600160a01b039384166001600160a01b03199182161790915560098054929093169116179055565b600e5460009060ff16600114610b0e5760405162461bcd60e51b81526004016104759061267e565b600e805460ff19169055600080610b236109db565b506008546040516370a0823160e01b81523060048201529294509092506000916001600160a01b03909116906370a082319060240160206040518083038186803b158015610b7057600080fd5b505afa158015610b84573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610ba89190612517565b6009546040516370a0823160e01b81523060048201529192506000916001600160a01b03909116906370a082319060240160206040518083038186803b158015610bf157600080fd5b505afa158015610c05573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610c299190612517565b90506000610c40836001600160701b0387166118ed565b90506000610c57836001600160701b0387166118ed565b90506000610c658787611e91565b90506000610c7260025490565b905080610d245760075460408051632b8fc7cb60e21b815290516000926001600160a01b03169163ae3f1f2c916004808301926020929190829003018186803b158015610cbe57600080fd5b505afa158015610cd2573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610cf691906123c1565b9050610d106103e861084d610d0b8888611886565b612074565b9950610d1e816103e86120e4565b50610d6b565b610d686001600160701b038916610d3b8684611886565b610d4591906126dc565b6001600160701b038916610d598685611886565b610d6391906126dc565b6121c3565b98505b60008911610dbb5760405162461bcd60e51b815260206004820152601d60248201527f494e53554646494349454e545f4c49515549444954595f4d494e5445440000006044820152606401610475565b610dc58a8a6120e4565b610dd186868a8a611943565b60ff821615610dfe57600a54610dfa906001600160701b0380821691600160701b900416611886565b600d555b604080518581526020810185905233917f4c209b5fc8ad50758f13e2e1088ba56a560dff690a1c6fef26394f4c03821c4f910160405180910390a25050600e805460ff1916600117905550949695505050505050565b600e54600090819060ff16600114610e7e5760405162461bcd60e51b81526004016104759061267e565b600e805460ff19169055600080610e936109db565b506008546009546040516370a0823160e01b81523060048201529395509193506001600160a01b039081169291169060009083906370a082319060240160206040518083038186803b158015610ee857600080fd5b505afa158015610efc573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f209190612517565b6040516370a0823160e01b81523060048201529091506000906001600160a01b038416906370a082319060240160206040518083038186803b158015610f6557600080fd5b505afa158015610f79573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190610f9d9190612517565b30600090815260208190526040812054919250610fba8888611e91565b90506000610fc760025490565b905080610fd48487611886565b610fde91906126dc565b9a5080610feb8486611886565b610ff591906126dc565b995060008b118015611007575060008a115b6110535760405162461bcd60e51b815260206004820152601d60248201527f494e53554646494349454e545f4c49515549444954595f4255524e45440000006044820152606401610475565b61105d30846121db565b611068878d8d611749565b611073868d8c611749565b6040516370a0823160e01b81523060048201526001600160a01b038816906370a082319060240160206040518083038186803b1580156110b257600080fd5b505afa1580156110c6573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906110ea9190612517565b6040516370a0823160e01b81523060048201529095506001600160a01b038716906370a082319060240160206040518083038186803b15801561112c57600080fd5b505afa158015611140573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906111649190612517565b935061117285858b8b611943565b60ff82161561119f57600a5461119b906001600160701b0380821691600160701b900416611886565b600d555b604080518c8152602081018c90526001600160a01b038e169133917fdccd412f0b1252819cb1fd330b93224ca42612892bb3f4f789976e6d81936496910160405180910390a35050600e805460ff191660011790555096989597509495505050505050565b606060048054610958906127c9565b6000338161122182866115cc565b9050838110156112815760405162461bcd60e51b815260206004820152602560248201527f45524332303a2064656372656173656420616c6c6f77616e63652062656c6f77604482015264207a65726f60d81b6064820152608401610475565b610a388286868403611b24565b600033610a13818585611cc3565b600e5460ff166001146112c15760405162461bcd60e51b81526004016104759061267e565b600e805460ff19169055600854600954600a546040516370a0823160e01b81523060048201526001600160a01b039384169390921691611370918491869161136b916001600160701b039091169084906370a08231906024015b60206040518083038186803b15801561133357600080fd5b505afa158015611347573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061084d9190612517565b611749565b600a546040516370a0823160e01b81523060048201526113bd918391869161136b91600160701b9091046001600160701b0316906001600160a01b038516906370a082319060240161131b565b5050600e805460ff1916600117905550565b428410156114095760405162461bcd60e51b81526020600482015260076024820152661156141254915160ca1b6044820152606401610475565b6005546001600160a01b038816600090815260066020526040812080549192917f6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9918b918b918b91908761145c836127fe565b909155506040805160208101969096526001600160a01b0394851690860152929091166060840152608083015260a082015260c0810187905260e001604051602081830303815290604052805190602001206040516020016114d592919061190160f01b81526002810192909252602282015260420190565b60408051601f198184030181528282528051602091820120600080855291840180845281905260ff88169284019290925260608301869052608083018590529092509060019060a0016020604051602081039080840390855afa158015611540573d6000803e3d6000fd5b5050604051601f1901519150506001600160a01b038116158015906115765750886001600160a01b0316816001600160a01b0316145b6115b65760405162461bcd60e51b8152602060048201526011602482015270494e56414c49445f5349474e415455524560781b6044820152606401610475565b6115c1898989611b24565b505050505050505050565b6001600160a01b03918216600090815260016020908152604080832093909416825291909152205490565b600e5460ff1660011461161c5760405162461bcd60e51b81526004016104759061267e565b600e805460ff191690556008546040516370a0823160e01b815230600482015261173a916001600160a01b0316906370a082319060240160206040518083038186803b15801561166b57600080fd5b505afa15801561167f573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906116a39190612517565b6009546040516370a0823160e01b81523060048201526001600160a01b03909116906370a082319060240160206040518083038186803b1580156116e657600080fd5b505afa1580156116fa573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525081019061171e9190612517565b600a546001600160701b0380821691600160701b900416611943565b600e805460ff19166001179055565b604080518082018252601981527f7472616e7366657228616464726573732c75696e74323536290000000000000060209182015281516001600160a01b0385811660248301526044808301869052845180840390910181526064909201845291810180516001600160e01b031663a9059cbb60e01b179052915160009283928716916117d591906125e3565b6000604051808303816000865af19150503d8060008114611812576040519150601f19603f3d011682016040523d82523d6000602084013e611817565b606091505b509150915081801561184157508051158061184157508080602001905181019061184191906124f5565b61187f5760405162461bcd60e51b815260206004820152600f60248201526e1514905394d1915497d19052531151608a1b6044820152606401610475565b5050505050565b60008115806118aa5750828261189c818361271f565b92506118a890836126dc565b145b610a195760405162461bcd60e51b815260206004820152601460248201527364732d6d6174682d6d756c2d6f766572666c6f7760601b6044820152606401610475565b6000826118fa838261273e565b9150811115610a195760405162461bcd60e51b815260206004820152601560248201527464732d6d6174682d7375622d756e646572666c6f7760581b6044820152606401610475565b6001600160701b03841180159061196157506001600160701b038311155b6119985760405162461bcd60e51b81526020600482015260086024820152674f564552464c4f5760c01b6044820152606401610475565b60006119a964010000000042612819565b600a549091506000906119c990600160e01b900463ffffffff1683612755565b905060008163ffffffff161180156119e957506001600160701b03841615155b80156119fd57506001600160701b03831615155b15611a8c578063ffffffff16611a2585611a1686612321565b6001600160e01b03169061233a565b6001600160e01b0316611a38919061271f565b600b6000828254611a49919061269e565b909155505063ffffffff8116611a6284611a1687612321565b6001600160e01b0316611a75919061271f565b600c6000828254611a86919061269e565b90915550505b600a805463ffffffff8416600160e01b026001600160e01b036001600160701b03898116600160701b9081026001600160e01b03199095168c83161794909417918216831794859055604080519382169282169290921783529290930490911660208201527f1c411e9a96e071241c2f21f7726b17ae89e3cab4c78be50e062b03a9fffbbad1910160405180910390a1505050505050565b6001600160a01b038316611b865760405162461bcd60e51b8152602060048201526024808201527f45524332303a20617070726f76652066726f6d20746865207a65726f206164646044820152637265737360e01b6064820152608401610475565b6001600160a01b038216611be75760405162461bcd60e51b815260206004820152602260248201527f45524332303a20617070726f766520746f20746865207a65726f206164647265604482015261737360f01b6064820152608401610475565b6001600160a01b0383811660008181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b6000611c5584846115cc565b90506000198114611cbd5781811015611cb05760405162461bcd60e51b815260206004820152601d60248201527f45524332303a20696e73756666696369656e7420616c6c6f77616e63650000006044820152606401610475565b611cbd8484848403611b24565b50505050565b6001600160a01b038316611d275760405162461bcd60e51b815260206004820152602560248201527f45524332303a207472616e736665722066726f6d20746865207a65726f206164604482015264647265737360d81b6064820152608401610475565b6001600160a01b038216611d895760405162461bcd60e51b815260206004820152602360248201527f45524332303a207472616e7366657220746f20746865207a65726f206164647260448201526265737360e81b6064820152608401610475565b6001600160a01b03831660009081526020819052604090205481811015611e015760405162461bcd60e51b815260206004820152602660248201527f45524332303a207472616e7366657220616d6f756e7420657863656564732062604482015265616c616e636560d01b6064820152608401610475565b6001600160a01b03808516600090815260208190526040808220858503905591851681529081208054849290611e3890849061269e565b92505081905550826001600160a01b0316846001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef84604051611e8491815260200190565b60405180910390a3611cbd565b600080600760009054906101000a90046001600160a01b03166001600160a01b031663ae3f1f2c6040518163ffffffff1660e01b815260040160206040518083038186803b158015611ee257600080fd5b505afa158015611ef6573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611f1a91906123c1565b9050600760009054906101000a90046001600160a01b03166001600160a01b0316631ef414f76040518163ffffffff1660e01b815260040160206040518083038186803b158015611f6a57600080fd5b505afa158015611f7e573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250810190611fa291906125c6565b600d5490925060ff83161561206057801561205b576000611fd2610d0b6001600160701b03888116908816611886565b90506000611fdf83612074565b905080821115612058576000612000611ff884846118ed565b600254610884565b905060006120348360ff891661202461201a8b601e61277a565b889060ff16611886565b61202e91906126dc565b9061234f565b9050600061204282846126dc565b905080156120545761205487826120e4565b5050505b50505b61206c565b801561206c576000600d555b505092915050565b600060038211156120d5575080600061208e6002836126dc565b61209990600161269e565b90505b818110156120cf579050806002816120b481866126dc565b6120be919061269e565b6120c891906126dc565b905061209c565b50919050565b81156120df575060015b919050565b6001600160a01b03821661213a5760405162461bcd60e51b815260206004820152601f60248201527f45524332303a206d696e7420746f20746865207a65726f2061646472657373006044820152606401610475565b806002600082825461214c919061269e565b90915550506001600160a01b0382166000908152602081905260408120805483929061217990849061269e565b90915550506040518181526001600160a01b038316906000907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef9060200160405180910390a35050565b60008183106121d257816121d4565b825b9392505050565b6001600160a01b03821661223b5760405162461bcd60e51b815260206004820152602160248201527f45524332303a206275726e2066726f6d20746865207a65726f206164647265736044820152607360f81b6064820152608401610475565b6001600160a01b038216600090815260208190526040902054818110156122af5760405162461bcd60e51b815260206004820152602260248201527f45524332303a206275726e20616d6f756e7420657863656564732062616c616e604482015261636560f01b6064820152608401610475565b6001600160a01b03831660009081526020819052604081208383039055600280548492906122de90849061273e565b90915550506040518281526000906001600160a01b038516907fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef90602001611c3c565b6000610a19600160701b6001600160701b0384166126f0565b60006121d46001600160701b038316846126b6565b60008261235c838261269e565b9150811015610a195760405162461bcd60e51b815260206004820152601460248201527364732d6d6174682d6164642d6f766572666c6f7760601b6044820152606401610475565b6000602082840312156123b657600080fd5b81356121d481612859565b6000602082840312156123d357600080fd5b81516121d481612859565b600080604083850312156123f157600080fd5b82356123fc81612859565b9150602083013561240c81612859565b809150509250929050565b60008060006060848603121561242c57600080fd5b833561243781612859565b9250602084013561244781612859565b929592945050506040919091013590565b600080600080600080600060e0888a03121561247357600080fd5b873561247e81612859565b9650602088013561248e81612859565b9550604088013594506060880135935060808801356124ac81612871565b9699959850939692959460a0840135945060c09093013592915050565b600080604083850312156124dc57600080fd5b82356124e781612859565b946020939093013593505050565b60006020828403121561250757600080fd5b815180151581146121d457600080fd5b60006020828403121561252957600080fd5b5051919050565b60008060008060006080868803121561254857600080fd5b8535945060208601359350604086013561256181612859565b9250606086013567ffffffffffffffff8082111561257e57600080fd5b818801915088601f83011261259257600080fd5b8135818111156125a157600080fd5b8960208285010111156125b357600080fd5b9699959850939650602001949392505050565b6000602082840312156125d857600080fd5b81516121d481612871565b600082516125f581846020870161279d565b9190910192915050565b60018060a01b038616815284602082015283604082015260806060820152816080820152818360a0830137600081830160a090810191909152601f909201601f19160101949350505050565b602081526000825180602084015261266a81604085016020870161279d565b601f01601f19169190910160400192915050565b6020808252600690820152651313d0d2d15160d21b604082015260600190565b600082198211156126b1576126b161282d565b500190565b60006001600160e01b03838116806126d0576126d0612843565b92169190910492915050565b6000826126eb576126eb612843565b500490565b60006001600160e01b03828116848216811515828404821116156127165761271661282d565b02949350505050565b60008160001904831182151516156127395761273961282d565b500290565b6000828210156127505761275061282d565b500390565b600063ffffffff838116908316818110156127725761277261282d565b039392505050565b600060ff821660ff8416808210156127945761279461282d565b90039392505050565b60005b838110156127b85781810151838201526020016127a0565b83811115611cbd5750506000910152565b600181811c908216806127dd57607f821691505b602082108114156120cf57634e487b7160e01b600052602260045260246000fd5b60006000198214156128125761281261282d565b5060010190565b60008261282857612828612843565b500690565b634e487b7160e01b600052601160045260246000fd5b634e487b7160e01b600052601260045260246000fd5b6001600160a01b038116811461286e57600080fd5b50565b60ff8116811461286e57600080fdfea26469706673582212206f93f83d7457b7e263647eb1c4f3dec2e14897e53fdff43bc3969fd0f10c177064736f6c63430008070033
Deployed ByteCode Sourcemap
269:8742:18:-:0;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;5640:1874;;;;;;:::i;:::-;;:::i;:::-;;2156:98:5;;;:::i;:::-;;;;;;;:::i;:::-;;;;;;;;1683:272:18;1860:8;;1683:272;;;-1:-1:-1;;;;;1860:8:18;;;17722:34:72;;-1:-1:-1;;;1890:8:18;;;17787:2:72;17772:18;;17765:43;-1:-1:-1;;;1930:18:18;;;;;17824::72;;;17817:51;17661:2;17646:18;1683:272:18;17473:401:72;4433:197:5;;;;;;:::i;:::-;;:::i;:::-;;;6058:14:72;;6051:22;6033:41;;6021:2;6006:18;4433:197:5;5893:187:72;578:30:18;;;;;-1:-1:-1;;;;;578:30:18;;;;;;-1:-1:-1;;;;;4933:32:72;;;;4915:51;;4903:2;4888:18;578:30:18;4769:203:72;3244:106:5;3331:12;;3244:106;;;6231:25:72;;;6219:2;6204:18;3244:106:5;6085:177:72;5192:286:5;;;;;;:::i;:::-;;:::i;360:117:19:-;;411:66;360:117;;3093:91:5;;;3175:2;18852:36:72;;18840:2;18825:18;3093:91:5;18710:184:72;210:40:19;;;;;;5873:234:5;;;;;;:::i;:::-;;:::i;2018:197:18:-;;;;;;:::i;:::-;;:::i;940:44::-;;;;;;990;;;;;;3223:1205;;;;;;:::i;:::-;;:::i;3408:125:5:-;;;;;;:::i;:::-;-1:-1:-1;;;;;3508:18:5;3482:7;3508:18;;;;;;;;;;;;3408:125;1040:29:18;;;;;;483:50:19;;;;;;:::i;:::-;;;;;;;;;;;;;;4434:1200:18;;;;;;:::i;:::-;;:::i;:::-;;;;18235:25:72;;;18291:2;18276:18;;18269:34;;;;18208:18;4434:1200:18;18061:248:72;2367:102:5;;;:::i;6594:427::-;;;;;;:::i;:::-;;:::i;3729:189::-;;;;;;:::i;:::-;;:::i;374:58:18:-;;427:5;374:58;;8460:338;;;;;;:::i;:::-;;:::i;541:31::-;;;;;-1:-1:-1;;;;;541:31:18;;;614:30;;;;;-1:-1:-1;;;;;614:30:18;;;1023:655:19;;;;;;:::i;:::-;;:::i;3976:149:5:-;;;;;;:::i;:::-;-1:-1:-1;;;;;4091:18:5;;;4065:7;4091:18;;;-1:-1:-1;4091:18:5;;;;;;;;:27;;;;;;;;;;;;;3976:149;8844:165:18;;;:::i;5640:1874::-;1223:8;;;;;:13;1215:32;;;;-1:-1:-1;;;1215:32:18;;16255:2:72;1215:32:18;;;16237:21:72;16294:1;16274:18;;;16267:29;-1:-1:-1;;;16312:18:72;;;16305:36;16358:18;;1215:32:18;;;;;;;;;1257:8;:12;;-1:-1:-1;;1257:12:18;;;5806:14;;;;:32:::1;;;5837:1;5824:10;:14;5806:32;5798:71;;;::::0;-1:-1:-1;;;5798:71:18;;14473:2:72;5798:71:18::1;::::0;::::1;14455:21:72::0;14512:2;14492:18;;;14485:30;14551:28;14531:18;;;14524:56;14597:18;;5798:71:18::1;14271:350:72::0;5798:71:18::1;1860:8:::0;;-1:-1:-1;;;;;1860:8:18;;;;-1:-1:-1;;;1890:8:18;;;5966:22;;::::1;:48:::0;::::1;;;-1:-1:-1::0;;;;;;5992:22:18;::::1;::::0;::::1;5966:48;5945:117;;;::::0;-1:-1:-1;;;5945:117:18;;15904:2:72;5945:117:18::1;::::0;::::1;15886:21:72::0;15943:2;15923:18;;;15916:30;-1:-1:-1;;;15962:18:72;;;15955:52;16024:18;;5945:117:18::1;15702:346:72::0;5945:117:18::1;6157:6;::::0;6195::::1;::::0;6073:16:::1;::::0;;;-1:-1:-1;;;;;6157:6:18;;::::1;::::0;6195;;::::1;::::0;6223:13;::::1;::::0;::::1;::::0;::::1;::::0;:30:::1;;-1:-1:-1::0;;;;;;6240:13:18;;::::1;::::0;;::::1;;;6223:30;6215:53;;;::::0;-1:-1:-1;;;6215:53:18;;11583:2:72;6215:53:18::1;::::0;::::1;11565:21:72::0;11622:2;11602:18;;;11595:30;-1:-1:-1;;;11641:18:72;;;11634:40;11691:18;;6215:53:18::1;11381:334:72::0;6215:53:18::1;6286:14:::0;;6282:58:::1;;6302:38;6316:7;6325:2;6329:10;6302:13;:38::i;:::-;6358:14:::0;;6354:58:::1;;6374:38;6388:7;6397:2;6401:10;6374:13;:38::i;:::-;6430:15:::0;;6426:93:::1;;6447:72;::::0;-1:-1:-1;;;6447:72:18;;-1:-1:-1;;;;;6447:30:18;::::1;::::0;::::1;::::0;:72:::1;::::0;6478:10:::1;::::0;6490;;6502;;6514:4;;;;6447:72:::1;;;:::i;:::-;;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;6426:93;6544:40;::::0;-1:-1:-1;;;6544:40:18;;6578:4:::1;6544:40;::::0;::::1;4915:51:72::0;-1:-1:-1;;;;;6544:25:18;::::1;::::0;::::1;::::0;4888:18:72;;6544:40:18::1;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;6609;::::0;-1:-1:-1;;;6609:40:18;;6643:4:::1;6609:40;::::0;::::1;4915:51:72::0;6533::18;;-1:-1:-1;;;;;;6609:25:18;::::1;::::0;::::1;::::0;4888:18:72;;6609:40:18::1;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;6598:51:::0;-1:-1:-1;6669:17:18::1;::::0;-1:-1:-1;6700:22:18::1;::::0;-1:-1:-1;6712:10:18;-1:-1:-1;;;;;6700:22:18;::::1;;:::i;:::-;6689:8;:33;:99;;6787:1;6689:99;;;6749:22;6761:10:::0;-1:-1:-1;;;;;6749:22:18;::::1;;:::i;:::-;6737:35;::::0;:8;:35:::1;:::i;:::-;6669:119:::0;-1:-1:-1;6798:17:18::1;6829:22;6841:10:::0;-1:-1:-1;;;;;6829:22:18;::::1;;:::i;:::-;6818:8;:33;:99;;6916:1;6818:99;;;6878:22;6890:10:::0;-1:-1:-1;;;;;6878:22:18;::::1;;:::i;:::-;6866:35;::::0;:8;:35:::1;:::i;:::-;6798:119;;6947:1;6935:9;:13;:30;;;;6964:1;6952:9;:13;6935:30;6927:69;;;::::0;-1:-1:-1;;;6927:69:18;;14118:2:72;6927:69:18::1;::::0;::::1;14100:21:72::0;14157:2;14137:18;;;14130:30;14196:28;14176:18;;;14169:56;14242:18;;6927:69:18::1;13916:350:72::0;6927:69:18::1;7020:24;7047:40;7070:16;:9:::0;7084:1:::1;7070:13;:16::i;:::-;7047:18;:8:::0;7060:4:::1;7047:12;:18::i;:::-;:22:::0;::::1;:40::i;:::-;7020:67:::0;-1:-1:-1;7101:24:18::1;7128:40;7151:16;:9:::0;7165:1:::1;7151:13;:16::i;7128:40::-;7101:67:::0;-1:-1:-1;7269:46:18::1;7307:7;7269:33;-1:-1:-1::0;;;;;7269:18:18;;::::1;::::0;:33;::::1;:22;:33::i;:::-;:37:::0;::::1;:46::i;:::-;7207:38;:16:::0;7228;7207:20:::1;:38::i;:::-;:108;;7182:174;;;::::0;-1:-1:-1;;;7182:174:18;;12266:2:72;7182:174:18::1;::::0;::::1;12248:21:72::0;12305:1;12285:18;;;12278:29;-1:-1:-1;;;12323:18:72;;;12316:37;12370:18;;7182:174:18::1;12064:330:72::0;7182:174:18::1;7006:361;;7377:49;7385:8;7395;7405:9;7416;7377:7;:49::i;:::-;7441:66;::::0;;18545:25:72;;;18601:2;18586:18;;18579:34;;;18629:18;;;18622:34;;;18687:2;18672:18;;18665:34;;;7441:66:18;;-1:-1:-1;;;;;7441:66:18;::::1;::::0;7446:10:::1;::::0;7441:66:::1;::::0;;;;18532:3:72;7441:66:18;;::::1;-1:-1:-1::0;;1290:8:18;:12;;-1:-1:-1;;1290:12:18;1301:1;1290:12;;;-1:-1:-1;;;;;;;;;5640:1874:18:o;2156:98:5:-;2210:13;2242:5;2235:12;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;2156:98;:::o;4433:197::-;4516:4;719:10:13;4570:32:5;719:10:13;4586:7:5;4595:6;4570:8;:32::i;:::-;4619:4;4612:11;;;4433:197;;;;;:::o;5192:286::-;5319:4;719:10:13;5375:38:5;5391:4;719:10:13;5406:6:5;5375:15;:38::i;:::-;5423:27;5433:4;5439:2;5443:6;5423:9;:27::i;:::-;-1:-1:-1;5467:4:5;;5192:286;-1:-1:-1;;;;5192:286:5:o;5873:234::-;719:10:13;5961:4:5;4091:18;;;-1:-1:-1;4091:18:5;;;;;;;;-1:-1:-1;;;;;4091:27:5;;;;;;;;;;5961:4;;719:10:13;6015:64:5;;719:10:13;;4091:27:5;;6040:38;;6068:10;;6040:38;:::i;:::-;6015:8;:64::i;2018:197:18:-;2122:7;;-1:-1:-1;;;;;2122:7:18;2108:10;:21;2100:56;;;;-1:-1:-1;;;2100:56:18;;12959:2:72;2100:56:18;;;12941:21:72;12998:2;12978:18;;;12971:30;-1:-1:-1;;;13017:18:72;;;13010:52;13079:18;;2100:56:18;12757:346:72;2100:56:18;2166:6;:16;;-1:-1:-1;;;;;2166:16:18;;;-1:-1:-1;;;;;;2166:16:18;;;;;;;2192:6;:16;;;;;;;;;;;2018:197::o;3223:1205::-;1223:8;;3313:17;;1223:8;;;:13;1215:32;;;;-1:-1:-1;;;1215:32:18;;16255:2:72;1215:32:18;;;16237:21:72;16294:1;16274:18;;;16267:29;-1:-1:-1;;;16312:18:72;;;16305:36;16358:18;;1215:32:18;16053:329:72;1215:32:18;1257:8;:12;;-1:-1:-1;;1257:12:18;;;1860:8;;3438:6:::1;::::0;3431:39:::1;::::0;;-1:-1:-1;;;3431:39:18;;3464:4:::1;3431:39;::::0;::::1;4915:51:72::0;3431:39:18;;-1:-1:-1;;;;;1860:8:18;;;;-1:-1:-1;;;1890:8:18;;;;-1:-1:-1;;;;;;;3438:6:18;;::::1;::::0;-1:-1:-1;;4888:18:72;;;;;3431:39:18::1;::::0;;;;;;;;;3438:6;3431:39;::::1;;::::0;::::1;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;3506:6;::::0;3499:39:::1;::::0;-1:-1:-1;;;3499:39:18;;3532:4:::1;3499:39;::::0;::::1;4915:51:72::0;3412:58:18;;-1:-1:-1;3480:16:18::1;::::0;-1:-1:-1;;;;;3506:6:18;;::::1;::::0;3499:24:::1;::::0;4888:18:72;;3499:39:18::1;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;3480:58:::0;-1:-1:-1;3548:15:18::1;3566:23;:8:::0;-1:-1:-1;;;;;3566:23:18;::::1;:12;:23::i;:::-;3548:41:::0;-1:-1:-1;3599:15:18::1;3617:23;:8:::0;-1:-1:-1;;;;;3617:23:18;::::1;:12;:23::i;:::-;3599:41;;3651:18;3672:30;3681:9;3692;3672:8;:30::i;:::-;3651:51;;3712:20;3735:13;3331:12:5::0;;;3244:106;3735:13:18::1;3712:36:::0;-1:-1:-1;3762:17:18;3758:389:::1;;3820:7;::::0;3811:25:::1;::::0;;-1:-1:-1;;;3811:25:18;;;;3795:13:::1;::::0;-1:-1:-1;;;;;3820:7:18::1;::::0;3811:23:::1;::::0;:25:::1;::::0;;::::1;::::0;::::1;::::0;;;;;;;;3820:7;3811:25;::::1;;::::0;::::1;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;3795:41:::0;-1:-1:-1;3862:54:18::1;427:5;3862:31;3872:20;:7:::0;3884;3872:11:::1;:20::i;:::-;3862:9;:31::i;:54::-;3850:66;;3930:31;3936:5;427;3930;:31::i;:::-;3781:191;3758:389;;;4004:132;-1:-1:-1::0;;;;;4030:37:18;::::1;:25;:7:::0;4042:12;4030:11:::1;:25::i;:::-;:37;;;;:::i;:::-;-1:-1:-1::0;;;;;4085:37:18;::::1;:25;:7:::0;4097:12;4085:11:::1;:25::i;:::-;:37;;;;:::i;:::-;4004:8;:132::i;:::-;3992:144;;3758:389;4176:1;4164:9;:13;4156:55;;;::::0;-1:-1:-1;;;4156:55:18;;10879:2:72;4156:55:18::1;::::0;::::1;10861:21:72::0;10918:2;10898:18;;;10891:30;10957:31;10937:18;;;10930:59;11006:18;;4156:55:18::1;10677:353:72::0;4156:55:18::1;4221:20;4227:2;4231:9;4221:5;:20::i;:::-;4252:49;4260:8;4270;4280:9;4291;4252:7;:49::i;:::-;4315:16;::::0;::::1;::::0;4311:61:::1;;4363:8;::::0;4341:31:::1;::::0;-1:-1:-1;;;;;4349:8:18;;::::1;::::0;-1:-1:-1;;;4363:8:18;::::1;;4341:21;:31::i;:::-;4333:5;:39:::0;4311:61:::1;4387:34;::::0;;18235:25:72;;;18291:2;18276:18;;18269:34;;;4392:10:18::1;::::0;4387:34:::1;::::0;18208:18:72;4387:34:18::1;;;;;;;-1:-1:-1::0;;1290:8:18;:12;;-1:-1:-1;;1290:12:18;1301:1;1290:12;;;-1:-1:-1;3223:1205:18;;;-1:-1:-1;;;;;;3223:1205:18:o;4434:1200::-;1223:8;;4524:15;;;;1223:8;;;:13;1215:32;;;;-1:-1:-1;;;1215:32:18;;16255:2:72;1215:32:18;;;16237:21:72;16294:1;16274:18;;;16267:29;-1:-1:-1;;;16312:18:72;;;16305:36;16358:18;;1215:32:18;16053:329:72;1215:32:18;1257:8;:12;;-1:-1:-1;;1257:12:18;;;1860:8;;4656:6:::1;::::0;4690::::1;::::0;4725:40:::1;::::0;;-1:-1:-1;;;4725:40:18;;4759:4:::1;4725:40;::::0;::::1;4915:51:72::0;4725:40:18;;-1:-1:-1;;;;;1860:8:18;;;;-1:-1:-1;;;1890:8:18;;;;-1:-1:-1;;;;;4656:6:18;;::::1;::::0;4690::::1;::::0;-1:-1:-1;;4656:6:18;;-1:-1:-1;;4888:18:72;;;;;4725:40:18::1;::::0;;;;;;;;4656:6;4725:40;::::1;;::::0;::::1;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;4794;::::0;-1:-1:-1;;;4794:40:18;;4828:4:::1;4794:40;::::0;::::1;4915:51:72::0;4706:59:18;;-1:-1:-1;4775:16:18::1;::::0;-1:-1:-1;;;;;4794:25:18;::::1;::::0;::::1;::::0;4888:18:72;;4794:40:18::1;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;4882:4;4844:17;3508:18:5::0;;;;;;;;;;;4775:59:18;;-1:-1:-1;4920:30:18::1;4929:9:::0;4940;4920:8:::1;:30::i;:::-;4899:51;;4960:20;4983:13;3331:12:5::0;;;3244:106;4983:13:18::1;4960:36:::0;-1:-1:-1;4960:36:18;5016:23:::1;:9:::0;5030:8;5016:13:::1;:23::i;:::-;:38;;;;:::i;:::-;5006:48:::0;-1:-1:-1;5100:12:18;5074:23:::1;:9:::0;5088:8;5074:13:::1;:23::i;:::-;:38;;;;:::i;:::-;5064:48;;5140:1;5130:7;:11;:26;;;;;5155:1;5145:7;:11;5130:26;5122:68;;;::::0;-1:-1:-1;;;5122:68:18;;12601:2:72;5122:68:18::1;::::0;::::1;12583:21:72::0;12640:2;12620:18;;;12613:30;12679:31;12659:18;;;12652:59;12728:18;;5122:68:18::1;12399:353:72::0;5122:68:18::1;5200:31;5214:4;5221:9;5200:5;:31::i;:::-;5241:35;5255:7;5264:2;5268:7;5241:13;:35::i;:::-;5286;5300:7;5309:2;5313:7;5286:13;:35::i;:::-;5342:40;::::0;-1:-1:-1;;;5342:40:18;;5376:4:::1;5342:40;::::0;::::1;4915:51:72::0;-1:-1:-1;;;;;5342:25:18;::::1;::::0;::::1;::::0;4888:18:72;;5342:40:18::1;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;5403;::::0;-1:-1:-1;;;5403:40:18;;5437:4:::1;5403:40;::::0;::::1;4915:51:72::0;5331::18;;-1:-1:-1;;;;;;5403:25:18;::::1;::::0;::::1;::::0;4888:18:72;;5403:40:18::1;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;5392:51;;5454:49;5462:8;5472;5482:9;5493;5454:7;:49::i;:::-;5517:16;::::0;::::1;::::0;5513:61:::1;;5565:8;::::0;5543:31:::1;::::0;-1:-1:-1;;;;;5551:8:18;;::::1;::::0;-1:-1:-1;;;5565:8:18;::::1;;5543:21;:31::i;:::-;5535:5;:39:::0;5513:61:::1;5589:38;::::0;;18235:25:72;;;18291:2;18276:18;;18269:34;;;5589:38:18;;-1:-1:-1;;;;;5589:38:18;::::1;::::0;5594:10:::1;::::0;5589:38:::1;::::0;;;;;;;;;::::1;-1:-1:-1::0;;1290:8:18;:12;;-1:-1:-1;;1290:12:18;1301:1;1290:12;;;-1:-1:-1;4434:1200:18;;;;-1:-1:-1;4434:1200:18;;-1:-1:-1;;;;;;4434:1200:18:o;2367:102:5:-;2423:13;2455:7;2448:14;;;;;:::i;6594:427::-;719:10:13;6687:4:5;4091:18;;;-1:-1:-1;4091:18:5;;;;;;;;-1:-1:-1;;;;;4091:27:5;;;;;;;;;;6687:4;;719:10:13;6831:15:5;6811:16;:35;;6803:85;;;;-1:-1:-1;;;6803:85:5;;16589:2:72;6803:85:5;;;16571:21:72;16628:2;16608:18;;;16601:30;16667:34;16647:18;;;16640:62;-1:-1:-1;;;16718:18:72;;;16711:35;16763:19;;6803:85:5;16387:401:72;6803:85:5;6922:60;6931:5;6938:7;6966:15;6947:16;:34;6922:8;:60::i;3729:189::-;3808:4;719:10:13;3862:28:5;719:10:13;3879:2:5;3883:6;3862:9;:28::i;8460:338:18:-;1223:8;;;;;:13;1215:32;;;;-1:-1:-1;;;1215:32:18;;16255:2:72;1215:32:18;;;16237:21:72;16294:1;16274:18;;;16267:29;-1:-1:-1;;;16312:18:72;;;16305:36;16358:18;;1215:32:18;16053:329:72;1215:32:18;1257:8;:12;;-1:-1:-1;;1257:12:18;;;8537:6:::1;::::0;8586::::1;::::0;8689:8:::1;::::0;8644:40:::1;::::0;-1:-1:-1;;;8644:40:18;;8678:4:::1;8644:40;::::0;::::1;4915:51:72::0;-1:-1:-1;;;;;8537:6:18;;::::1;::::0;8586;;::::1;::::0;8617:82:::1;::::0;8537:6;;8640:2;;8644:54:::1;::::0;-1:-1:-1;;;;;8689:8:18;;::::1;::::0;8537:6;;-1:-1:-1;;4888:18:72;;8644:40:18::1;;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:54::-;8617:13;:82::i;:::-;8781:8;::::0;8736:40:::1;::::0;-1:-1:-1;;;8736:40:18;;8770:4:::1;8736:40;::::0;::::1;4915:51:72::0;8709:82:18::1;::::0;8723:7;;8732:2;;8736:54:::1;::::0;-1:-1:-1;;;8781:8:18;;::::1;-1:-1:-1::0;;;;;8781:8:18::1;::::0;-1:-1:-1;;;;;8736:25:18;::::1;::::0;-1:-1:-1;;4888:18:72;;8736:40:18::1;4769:203:72::0;8709:82:18::1;-1:-1:-1::0;;1290:8:18;:12;;-1:-1:-1;;1290:12:18;1301:1;1290:12;;;-1:-1:-1;8460:338:18:o;1023:655:19:-;1183:15;1171:8;:27;;1163:47;;;;-1:-1:-1;;;1163:47:19;;14828:2:72;1163:47:19;;;14810:21:72;14867:1;14847:18;;;14840:29;-1:-1:-1;;;14885:18:72;;;14878:37;14932:18;;1163:47:19;14626:330:72;1163:47:19;1322:16;;-1:-1:-1;;;;;1417:13:19;;1220:14;1417:13;;;:6;:13;;;;;:15;;1220:14;;1322:16;411:66;;1417:13;;1401:7;;1410:5;;1417:15;1220:14;1417:15;;;:::i;:::-;;;;-1:-1:-1;1366:77:19;;;;;;;6554:25:72;;;;-1:-1:-1;;;;;6653:15:72;;;6633:18;;;6626:43;6705:15;;;;6685:18;;;6678:43;6737:18;;;6730:34;;;;-1:-1:-1;6780:19:72;;6773:35;6824:19;;;;6817:35;;;1366:77:19;;;;;;;;;;6526:19:72;;;1366:77:19;;;1356:88;;;;;;;-1:-1:-1;;;1260:198:19;;;4630:27:72;4673:11;;;4666:27;;;;4709:12;;;4702:28;;;;4746:12;;1260:198:19;;;-1:-1:-1;;1260:198:19;;;;;;;;;1237:231;;1260:198;1237:231;;;;1478:24;1505:26;;;;;;;;;7090:25:72;;;7163:4;7151:17;;7131:18;;;7124:45;;;;7185:18;;;7178:34;;;7228:18;;;7221:34;;;1237:231:19;;-1:-1:-1;1478:24:19;1505:26;;7062:19:72;;1505:26:19;;;;;;;;;;;;;;;;;;;;;;;;;;;-1:-1:-1;;1505:26:19;;-1:-1:-1;;1505:26:19;;;-1:-1:-1;;;;;;;1549:30:19;;;;;;:59;;-1:-1:-1;;;;;;1583:25:19;;;;;;;1549:59;1541:89;;;;-1:-1:-1;;;1541:89:19;;11237:2:72;1541:89:19;;;11219:21:72;11276:2;11256:18;;;11249:30;-1:-1:-1;;;11295:18:72;;;11288:47;11352:18;;1541:89:19;11035:341:72;1541:89:19;1640:31;1649:5;1656:7;1665:5;1640:8;:31::i;:::-;1153:525;;1023:655;;;;;;;:::o;8844:165:18:-;1223:8;;;;;:13;1215:32;;;;-1:-1:-1;;;1215:32:18;;16255:2:72;1215:32:18;;;16237:21:72;16294:1;16274:18;;;16267:29;-1:-1:-1;;;16312:18:72;;;16305:36;16358:18;;1215:32:18;16053:329:72;1215:32:18;1257:8;:12;;-1:-1:-1;;1257:12:18;;;8908:6:::1;::::0;8901:39:::1;::::0;-1:-1:-1;;;8901:39:18;;8934:4:::1;8901:39;::::0;::::1;4915:51:72::0;8893:109:18::1;::::0;-1:-1:-1;;;;;8908:6:18::1;::::0;8901:24:::1;::::0;4888:18:72;;8901:39:18::1;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;8949:6;::::0;8942:39:::1;::::0;-1:-1:-1;;;8942:39:18;;8975:4:::1;8942:39;::::0;::::1;4915:51:72::0;-1:-1:-1;;;;;8949:6:18;;::::1;::::0;8942:24:::1;::::0;4888:18:72;;8942:39:18::1;;;;;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;::::0;::::1;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;8983:8;::::0;-1:-1:-1;;;;;8983:8:18;;::::1;::::0;-1:-1:-1;;;8993:8:18;::::1;;8893:7;:109::i;:::-;1290:8:::0;:12;;-1:-1:-1;;1290:12:18;1301:1;1290:12;;;8844:165::o;1315:362::-;498:34;;;;;;;;;;;;;;;;;1488:43;;-1:-1:-1;;;;;5169:32:72;;;1488:43:18;;;5151:51:72;5218:18;;;;5211:34;;;1488:43:18;;;;;;;;;;5124:18:72;;;;1488:43:18;;;;;;;-1:-1:-1;;;;;1488:43:18;-1:-1:-1;;;1488:43:18;;;1464:77;;-1:-1:-1;;;;1464:10:18;;;:77;;1488:43;1464:77;:::i;:::-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;1428:113;;;;1572:7;:57;;;;-1:-1:-1;1584:11:18;;:16;;:44;;;1615:4;1604:24;;;;;;;;;;;;:::i;:::-;1551:119;;;;-1:-1:-1;;;1551:119:18;;11922:2:72;1551:119:18;;;11904:21:72;11961:2;11941:18;;;11934:30;-1:-1:-1;;;11980:18:72;;;11973:45;12035:18;;1551:119:18;11720:339:72;1551:119:18;1418:259;;1315:362;;;:::o;939:149:29:-;997:9;1026:6;;;:30;;-1:-1:-1;1055:1:29;1050;1041:5;1050:1;1055;1041:5;:::i;:::-;1037:9;-1:-1:-1;1036:15:29;;1037:9;1036:15;:::i;:::-;:20;1026:30;1018:63;;;;-1:-1:-1;;;1018:63:29;;9416:2:72;1018:63:29;;;9398:21:72;9455:2;9435:18;;;9428:30;-1:-1:-1;;;9474:18:72;;;9467:50;9534:18;;1018:63:29;9214:344:72;797:136:29;855:9;899:1;889:5;893:1;899;889:5;:::i;:::-;885:9;;;884:16;;876:50;;;;-1:-1:-1;;;876:50:29;;7856:2:72;876:50:29;;;7838:21:72;7895:2;7875:18;;;7868:30;-1:-1:-1;;;7914:18:72;;;7907:51;7975:18;;876:50:29;7654:345:72;7520:894:18;-1:-1:-1;;;;;7650:29:18;;;;;:62;;-1:-1:-1;;;;;;7683:29:18;;;7650:62;7629:117;;;;-1:-1:-1;;;7629:117:18;;15568:2:72;7629:117:18;;;15550:21:72;15607:1;15587:18;;;15580:29;-1:-1:-1;;;15625:18:72;;;15618:38;15673:18;;7629:117:18;15366:331:72;7629:117:18;7756:21;7787:23;7805:5;7787:15;:23;:::i;:::-;7859:18;;7756:55;;-1:-1:-1;7821:18:18;;7842:35;;-1:-1:-1;;;7859:18:18;;;;7756:55;7842:35;:::i;:::-;7821:56;;7928:1;7914:11;:15;;;:33;;;;-1:-1:-1;;;;;;7933:14:18;;;;7914:33;:51;;;;-1:-1:-1;;;;;;7951:14:18;;;;7914:51;7910:338;;;8121:11;8065:67;;8073:44;8107:9;8073:27;8090:9;8073:16;:27::i;:::-;-1:-1:-1;;;;;8073:33:18;;;:44::i;:::-;8065:67;;;-1:-1:-1;;;;;8065:53:18;:67;:::i;:::-;8041:20;;:91;;;;;;;:::i;:::-;;;;-1:-1:-1;;8170:67:18;;;8178:44;8212:9;8178:27;8195:9;8178:16;:27::i;:44::-;8170:67;;;-1:-1:-1;;;;;8170:53:18;:67;:::i;:::-;8146:20;;:91;;;;;;;:::i;:::-;;;;-1:-1:-1;;7910:338:18;8257:8;:28;;8333:35;;;-1:-1:-1;;;8333:35:18;-1:-1:-1;;;;;;;;;;;;;8295:28:18;;;;;-1:-1:-1;;;;;;8295:28:18;;;8257;;;8295;;;;;8333:35;;;;;;;;;8383:24;;;8388:8;;;;;;;;;;17376:34:72;;8398:8:18;;;;;;17441:2:72;17426:18;;17419:43;8383:24:18;;;;;;;;;;;;;7619:795;;7520:894;;;;:::o;10110:370:5:-;-1:-1:-1;;;;;10241:19:5;;10233:68;;;;-1:-1:-1;;;10233:68:5;;15163:2:72;10233:68:5;;;15145:21:72;15202:2;15182:18;;;15175:30;15241:34;15221:18;;;15214:62;-1:-1:-1;;;15292:18:72;;;15285:34;15336:19;;10233:68:5;14961:400:72;10233:68:5;-1:-1:-1;;;;;10319:21:5;;10311:68;;;;-1:-1:-1;;;10311:68:5;;9013:2:72;10311:68:5;;;8995:21:72;9052:2;9032:18;;;9025:30;9091:34;9071:18;;;9064:62;-1:-1:-1;;;9142:18:72;;;9135:32;9184:19;;10311:68:5;8811:398:72;10311:68:5;-1:-1:-1;;;;;10390:18:5;;;;;;;-1:-1:-1;10390:18:5;;;;;;;;:27;;;;;;;;;;;;;:36;;;10441:32;;6231:25:72;;;10441:32:5;;6204:18:72;10441:32:5;;;;;;;;10110:370;;;:::o;10761:441::-;-1:-1:-1;;;;;4091:18:5;;;10891:24;4091:18;;;-1:-1:-1;4091:18:5;;;;;;;;:27;;;;;;;;;;-1:-1:-1;;10957:37:5;;10953:243;;11038:6;11018:16;:26;;11010:68;;;;-1:-1:-1;;;11010:68:5;;10114:2:72;11010:68:5;;;10096:21:72;10153:2;10133:18;;;10126:30;10192:31;10172:18;;;10165:59;10241:18;;11010:68:5;9912:353:72;11010:68:5;11120:51;11129:5;11136:7;11164:6;11145:16;:25;11120:8;:51::i;:::-;10881:321;10761:441;;;:::o;7475:651::-;-1:-1:-1;;;;;7601:18:5;;7593:68;;;;-1:-1:-1;;;7593:68:5;;13712:2:72;7593:68:5;;;13694:21:72;13751:2;13731:18;;;13724:30;13790:34;13770:18;;;13763:62;-1:-1:-1;;;13841:18:72;;;13834:35;13886:19;;7593:68:5;13510:401:72;7593:68:5;-1:-1:-1;;;;;7679:16:5;;7671:64;;;;-1:-1:-1;;;7671:64:5;;8206:2:72;7671:64:5;;;8188:21:72;8245:2;8225:18;;;8218:30;8284:34;8264:18;;;8257:62;-1:-1:-1;;;8335:18:72;;;8328:33;8378:19;;7671:64:5;8004:399:72;7671:64:5;-1:-1:-1;;;;;7817:15:5;;7795:19;7817:15;;;;;;;;;;;7850:21;;;;7842:72;;;;-1:-1:-1;;;7842:72:5;;10472:2:72;7842:72:5;;;10454:21:72;10511:2;10491:18;;;10484:30;10550:34;10530:18;;;10523:62;-1:-1:-1;;;10601:18:72;;;10594:36;10647:19;;7842:72:5;10270:402:72;7842:72:5;-1:-1:-1;;;;;7948:15:5;;;:9;:15;;;;;;;;;;;7966:20;;;7948:38;;8006:13;;;;;;;;:23;;7966:20;;7948:9;8006:23;;7966:20;;8006:23;:::i;:::-;;;;-1:-1:-1;;8045:26:5;;6231:25:72;;;-1:-1:-1;;;;;8045:26:5;;;;;;;;;;6219:2:72;6204:18;8045:26:5;;;;;;;8082:37;9111:576;2221:996:18;2369:7;;2360:25;;;-1:-1:-1;;;2360:25:18;;;;2310:18;;;;-1:-1:-1;;;;;2369:7:18;;;;2360:23;;:25;;;;;;;;;;;;;;;2369:7;2360:25;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;2419:7;;2410:32;;;-1:-1:-1;;;2410:32:18;;;;2344:41;;-1:-1:-1;;;;;;2419:7:18;;;;2410:30;;:32;;;;;;;;;;;;;;;2419:7;2410:32;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;:::i;:::-;2469:5;;2395:47;;-1:-1:-1;2503:16:18;;;;2499:712;;2539:11;;2535:609;;2570:13;2586:91;2617:42;-1:-1:-1;;;;;2617:18:18;;;;2640;;2617:22;:42::i;2586:91::-;2570:107;;2695:17;2715;2725:6;2715:9;:17::i;:::-;2695:37;;2762:9;2754:5;:17;2750:380;;;2795:17;2815:39;2833:20;:5;2843:9;2833;:20::i;:::-;3331:12:5;;2815:13:18;3244:106:5;2815:39:18;2795:59;-1:-1:-1;2876:19:18;2898:84;2972:9;2899:67;;;:28;2909:17;2954:12;2909:2;:17;:::i;:::-;2899:5;;:28;;:9;:28::i;:::-;:67;;;;:::i;:::-;2898:73;;:84::i;:::-;2876:106;-1:-1:-1;3004:17:18;3024:23;2876:106;3024:9;:23;:::i;:::-;3004:43;-1:-1:-1;3073:13:18;;3069:42;;3088:23;3094:5;3101:9;3088:5;:23::i;:::-;2773:357;;;2750:380;2552:592;;2535:609;2499:712;;;3164:11;;3160:51;;3199:1;3191:5;:9;3160:51;2334:883;;2221:996;;;;:::o;349:301:29:-;397:9;426:1;422;:5;418:226;;;-1:-1:-1;447:1:29;462:9;474:5;478:1;447;474:5;:::i;:::-;:9;;482:1;474:9;:::i;:::-;462:21;;497:89;508:1;504;:5;497:89;;;533:1;-1:-1:-1;533:1:29;570;533;557:5;533:1;557;:5;:::i;:::-;:9;;;;:::i;:::-;556:15;;;;:::i;:::-;552:19;;497:89;;;429:167;349:301;;;:::o;418:226::-;606:6;;602:42;;-1:-1:-1;632:1:29;602:42;349:301;;;:::o;8402:389:5:-;-1:-1:-1;;;;;8485:21:5;;8477:65;;;;-1:-1:-1;;;8477:65:5;;16995:2:72;8477:65:5;;;16977:21:72;17034:2;17014:18;;;17007:30;17073:33;17053:18;;;17046:61;17124:18;;8477:65:5;16793:355:72;8477:65:5;8629:6;8613:12;;:22;;;;;;;:::i;:::-;;;;-1:-1:-1;;;;;;;8645:18:5;;:9;:18;;;;;;;;;;:28;;8667:6;;8645:9;:28;;8667:6;;8645:28;:::i;:::-;;;;-1:-1:-1;;8688:37:5;;;6231:25:72;;;8688:37:5;;-1:-1:-1;;;;;8688:37:5;;;8705:1;;8688:37;;;;;6219:2:72;8688:37:5;;;8402:389;;:::o;131:103:29:-;189:9;218:1;214;:5;:13;;226:1;214:13;;;222:1;214:13;210:17;131:103;-1:-1:-1;;;131:103:29:o;9111:576:5:-;-1:-1:-1;;;;;9194:21:5;;9186:67;;;;-1:-1:-1;;;9186:67:5;;13310:2:72;9186:67:5;;;13292:21:72;13349:2;13329:18;;;13322:30;13388:34;13368:18;;;13361:62;-1:-1:-1;;;13439:18:72;;;13432:31;13480:19;;9186:67:5;13108:397:72;9186:67:5;-1:-1:-1;;;;;9349:18:5;;9324:22;9349:18;;;;;;;;;;;9385:24;;;;9377:71;;;;-1:-1:-1;;;9377:71:5;;8610:2:72;9377:71:5;;;8592:21:72;8649:2;8629:18;;;8622:30;8688:34;8668:18;;;8661:62;-1:-1:-1;;;8739:18:72;;;8732:32;8781:19;;9377:71:5;8408:398:72;9377:71:5;-1:-1:-1;;;;;9482:18:5;;:9;:18;;;;;;;;;;9503:23;;;9482:44;;9546:12;:22;;9503:23;;9482:9;9546:22;;9503:23;;9546:22;:::i;:::-;;;;-1:-1:-1;;9584:37:5;;6231:25:72;;;9610:1:5;;-1:-1:-1;;;;;9584:37:5;;;;;6219:2:72;6204:18;9584:37:5;6085:177:72;316:118:30;366:9;391:17;-1:-1:-1;;;;;;;;391:10:30;;:17;:::i;502:106::-;562:9;587:14;-1:-1:-1;;;;;591:10:30;;587:1;:14;:::i;656:135:29:-;714:9;758:1;748:5;752:1;758;748:5;:::i;:::-;744:9;;;743:16;;735:49;;;;-1:-1:-1;;;735:49:29;;9765:2:72;735:49:29;;;9747:21:72;9804:2;9784:18;;;9777:30;-1:-1:-1;;;9823:18:72;;;9816:50;9883:18;;735:49:29;9563:344:72;14:247;73:6;126:2;114:9;105:7;101:23;97:32;94:52;;;142:1;139;132:12;94:52;181:9;168:23;200:31;225:5;200:31;:::i;266:251::-;336:6;389:2;377:9;368:7;364:23;360:32;357:52;;;405:1;402;395:12;357:52;437:9;431:16;456:31;481:5;456:31;:::i;522:388::-;590:6;598;651:2;639:9;630:7;626:23;622:32;619:52;;;667:1;664;657:12;619:52;706:9;693:23;725:31;750:5;725:31;:::i;:::-;775:5;-1:-1:-1;832:2:72;817:18;;804:32;845:33;804:32;845:33;:::i;:::-;897:7;887:17;;;522:388;;;;;:::o;915:456::-;992:6;1000;1008;1061:2;1049:9;1040:7;1036:23;1032:32;1029:52;;;1077:1;1074;1067:12;1029:52;1116:9;1103:23;1135:31;1160:5;1135:31;:::i;:::-;1185:5;-1:-1:-1;1242:2:72;1227:18;;1214:32;1255:33;1214:32;1255:33;:::i;:::-;915:456;;1307:7;;-1:-1:-1;;;1361:2:72;1346:18;;;;1333:32;;915:456::o;1376:801::-;1487:6;1495;1503;1511;1519;1527;1535;1588:3;1576:9;1567:7;1563:23;1559:33;1556:53;;;1605:1;1602;1595:12;1556:53;1644:9;1631:23;1663:31;1688:5;1663:31;:::i;:::-;1713:5;-1:-1:-1;1770:2:72;1755:18;;1742:32;1783:33;1742:32;1783:33;:::i;:::-;1835:7;-1:-1:-1;1889:2:72;1874:18;;1861:32;;-1:-1:-1;1940:2:72;1925:18;;1912:32;;-1:-1:-1;1996:3:72;1981:19;;1968:33;2010:31;1968:33;2010:31;:::i;:::-;1376:801;;;;-1:-1:-1;1376:801:72;;;;2060:7;2114:3;2099:19;;2086:33;;-1:-1:-1;2166:3:72;2151:19;;;2138:33;;1376:801;-1:-1:-1;;1376:801:72:o;2182:315::-;2250:6;2258;2311:2;2299:9;2290:7;2286:23;2282:32;2279:52;;;2327:1;2324;2317:12;2279:52;2366:9;2353:23;2385:31;2410:5;2385:31;:::i;:::-;2435:5;2487:2;2472:18;;;;2459:32;;-1:-1:-1;;;2182:315:72:o;2502:277::-;2569:6;2622:2;2610:9;2601:7;2597:23;2593:32;2590:52;;;2638:1;2635;2628:12;2590:52;2670:9;2664:16;2723:5;2716:13;2709:21;2702:5;2699:32;2689:60;;2745:1;2742;2735:12;2784:184;2854:6;2907:2;2895:9;2886:7;2882:23;2878:32;2875:52;;;2923:1;2920;2913:12;2875:52;-1:-1:-1;2946:16:72;;2784:184;-1:-1:-1;2784:184:72:o;2973:863::-;3070:6;3078;3086;3094;3102;3155:3;3143:9;3134:7;3130:23;3126:33;3123:53;;;3172:1;3169;3162:12;3123:53;3208:9;3195:23;3185:33;;3265:2;3254:9;3250:18;3237:32;3227:42;;3319:2;3308:9;3304:18;3291:32;3332:31;3357:5;3332:31;:::i;:::-;3382:5;-1:-1:-1;3438:2:72;3423:18;;3410:32;3461:18;3491:14;;;3488:34;;;3518:1;3515;3508:12;3488:34;3556:6;3545:9;3541:22;3531:32;;3601:7;3594:4;3590:2;3586:13;3582:27;3572:55;;3623:1;3620;3613:12;3572:55;3663:2;3650:16;3689:2;3681:6;3678:14;3675:34;;;3705:1;3702;3695:12;3675:34;3750:7;3745:2;3736:6;3732:2;3728:15;3724:24;3721:37;3718:57;;;3771:1;3768;3761:12;3718:57;2973:863;;;;-1:-1:-1;2973:863:72;;-1:-1:-1;3802:2:72;3794:11;;3824:6;2973:863;-1:-1:-1;;;2973:863:72:o;3841:247::-;3909:6;3962:2;3950:9;3941:7;3937:23;3933:32;3930:52;;;3978:1;3975;3968:12;3930:52;4010:9;4004:16;4029:29;4052:5;4029:29;:::i;4093:274::-;4222:3;4260:6;4254:13;4276:53;4322:6;4317:3;4310:4;4302:6;4298:17;4276:53;:::i;:::-;4345:16;;;;;4093:274;-1:-1:-1;;4093:274:72:o;5256:632::-;5526:1;5522;5517:3;5513:11;5509:19;5501:6;5497:32;5486:9;5479:51;5566:6;5561:2;5550:9;5546:18;5539:34;5609:6;5604:2;5593:9;5589:18;5582:34;5652:3;5647:2;5636:9;5632:18;5625:31;5693:6;5687:3;5676:9;5672:19;5665:35;5751:6;5743;5737:3;5726:9;5722:19;5709:49;5808:1;5778:22;;;5802:3;5774:32;;;5767:43;;;;5871:2;5850:15;;;-1:-1:-1;;5846:29:72;5831:45;5827:55;;5256:632;-1:-1:-1;;;;5256:632:72:o;7266:383::-;7415:2;7404:9;7397:21;7378:4;7447:6;7441:13;7490:6;7485:2;7474:9;7470:18;7463:34;7506:66;7565:6;7560:2;7549:9;7545:18;7540:2;7532:6;7528:15;7506:66;:::i;:::-;7633:2;7612:15;-1:-1:-1;;7608:29:72;7593:45;;;;7640:2;7589:54;;7266:383;-1:-1:-1;;7266:383:72:o;18899:128::-;18939:3;18970:1;18966:6;18963:1;18960:13;18957:39;;;18976:18;;:::i;:::-;-1:-1:-1;19012:9:72;;18899:128::o;19032:201::-;19072:1;-1:-1:-1;;;;;19137:10:72;;;;19156:37;;19173:18;;:::i;:::-;19211:10;;19207:20;;;;;19032:201;-1:-1:-1;;19032:201:72:o;19238:120::-;19278:1;19304;19294:35;;19309:18;;:::i;:::-;-1:-1:-1;19343:9:72;;19238:120::o;19363:272::-;19403:7;-1:-1:-1;;;;;19474:10:72;;;19504;;;19559:12;;;19551:21;;19537:11;;19530:19;19526:47;19523:73;;;19576:18;;:::i;:::-;19616:13;;19363:272;-1:-1:-1;;;;19363:272:72:o;19640:168::-;19680:7;19746:1;19742;19738:6;19734:14;19731:1;19728:21;19723:1;19716:9;19709:17;19705:45;19702:71;;;19753:18;;:::i;:::-;-1:-1:-1;19793:9:72;;19640:168::o;19813:125::-;19853:4;19881:1;19878;19875:8;19872:34;;;19886:18;;:::i;:::-;-1:-1:-1;19923:9:72;;19813:125::o;19943:221::-;19982:4;20011:10;20071;;;;20041;;20093:12;;;20090:38;;;20108:18;;:::i;:::-;20145:13;;19943:221;-1:-1:-1;;;19943:221:72:o;20169:195::-;20207:4;20244;20241:1;20237:12;20276:4;20273:1;20269:12;20301:3;20296;20293:12;20290:38;;;20308:18;;:::i;:::-;20345:13;;;20169:195;-1:-1:-1;;;20169:195:72:o;20369:258::-;20441:1;20451:113;20465:6;20462:1;20459:13;20451:113;;;20541:11;;;20535:18;20522:11;;;20515:39;20487:2;20480:10;20451:113;;;20582:6;20579:1;20576:13;20573:48;;;-1:-1:-1;;20617:1:72;20599:16;;20592:27;20369:258::o;20632:380::-;20711:1;20707:12;;;;20754;;;20775:61;;20829:4;20821:6;20817:17;20807:27;;20775:61;20882:2;20874:6;20871:14;20851:18;20848:38;20845:161;;;20928:10;20923:3;20919:20;20916:1;20909:31;20963:4;20960:1;20953:15;20991:4;20988:1;20981:15;21017:135;21056:3;-1:-1:-1;;21077:17:72;;21074:43;;;21097:18;;:::i;:::-;-1:-1:-1;21144:1:72;21133:13;;21017:135::o;21157:112::-;21189:1;21215;21205:35;;21220:18;;:::i;:::-;-1:-1:-1;21254:9:72;;21157:112::o;21274:127::-;21335:10;21330:3;21326:20;21323:1;21316:31;21366:4;21363:1;21356:15;21390:4;21387:1;21380:15;21406:127;21467:10;21462:3;21458:20;21455:1;21448:31;21498:4;21495:1;21488:15;21522:4;21519:1;21512:15;21538:131;-1:-1:-1;;;;;21613:31:72;;21603:42;;21593:70;;21659:1;21656;21649:12;21593:70;21538:131;:::o;21674:114::-;21758:4;21751:5;21747:16;21740:5;21737:27;21727:55;;21778:1;21775;21768:12
Swarm Source
ipfs://6f93f83d7457b7e263647eb1c4f3dec2e14897e53fdff43bc3969fd0f10c1770
Age | Block | Fee Address | BC Fee Address | Voting Power | Jailed | Incoming |
---|
Make sure to use the "Vote Down" button for any spammy posts, and the "Vote Up" for interesting conversations.