{ "language": "Solidity", "settings": { "evmVersion": "london", "libraries": {}, "metadata": { "bytecodeHash": "ipfs", "useLiteralContent": true }, "optimizer": { "enabled": true, "runs": 200 }, "remappings": [], "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } } }, "sources": { "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module which provides a basic access control mechanism, where\n * there is an account (an owner) that can be granted exclusive access to\n * specific functions.\n *\n * By default, the owner account will be the one that deploys the contract. This\n * can later be changed with {transferOwnership}.\n *\n * This module is used through inheritance. It will make available the modifier\n * `onlyOwner`, which can be applied to your functions to restrict their use to\n * the owner.\n */\nabstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {\n address private _owner;\n\n event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\n\n /**\n * @dev Initializes the contract setting the deployer as the initial owner.\n */\n function __Ownable_init() internal onlyInitializing {\n __Ownable_init_unchained();\n }\n\n function __Ownable_init_unchained() internal onlyInitializing {\n _transferOwnership(_msgSender());\n }\n\n /**\n * @dev Throws if called by any account other than the owner.\n */\n modifier onlyOwner() {\n _checkOwner();\n _;\n }\n\n /**\n * @dev Returns the address of the current owner.\n */\n function owner() public view virtual returns (address) {\n return _owner;\n }\n\n /**\n * @dev Throws if the sender is not the owner.\n */\n function _checkOwner() internal view virtual {\n require(owner() == _msgSender(), \"Ownable: caller is not the owner\");\n }\n\n /**\n * @dev Leaves the contract without owner. It will not be possible to call\n * `onlyOwner` functions anymore. Can only be called by the current owner.\n *\n * NOTE: Renouncing ownership will leave the contract without an owner,\n * thereby removing any functionality that is only available to the owner.\n */\n function renounceOwnership() public virtual onlyOwner {\n _transferOwnership(address(0));\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Can only be called by the current owner.\n */\n function transferOwnership(address newOwner) public virtual onlyOwner {\n require(newOwner != address(0), \"Ownable: new owner is the zero address\");\n _transferOwnership(newOwner);\n }\n\n /**\n * @dev Transfers ownership of the contract to a new account (`newOwner`).\n * Internal function without access restriction.\n */\n function _transferOwnership(address newOwner) internal virtual {\n address oldOwner = _owner;\n _owner = newOwner;\n emit OwnershipTransferred(oldOwner, newOwner);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[49] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol)\n\npragma solidity ^0.8.2;\n\nimport \"../../utils/AddressUpgradeable.sol\";\n\n/**\n * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed\n * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an\n * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer\n * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.\n *\n * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be\n * reused. This mechanism prevents re-execution of each \"step\" but allows the creation of new initialization steps in\n * case an upgrade adds a module that needs to be initialized.\n *\n * For example:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * contract MyToken is ERC20Upgradeable {\n * function initialize() initializer public {\n * __ERC20_init(\"MyToken\", \"MTK\");\n * }\n * }\n * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {\n * function initializeV2() reinitializer(2) public {\n * __ERC20Permit_init(\"MyToken\");\n * }\n * }\n * ```\n *\n * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as\n * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.\n *\n * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure\n * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.\n *\n * [CAUTION]\n * ====\n * Avoid leaving a contract uninitialized.\n *\n * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation\n * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke\n * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:\n *\n * [.hljs-theme-light.nopadding]\n * ```\n * /// @custom:oz-upgrades-unsafe-allow constructor\n * constructor() {\n * _disableInitializers();\n * }\n * ```\n * ====\n */\nabstract contract Initializable {\n /**\n * @dev Indicates that the contract has been initialized.\n * @custom:oz-retyped-from bool\n */\n uint8 private _initialized;\n\n /**\n * @dev Indicates that the contract is in the process of being initialized.\n */\n bool private _initializing;\n\n /**\n * @dev Triggered when the contract has been initialized or reinitialized.\n */\n event Initialized(uint8 version);\n\n /**\n * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,\n * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.\n */\n modifier initializer() {\n bool isTopLevelCall = !_initializing;\n require(\n (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1),\n \"Initializable: contract is already initialized\"\n );\n _initialized = 1;\n if (isTopLevelCall) {\n _initializing = true;\n }\n _;\n if (isTopLevelCall) {\n _initializing = false;\n emit Initialized(1);\n }\n }\n\n /**\n * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the\n * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be\n * used to initialize parent contracts.\n *\n * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original\n * initialization step. This is essential to configure modules that are added through upgrades and that require\n * initialization.\n *\n * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in\n * a contract, executing them in the right order is up to the developer or operator.\n */\n modifier reinitializer(uint8 version) {\n require(!_initializing && _initialized < version, \"Initializable: contract is already initialized\");\n _initialized = version;\n _initializing = true;\n _;\n _initializing = false;\n emit Initialized(version);\n }\n\n /**\n * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the\n * {initializer} and {reinitializer} modifiers, directly or indirectly.\n */\n modifier onlyInitializing() {\n require(_initializing, \"Initializable: contract is not initializing\");\n _;\n }\n\n /**\n * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.\n * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized\n * to any version. It is recommended to use this to lock implementation contracts that are designed to be called\n * through proxies.\n */\n function _disableInitializers() internal virtual {\n require(!_initializing, \"Initializable: contract is initializing\");\n if (_initialized < type(uint8).max) {\n _initialized = type(uint8).max;\n emit Initialized(type(uint8).max);\n }\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20Upgradeable.sol\";\nimport \"./extensions/IERC20MetadataUpgradeable.sol\";\nimport \"../../utils/ContextUpgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC20} interface.\n *\n * This implementation is agnostic to the way tokens are created. This means\n * that a supply mechanism has to be added in a derived contract using {_mint}.\n * For a generic mechanism see {ERC20PresetMinterPauser}.\n *\n * TIP: For a detailed writeup see our guide\n * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How\n * to implement supply mechanisms].\n *\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\n * instead returning `false` on failure. This behavior is nonetheless\n * conventional and does not conflict with the expectations of ERC20\n * applications.\n *\n * Additionally, an {Approval} event is emitted on calls to {transferFrom}.\n * This allows applications to reconstruct the allowance for all accounts just\n * by listening to said events. Other implementations of the EIP may not emit\n * these events, as it isn't required by the specification.\n *\n * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}\n * functions have been added to mitigate the well-known issues around setting\n * allowances. See {IERC20-approve}.\n */\ncontract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {\n mapping(address => uint256) private _balances;\n\n mapping(address => mapping(address => uint256)) private _allowances;\n\n uint256 private _totalSupply;\n\n string private _name;\n string private _symbol;\n\n /**\n * @dev Sets the values for {name} and {symbol}.\n *\n * The default value of {decimals} is 18. To select a different value for\n * {decimals} you should overload it.\n *\n * All two of these values are immutable: they can only be set once during\n * construction.\n */\n function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {\n __ERC20_init_unchained(name_, symbol_);\n }\n\n function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {\n _name = name_;\n _symbol = symbol_;\n }\n\n /**\n * @dev Returns the name of the token.\n */\n function name() public view virtual override returns (string memory) {\n return _name;\n }\n\n /**\n * @dev Returns the symbol of the token, usually a shorter version of the\n * name.\n */\n function symbol() public view virtual override returns (string memory) {\n return _symbol;\n }\n\n /**\n * @dev Returns the number of decimals used to get its user representation.\n * For example, if `decimals` equals `2`, a balance of `505` tokens should\n * be displayed to a user as `5.05` (`505 / 10 ** 2`).\n *\n * Tokens usually opt for a value of 18, imitating the relationship between\n * Ether and Wei. This is the value {ERC20} uses, unless this function is\n * overridden;\n *\n * NOTE: This information is only used for _display_ purposes: it in\n * no way affects any of the arithmetic of the contract, including\n * {IERC20-balanceOf} and {IERC20-transfer}.\n */\n function decimals() public view virtual override returns (uint8) {\n return 18;\n }\n\n /**\n * @dev See {IERC20-totalSupply}.\n */\n function totalSupply() public view virtual override returns (uint256) {\n return _totalSupply;\n }\n\n /**\n * @dev See {IERC20-balanceOf}.\n */\n function balanceOf(address account) public view virtual override returns (uint256) {\n return _balances[account];\n }\n\n /**\n * @dev See {IERC20-transfer}.\n *\n * Requirements:\n *\n * - `to` cannot be the zero address.\n * - the caller must have a balance of at least `amount`.\n */\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _transfer(owner, to, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-allowance}.\n */\n function allowance(address owner, address spender) public view virtual override returns (uint256) {\n return _allowances[owner][spender];\n }\n\n /**\n * @dev See {IERC20-approve}.\n *\n * NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on\n * `transferFrom`. This is semantically equivalent to an infinite approval.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function approve(address spender, uint256 amount) public virtual override returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, amount);\n return true;\n }\n\n /**\n * @dev See {IERC20-transferFrom}.\n *\n * Emits an {Approval} event indicating the updated allowance. This is not\n * required by the EIP. See the note at the beginning of {ERC20}.\n *\n * NOTE: Does not update the allowance if the current allowance\n * is the maximum `uint256`.\n *\n * Requirements:\n *\n * - `from` and `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n * - the caller must have allowance for ``from``'s tokens of at least\n * `amount`.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) public virtual override returns (bool) {\n address spender = _msgSender();\n _spendAllowance(from, spender, amount);\n _transfer(from, to, amount);\n return true;\n }\n\n /**\n * @dev Atomically increases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n */\n function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {\n address owner = _msgSender();\n _approve(owner, spender, allowance(owner, spender) + addedValue);\n return true;\n }\n\n /**\n * @dev Atomically decreases the allowance granted to `spender` by the caller.\n *\n * This is an alternative to {approve} that can be used as a mitigation for\n * problems described in {IERC20-approve}.\n *\n * Emits an {Approval} event indicating the updated allowance.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `spender` must have allowance for the caller of at least\n * `subtractedValue`.\n */\n function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {\n address owner = _msgSender();\n uint256 currentAllowance = allowance(owner, spender);\n require(currentAllowance >= subtractedValue, \"ERC20: decreased allowance below zero\");\n unchecked {\n _approve(owner, spender, currentAllowance - subtractedValue);\n }\n\n return true;\n }\n\n /**\n * @dev Moves `amount` of tokens from `from` to `to`.\n *\n * This internal function is equivalent to {transfer}, and can be used to\n * e.g. implement automatic token fees, slashing mechanisms, etc.\n *\n * Emits a {Transfer} event.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `from` must have a balance of at least `amount`.\n */\n function _transfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {\n require(from != address(0), \"ERC20: transfer from the zero address\");\n require(to != address(0), \"ERC20: transfer to the zero address\");\n\n _beforeTokenTransfer(from, to, amount);\n\n uint256 fromBalance = _balances[from];\n require(fromBalance >= amount, \"ERC20: transfer amount exceeds balance\");\n unchecked {\n _balances[from] = fromBalance - amount;\n }\n _balances[to] += amount;\n\n emit Transfer(from, to, amount);\n\n _afterTokenTransfer(from, to, amount);\n }\n\n /** @dev Creates `amount` tokens and assigns them to `account`, increasing\n * the total supply.\n *\n * Emits a {Transfer} event with `from` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n */\n function _mint(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: mint to the zero address\");\n\n _beforeTokenTransfer(address(0), account, amount);\n\n _totalSupply += amount;\n _balances[account] += amount;\n emit Transfer(address(0), account, amount);\n\n _afterTokenTransfer(address(0), account, amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, reducing the\n * total supply.\n *\n * Emits a {Transfer} event with `to` set to the zero address.\n *\n * Requirements:\n *\n * - `account` cannot be the zero address.\n * - `account` must have at least `amount` tokens.\n */\n function _burn(address account, uint256 amount) internal virtual {\n require(account != address(0), \"ERC20: burn from the zero address\");\n\n _beforeTokenTransfer(account, address(0), amount);\n\n uint256 accountBalance = _balances[account];\n require(accountBalance >= amount, \"ERC20: burn amount exceeds balance\");\n unchecked {\n _balances[account] = accountBalance - amount;\n }\n _totalSupply -= amount;\n\n emit Transfer(account, address(0), amount);\n\n _afterTokenTransfer(account, address(0), amount);\n }\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.\n *\n * This internal function is equivalent to `approve`, and can be used to\n * e.g. set automatic allowances for certain subsystems, etc.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `owner` cannot be the zero address.\n * - `spender` cannot be the zero address.\n */\n function _approve(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n require(owner != address(0), \"ERC20: approve from the zero address\");\n require(spender != address(0), \"ERC20: approve to the zero address\");\n\n _allowances[owner][spender] = amount;\n emit Approval(owner, spender, amount);\n }\n\n /**\n * @dev Updates `owner` s allowance for `spender` based on spent `amount`.\n *\n * Does not update the allowance amount in case of infinite allowance.\n * Revert if not enough allowance is available.\n *\n * Might emit an {Approval} event.\n */\n function _spendAllowance(\n address owner,\n address spender,\n uint256 amount\n ) internal virtual {\n uint256 currentAllowance = allowance(owner, spender);\n if (currentAllowance != type(uint256).max) {\n require(currentAllowance >= amount, \"ERC20: insufficient allowance\");\n unchecked {\n _approve(owner, spender, currentAllowance - amount);\n }\n }\n }\n\n /**\n * @dev Hook that is called before any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * will be transferred to `to`.\n * - when `from` is zero, `amount` tokens will be minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens will be burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev Hook that is called after any transfer of tokens. This includes\n * minting and burning.\n *\n * Calling conditions:\n *\n * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens\n * has been transferred to `to`.\n * - when `from` is zero, `amount` tokens have been minted for `to`.\n * - when `to` is zero, `amount` of ``from``'s tokens have been burned.\n * - `from` and `to` are never both zero.\n *\n * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].\n */\n function _afterTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual {}\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[45] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20Upgradeable {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/extensions/ERC20Burnable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20Upgradeable.sol\";\nimport \"../../../utils/ContextUpgradeable.sol\";\nimport \"../../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Extension of {ERC20} that allows token holders to destroy both their own\n * tokens and those that they have an allowance for, in a way that can be\n * recognized off-chain (via event analysis).\n */\nabstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable {\n function __ERC20Burnable_init() internal onlyInitializing {\n }\n\n function __ERC20Burnable_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev Destroys `amount` tokens from the caller.\n *\n * See {ERC20-_burn}.\n */\n function burn(uint256 amount) public virtual {\n _burn(_msgSender(), amount);\n }\n\n /**\n * @dev Destroys `amount` tokens from `account`, deducting from the caller's\n * allowance.\n *\n * See {ERC20-_burn} and {ERC20-allowance}.\n *\n * Requirements:\n *\n * - the caller must have allowance for ``accounts``'s tokens of at least\n * `amount`.\n */\n function burnFrom(address account, uint256 amount) public virtual {\n _spendAllowance(account, _msgSender(), amount);\n _burn(account, amount);\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" }, "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20Upgradeable.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20MetadataUpgradeable is IERC20Upgradeable {\n /**\n * @dev Returns the name of the token.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the symbol of the token.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the decimals places of the token.\n */\n function decimals() external view returns (uint8);\n}\n" }, "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary AddressUpgradeable {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Provides information about the current execution context, including the\n * sender of the transaction and its data. While these are generally available\n * via msg.sender and msg.data, they should not be accessed in such a direct\n * manner, since when dealing with meta-transactions the account sending and\n * paying for execution may not be the actual sender (as far as an application\n * is concerned).\n *\n * This contract is only required for intermediate, library-like contracts.\n */\nabstract contract ContextUpgradeable is Initializable {\n function __Context_init() internal onlyInitializing {\n }\n\n function __Context_init_unchained() internal onlyInitializing {\n }\n function _msgSender() internal view virtual returns (address) {\n return msg.sender;\n }\n\n function _msgData() internal view virtual returns (bytes calldata) {\n return msg.data;\n }\n\n /**\n * @dev This empty reserved space is put in place to allow future versions to add new\n * variables without shifting down storage in the inheritance chain.\n * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps\n */\n uint256[50] private __gap;\n}\n" }, "@openzeppelin/contracts/token/ERC20/IERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 standard as defined in the EIP.\n */\ninterface IERC20 {\n /**\n * @dev Emitted when `value` tokens are moved from one account (`from`) to\n * another (`to`).\n *\n * Note that `value` may be zero.\n */\n event Transfer(address indexed from, address indexed to, uint256 value);\n\n /**\n * @dev Emitted when the allowance of a `spender` for an `owner` is set by\n * a call to {approve}. `value` is the new allowance.\n */\n event Approval(address indexed owner, address indexed spender, uint256 value);\n\n /**\n * @dev Returns the amount of tokens in existence.\n */\n function totalSupply() external view returns (uint256);\n\n /**\n * @dev Returns the amount of tokens owned by `account`.\n */\n function balanceOf(address account) external view returns (uint256);\n\n /**\n * @dev Moves `amount` tokens from the caller's account to `to`.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transfer(address to, uint256 amount) external returns (bool);\n\n /**\n * @dev Returns the remaining number of tokens that `spender` will be\n * allowed to spend on behalf of `owner` through {transferFrom}. This is\n * zero by default.\n *\n * This value changes when {approve} or {transferFrom} are called.\n */\n function allowance(address owner, address spender) external view returns (uint256);\n\n /**\n * @dev Sets `amount` as the allowance of `spender` over the caller's tokens.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * IMPORTANT: Beware that changing an allowance with this method brings the risk\n * that someone may use both the old and the new allowance by unfortunate\n * transaction ordering. One possible solution to mitigate this race\n * condition is to first reduce the spender's allowance to 0 and set the\n * desired value afterwards:\n * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\n *\n * Emits an {Approval} event.\n */\n function approve(address spender, uint256 amount) external returns (bool);\n\n /**\n * @dev Moves `amount` tokens from `from` to `to` using the\n * allowance mechanism. `amount` is then deducted from the caller's\n * allowance.\n *\n * Returns a boolean value indicating whether the operation succeeded.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 amount\n ) external returns (bool);\n}\n" }, "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in\n * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].\n *\n * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by\n * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't\n * need to send a transaction, and thus is not required to hold Ether at all.\n */\ninterface IERC20Permit {\n /**\n * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,\n * given ``owner``'s signed approval.\n *\n * IMPORTANT: The same issues {IERC20-approve} has related to transaction\n * ordering also apply here.\n *\n * Emits an {Approval} event.\n *\n * Requirements:\n *\n * - `spender` cannot be the zero address.\n * - `deadline` must be a timestamp in the future.\n * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`\n * over the EIP712-formatted function arguments.\n * - the signature must use ``owner``'s current nonce (see {nonces}).\n *\n * For more information on the signature format, see the\n * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP\n * section].\n */\n function permit(\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n\n /**\n * @dev Returns the current nonce for `owner`. This value must be\n * included whenever a signature is generated for {permit}.\n *\n * Every successful call to {permit} increases ``owner``'s nonce by one. This\n * prevents a signature from being used multiple times.\n */\n function nonces(address owner) external view returns (uint256);\n\n /**\n * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.\n */\n // solhint-disable-next-line func-name-mixedcase\n function DOMAIN_SEPARATOR() external view returns (bytes32);\n}\n" }, "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC20/utils/SafeERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC20.sol\";\nimport \"../extensions/draft-IERC20Permit.sol\";\nimport \"../../../utils/Address.sol\";\n\n/**\n * @title SafeERC20\n * @dev Wrappers around ERC20 operations that throw on failure (when the token\n * contract returns false). Tokens that return no value (and instead revert or\n * throw on failure) are also supported, non-reverting calls are assumed to be\n * successful.\n * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,\n * which allows you to call the safe operations as `token.safeTransfer(...)`, etc.\n */\nlibrary SafeERC20 {\n using Address for address;\n\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));\n }\n\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 value\n ) internal {\n _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));\n }\n\n /**\n * @dev Deprecated. This function has issues similar to the ones found in\n * {IERC20-approve}, and its usage is discouraged.\n *\n * Whenever possible, use {safeIncreaseAllowance} and\n * {safeDecreaseAllowance} instead.\n */\n function safeApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n // safeApprove should only be called when setting an initial allowance,\n // or when resetting it to zero. To increase and decrease it, use\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\n require(\n (value == 0) || (token.allowance(address(this), spender) == 0),\n \"SafeERC20: approve from non-zero to non-zero allowance\"\n );\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\n }\n\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 newAllowance = token.allowance(address(this), spender) + value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n unchecked {\n uint256 oldAllowance = token.allowance(address(this), spender);\n require(oldAllowance >= value, \"SafeERC20: decreased allowance below zero\");\n uint256 newAllowance = oldAllowance - value;\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));\n }\n }\n\n function safePermit(\n IERC20Permit token,\n address owner,\n address spender,\n uint256 value,\n uint256 deadline,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) internal {\n uint256 nonceBefore = token.nonces(owner);\n token.permit(owner, spender, value, deadline, v, r, s);\n uint256 nonceAfter = token.nonces(owner);\n require(nonceAfter == nonceBefore + 1, \"SafeERC20: permit did not succeed\");\n }\n\n /**\n * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement\n * on the return value: the return value is optional (but if data is returned, it must not be false).\n * @param token The token targeted by the call.\n * @param data The call data (encoded using abi.encode or one of its variants).\n */\n function _callOptionalReturn(IERC20 token, bytes memory data) private {\n // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since\n // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that\n // the target address contains contract code and also asserts for success in the low-level call.\n\n bytes memory returndata = address(token).functionCall(data, \"SafeERC20: low-level call failed\");\n if (returndata.length > 0) {\n // Return data is optional\n require(abi.decode(returndata, (bool)), \"SafeERC20: ERC20 operation did not succeed\");\n }\n }\n}\n" }, "@openzeppelin/contracts/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol)\n\npragma solidity ^0.8.1;\n\n/**\n * @dev Collection of functions related to the address type\n */\nlibrary Address {\n /**\n * @dev Returns true if `account` is a contract.\n *\n * [IMPORTANT]\n * ====\n * It is unsafe to assume that an address for which this function returns\n * false is an externally-owned account (EOA) and not a contract.\n *\n * Among others, `isContract` will return false for the following\n * types of addresses:\n *\n * - an externally-owned account\n * - a contract in construction\n * - an address where a contract will be created\n * - an address where a contract lived, but was destroyed\n * ====\n *\n * [IMPORTANT]\n * ====\n * You shouldn't rely on `isContract` to protect against flash loan attacks!\n *\n * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets\n * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract\n * constructor.\n * ====\n */\n function isContract(address account) internal view returns (bool) {\n // This method relies on extcodesize/address.code.length, which returns 0\n // for contracts in construction, since the code is only stored at the end\n // of the constructor execution.\n\n return account.code.length > 0;\n }\n\n /**\n * @dev Replacement for Solidity's `transfer`: sends `amount` wei to\n * `recipient`, forwarding all available gas and reverting on errors.\n *\n * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost\n * of certain opcodes, possibly making contracts go over the 2300 gas limit\n * imposed by `transfer`, making them unable to receive funds via\n * `transfer`. {sendValue} removes this limitation.\n *\n * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].\n *\n * IMPORTANT: because control is transferred to `recipient`, care must be\n * taken to not create reentrancy vulnerabilities. Consider using\n * {ReentrancyGuard} or the\n * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].\n */\n function sendValue(address payable recipient, uint256 amount) internal {\n require(address(this).balance >= amount, \"Address: insufficient balance\");\n\n (bool success, ) = recipient.call{value: amount}(\"\");\n require(success, \"Address: unable to send value, recipient may have reverted\");\n }\n\n /**\n * @dev Performs a Solidity function call using a low level `call`. A\n * plain `call` is an unsafe replacement for a function call: use this\n * function instead.\n *\n * If `target` reverts with a revert reason, it is bubbled up by this\n * function (like regular Solidity function calls).\n *\n * Returns the raw returned data. To convert to the expected return value,\n * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].\n *\n * Requirements:\n *\n * - `target` must be a contract.\n * - calling `target` with `data` must not revert.\n *\n * _Available since v3.1._\n */\n function functionCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionCall(target, data, \"Address: low-level call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with\n * `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, 0, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but also transferring `value` wei to `target`.\n *\n * Requirements:\n *\n * - the calling contract must have an ETH balance of at least `value`.\n * - the called Solidity function must be `payable`.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value\n ) internal returns (bytes memory) {\n return functionCallWithValue(target, data, value, \"Address: low-level call with value failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but\n * with `errorMessage` as a fallback revert reason when `target` reverts.\n *\n * _Available since v3.1._\n */\n function functionCallWithValue(\n address target,\n bytes memory data,\n uint256 value,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(address(this).balance >= value, \"Address: insufficient balance for call\");\n require(isContract(target), \"Address: call to non-contract\");\n\n (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {\n return functionStaticCall(target, data, \"Address: low-level static call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a static call.\n *\n * _Available since v3.3._\n */\n function functionStaticCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n require(isContract(target), \"Address: static call to non-contract\");\n\n (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {\n return functionDelegateCall(target, data, \"Address: low-level delegate call failed\");\n }\n\n /**\n * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],\n * but performing a delegate call.\n *\n * _Available since v3.4._\n */\n function functionDelegateCall(\n address target,\n bytes memory data,\n string memory errorMessage\n ) internal returns (bytes memory) {\n require(isContract(target), \"Address: delegate call to non-contract\");\n\n (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResult(success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason using the provided one.\n *\n * _Available since v4.3._\n */\n function verifyCallResult(\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal pure returns (bytes memory) {\n if (success) {\n return returndata;\n } else {\n // Look for revert reason and bubble it up if present\n if (returndata.length > 0) {\n // The easiest way to bubble the revert reason is using memory via assembly\n /// @solidity memory-safe-assembly\n assembly {\n let returndata_size := mload(returndata)\n revert(add(32, returndata), returndata_size)\n }\n } else {\n revert(errorMessage);\n }\n }\n }\n}\n" }, "contracts/core/connext/helpers/LPToken.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.15;\n\nimport {ERC20Upgradeable} from \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol\";\nimport {OwnableUpgradeable} from \"@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol\";\n\n/**\n * @title Liquidity Provider Token\n * @notice This token is an ERC20 detailed token with added capability to be minted by the owner.\n * It is used to represent user's shares when providing liquidity to swap contracts.\n * @dev Only Swap contracts should initialize and own LPToken contracts.\n */\ncontract LPToken is ERC20Upgradeable, OwnableUpgradeable {\n // ============ Upgrade Gap ============\n\n uint256[49] private __GAP; // gap for upgrade safety\n\n // ============ Storage ============\n\n /**\n * @notice Used to enforce proper token dilution\n * @dev If this is the first mint of the LP token, this amount of funds are burned.\n * See audit recommendations here:\n * - https://github.com/code-423n4/2022-03-prepo-findings/issues/27\n * - https://github.com/code-423n4/2022-04-jpegd-findings/issues/12\n * and uniswap v2 implementation here:\n * https://github.com/Uniswap/v2-core/blob/8b82b04a0b9e696c0e83f8b2f00e5d7be6888c79/contracts/UniswapV2Pair.sol#L15\n */\n uint256 public constant MINIMUM_LIQUIDITY = 10**3;\n\n // ============ Initializer ============\n\n /**\n * @notice Initializes this LPToken contract with the given name and symbol\n * @dev The caller of this function will become the owner. A Swap contract should call this\n * in its initializer function.\n * @param name name of this token\n * @param symbol symbol of this token\n */\n function initialize(string memory name, string memory symbol) external initializer returns (bool) {\n __Context_init_unchained();\n __ERC20_init_unchained(name, symbol);\n __Ownable_init_unchained();\n return true;\n }\n\n // ============ External functions ============\n\n /**\n * @notice Mints the given amount of LPToken to the recipient.\n * @dev only owner can call this mint function\n * @param recipient address of account to receive the tokens\n * @param amount amount of tokens to mint\n */\n function mint(address recipient, uint256 amount) external onlyOwner {\n require(amount != 0, \"LPToken: cannot mint 0\");\n if (totalSupply() == 0) {\n // NOTE: using the _mint function directly will error because it is going\n // to the 0 address. fix by using the address(1) here instead\n _mint(address(1), MINIMUM_LIQUIDITY);\n }\n _mint(recipient, amount);\n }\n\n /**\n * @notice Burns the given amount of LPToken from provided account\n * @dev only owner can call this burn function\n * @param account address of account from which to burn token\n * @param amount amount of tokens to mint\n */\n function burnFrom(address account, uint256 amount) external onlyOwner {\n require(amount != 0, \"LPToken: cannot burn 0\");\n _burn(account, amount);\n }\n\n // ============ Internal functions ============\n\n /**\n * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including\n * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime.\n * This assumes the owner is set to a Swap contract's address.\n */\n function _beforeTokenTransfer(\n address from,\n address to,\n uint256 amount\n ) internal virtual override(ERC20Upgradeable) {\n super._beforeTokenTransfer(from, to, amount);\n require(to != address(this), \"LPToken: cannot send to itself\");\n }\n}\n" }, "contracts/core/connext/libraries/MathUtils.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.15;\n\n/**\n * @title MathUtils library\n * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating\n * differences between two uint256.\n */\nlibrary MathUtils {\n /**\n * @notice Compares a and b and returns true if the difference between a and b\n * is less than 1 or equal to each other.\n * @param a uint256 to compare with\n * @param b uint256 to compare with\n * @return True if the difference between a and b is less than 1 or equal,\n * otherwise return false\n */\n function within1(uint256 a, uint256 b) internal pure returns (bool) {\n return (difference(a, b) <= 1);\n }\n\n /**\n * @notice Calculates absolute difference between a and b\n * @param a uint256 to compare with\n * @param b uint256 to compare with\n * @return Difference between a and b\n */\n function difference(uint256 a, uint256 b) internal pure returns (uint256) {\n if (a > b) {\n return a - b;\n }\n return b - a;\n }\n}\n" }, "contracts/core/connext/libraries/SwapUtilsExternal.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity 0.8.15;\n\nimport {SafeERC20, IERC20} from \"@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol\";\n\nimport {LPToken} from \"../helpers/LPToken.sol\";\n\nimport {MathUtils} from \"./MathUtils.sol\";\n\n/**\n * @title SwapUtilsExternal library\n * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities.\n * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library\n * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins.\n * Admin functions should be protected within contracts using this library.\n */\nlibrary SwapUtilsExternal {\n using SafeERC20 for IERC20;\n using MathUtils for uint256;\n\n /*** EVENTS ***/\n\n event TokenSwap(address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId);\n event AddLiquidity(\n address indexed provider,\n uint256[] tokenAmounts,\n uint256[] fees,\n uint256 invariant,\n uint256 lpTokenSupply\n );\n event RemoveLiquidity(address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply);\n event RemoveLiquidityOne(\n address indexed provider,\n uint256 lpTokenAmount,\n uint256 lpTokenSupply,\n uint256 boughtId,\n uint256 tokensBought\n );\n event RemoveLiquidityImbalance(\n address indexed provider,\n uint256[] tokenAmounts,\n uint256[] fees,\n uint256 invariant,\n uint256 lpTokenSupply\n );\n event NewAdminFee(uint256 newAdminFee);\n event NewSwapFee(uint256 newSwapFee);\n\n event RampA(uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime);\n event StopRampA(uint256 currentA, uint256 time);\n\n struct Swap {\n // variables around the ramp management of A,\n // the amplification coefficient * n * (n - 1)\n // see https://www.curve.fi/stableswap-paper.pdf for details\n uint256 initialA;\n uint256 futureA;\n uint256 initialATime;\n uint256 futureATime;\n // fee calculation\n uint256 swapFee;\n uint256 adminFee;\n LPToken lpToken;\n // contract references for all tokens being pooled\n IERC20[] pooledTokens;\n // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS\n // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC\n // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10\n uint256[] tokenPrecisionMultipliers;\n // the pool balance of each token, in the token's precision\n // the contract's actual token balance might differ\n uint256[] balances;\n // the admin fee balance of each token, in the token's precision\n uint256[] adminFees;\n }\n\n // Struct storing variables used in calculations in the\n // calculateWithdrawOneTokenDY function to avoid stack too deep errors\n struct CalculateWithdrawOneTokenDYInfo {\n uint256 d0;\n uint256 d1;\n uint256 newY;\n uint256 feePerToken;\n uint256 preciseA;\n }\n\n // Struct storing variables used in calculations in the\n // {add,remove}Liquidity functions to avoid stack too deep errors\n struct ManageLiquidityInfo {\n uint256 d0;\n uint256 d1;\n uint256 d2;\n uint256 preciseA;\n LPToken lpToken;\n uint256 totalSupply;\n uint256[] balances;\n uint256[] multipliers;\n }\n\n // the precision all pools tokens will be converted to\n uint8 internal constant POOL_PRECISION_DECIMALS = 18;\n\n // the denominator used to calculate admin and LP fees. For example, an\n // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR)\n uint256 internal constant FEE_DENOMINATOR = 1e10;\n\n // Max swap fee is 1% or 100bps of each swap\n uint256 internal constant MAX_SWAP_FEE = 1e8;\n\n // Max adminFee is 100% of the swapFee\n // adminFee does not add additional fee on top of swapFee\n // Instead it takes a certain % of the swapFee. Therefore it has no impact on the\n // users but only on the earnings of LPs\n uint256 internal constant MAX_ADMIN_FEE = 1e10;\n\n // Constant value used as max loop limit\n uint256 internal constant MAX_LOOP_LIMIT = 256;\n\n // Constant values used in ramping A calculations\n uint256 public constant A_PRECISION = 100;\n uint256 public constant MAX_A = 10**6;\n uint256 private constant MAX_A_CHANGE = 2;\n uint256 private constant MIN_RAMP_TIME = 14 days;\n\n /*** VIEW & PURE FUNCTIONS ***/\n /**\n * @notice Return A, the amplification coefficient * n * (n - 1)\n * @dev See the StableSwap paper for details\n * @param self Swap struct to read from\n * @return A parameter\n */\n function getA(Swap storage self) external view returns (uint256) {\n return _getAPrecise(self) / A_PRECISION;\n }\n\n /**\n * @notice Return A in its raw precision\n * @dev See the StableSwap paper for details\n * @param self Swap struct to read from\n * @return A parameter in its raw precision form\n */\n function getAPrecise(Swap storage self) external view returns (uint256) {\n return _getAPrecise(self);\n }\n\n /**\n * @notice Return A in its raw precision\n * @dev See the StableSwap paper for details\n * @param self Swap struct to read from\n * @return A parameter in its raw precision form\n */\n function _getAPrecise(Swap storage self) internal view returns (uint256) {\n uint256 t1 = self.futureATime; // time when ramp is finished\n uint256 a1 = self.futureA; // final A value when ramp is finished\n\n if (block.timestamp < t1) {\n uint256 t0 = self.initialATime; // time when ramp is started\n uint256 a0 = self.initialA; // initial A value when ramp is started\n if (a1 > a0) {\n // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0)\n return a0 + ((a1 - a0) * (block.timestamp - t0)) / (t1 - t0);\n } else {\n // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0)\n return a0 - ((a0 - a1) * (block.timestamp - t0)) / (t1 - t0);\n }\n } else {\n return a1;\n }\n }\n\n /**\n * @notice Calculate the dy, the amount of selected token that user receives and\n * the fee of withdrawing in one token\n * @param tokenAmount the amount to withdraw in the pool's precision\n * @param tokenIndex which token will be withdrawn\n * @param self Swap struct to read from\n * @return the amount of token user will receive\n */\n function calculateWithdrawOneToken(\n Swap storage self,\n uint256 tokenAmount,\n uint8 tokenIndex\n ) external view returns (uint256) {\n (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken(\n self,\n tokenAmount,\n tokenIndex,\n self.lpToken.totalSupply()\n );\n return availableTokenAmount;\n }\n\n function _calculateWithdrawOneToken(\n Swap storage self,\n uint256 tokenAmount,\n uint8 tokenIndex,\n uint256 totalSupply\n ) private view returns (uint256, uint256) {\n uint256 dy;\n uint256 newY;\n uint256 currentY;\n\n (dy, newY, currentY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount, totalSupply);\n\n // dy_0 (without fees)\n // dy, dy_0 - dy\n\n uint256 dySwapFee = (currentY - newY) / self.tokenPrecisionMultipliers[tokenIndex] - dy;\n\n return (dy, dySwapFee);\n }\n\n /**\n * @notice Calculate the dy of withdrawing in one token\n * @param self Swap struct to read from\n * @param tokenIndex which token will be withdrawn\n * @param tokenAmount the amount to withdraw in the pools precision\n * @return the d and the new y after withdrawing one token\n */\n function calculateWithdrawOneTokenDY(\n Swap storage self,\n uint8 tokenIndex,\n uint256 tokenAmount,\n uint256 totalSupply\n )\n public\n view\n returns (\n uint256,\n uint256,\n uint256\n )\n {\n // Get the current D, then solve the stableswap invariant\n // y_i for D - tokenAmount\n uint256[] memory xp = _xp(self);\n\n require(tokenIndex < xp.length, \"index out of range\");\n\n CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0);\n v.preciseA = _getAPrecise(self);\n v.d0 = getD(xp, v.preciseA);\n v.d1 = v.d0 - ((tokenAmount * v.d0) / totalSupply);\n\n require(tokenAmount <= xp[tokenIndex], \"exceeds available\");\n\n v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1);\n\n uint256[] memory xpReduced = new uint256[](xp.length);\n\n v.feePerToken = _feePerToken(self.swapFee, xp.length);\n // TODO: Set a length variable (at top) instead of reading xp.length on each loop.\n for (uint256 i; i < xp.length; ) {\n uint256 xpi = xp[i];\n // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY\n // else dxExpected = xp[i] - (xp[i] * d1 / d0)\n // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR\n xpReduced[i] =\n xpi -\n ((((i == tokenIndex) ? ((xpi * v.d1) / v.d0 - v.newY) : (xpi - (xpi * v.d1) / v.d0)) * v.feePerToken) /\n FEE_DENOMINATOR);\n\n unchecked {\n ++i;\n }\n }\n\n uint256 dy = xpReduced[tokenIndex] - getYD(v.preciseA, tokenIndex, xpReduced, v.d1);\n dy = (dy - 1) / (self.tokenPrecisionMultipliers[tokenIndex]);\n\n return (dy, v.newY, xp[tokenIndex]);\n }\n\n /**\n * @notice Calculate the price of a token in the pool with given\n * precision-adjusted balances and a particular D.\n *\n * @dev This is accomplished via solving the invariant iteratively.\n * See the StableSwap paper and Curve.fi implementation for further details.\n *\n * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A)\n * x_1**2 + b*x_1 = c\n * x_1 = (x_1**2 + c) / (2*x_1 + b)\n *\n * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details.\n * @param tokenIndex Index of token we are calculating for.\n * @param xp a precision-adjusted set of pool balances. Array should be\n * the same cardinality as the pool.\n * @param d the stableswap invariant\n * @return the price of the token, in the same precision as in xp\n */\n function getYD(\n uint256 a,\n uint8 tokenIndex,\n uint256[] memory xp,\n uint256 d\n ) public pure returns (uint256) {\n uint256 numTokens = xp.length;\n require(tokenIndex < numTokens, \"Token not found\");\n\n uint256 c = d;\n uint256 s;\n uint256 nA = a * numTokens;\n\n for (uint256 i; i < numTokens; ) {\n if (i != tokenIndex) {\n s += xp[i];\n c = (c * d) / (xp[i] * numTokens);\n // If we were to protect the division loss we would have to keep the denominator separate\n // and divide at the end. However this leads to overflow with large numTokens or/and D.\n // c = c * D * D * D * ... overflow!\n }\n\n unchecked {\n ++i;\n }\n }\n c = (c * d * A_PRECISION) / (nA * numTokens);\n\n uint256 b = s + ((d * A_PRECISION) / nA);\n uint256 yPrev;\n uint256 y = d;\n for (uint256 i; i < MAX_LOOP_LIMIT; ) {\n yPrev = y;\n y = ((y * y) + c) / ((y * 2) + b - d);\n if (y.within1(yPrev)) {\n return y;\n }\n\n unchecked {\n ++i;\n }\n }\n revert(\"Approximation did not converge\");\n }\n\n /**\n * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A.\n * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality\n * as the pool.\n * @param a the amplification coefficient * n * (n - 1) in A_PRECISION.\n * See the StableSwap paper for details\n * @return the invariant, at the precision of the pool\n */\n function getD(uint256[] memory xp, uint256 a) public pure returns (uint256) {\n uint256 numTokens = xp.length;\n uint256 s;\n for (uint256 i; i < numTokens; ) {\n s += xp[i];\n\n unchecked {\n ++i;\n }\n }\n if (s == 0) {\n return 0;\n }\n\n uint256 prevD;\n uint256 d = s;\n uint256 nA = a * numTokens;\n\n for (uint256 i; i < MAX_LOOP_LIMIT; ) {\n uint256 dP = d;\n for (uint256 j; j < numTokens; ) {\n dP = (dP * d) / (xp[j] * numTokens);\n // If we were to protect the division loss we would have to keep the denominator separate\n // and divide at the end. However this leads to overflow with large numTokens or/and D.\n // dP = dP * D * D * D * ... overflow!\n\n unchecked {\n ++j;\n }\n }\n prevD = d;\n d =\n (((nA * s) / A_PRECISION + dP * numTokens) * d) /\n ((((nA - A_PRECISION) * d) / A_PRECISION + (numTokens + 1) * dP));\n if (d.within1(prevD)) {\n return d;\n }\n\n unchecked {\n ++i;\n }\n }\n\n // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong\n // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()`\n // function which does not rely on D.\n revert(\"D does not converge\");\n }\n\n /**\n * @notice Given a set of balances and precision multipliers, return the\n * precision-adjusted balances.\n *\n * @param balances an array of token balances, in their native precisions.\n * These should generally correspond with pooled tokens.\n *\n * @param precisionMultipliers an array of multipliers, corresponding to\n * the amounts in the balances array. When multiplied together they\n * should yield amounts at the pool's precision.\n *\n * @return an array of amounts \"scaled\" to the pool's precision\n */\n function _xp(uint256[] memory balances, uint256[] memory precisionMultipliers)\n internal\n pure\n returns (uint256[] memory)\n {\n uint256 numTokens = balances.length;\n require(numTokens == precisionMultipliers.length, \"mismatch multipliers\");\n uint256[] memory xp = new uint256[](numTokens);\n for (uint256 i; i < numTokens; ) {\n xp[i] = balances[i] * precisionMultipliers[i];\n\n unchecked {\n ++i;\n }\n }\n return xp;\n }\n\n /**\n * @notice Return the precision-adjusted balances of all tokens in the pool\n * @param self Swap struct to read from\n * @return the pool balances \"scaled\" to the pool's precision, allowing\n * them to be more easily compared.\n */\n function _xp(Swap storage self) internal view returns (uint256[] memory) {\n return _xp(self.balances, self.tokenPrecisionMultipliers);\n }\n\n /**\n * @notice Get the virtual price, to help calculate profit\n * @param self Swap struct to read from\n * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS\n */\n function getVirtualPrice(Swap storage self) external view returns (uint256) {\n uint256 d = getD(_xp(self), _getAPrecise(self));\n LPToken lpToken = self.lpToken;\n uint256 supply = lpToken.totalSupply();\n if (supply != 0) {\n return (d * (10**uint256(POOL_PRECISION_DECIMALS))) / supply;\n }\n return 0;\n }\n\n /**\n * @notice Calculate the new balances of the tokens given the indexes of the token\n * that is swapped from (FROM) and the token that is swapped to (TO).\n * This function is used as a helper function to calculate how much TO token\n * the user should receive on swap.\n *\n * @param preciseA precise form of amplification coefficient\n * @param tokenIndexFrom index of FROM token\n * @param tokenIndexTo index of TO token\n * @param x the new total amount of FROM token\n * @param xp balances of the tokens in the pool\n * @return the amount of TO token that should remain in the pool\n */\n function getY(\n uint256 preciseA,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 x,\n uint256[] memory xp\n ) public pure returns (uint256) {\n uint256 numTokens = xp.length;\n require(tokenIndexFrom != tokenIndexTo, \"compare token to itself\");\n require(tokenIndexFrom < numTokens && tokenIndexTo < numTokens, \"token not found\");\n\n uint256 d = getD(xp, preciseA);\n uint256 c = d;\n uint256 s;\n uint256 nA = numTokens * preciseA;\n\n uint256 _x;\n for (uint256 i; i < numTokens; ) {\n if (i == tokenIndexFrom) {\n _x = x;\n } else if (i != tokenIndexTo) {\n _x = xp[i];\n } else {\n unchecked {\n ++i;\n }\n continue;\n }\n s += _x;\n c = (c * d) / (_x * numTokens);\n // If we were to protect the division loss we would have to keep the denominator separate\n // and divide at the end. However this leads to overflow with large numTokens or/and D.\n // c = c * D * D * D * ... overflow!\n\n unchecked {\n ++i;\n }\n }\n c = (c * d * A_PRECISION) / (nA * numTokens);\n uint256 b = s + ((d * A_PRECISION) / nA);\n uint256 yPrev;\n uint256 y = d;\n\n // iterative approximation\n for (uint256 i; i < MAX_LOOP_LIMIT; ) {\n yPrev = y;\n y = ((y * y) + c) / ((y * 2) + b - d);\n if (y.within1(yPrev)) {\n return y;\n }\n\n unchecked {\n ++i;\n }\n }\n revert(\"Approximation did not converge\");\n }\n\n /**\n * @notice Externally calculates a swap between two tokens.\n * @param self Swap struct to read from\n * @param tokenIndexFrom the token to sell\n * @param tokenIndexTo the token to buy\n * @param dx the number of tokens to sell. If the token charges a fee on transfers,\n * use the amount that gets transferred after the fee.\n * @return dy the number of tokens the user will get\n */\n function calculateSwap(\n Swap storage self,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dx\n ) external view returns (uint256 dy) {\n (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx, self.balances);\n }\n\n /**\n * @notice Externally calculates a swap between two tokens.\n * @param self Swap struct to read from\n * @param tokenIndexFrom the token to sell\n * @param tokenIndexTo the token to buy\n * @param dy the number of tokens to buy.\n * @return dx the number of tokens the user have to transfer + fee\n */\n function calculateSwapInv(\n Swap storage self,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dy\n ) external view returns (uint256 dx) {\n (dx, ) = _calculateSwapInv(self, tokenIndexFrom, tokenIndexTo, dy, self.balances);\n }\n\n /**\n * @notice Internally calculates a swap between two tokens.\n *\n * @dev The caller is expected to transfer the actual amounts (dx and dy)\n * using the token contracts.\n *\n * @param self Swap struct to read from\n * @param tokenIndexFrom the token to sell\n * @param tokenIndexTo the token to buy\n * @param dx the number of tokens to sell. If the token charges a fee on transfers,\n * use the amount that gets transferred after the fee.\n * @return dy the number of tokens the user will get in the token's precision. ex WBTC -> 8\n * @return dyFee the associated fee in multiplied precision (POOL_PRECISION_DECIMALS)\n */\n function _calculateSwap(\n Swap storage self,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dx,\n uint256[] memory balances\n ) internal view returns (uint256 dy, uint256 dyFee) {\n uint256[] memory multipliers = self.tokenPrecisionMultipliers;\n uint256[] memory xp = _xp(balances, multipliers);\n require(tokenIndexFrom < xp.length && tokenIndexTo < xp.length, \"index out of range\");\n uint256 x = dx * multipliers[tokenIndexFrom] + xp[tokenIndexFrom];\n uint256 y = getY(_getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp);\n dy = xp[tokenIndexTo] - y - 1;\n dyFee = (dy * self.swapFee) / FEE_DENOMINATOR;\n dy = (dy - dyFee) / multipliers[tokenIndexTo];\n }\n\n /**\n * @notice Internally calculates a swap between two tokens.\n *\n * @dev The caller is expected to transfer the actual amounts (dx and dy)\n * using the token contracts.\n *\n * @param self Swap struct to read from\n * @param tokenIndexFrom the token to sell\n * @param tokenIndexTo the token to buy\n * @param dy the number of tokens to buy. If the token charges a fee on transfers,\n * use the amount that gets transferred after the fee.\n * @return dx the number of tokens the user have to deposit in the token's precision. ex WBTC -> 8\n * @return dxFee the associated fee in multiplied precision (POOL_PRECISION_DECIMALS)\n */\n function _calculateSwapInv(\n Swap storage self,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dy,\n uint256[] memory balances\n ) internal view returns (uint256 dx, uint256 dxFee) {\n require(tokenIndexFrom != tokenIndexTo, \"compare token to itself\");\n uint256[] memory multipliers = self.tokenPrecisionMultipliers;\n uint256[] memory xp = _xp(balances, multipliers);\n require(tokenIndexFrom < xp.length && tokenIndexTo < xp.length, \"index out of range\");\n\n uint256 a = _getAPrecise(self);\n uint256 d0 = getD(xp, a);\n\n xp[tokenIndexTo] = xp[tokenIndexTo] - (dy * multipliers[tokenIndexTo]);\n uint256 x = getYD(a, tokenIndexFrom, xp, d0);\n dx = x - xp[tokenIndexFrom] + 1;\n dxFee = (dx * self.swapFee) / FEE_DENOMINATOR;\n dx = (dx + dxFee) / multipliers[tokenIndexFrom];\n }\n\n /**\n * @notice A simple method to calculate amount of each underlying\n * tokens that is returned upon burning given amount of\n * LP tokens\n *\n * @param amount the amount of LP tokens that would to be burned on\n * withdrawal\n * @return array of amounts of tokens user will receive\n */\n function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) {\n return _calculateRemoveLiquidity(self.balances, amount, self.lpToken.totalSupply());\n }\n\n function _calculateRemoveLiquidity(\n uint256[] memory balances,\n uint256 amount,\n uint256 totalSupply\n ) internal pure returns (uint256[] memory) {\n require(amount <= totalSupply, \"exceed total supply\");\n\n uint256 numBalances = balances.length;\n uint256[] memory amounts = new uint256[](numBalances);\n\n for (uint256 i; i < numBalances; ) {\n amounts[i] = (balances[i] * amount) / totalSupply;\n\n unchecked {\n ++i;\n }\n }\n return amounts;\n }\n\n /**\n * @notice A simple method to calculate prices from deposits or\n * withdrawals, excluding fees but including slippage. This is\n * helpful as an input into the various \"min\" parameters on calls\n * to fight front-running\n *\n * @dev This shouldn't be used outside frontends for user estimates.\n *\n * @param self Swap struct to read from\n * @param amounts an array of token amounts to deposit or withdrawal,\n * corresponding to pooledTokens. The amount should be in each\n * pooled token's native precision. If a token charges a fee on transfers,\n * use the amount that gets transferred after the fee.\n * @param deposit whether this is a deposit or a withdrawal\n * @return if deposit was true, total amount of lp token that will be minted and if\n * deposit was false, total amount of lp token that will be burned\n */\n function calculateTokenAmount(\n Swap storage self,\n uint256[] calldata amounts,\n bool deposit\n ) external view returns (uint256) {\n uint256 a = _getAPrecise(self);\n uint256[] memory balances = self.balances;\n uint256[] memory multipliers = self.tokenPrecisionMultipliers;\n\n uint256 numBalances = balances.length;\n uint256 d0 = getD(_xp(balances, multipliers), a);\n for (uint256 i; i < numBalances; ) {\n if (deposit) {\n balances[i] = balances[i] + amounts[i];\n } else {\n balances[i] = balances[i] - amounts[i];\n }\n\n unchecked {\n ++i;\n }\n }\n uint256 d1 = getD(_xp(balances, multipliers), a);\n uint256 totalSupply = self.lpToken.totalSupply();\n\n if (deposit) {\n return ((d1 - d0) * totalSupply) / d0;\n } else {\n return ((d0 - d1) * totalSupply) / d0;\n }\n }\n\n /**\n * @notice return accumulated amount of admin fees of the token with given index\n * @param self Swap struct to read from\n * @param index Index of the pooled token\n * @return admin balance in the token's precision\n */\n function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) {\n require(index < self.pooledTokens.length, \"index out of range\");\n return self.adminFees[index];\n }\n\n /**\n * @notice internal helper function to calculate fee per token multiplier used in\n * swap fee calculations\n * @param swapFee swap fee for the tokens\n * @param numTokens number of tokens pooled\n */\n function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) {\n return (swapFee * numTokens) / ((numTokens - 1) * 4);\n }\n\n /*** STATE MODIFYING FUNCTIONS ***/\n\n /**\n * @notice swap two tokens in the pool\n * @param self Swap struct to read from and write to\n * @param tokenIndexFrom the token the user wants to sell\n * @param tokenIndexTo the token the user wants to buy\n * @param dx the amount of tokens the user wants to sell\n * @param minDy the min amount the user would like to receive, or revert.\n * @return amount of token user received on swap\n */\n function swap(\n Swap storage self,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dx,\n uint256 minDy\n ) external returns (uint256) {\n {\n IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];\n require(dx <= tokenFrom.balanceOf(msg.sender), \"swap more than you own\");\n // Transfer tokens first to see if a fee was charged on transfer\n uint256 beforeBalance = tokenFrom.balanceOf(address(this));\n tokenFrom.safeTransferFrom(msg.sender, address(this), dx);\n\n // Use the actual transferred amount for AMM math\n dx = tokenFrom.balanceOf(address(this)) - beforeBalance;\n }\n\n uint256 dy;\n uint256 dyFee;\n uint256[] memory balances = self.balances;\n (dy, dyFee) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx, balances);\n require(dy >= minDy, \"dy < minDy\");\n\n uint256 dyAdminFee = (dyFee * self.adminFee) / FEE_DENOMINATOR / self.tokenPrecisionMultipliers[tokenIndexTo];\n\n self.balances[tokenIndexFrom] = balances[tokenIndexFrom] + dx;\n self.balances[tokenIndexTo] = balances[tokenIndexTo] - dy - dyAdminFee;\n if (dyAdminFee != 0) {\n self.adminFees[tokenIndexTo] = self.adminFees[tokenIndexTo] + dyAdminFee;\n }\n\n self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy);\n\n emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo);\n\n return dy;\n }\n\n /**\n * @notice swap two tokens in the pool\n * @param self Swap struct to read from and write to\n * @param tokenIndexFrom the token the user wants to sell\n * @param tokenIndexTo the token the user wants to buy\n * @param dy the amount of tokens the user wants to buy\n * @param maxDx the max amount the user would like to send.\n * @return amount of token user have to transfer on swap\n */\n function swapOut(\n Swap storage self,\n uint8 tokenIndexFrom,\n uint8 tokenIndexTo,\n uint256 dy,\n uint256 maxDx\n ) external returns (uint256) {\n require(dy <= self.balances[tokenIndexTo], \">pool balance\");\n\n uint256 dx;\n uint256 dxFee;\n uint256[] memory balances = self.balances;\n (dx, dxFee) = _calculateSwapInv(self, tokenIndexFrom, tokenIndexTo, dy, balances);\n require(dx <= maxDx, \"dx > maxDx\");\n\n uint256 dxAdminFee = (dxFee * self.adminFee) / FEE_DENOMINATOR / self.tokenPrecisionMultipliers[tokenIndexFrom];\n\n self.balances[tokenIndexFrom] = balances[tokenIndexFrom] + dx - dxAdminFee;\n self.balances[tokenIndexTo] = balances[tokenIndexTo] - dy;\n if (dxAdminFee != 0) {\n self.adminFees[tokenIndexFrom] = self.adminFees[tokenIndexFrom] + dxAdminFee;\n }\n\n {\n IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom];\n require(dx <= tokenFrom.balanceOf(msg.sender), \"more than you own\");\n // Transfer tokens first to see if a fee was charged on transfer\n uint256 beforeBalance = tokenFrom.balanceOf(address(this));\n tokenFrom.safeTransferFrom(msg.sender, address(this), dx);\n\n // Use the actual transferred amount for AMM math\n require(dx == tokenFrom.balanceOf(address(this)) - beforeBalance, \"not support fee token\");\n }\n\n self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy);\n\n emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo);\n\n return dx;\n }\n\n /**\n * @notice Add liquidity to the pool\n * @param self Swap struct to read from and write to\n * @param amounts the amounts of each token to add, in their native precision\n * @param minToMint the minimum LP tokens adding this amount of liquidity\n * should mint, otherwise revert. Handy for front-running mitigation\n * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored.\n * @return amount of LP token user received\n */\n function addLiquidity(\n Swap storage self,\n uint256[] memory amounts,\n uint256 minToMint\n ) external returns (uint256) {\n uint256 numTokens = self.pooledTokens.length;\n require(amounts.length == numTokens, \"mismatch pooled tokens\");\n\n // current state\n ManageLiquidityInfo memory v = ManageLiquidityInfo(\n 0,\n 0,\n 0,\n _getAPrecise(self),\n self.lpToken,\n 0,\n self.balances,\n self.tokenPrecisionMultipliers\n );\n v.totalSupply = v.lpToken.totalSupply();\n if (v.totalSupply != 0) {\n v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA);\n }\n\n uint256[] memory newBalances = new uint256[](numTokens);\n\n for (uint256 i; i < numTokens; ) {\n require(v.totalSupply != 0 || amounts[i] != 0, \"!supply all tokens\");\n\n // Transfer tokens first to see if a fee was charged on transfer\n if (amounts[i] != 0) {\n IERC20 token = self.pooledTokens[i];\n uint256 beforeBalance = token.balanceOf(address(this));\n token.safeTransferFrom(msg.sender, address(this), amounts[i]);\n\n // Update the amounts[] with actual transfer amount\n amounts[i] = token.balanceOf(address(this)) - beforeBalance;\n }\n\n newBalances[i] = v.balances[i] + amounts[i];\n\n unchecked {\n ++i;\n }\n }\n\n // invariant after change\n v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA);\n require(v.d1 > v.d0, \"D should increase\");\n\n // updated to reflect fees and calculate the user's LP tokens\n v.d2 = v.d1;\n uint256[] memory fees = new uint256[](numTokens);\n\n if (v.totalSupply != 0) {\n uint256 feePerToken = _feePerToken(self.swapFee, numTokens);\n for (uint256 i; i < numTokens; ) {\n uint256 idealBalance = (v.d1 * v.balances[i]) / v.d0;\n fees[i] = (feePerToken * (idealBalance.difference(newBalances[i]))) / FEE_DENOMINATOR;\n uint256 adminFee = (fees[i] * self.adminFee) / FEE_DENOMINATOR;\n self.balances[i] = newBalances[i] - adminFee;\n self.adminFees[i] = self.adminFees[i] + adminFee;\n newBalances[i] = newBalances[i] - fees[i];\n\n unchecked {\n ++i;\n }\n }\n v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA);\n } else {\n // the initial depositor doesn't pay fees\n self.balances = newBalances;\n }\n\n uint256 toMint;\n if (v.totalSupply == 0) {\n toMint = v.d1;\n } else {\n toMint = ((v.d2 - v.d0) * v.totalSupply) / v.d0;\n }\n\n require(toMint >= minToMint, \"mint < min\");\n\n // mint the user's LP tokens\n v.lpToken.mint(msg.sender, toMint);\n\n emit AddLiquidity(msg.sender, amounts, fees, v.d1, v.totalSupply + toMint);\n\n return toMint;\n }\n\n /**\n * @notice Burn LP tokens to remove liquidity from the pool.\n * @dev Liquidity can always be removed, even when the pool is paused.\n * @param self Swap struct to read from and write to\n * @param amount the amount of LP tokens to burn\n * @param minAmounts the minimum amounts of each token in the pool\n * acceptable for this burn. Useful as a front-running mitigation\n * @return amounts of tokens the user received\n */\n function removeLiquidity(\n Swap storage self,\n uint256 amount,\n uint256[] calldata minAmounts\n ) external returns (uint256[] memory) {\n LPToken lpToken = self.lpToken;\n require(amount <= lpToken.balanceOf(msg.sender), \">LP.balanceOf\");\n uint256 numTokens = self.pooledTokens.length;\n require(minAmounts.length == numTokens, \"mismatch poolTokens\");\n\n uint256[] memory balances = self.balances;\n uint256 totalSupply = lpToken.totalSupply();\n\n uint256[] memory amounts = _calculateRemoveLiquidity(balances, amount, totalSupply);\n\n uint256 numAmounts = amounts.length;\n for (uint256 i; i < numAmounts; ) {\n require(amounts[i] >= minAmounts[i], \"amounts[i] < minAmounts[i]\");\n self.balances[i] = balances[i] - amounts[i];\n self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]);\n\n unchecked {\n ++i;\n }\n }\n\n lpToken.burnFrom(msg.sender, amount);\n\n emit RemoveLiquidity(msg.sender, amounts, totalSupply - amount);\n\n return amounts;\n }\n\n /**\n * @notice Remove liquidity from the pool all in one token.\n * @param self Swap struct to read from and write to\n * @param tokenAmount the amount of the lp tokens to burn\n * @param tokenIndex the index of the token you want to receive\n * @param minAmount the minimum amount to withdraw, otherwise revert\n * @return amount chosen token that user received\n */\n function removeLiquidityOneToken(\n Swap storage self,\n uint256 tokenAmount,\n uint8 tokenIndex,\n uint256 minAmount\n ) external returns (uint256) {\n LPToken lpToken = self.lpToken;\n\n require(tokenAmount <= lpToken.balanceOf(msg.sender), \">LP.balanceOf\");\n uint256 numTokens = self.pooledTokens.length;\n require(tokenIndex < numTokens, \"not found\");\n\n uint256 totalSupply = lpToken.totalSupply();\n\n (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken(self, tokenAmount, tokenIndex, totalSupply);\n\n require(dy >= minAmount, \"dy < minAmount\");\n\n uint256 adminFee = (dyFee * self.adminFee) / FEE_DENOMINATOR;\n self.balances[tokenIndex] = self.balances[tokenIndex] - (dy + adminFee);\n if (adminFee != 0) {\n self.adminFees[tokenIndex] = self.adminFees[tokenIndex] + adminFee;\n }\n lpToken.burnFrom(msg.sender, tokenAmount);\n self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy);\n\n emit RemoveLiquidityOne(msg.sender, tokenAmount, totalSupply, tokenIndex, dy);\n\n return dy;\n }\n\n /**\n * @notice Remove liquidity from the pool, weighted differently than the\n * pool's current balances.\n *\n * @param self Swap struct to read from and write to\n * @param amounts how much of each token to withdraw\n * @param maxBurnAmount the max LP token provider is willing to pay to\n * remove liquidity. Useful as a front-running mitigation.\n * @return actual amount of LP tokens burned in the withdrawal\n */\n function removeLiquidityImbalance(\n Swap storage self,\n uint256[] memory amounts,\n uint256 maxBurnAmount\n ) external returns (uint256) {\n ManageLiquidityInfo memory v = ManageLiquidityInfo(\n 0,\n 0,\n 0,\n _getAPrecise(self),\n self.lpToken,\n 0,\n self.balances,\n self.tokenPrecisionMultipliers\n );\n v.totalSupply = v.lpToken.totalSupply();\n\n uint256 numTokens = self.pooledTokens.length;\n uint256 numAmounts = amounts.length;\n require(numAmounts == numTokens, \"mismatch pool tokens\");\n\n require(maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, \">LP.balanceOf\");\n\n uint256 feePerToken = _feePerToken(self.swapFee, numTokens);\n uint256[] memory fees = new uint256[](numTokens);\n {\n uint256[] memory balances1 = new uint256[](numTokens);\n v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA);\n for (uint256 i; i < numTokens; ) {\n require(v.balances[i] >= amounts[i], \"withdraw more than available\");\n\n unchecked {\n balances1[i] = v.balances[i] - amounts[i];\n ++i;\n }\n }\n v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA);\n\n for (uint256 i; i < numTokens; ) {\n {\n uint256 idealBalance = (v.d1 * v.balances[i]) / v.d0;\n uint256 difference = idealBalance.difference(balances1[i]);\n fees[i] = (feePerToken * difference) / FEE_DENOMINATOR;\n }\n uint256 adminFee = (fees[i] * self.adminFee) / FEE_DENOMINATOR;\n self.balances[i] = balances1[i] - adminFee;\n self.adminFees[i] = self.adminFees[i] + adminFee;\n balances1[i] = balances1[i] - fees[i];\n\n unchecked {\n ++i;\n }\n }\n\n v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA);\n }\n uint256 tokenAmount = ((v.d0 - v.d2) * v.totalSupply) / v.d0;\n require(tokenAmount != 0, \"!zero amount\");\n tokenAmount = tokenAmount + 1;\n\n require(tokenAmount <= maxBurnAmount, \"tokenAmount > maxBurnAmount\");\n\n v.lpToken.burnFrom(msg.sender, tokenAmount);\n\n for (uint256 i; i < numTokens; ) {\n self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]);\n\n unchecked {\n ++i;\n }\n }\n\n emit RemoveLiquidityImbalance(msg.sender, amounts, fees, v.d1, v.totalSupply - tokenAmount);\n\n return tokenAmount;\n }\n\n /**\n * @notice withdraw all admin fees to a given address\n * @param self Swap struct to withdraw fees from\n * @param to Address to send the fees to\n */\n function withdrawAdminFees(Swap storage self, address to) external {\n uint256 numTokens = self.pooledTokens.length;\n for (uint256 i; i < numTokens; ) {\n IERC20 token = self.pooledTokens[i];\n uint256 balance = self.adminFees[i];\n if (balance != 0) {\n self.adminFees[i] = 0;\n token.safeTransfer(to, balance);\n }\n\n unchecked {\n ++i;\n }\n }\n }\n\n /**\n * @notice Sets the admin fee\n * @dev adminFee cannot be higher than 100% of the swap fee\n * @param self Swap struct to update\n * @param newAdminFee new admin fee to be applied on future transactions\n */\n function setAdminFee(Swap storage self, uint256 newAdminFee) external {\n require(newAdminFee <= MAX_ADMIN_FEE, \"too high\");\n self.adminFee = newAdminFee;\n\n emit NewAdminFee(newAdminFee);\n }\n\n /**\n * @notice update the swap fee\n * @dev fee cannot be higher than 1% of each swap\n * @param self Swap struct to update\n * @param newSwapFee new swap fee to be applied on future transactions\n */\n function setSwapFee(Swap storage self, uint256 newSwapFee) external {\n require(newSwapFee <= MAX_SWAP_FEE, \"too high\");\n self.swapFee = newSwapFee;\n\n emit NewSwapFee(newSwapFee);\n }\n\n /**\n * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_\n * Checks if the change is too rapid, and commits the new A value only when it falls under\n * the limit range.\n * @param self Swap struct to update\n * @param futureA_ the new A to ramp towards\n * @param futureTime_ timestamp when the new A should be reached\n */\n function rampA(\n Swap storage self,\n uint256 futureA_,\n uint256 futureTime_\n ) external {\n require(block.timestamp >= self.initialATime + 1 days, \"Wait 1 day before starting ramp\");\n require(futureTime_ >= block.timestamp + MIN_RAMP_TIME, \"Insufficient ramp time\");\n require(futureA_ != 0 && futureA_ < MAX_A, \"futureA_ must be > 0 and < MAX_A\");\n\n uint256 initialAPrecise = _getAPrecise(self);\n uint256 futureAPrecise = futureA_ * A_PRECISION;\n\n if (futureAPrecise < initialAPrecise) {\n require(futureAPrecise * MAX_A_CHANGE >= initialAPrecise, \"futureA_ is too small\");\n } else {\n require(futureAPrecise <= initialAPrecise * MAX_A_CHANGE, \"futureA_ is too large\");\n }\n\n self.initialA = initialAPrecise;\n self.futureA = futureAPrecise;\n self.initialATime = block.timestamp;\n self.futureATime = futureTime_;\n\n emit RampA(initialAPrecise, futureAPrecise, block.timestamp, futureTime_);\n }\n\n /**\n * @notice Stops ramping A immediately. Once this function is called, rampA()\n * cannot be called for another 24 hours\n * @param self Swap struct to update\n */\n function stopRampA(Swap storage self) external {\n require(self.futureATime > block.timestamp, \"Ramp is already stopped\");\n\n uint256 currentA = _getAPrecise(self);\n self.initialA = currentA;\n self.futureA = currentA;\n self.initialATime = block.timestamp;\n self.futureATime = block.timestamp;\n\n emit StopRampA(currentA, block.timestamp);\n }\n}\n" } } }