{ "language": "Solidity", "sources": { "@1inch/erc20-pods/contracts/ERC20Pods.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@1inch/solidity-utils/contracts/libraries/AddressSet.sol\";\n\nimport \"./interfaces/IERC20Pods.sol\";\nimport \"./interfaces/IPod.sol\";\nimport \"./libs/ReentrancyGuard.sol\";\n\nabstract contract ERC20Pods is ERC20, IERC20Pods, ReentrancyGuardExt {\n using AddressSet for AddressSet.Data;\n using AddressArray for AddressArray.Data;\n using ReentrancyGuardLib for ReentrancyGuardLib.Data;\n\n error PodAlreadyAdded();\n error PodNotFound();\n error InvalidPodAddress();\n error PodsLimitReachedForAccount();\n error InsufficientGas();\n error ZeroPodsLimit();\n\n uint256 public immutable podsLimit;\n uint256 public immutable podCallGasLimit;\n\n ReentrancyGuardLib.Data private _guard;\n mapping(address => AddressSet.Data) private _pods;\n\n constructor(uint256 podsLimit_, uint256 podCallGasLimit_) {\n if (podsLimit_ == 0) revert ZeroPodsLimit();\n podsLimit = podsLimit_;\n podCallGasLimit = podCallGasLimit_;\n _guard.init();\n }\n\n function hasPod(address account, address pod) public view virtual returns(bool) {\n return _pods[account].contains(pod);\n }\n\n function podsCount(address account) public view virtual returns(uint256) {\n return _pods[account].length();\n }\n\n function podAt(address account, uint256 index) public view virtual returns(address) {\n return _pods[account].at(index);\n }\n\n function pods(address account) public view virtual returns(address[] memory) {\n return _pods[account].items.get();\n }\n\n function balanceOf(address account) public nonReentrantView(_guard) view override(IERC20, ERC20) virtual returns(uint256) {\n return super.balanceOf(account);\n }\n\n function podBalanceOf(address pod, address account) public nonReentrantView(_guard) view virtual returns(uint256) {\n if (hasPod(account, pod)) {\n return super.balanceOf(account);\n }\n return 0;\n }\n\n function addPod(address pod) public virtual {\n _addPod(msg.sender, pod);\n }\n\n function removePod(address pod) public virtual {\n _removePod(msg.sender, pod);\n }\n\n function removeAllPods() public virtual {\n _removeAllPods(msg.sender);\n }\n\n function _addPod(address account, address pod) internal virtual {\n if (pod == address(0)) revert InvalidPodAddress();\n if (!_pods[account].add(pod)) revert PodAlreadyAdded();\n if (_pods[account].length() > podsLimit) revert PodsLimitReachedForAccount();\n\n emit PodAdded(account, pod);\n uint256 balance = balanceOf(account);\n if (balance > 0) {\n _updateBalances(pod, address(0), account, balance);\n }\n }\n\n function _removePod(address account, address pod) internal virtual {\n if (!_pods[account].remove(pod)) revert PodNotFound();\n\n emit PodRemoved(account, pod);\n uint256 balance = balanceOf(account);\n if (balance > 0) {\n _updateBalances(pod, account, address(0), balance);\n }\n }\n\n function _removeAllPods(address account) internal virtual {\n address[] memory items = _pods[account].items.get();\n uint256 balance = balanceOf(account);\n unchecked {\n for (uint256 i = items.length; i > 0; i--) {\n _pods[account].remove(items[i - 1]);\n emit PodRemoved(account, items[i - 1]);\n if (balance > 0) {\n _updateBalances(items[i - 1], account, address(0), balance);\n }\n }\n }\n }\n\n /// @notice Assembly implementation of the gas limited call to avoid return gas bomb,\n // moreover call to a destructed pod would also revert even inside try-catch block in Solidity 0.8.17\n /// @dev try IPod(pod).updateBalances{gas: _POD_CALL_GAS_LIMIT}(from, to, amount) {} catch {}\n function _updateBalances(address pod, address from, address to, uint256 amount) private {\n bytes4 selector = IPod.updateBalances.selector;\n bytes4 exception = InsufficientGas.selector;\n uint256 gasLimit = podCallGasLimit;\n assembly { // solhint-disable-line no-inline-assembly\n let ptr := mload(0x40)\n mstore(ptr, selector)\n mstore(add(ptr, 0x04), from)\n mstore(add(ptr, 0x24), to)\n mstore(add(ptr, 0x44), amount)\n\n if lt(div(mul(gas(), 63), 64), gasLimit) {\n mstore(0, exception)\n revert(0, 4)\n }\n pop(call(gasLimit, pod, 0, ptr, 0x64, 0, 0))\n }\n }\n\n // ERC20 Overrides\n\n function _afterTokenTransfer(address from, address to, uint256 amount) internal nonReentrant(_guard) override virtual {\n super._afterTokenTransfer(from, to, amount);\n\n unchecked {\n if (amount > 0 && from != to) {\n address[] memory a = _pods[from].items.get();\n address[] memory b = _pods[to].items.get();\n uint256 aLength = a.length;\n uint256 bLength = b.length;\n\n for (uint256 i = 0; i < aLength; i++) {\n address pod = a[i];\n\n uint256 j;\n for (j = 0; j < bLength; j++) {\n if (pod == b[j]) {\n // Both parties are participating of the same Pod\n _updateBalances(pod, from, to, amount);\n b[j] = address(0);\n break;\n }\n }\n\n if (j == bLength) {\n // Sender is participating in a Pod, but receiver is not\n _updateBalances(pod, from, address(0), amount);\n }\n }\n\n for (uint256 j = 0; j < bLength; j++) {\n address pod = b[j];\n if (pod != address(0)) {\n // Receiver is participating in a Pod, but sender is not\n _updateBalances(pod, address(0), to, amount);\n }\n }\n }\n }\n }\n}\n" }, "@1inch/erc20-pods/contracts/interfaces/IERC20Pods.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\n\ninterface IERC20Pods is IERC20 {\n event PodAdded(address account, address pod);\n event PodRemoved(address account, address pod);\n\n function hasPod(address account, address pod) external view returns(bool);\n function podsCount(address account) external view returns(uint256);\n function podAt(address account, uint256 index) external view returns(address);\n function pods(address account) external view returns(address[] memory);\n function podBalanceOf(address pod, address account) external view returns(uint256);\n\n function addPod(address pod) external;\n function removePod(address pod) external;\n function removeAllPods() external;\n}\n" }, "@1inch/erc20-pods/contracts/interfaces/IPod.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\ninterface IPod {\n function updateBalances(address from, address to, uint256 amount) external;\n}\n" }, "@1inch/erc20-pods/contracts/libs/ReentrancyGuard.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nlibrary ReentrancyGuardLib {\n error ReentrantCall();\n\n uint256 private constant _NOT_ENTERED = 1;\n uint256 private constant _ENTERED = 2;\n\n struct Data {\n uint256 _status;\n }\n\n function init(Data storage self) internal {\n self._status = _NOT_ENTERED;\n }\n\n function enter(Data storage self) internal {\n if (self._status == _ENTERED) revert ReentrantCall();\n self._status = _ENTERED;\n }\n\n function exit(Data storage self) internal {\n self._status = _NOT_ENTERED;\n }\n\n function check(Data storage self) internal view returns (bool) {\n return self._status == _ENTERED;\n }\n}\n\ncontract ReentrancyGuardExt {\n using ReentrancyGuardLib for ReentrancyGuardLib.Data;\n\n modifier nonReentrant(ReentrancyGuardLib.Data storage self) {\n self.enter();\n _;\n self.exit();\n }\n\n modifier nonReentrantView(ReentrancyGuardLib.Data storage self) {\n if (self.check()) revert ReentrancyGuardLib.ReentrantCall();\n _;\n }\n}\n" }, "@1inch/erc20-pods/contracts/mocks/ERC20PodsMock.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"../ERC20Pods.sol\";\n\ncontract ERC20PodsMock is ERC20Pods {\n constructor(string memory name, string memory symbol, uint256 podsLimit, uint256 podCallGasLimit)\n ERC20(name, symbol)\n ERC20Pods(podsLimit, podCallGasLimit)\n {} // solhint-disable-line no-empty-blocks\n\n function mint(address account, uint256 amount) external {\n _mint(account, amount);\n }\n}\n" }, "@1inch/erc20-pods/contracts/Pod.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./interfaces/IPod.sol\";\nimport \"./interfaces/IERC20Pods.sol\";\n\nabstract contract Pod is IPod {\n error AccessDenied();\n\n IERC20Pods public immutable token;\n\n modifier onlyToken {\n if (msg.sender != address(token)) revert AccessDenied();\n _;\n }\n\n constructor(IERC20Pods token_) {\n token = token_;\n }\n\n function updateBalances(address from, address to, uint256 amount) external onlyToken {\n _updateBalances(from, to, amount);\n }\n\n function _updateBalances(address from, address to, uint256 amount) internal virtual;\n}\n" }, "@1inch/solidity-utils/contracts/interfaces/IDaiLikePermit.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\npragma abicoder v1;\n\ninterface IDaiLikePermit {\n function permit(\n address holder,\n address spender,\n uint256 nonce,\n uint256 expiry,\n bool allowed,\n uint8 v,\n bytes32 r,\n bytes32 s\n ) external;\n}\n" }, "@1inch/solidity-utils/contracts/libraries/AddressArray.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\npragma abicoder v1;\n\n/// @title Library that implements address array on mapping, stores array length at 0 index.\nlibrary AddressArray {\n error IndexOutOfBounds();\n error PopFromEmptyArray();\n error OutputArrayTooSmall();\n\n /// @dev Data struct containing raw mapping.\n struct Data {\n mapping(uint256 => uint256) _raw;\n }\n\n /// @dev Length of array.\n function length(Data storage self) internal view returns (uint256) {\n return self._raw[0] >> 160;\n }\n\n /// @dev Returns data item from `self` storage at `i`.\n function at(Data storage self, uint256 i) internal view returns (address) {\n return address(uint160(self._raw[i]));\n }\n\n /// @dev Returns list of addresses from storage `self`.\n function get(Data storage self) internal view returns (address[] memory arr) {\n uint256 lengthAndFirst = self._raw[0];\n arr = new address[](lengthAndFirst >> 160);\n _get(self, arr, lengthAndFirst);\n }\n\n /// @dev Puts list of addresses from `self` storage into `output` array.\n function get(Data storage self, address[] memory output) internal view returns (address[] memory) {\n return _get(self, output, self._raw[0]);\n }\n\n function _get(\n Data storage self,\n address[] memory output,\n uint256 lengthAndFirst\n ) private view returns (address[] memory) {\n uint256 len = lengthAndFirst >> 160;\n if (len > output.length) revert OutputArrayTooSmall();\n if (len > 0) {\n output[0] = address(uint160(lengthAndFirst));\n unchecked {\n for (uint256 i = 1; i < len; i++) {\n output[i] = address(uint160(self._raw[i]));\n }\n }\n }\n return output;\n }\n\n /// @dev Array push back `account` operation on storage `self`.\n function push(Data storage self, address account) internal returns (uint256) {\n unchecked {\n uint256 lengthAndFirst = self._raw[0];\n uint256 len = lengthAndFirst >> 160;\n if (len == 0) {\n self._raw[0] = (1 << 160) + uint160(account);\n } else {\n self._raw[0] = lengthAndFirst + (1 << 160);\n self._raw[len] = uint160(account);\n }\n return len + 1;\n }\n }\n\n /// @dev Array pop back operation for storage `self`.\n function pop(Data storage self) internal {\n unchecked {\n uint256 lengthAndFirst = self._raw[0];\n uint256 len = lengthAndFirst >> 160;\n if (len == 0) revert PopFromEmptyArray();\n self._raw[len - 1] = 0;\n if (len > 1) {\n self._raw[0] = lengthAndFirst - (1 << 160);\n }\n }\n }\n\n /// @dev Set element for storage `self` at `index` to `account`.\n function set(\n Data storage self,\n uint256 index,\n address account\n ) internal {\n uint256 len = length(self);\n if (index >= len) revert IndexOutOfBounds();\n\n if (index == 0) {\n self._raw[0] = (len << 160) | uint160(account);\n } else {\n self._raw[index] = uint160(account);\n }\n }\n}\n" }, "@1inch/solidity-utils/contracts/libraries/AddressSet.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\npragma abicoder v1;\n\nimport \"./AddressArray.sol\";\n\n/** @title Library that is using AddressArray library for AddressArray.Data\n * and allows Set operations on address storage data:\n * 1. add\n * 2. remove\n * 3. contains\n */\nlibrary AddressSet {\n using AddressArray for AddressArray.Data;\n\n /** @dev Data struct from AddressArray.Data items\n * and lookup mapping address => index in data array.\n */\n struct Data {\n AddressArray.Data items;\n mapping(address => uint256) lookup;\n }\n\n /// @dev Length of data storage.\n function length(Data storage s) internal view returns (uint256) {\n return s.items.length();\n }\n\n /// @dev Returns data item from `s` storage at `index`.\n function at(Data storage s, uint256 index) internal view returns (address) {\n return s.items.at(index);\n }\n\n /// @dev Returns true if storage `s` has `item`.\n function contains(Data storage s, address item) internal view returns (bool) {\n return s.lookup[item] != 0;\n }\n\n /// @dev Adds `item` into storage `s` and returns true if successful.\n function add(Data storage s, address item) internal returns (bool) {\n if (s.lookup[item] > 0) {\n return false;\n }\n s.lookup[item] = s.items.push(item);\n return true;\n }\n\n /// @dev Removes `item` from storage `s` and returns true if successful.\n function remove(Data storage s, address item) internal returns (bool) {\n uint256 index = s.lookup[item];\n if (index == 0) {\n return false;\n }\n if (index < s.items.length()) {\n unchecked {\n address lastItem = s.items.at(s.items.length() - 1);\n s.items.set(index - 1, lastItem);\n s.lookup[lastItem] = index;\n }\n }\n s.items.pop();\n delete s.lookup[item];\n return true;\n }\n}\n" }, "@1inch/solidity-utils/contracts/libraries/RevertReasonForwarder.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\npragma abicoder v1;\n\n/// @title Revert reason forwarder.\nlibrary RevertReasonForwarder {\n /// @dev Forwards latest externall call revert.\n function reRevert() internal pure {\n // bubble up revert reason from latest external call\n /// @solidity memory-safe-assembly\n assembly { // solhint-disable-line no-inline-assembly\n let ptr := mload(0x40)\n returndatacopy(ptr, 0, returndatasize())\n revert(ptr, returndatasize())\n }\n }\n}\n" }, "@1inch/solidity-utils/contracts/libraries/SafeERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\npragma abicoder v1;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol\";\nimport \"../interfaces/IDaiLikePermit.sol\";\nimport \"../libraries/RevertReasonForwarder.sol\";\n\n/// @title Implements efficient safe methods for ERC20 interface.\nlibrary SafeERC20 {\n error SafeTransferFailed();\n error SafeTransferFromFailed();\n error ForceApproveFailed();\n error SafeIncreaseAllowanceFailed();\n error SafeDecreaseAllowanceFailed();\n error SafePermitBadLength();\n\n /// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.\n function safeTransferFrom(\n IERC20 token,\n address from,\n address to,\n uint256 amount\n ) internal {\n bytes4 selector = token.transferFrom.selector;\n bool success;\n /// @solidity memory-safe-assembly\n assembly { // solhint-disable-line no-inline-assembly\n let data := mload(0x40)\n\n mstore(data, selector)\n mstore(add(data, 0x04), from)\n mstore(add(data, 0x24), to)\n mstore(add(data, 0x44), amount)\n success := call(gas(), token, 0, data, 100, 0x0, 0x20)\n if success {\n switch returndatasize()\n case 0 {\n success := gt(extcodesize(token), 0)\n }\n default {\n success := and(gt(returndatasize(), 31), eq(mload(0), 1))\n }\n }\n }\n if (!success) revert SafeTransferFromFailed();\n }\n\n /// @dev Ensures method do not revert or return boolean `true`, admits call to non-smart-contract.\n function safeTransfer(\n IERC20 token,\n address to,\n uint256 value\n ) internal {\n if (!_makeCall(token, token.transfer.selector, to, value)) {\n revert SafeTransferFailed();\n }\n }\n\n /// @dev If `approve(from, to, amount)` fails, try to `approve(from, to, 0)` before retry.\n function forceApprove(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n if (!_makeCall(token, token.approve.selector, spender, value)) {\n if (\n !_makeCall(token, token.approve.selector, spender, 0) ||\n !_makeCall(token, token.approve.selector, spender, value)\n ) {\n revert ForceApproveFailed();\n }\n }\n }\n\n /// @dev Allowance increase with safe math check.\n function safeIncreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 allowance = token.allowance(address(this), spender);\n if (value > type(uint256).max - allowance) revert SafeIncreaseAllowanceFailed();\n forceApprove(token, spender, allowance + value);\n }\n\n /// @dev Allowance decrease with safe math check.\n function safeDecreaseAllowance(\n IERC20 token,\n address spender,\n uint256 value\n ) internal {\n uint256 allowance = token.allowance(address(this), spender);\n if (value > allowance) revert SafeDecreaseAllowanceFailed();\n forceApprove(token, spender, allowance - value);\n }\n\n /// @dev Calls either ERC20 or Dai `permit` for `token`, if unsuccessful forwards revert from external call.\n function safePermit(IERC20 token, bytes calldata permit) internal {\n if (!tryPermit(token, permit)) RevertReasonForwarder.reRevert();\n }\n\n function tryPermit(IERC20 token, bytes calldata permit) internal returns(bool) {\n if (permit.length == 32 * 7) {\n return _makeCalldataCall(token, IERC20Permit.permit.selector, permit);\n }\n if (permit.length == 32 * 8) {\n return _makeCalldataCall(token, IDaiLikePermit.permit.selector, permit);\n }\n revert SafePermitBadLength();\n }\n\n function _makeCall(\n IERC20 token,\n bytes4 selector,\n address to,\n uint256 amount\n ) private returns (bool success) {\n /// @solidity memory-safe-assembly\n assembly { // solhint-disable-line no-inline-assembly\n let data := mload(0x40)\n\n mstore(data, selector)\n mstore(add(data, 0x04), to)\n mstore(add(data, 0x24), amount)\n success := call(gas(), token, 0, data, 0x44, 0x0, 0x20)\n if success {\n switch returndatasize()\n case 0 {\n success := gt(extcodesize(token), 0)\n }\n default {\n success := and(gt(returndatasize(), 31), eq(mload(0), 1))\n }\n }\n }\n }\n\n function _makeCalldataCall(\n IERC20 token,\n bytes4 selector,\n bytes calldata args\n ) private returns (bool success) {\n /// @solidity memory-safe-assembly\n assembly { // solhint-disable-line no-inline-assembly\n let len := add(4, args.length)\n let data := mload(0x40)\n\n mstore(data, selector)\n calldatacopy(add(data, 0x04), args.offset, args.length)\n success := call(gas(), token, 0, data, len, 0x0, 0x20)\n if success {\n switch returndatasize()\n case 0 {\n success := gt(extcodesize(token), 0)\n }\n default {\n success := and(gt(returndatasize(), 31), eq(mload(0), 1))\n }\n }\n }\n }\n}\n" }, "@1inch/solidity-utils/contracts/mocks/TokenMock.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\npragma abicoder v1;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\n\ncontract TokenMock is ERC20, Ownable {\n // solhint-disable-next-line no-empty-blocks\n constructor(string memory name, string memory symbol) ERC20(name, symbol) {}\n\n function mint(address account, uint256 amount) external onlyOwner {\n _mint(account, amount);\n }\n\n function burn(address account, uint256 amount) external onlyOwner {\n _burn(account, amount);\n }\n}\n" }, "@openzeppelin/contracts/access/Ownable.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/Context.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 Ownable is Context {\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 constructor() {\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" }, "@openzeppelin/contracts/token/ERC20/ERC20.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (token/ERC20/ERC20.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC20.sol\";\nimport \"./extensions/IERC20Metadata.sol\";\nimport \"../../utils/Context.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.openzeppelin.com/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 ERC20 is Context, IERC20, IERC20Metadata {\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 constructor(string memory name_, string memory symbol_) {\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 // Overflow not possible: the sum of all balances is capped by totalSupply, and the sum is preserved by\n // decrementing then incrementing.\n _balances[to] += amount;\n }\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 unchecked {\n // Overflow not possible: balance + amount is at most totalSupply + amount, which is checked above.\n _balances[account] += amount;\n }\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 // Overflow not possible: amount <= accountBalance <= totalSupply.\n _totalSupply -= amount;\n }\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" }, "@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/extensions/IERC20Metadata.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 \"../IERC20.sol\";\n\n/**\n * @dev Interface for the optional metadata functions from the ERC20 standard.\n *\n * _Available since v4.1._\n */\ninterface IERC20Metadata is IERC20 {\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/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/utils/Address.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.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 functionCallWithValue(target, data, 0, \"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 (bool success, bytes memory returndata) = target.call{value: value}(data);\n return verifyCallResultFromTarget(target, 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 (bool success, bytes memory returndata) = target.staticcall(data);\n return verifyCallResultFromTarget(target, 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 (bool success, bytes memory returndata) = target.delegatecall(data);\n return verifyCallResultFromTarget(target, success, returndata, errorMessage);\n }\n\n /**\n * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling\n * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract.\n *\n * _Available since v4.8._\n */\n function verifyCallResultFromTarget(\n address target,\n bool success,\n bytes memory returndata,\n string memory errorMessage\n ) internal view returns (bytes memory) {\n if (success) {\n if (returndata.length == 0) {\n // only check isContract if the call was successful and the return data is empty\n // otherwise we already know that it was a contract\n require(isContract(target), \"Address: call to non-contract\");\n }\n return returndata;\n } else {\n _revert(returndata, errorMessage);\n }\n }\n\n /**\n * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the\n * revert reason or 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 _revert(returndata, errorMessage);\n }\n }\n\n function _revert(bytes memory returndata, string memory errorMessage) private pure {\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" }, "@openzeppelin/contracts/utils/Context.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)\n\npragma solidity ^0.8.0;\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 Context {\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" }, "@openzeppelin/contracts/utils/math/Math.sol": { "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n enum Rounding {\n Down, // Toward negative infinity\n Up, // Toward infinity\n Zero // Toward zero\n }\n\n /**\n * @dev Returns the largest of two numbers.\n */\n function max(uint256 a, uint256 b) internal pure returns (uint256) {\n return a > b ? a : b;\n }\n\n /**\n * @dev Returns the smallest of two numbers.\n */\n function min(uint256 a, uint256 b) internal pure returns (uint256) {\n return a < b ? a : b;\n }\n\n /**\n * @dev Returns the average of two numbers. The result is rounded towards\n * zero.\n */\n function average(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b) / 2 can overflow.\n return (a & b) + (a ^ b) / 2;\n }\n\n /**\n * @dev Returns the ceiling of the division of two numbers.\n *\n * This differs from standard division with `/` in that it rounds up instead\n * of rounding down.\n */\n function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n // (a + b - 1) / b can overflow on addition, so we distribute.\n return a == 0 ? 0 : (a - 1) / b + 1;\n }\n\n /**\n * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n * with further edits by Uniswap Labs also under MIT license.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator\n ) internal pure returns (uint256 result) {\n unchecked {\n // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n // variables such that product = prod1 * 2^256 + prod0.\n uint256 prod0; // Least significant 256 bits of the product\n uint256 prod1; // Most significant 256 bits of the product\n assembly {\n let mm := mulmod(x, y, not(0))\n prod0 := mul(x, y)\n prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n }\n\n // Handle non-overflow cases, 256 by 256 division.\n if (prod1 == 0) {\n return prod0 / denominator;\n }\n\n // Make sure the result is less than 2^256. Also prevents denominator == 0.\n require(denominator > prod1);\n\n ///////////////////////////////////////////////\n // 512 by 256 division.\n ///////////////////////////////////////////////\n\n // Make division exact by subtracting the remainder from [prod1 prod0].\n uint256 remainder;\n assembly {\n // Compute remainder using mulmod.\n remainder := mulmod(x, y, denominator)\n\n // Subtract 256 bit number from 512 bit number.\n prod1 := sub(prod1, gt(remainder, prod0))\n prod0 := sub(prod0, remainder)\n }\n\n // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n // See https://cs.stackexchange.com/q/138556/92363.\n\n // Does not overflow because the denominator cannot be zero at this stage in the function.\n uint256 twos = denominator & (~denominator + 1);\n assembly {\n // Divide denominator by twos.\n denominator := div(denominator, twos)\n\n // Divide [prod1 prod0] by twos.\n prod0 := div(prod0, twos)\n\n // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n twos := add(div(sub(0, twos), twos), 1)\n }\n\n // Shift in bits from prod1 into prod0.\n prod0 |= prod1 * twos;\n\n // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n // four bits. That is, denominator * inv = 1 mod 2^4.\n uint256 inverse = (3 * denominator) ^ 2;\n\n // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n // in modular arithmetic, doubling the correct bits in each step.\n inverse *= 2 - denominator * inverse; // inverse mod 2^8\n inverse *= 2 - denominator * inverse; // inverse mod 2^16\n inverse *= 2 - denominator * inverse; // inverse mod 2^32\n inverse *= 2 - denominator * inverse; // inverse mod 2^64\n inverse *= 2 - denominator * inverse; // inverse mod 2^128\n inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n // is no longer required.\n result = prod0 * inverse;\n return result;\n }\n }\n\n /**\n * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n */\n function mulDiv(\n uint256 x,\n uint256 y,\n uint256 denominator,\n Rounding rounding\n ) internal pure returns (uint256) {\n uint256 result = mulDiv(x, y, denominator);\n if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n result += 1;\n }\n return result;\n }\n\n /**\n * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n *\n * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n */\n function sqrt(uint256 a) internal pure returns (uint256) {\n if (a == 0) {\n return 0;\n }\n\n // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n //\n // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n //\n // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n //\n // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1 << (log2(a) >> 1);\n\n // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n // into the expected uint128 result.\n unchecked {\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n result = (result + a / result) >> 1;\n return min(result, a / result);\n }\n }\n\n /**\n * @notice Calculates sqrt(a), following the selected rounding direction.\n */\n function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = sqrt(a);\n return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 2, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 128;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 64;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 32;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 16;\n }\n if (value >> 8 > 0) {\n value >>= 8;\n result += 8;\n }\n if (value >> 4 > 0) {\n value >>= 4;\n result += 4;\n }\n if (value >> 2 > 0) {\n value >>= 2;\n result += 2;\n }\n if (value >> 1 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log2(value);\n return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 10, rounded down, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >= 10**64) {\n value /= 10**64;\n result += 64;\n }\n if (value >= 10**32) {\n value /= 10**32;\n result += 32;\n }\n if (value >= 10**16) {\n value /= 10**16;\n result += 16;\n }\n if (value >= 10**8) {\n value /= 10**8;\n result += 8;\n }\n if (value >= 10**4) {\n value /= 10**4;\n result += 4;\n }\n if (value >= 10**2) {\n value /= 10**2;\n result += 2;\n }\n if (value >= 10**1) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log10(value);\n return result + (rounding == Rounding.Up && 10**result < value ? 1 : 0);\n }\n }\n\n /**\n * @dev Return the log in base 256, rounded down, of a positive value.\n * Returns 0 if given 0.\n *\n * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n */\n function log256(uint256 value) internal pure returns (uint256) {\n uint256 result = 0;\n unchecked {\n if (value >> 128 > 0) {\n value >>= 128;\n result += 16;\n }\n if (value >> 64 > 0) {\n value >>= 64;\n result += 8;\n }\n if (value >> 32 > 0) {\n value >>= 32;\n result += 4;\n }\n if (value >> 16 > 0) {\n value >>= 16;\n result += 2;\n }\n if (value >> 8 > 0) {\n result += 1;\n }\n }\n return result;\n }\n\n /**\n * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n * Returns 0 if given 0.\n */\n function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n unchecked {\n uint256 result = log256(value);\n return result + (rounding == Rounding.Up && 1 << (result * 8) < value ? 1 : 0);\n }\n }\n}\n" }, "contracts/accounting/FarmAccounting.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/utils/math/Math.sol\";\n\nlibrary FarmAccounting {\n error ZeroDuration();\n error DurationTooLarge();\n error AmountTooLarge();\n\n struct Info {\n uint40 finished;\n uint32 duration;\n uint184 reward;\n }\n\n uint256 internal constant _MAX_REWARD_AMOUNT = 1e32; // 108 bits\n uint256 internal constant _SCALE = 1e18; // 60 bits\n\n /// @dev Requires extra 18 decimals for precision, result fits in 168 bits\n function farmedSinceCheckpointScaled(Info memory info, uint256 checkpoint) internal view returns(uint256 amount) {\n unchecked {\n if (info.duration > 0) {\n uint256 elapsed = Math.min(block.timestamp, info.finished) - Math.min(checkpoint, info.finished);\n // size of (type(uint32).max * _MAX_REWARD_AMOUNT * _SCALE) is less than 200 bits, so there is no overflow\n return elapsed * info.reward * _SCALE / info.duration;\n }\n }\n }\n\n function startFarming(Info storage info, uint256 amount, uint256 period) internal returns(uint256) {\n if (period == 0) revert ZeroDuration();\n if (period > type(uint32).max) revert DurationTooLarge();\n if (amount > _MAX_REWARD_AMOUNT) revert AmountTooLarge();\n\n // If something left from prev farming add it to the new farming\n Info memory prev = info;\n if (block.timestamp < prev.finished) {\n amount += prev.reward - farmedSinceCheckpointScaled(prev, prev.finished - prev.duration) / _SCALE;\n }\n\n (info.finished, info.duration, info.reward) = (uint40(block.timestamp + period), uint32(period), uint184(amount));\n return amount;\n }\n}\n" }, "contracts/accounting/UserAccounting.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./FarmAccounting.sol\";\n\nlibrary UserAccounting {\n struct Info {\n uint40 checkpoint;\n uint216 farmedPerTokenStored;\n mapping(address => int256) corrections;\n }\n\n function farmedPerToken(\n Info storage info,\n bytes32 context,\n function(bytes32) internal view returns(uint256) lazyGetSupply,\n function(bytes32, uint256) internal view returns(uint256) lazyGetFarmed\n ) internal view returns(uint256) {\n (uint256 checkpoint, uint256 fpt) = (info.checkpoint, info.farmedPerTokenStored);\n if (block.timestamp != checkpoint) {\n uint256 supply = lazyGetSupply(context);\n if (supply > 0) {\n // fpt increases by 168 bit / supply\n unchecked { fpt += lazyGetFarmed(context, checkpoint) / supply; }\n }\n }\n return fpt;\n }\n\n function farmed(Info storage info, address account, uint256 balance, uint256 fpt) internal view returns(uint256) {\n // balance * fpt is less than 168 bit\n return uint256(int256(balance * fpt) - info.corrections[account]) / FarmAccounting._SCALE;\n }\n\n function eraseFarmed(Info storage info, address account, uint256 balance, uint256 fpt) internal {\n // balance * fpt is less than 168 bit\n info.corrections[account] = int256(balance * fpt);\n }\n\n function updateFarmedPerToken(Info storage info, uint256 fpt) internal {\n (info.checkpoint, info.farmedPerTokenStored) = (uint40(block.timestamp), uint216(fpt));\n }\n\n function updateBalances(Info storage info, address from, address to, uint256 amount, uint256 fpt) internal {\n bool fromZero = (from == address(0));\n bool toZero = (to == address(0));\n if (amount > 0 && from != to) {\n if (fromZero || toZero) {\n updateFarmedPerToken(info, fpt);\n }\n\n // fpt is less than 168 bit, so amount should be less 98 bit\n int256 diff = int256(amount * fpt);\n if (!fromZero) {\n info.corrections[from] -= diff;\n }\n if (!toZero) {\n info.corrections[to] += diff;\n }\n }\n }\n}\n" }, "contracts/FarmingLib.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"./accounting/FarmAccounting.sol\";\nimport \"./accounting/UserAccounting.sol\";\n\nlibrary FarmingLib {\n using FarmAccounting for FarmAccounting.Info;\n using UserAccounting for UserAccounting.Info;\n using FarmingLib for FarmingLib.Info;\n\n struct Data {\n FarmAccounting.Info farmInfo;\n UserAccounting.Info userInfo;\n }\n\n struct Info {\n function() internal view returns(uint256) getTotalSupply;\n bytes32 dataSlot;\n }\n\n function makeInfo(function() internal view returns(uint256) getTotalSupply, Data storage data) internal pure returns(Info memory info) {\n info.getTotalSupply = getTotalSupply;\n bytes32 dataSlot;\n assembly { // solhint-disable-line no-inline-assembly\n dataSlot := data.slot\n }\n info.dataSlot = dataSlot;\n }\n\n function getData(Info memory self) internal pure returns(Data storage data) {\n bytes32 dataSlot = self.dataSlot;\n assembly { // solhint-disable-line no-inline-assembly\n data.slot := dataSlot\n }\n }\n\n function startFarming(Info memory self, uint256 amount, uint256 period) internal returns(uint256 reward) {\n Data storage data = self.getData();\n data.userInfo.updateFarmedPerToken(_farmedPerToken(self));\n reward = data.farmInfo.startFarming(amount, period);\n }\n\n function farmed(Info memory self, address account, uint256 balance) internal view returns(uint256) {\n return self.getData().userInfo.farmed(account, balance, _farmedPerToken(self));\n }\n\n function claim(Info memory self, address account, uint256 balance) internal returns(uint256 amount) {\n Data storage data = self.getData();\n uint256 fpt = _farmedPerToken(self);\n amount = data.userInfo.farmed(account, balance, fpt);\n if (amount > 0) {\n data.userInfo.eraseFarmed(account, balance, fpt);\n }\n }\n\n function updateBalances(Info memory self, address from, address to, uint256 amount) internal {\n self.getData().userInfo.updateBalances(from, to, amount, _farmedPerToken(self));\n }\n\n function _farmedPerToken(Info memory self) private view returns (uint256) {\n return self.getData().userInfo.farmedPerToken(_infoToContext(self), _lazyGetSupply, _lazyGetFarmed);\n }\n\n // UserAccounting bindings\n\n function _lazyGetSupply(bytes32 context) private view returns(uint256) {\n Info memory self = _contextToInfo(context);\n return self.getTotalSupply();\n }\n\n function _lazyGetFarmed(bytes32 context, uint256 checkpoint) private view returns(uint256) {\n Info memory self = _contextToInfo(context);\n return self.getData().farmInfo.farmedSinceCheckpointScaled(checkpoint);\n }\n\n function _contextToInfo(bytes32 context) private pure returns(Info memory self) {\n assembly { // solhint-disable-line no-inline-assembly\n self := context\n }\n }\n\n function _infoToContext(Info memory self) private pure returns(bytes32 context) {\n assembly { // solhint-disable-line no-inline-assembly\n context := self\n }\n }\n}\n" }, "contracts/FarmingPod.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@1inch/solidity-utils/contracts/libraries/SafeERC20.sol\";\nimport \"@1inch/erc20-pods/contracts/Pod.sol\";\nimport \"@1inch/erc20-pods/contracts/interfaces/IERC20Pods.sol\";\n\nimport \"./interfaces/IFarmingPod.sol\";\nimport \"./FarmingLib.sol\";\n\ncontract FarmingPod is Pod, IFarmingPod, Ownable {\n using SafeERC20 for IERC20;\n using FarmingLib for FarmingLib.Info;\n using Address for address payable;\n\n error ZeroFarmableTokenAddress();\n error ZeroRewardsTokenAddress();\n error SameDistributor();\n\n IERC20 public immutable rewardsToken;\n\n address private _distributor;\n uint256 private _totalSupply;\n FarmingLib.Data private _farm;\n\n modifier onlyDistributor {\n if (msg.sender != _distributor) revert AccessDenied();\n _;\n }\n\n constructor(IERC20Pods farmableToken_, IERC20 rewardsToken_)\n Pod(farmableToken_)\n {\n if (address(farmableToken_) == address(0)) revert ZeroFarmableTokenAddress();\n if (address(rewardsToken_) == address(0)) revert ZeroRewardsTokenAddress();\n rewardsToken = rewardsToken_;\n emit FarmCreated(address(farmableToken_), address(rewardsToken_));\n }\n\n function farmInfo() public view returns(FarmAccounting.Info memory) {\n return _farm.farmInfo;\n }\n\n function totalSupply() public view returns(uint256) {\n return _totalSupply;\n }\n\n function distributor() public view returns(address) {\n return _distributor;\n }\n\n function setDistributor(address distributor_) public virtual onlyOwner {\n address oldDistributor = _distributor;\n if (distributor_ == oldDistributor) revert SameDistributor();\n emit DistributorChanged(oldDistributor, distributor_);\n _distributor = distributor_;\n }\n\n function startFarming(uint256 amount, uint256 period) public virtual onlyDistributor {\n uint256 reward = _makeInfo().startFarming(amount, period);\n emit RewardAdded(reward, period);\n rewardsToken.safeTransferFrom(msg.sender, address(this), amount);\n }\n\n function farmed(address account) public view virtual returns(uint256) {\n uint256 balance = IERC20Pods(token).podBalanceOf(address(this), account);\n return _makeInfo().farmed(account, balance);\n }\n\n function claim() public virtual {\n uint256 podBalance = IERC20Pods(token).podBalanceOf(address(this), msg.sender);\n uint256 amount = _makeInfo().claim(msg.sender, podBalance);\n if (amount > 0) {\n _transferReward(rewardsToken, msg.sender, amount);\n }\n }\n\n function _transferReward(IERC20 reward, address to, uint256 amount) internal virtual {\n reward.safeTransfer(to, amount);\n }\n\n function _updateBalances(address from, address to, uint256 amount) internal virtual override {\n _makeInfo().updateBalances(from, to, amount);\n if (from == address(0)) {\n _totalSupply += amount;\n }\n if (to == address(0)) {\n _totalSupply -= amount;\n }\n }\n\n function rescueFunds(IERC20 token, uint256 amount) public virtual onlyDistributor {\n if(token == IERC20(address(0))) {\n payable(_distributor).sendValue(amount);\n } else {\n token.safeTransfer(_distributor, amount);\n }\n }\n\n function _makeInfo() private view returns(FarmingLib.Info memory) {\n return FarmingLib.makeInfo(totalSupply, _farm);\n }\n}\n" }, "contracts/FarmingPool.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/ERC20.sol\";\nimport \"@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@1inch/solidity-utils/contracts/libraries/SafeERC20.sol\";\n\nimport \"./interfaces/IFarmingPool.sol\";\nimport \"./FarmingLib.sol\";\n\ncontract FarmingPool is IFarmingPool, Ownable, ERC20 {\n using SafeERC20 for IERC20;\n using Address for address payable;\n using FarmingLib for FarmingLib.Info;\n\n error ZeroStakingTokenAddress();\n error ZeroRewardsTokenAddress();\n error SameDistributor();\n error AccessDenied();\n error NotEnoughBalance();\n error MaxBalanceExceeded();\n\n uint256 internal constant _MAX_BALANCE = 1e32;\n\n IERC20 public immutable stakingToken;\n IERC20 public immutable rewardsToken;\n\n address private _distributor;\n FarmingLib.Data private _farm;\n\n modifier onlyDistributor {\n if (msg.sender != _distributor) revert AccessDenied();\n _;\n }\n\n constructor(IERC20Metadata stakingToken_, IERC20 rewardsToken_)\n ERC20(\n string(abi.encodePacked(\"Farming of \", stakingToken_.name())),\n string(abi.encodePacked(\"farm\", stakingToken_.symbol()))\n )\n {\n if (address(stakingToken_) == address(0)) revert ZeroStakingTokenAddress();\n if (address(rewardsToken_) == address(0)) revert ZeroRewardsTokenAddress();\n stakingToken = stakingToken_;\n rewardsToken = rewardsToken_;\n }\n\n function decimals() public view virtual override returns (uint8) {\n return IERC20Metadata(address(stakingToken)).decimals();\n }\n\n function farmInfo() public view returns(FarmAccounting.Info memory) {\n return _farm.farmInfo;\n }\n\n function distributor() public view virtual returns (address) {\n return _distributor;\n }\n\n function setDistributor(address distributor_) public virtual onlyOwner {\n address oldDistributor = _distributor;\n if (distributor_ == oldDistributor) revert SameDistributor();\n emit DistributorChanged(oldDistributor, distributor_);\n _distributor = distributor_;\n }\n\n function startFarming(uint256 amount, uint256 period) public virtual onlyDistributor {\n uint256 reward = _makeInfo().startFarming(amount, period);\n emit RewardAdded(reward, period);\n rewardsToken.safeTransferFrom(msg.sender, address(this), amount);\n }\n\n function farmed(address account) public view virtual returns (uint256) {\n return _makeInfo().farmed(account, balanceOf(account));\n }\n\n function deposit(uint256 amount) public virtual {\n _mint(msg.sender, amount);\n if (balanceOf(msg.sender) > _MAX_BALANCE) revert MaxBalanceExceeded();\n stakingToken.safeTransferFrom(msg.sender, address(this), amount);\n }\n\n function withdraw(uint256 amount) public virtual {\n _burn(msg.sender, amount);\n stakingToken.safeTransfer(msg.sender, amount);\n }\n\n function claim() public virtual {\n uint256 amount = _makeInfo().claim(msg.sender, balanceOf(msg.sender));\n if (amount > 0) {\n _transferReward(rewardsToken, msg.sender, amount);\n }\n }\n\n function _transferReward(IERC20 reward, address to, uint256 amount) internal virtual {\n reward.safeTransfer(to, amount);\n }\n\n function exit() public virtual {\n withdraw(balanceOf(msg.sender));\n claim();\n }\n\n function rescueFunds(IERC20 token, uint256 amount) public virtual onlyDistributor {\n if (token == IERC20(address(0))) {\n payable(_distributor).sendValue(amount);\n } else {\n token.safeTransfer(_distributor, amount);\n if (token == stakingToken) {\n if (stakingToken.balanceOf(address(this)) < totalSupply()) revert NotEnoughBalance();\n }\n }\n }\n\n function _makeInfo() private view returns(FarmingLib.Info memory) {\n return FarmingLib.makeInfo(totalSupply, _farm);\n }\n\n // ERC20 overrides\n\n function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {\n super._beforeTokenTransfer(from, to, amount);\n\n if (amount > 0 && from != to) {\n _makeInfo().updateBalances(from, to, amount);\n }\n }\n}\n" }, "contracts/hardhat-dependency-compiler/@1inch/erc20-pods/contracts/mocks/ERC20PodsMock.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >0.0.0;\nimport '@1inch/erc20-pods/contracts/mocks/ERC20PodsMock.sol';\n" }, "contracts/hardhat-dependency-compiler/@1inch/solidity-utils/contracts/mocks/TokenMock.sol": { "content": "// SPDX-License-Identifier: UNLICENSED\npragma solidity >0.0.0;\nimport '@1inch/solidity-utils/contracts/mocks/TokenMock.sol';\n" }, "contracts/interfaces/IFarmingPod.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@1inch/erc20-pods/contracts/interfaces/IPod.sol\";\nimport \"../accounting/FarmAccounting.sol\";\n\ninterface IFarmingPod is IPod {\n event FarmCreated(address token, address reward);\n event DistributorChanged(address oldDistributor, address newDistributor);\n event RewardAdded(uint256 reward, uint256 duration);\n\n // View functions\n function totalSupply() external view returns(uint256);\n function distributor() external view returns(address);\n function farmInfo() external view returns(FarmAccounting.Info memory);\n function farmed(address account) external view returns(uint256);\n\n // User functions\n function claim() external;\n\n // Owner functions\n function setDistributor(address distributor_) external;\n\n // Distributor functions\n function startFarming(uint256 amount, uint256 period) external;\n function rescueFunds(IERC20 token, uint256 amount) external;\n}\n" }, "contracts/interfaces/IFarmingPool.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"../accounting/FarmAccounting.sol\";\n\ninterface IFarmingPool is IERC20 {\n event DistributorChanged(address oldDistributor, address newDistributor);\n event RewardAdded(uint256 reward, uint256 duration);\n\n // View functions\n function distributor() external view returns(address);\n function farmInfo() external view returns(FarmAccounting.Info memory);\n function farmed(address account) external view returns(uint256);\n\n // User functions\n function deposit(uint256 amount) external;\n function withdraw(uint256 amount) external;\n function claim() external;\n function exit() external;\n\n // Owner functions\n function setDistributor(address distributor_) external;\n\n // Distributor functions\n function startFarming(uint256 amount, uint256 period) external;\n function rescueFunds(IERC20 token, uint256 amount) external;\n}\n" }, "contracts/interfaces/IMultiFarmingPod.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/token/ERC20/IERC20.sol\";\nimport \"@1inch/erc20-pods/contracts/interfaces/IPod.sol\";\nimport \"../accounting/FarmAccounting.sol\";\n\ninterface IMultiFarmingPod is IPod {\n event FarmCreated(address token, address reward);\n event DistributorChanged(address oldDistributor, address newDistributor);\n event RewardAdded(address token, uint256 reward, uint256 duration);\n\n // View functions\n function totalSupply() external view returns(uint256);\n function distributor() external view returns(address);\n function farmInfo(IERC20 rewardsToken) external view returns(FarmAccounting.Info memory);\n function farmed(IERC20 rewardsToken, address account) external view returns(uint256);\n\n // User functions\n function claim(IERC20 rewardsToken) external;\n function claim() external;\n\n // Owner functions\n function setDistributor(address distributor_) external;\n\n // Distributor functions\n function startFarming(IERC20 rewardsToken, uint256 amount, uint256 period) external;\n function rescueFunds(IERC20 token, uint256 amount) external;\n}\n" }, "contracts/MultiFarmingPod.sol": { "content": "// SPDX-License-Identifier: MIT\n\npragma solidity ^0.8.0;\n\nimport \"@openzeppelin/contracts/access/Ownable.sol\";\nimport \"@openzeppelin/contracts/utils/Address.sol\";\nimport \"@1inch/erc20-pods/contracts/Pod.sol\";\nimport \"@1inch/solidity-utils/contracts/libraries/SafeERC20.sol\";\nimport \"@1inch/solidity-utils/contracts/libraries/AddressSet.sol\";\nimport \"@1inch/erc20-pods/contracts/interfaces/IERC20Pods.sol\";\n\nimport \"./interfaces/IMultiFarmingPod.sol\";\nimport \"./FarmingLib.sol\";\n\ncontract MultiFarmingPod is Pod, IMultiFarmingPod, Ownable {\n using SafeERC20 for IERC20;\n using FarmingLib for FarmingLib.Info;\n using Address for address payable;\n using AddressSet for AddressSet.Data;\n using AddressArray for AddressArray.Data;\n\n error ZeroFarmableTokenAddress();\n error ZeroRewardsTokenAddress();\n error SameDistributor();\n error RewardsTokenAlreadyAdded();\n error RewardsTokensLimitTooHigh(uint256);\n error RewardsTokensLimitReached();\n error RewardsTokenNotFound();\n\n uint256 public immutable rewardsTokensLimit;\n\n address private _distributor;\n uint256 private _totalSupply;\n mapping(IERC20 => FarmingLib.Data) private _farms;\n AddressSet.Data private _rewardsTokens;\n\n modifier onlyDistributor {\n if (msg.sender != _distributor) revert AccessDenied();\n _;\n }\n\n constructor(IERC20Pods farmableToken_, uint256 rewardsTokensLimit_) Pod(farmableToken_) {\n if (rewardsTokensLimit_ > 5) revert RewardsTokensLimitTooHigh(rewardsTokensLimit_);\n if (address(farmableToken_) == address(0)) revert ZeroFarmableTokenAddress();\n\n rewardsTokensLimit = rewardsTokensLimit_;\n }\n\n function rewardsTokens() external view returns(address[] memory) {\n return _rewardsTokens.items.get();\n }\n\n function farmInfo(IERC20 rewardsToken) public view returns(FarmAccounting.Info memory) {\n return _farms[rewardsToken].farmInfo;\n }\n\n function totalSupply() public view returns(uint256) {\n return _totalSupply;\n }\n\n function distributor() public view returns(address) {\n return _distributor;\n }\n\n function setDistributor(address distributor_) public virtual onlyOwner {\n address oldDistributor = _distributor;\n if (distributor_ == oldDistributor) revert SameDistributor();\n emit DistributorChanged(oldDistributor, distributor_);\n _distributor = distributor_;\n }\n\n function addRewardsToken(address rewardsToken) public virtual onlyOwner {\n if (_rewardsTokens.length() == rewardsTokensLimit) revert RewardsTokensLimitReached();\n if (!_rewardsTokens.add(rewardsToken)) revert RewardsTokenAlreadyAdded();\n emit FarmCreated(address(token), rewardsToken);\n }\n\n function startFarming(IERC20 rewardsToken, uint256 amount, uint256 period) public virtual onlyDistributor {\n if (!_rewardsTokens.contains(address(rewardsToken))) revert RewardsTokenNotFound();\n\n uint256 reward = _makeInfo(rewardsToken).startFarming(amount, period);\n emit RewardAdded(address(rewardsToken), reward, period);\n rewardsToken.safeTransferFrom(msg.sender, address(this), amount);\n }\n\n function farmed(IERC20 rewardsToken, address account) public view virtual returns(uint256) {\n uint256 balance = IERC20Pods(token).podBalanceOf(address(this), account);\n return _makeInfo(rewardsToken).farmed(account, balance);\n }\n\n function claim(IERC20 rewardsToken) public virtual {\n uint256 podBalance = IERC20Pods(token).podBalanceOf(address(this), msg.sender);\n _claim(rewardsToken, msg.sender, podBalance);\n }\n\n function claim() public virtual {\n uint256 podBalance = IERC20Pods(token).podBalanceOf(address(this), msg.sender);\n address[] memory tokens = _rewardsTokens.items.get();\n unchecked {\n for (uint256 i = 0; i < tokens.length; i++) {\n _claim(IERC20(tokens[i]), msg.sender, podBalance);\n }\n }\n }\n\n function _claim(IERC20 rewardsToken, address account, uint256 podBalance) private {\n uint256 amount = _makeInfo(rewardsToken).claim(account, podBalance);\n if (amount > 0) {\n _transferReward(rewardsToken, account, amount);\n }\n }\n\n function _transferReward(IERC20 reward, address to, uint256 amount) internal virtual {\n reward.safeTransfer(to, amount);\n }\n\n function _updateBalances(address from, address to, uint256 amount) internal virtual override {\n address[] memory tokens = _rewardsTokens.items.get();\n unchecked {\n for (uint256 i = 0; i < tokens.length; i++) {\n _makeInfo(IERC20(tokens[i])).updateBalances(from, to, amount);\n }\n }\n if (from == address(0)) {\n _totalSupply += amount;\n }\n if (to == address(0)) {\n _totalSupply -= amount;\n }\n }\n\n function rescueFunds(IERC20 token, uint256 amount) public virtual onlyDistributor {\n if(token == IERC20(address(0))) {\n payable(_distributor).sendValue(amount);\n } else {\n token.safeTransfer(_distributor, amount);\n }\n }\n\n function _makeInfo(IERC20 rewardsToken) private view returns(FarmingLib.Info memory) {\n return FarmingLib.makeInfo(totalSupply, _farms[rewardsToken]);\n }\n}\n" } }, "settings": { "optimizer": { "enabled": true, "runs": 1000000 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "metadata": { "useLiteralContent": true } } }