{
"language": "Solidity",
"sources": {
"contracts/mainnet/DepositBoxes/DepositBoxERC20.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * DepositBoxERC20.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2019-Present SKALE Labs\n * @author Artem Payvin\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity 0.8.16;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/math/MathUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/DoubleEndedQueueUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/extensions/IERC20MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol\";\nimport \"@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxERC20.sol\";\n\nimport \"../../Messages.sol\";\nimport \"../DepositBox.sol\";\n\ninterface IERC20TransferVoid {\n function transferFrom(address _from, address _to, uint256 _amount) external;\n function transfer(address _to, uint256 _amount) external;\n}\n\n\n/**\n * @title DepositBoxERC20\n * @dev Runs on mainnet,\n * accepts messages from schain,\n * stores deposits of ERC20.\n */\ncontract DepositBoxERC20 is DepositBox, IDepositBoxERC20 {\n using AddressUpgradeable for address;\n using DoubleEndedQueueUpgradeable for DoubleEndedQueueUpgradeable.Bytes32Deque;\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n using SafeERC20Upgradeable for IERC20MetadataUpgradeable;\n using SafeERC20Upgradeable for IERC20Upgradeable;\n\n enum DelayedTransferStatus {\n DELAYED,\n ARBITRAGE,\n COMPLETED\n }\n\n struct DelayedTransfer {\n address receiver;\n bytes32 schainHash;\n address token;\n uint256 amount;\n uint256 untilTimestamp;\n DelayedTransferStatus status;\n }\n\n struct DelayConfig {\n // token address => value\n mapping(address => uint256) bigTransferThreshold;\n EnumerableSetUpgradeable.AddressSet trustedReceivers;\n uint256 transferDelay;\n uint256 arbitrageDuration;\n }\n\n uint256 private constant _QUEUE_PROCESSING_LIMIT = 10;\n\n bytes32 public constant ARBITER_ROLE = keccak256(\"ARBITER_ROLE\");\n\n // schainHash => address of ERC20 on Mainnet\n // Deprecated\n // slither-disable-next-line unused-state\n mapping(bytes32 => mapping(address => bool)) private _deprecatedSchainToERC20;\n mapping(bytes32 => mapping(address => uint256)) public transferredAmount;\n mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _schainToERC20;\n\n // exits delay configuration\n // schainHash => delay config\n mapping(bytes32 => DelayConfig) private _delayConfig;\n\n uint256 public delayedTransfersSize;\n // delayed transfer id => delayed transfer\n mapping(uint256 => DelayedTransfer) public delayedTransfers;\n // receiver address => delayed transfers ids queue\n mapping(address => DoubleEndedQueueUpgradeable.Bytes32Deque) public delayedTransfersByReceiver;\n\n /**\n * @dev Emitted when token is mapped in DepositBoxERC20.\n */\n event ERC20TokenAdded(string schainName, address indexed contractOnMainnet);\n\n /**\n * @dev Emitted when token is received by DepositBox and is ready to be cloned\n * or transferred on SKALE chain.\n */\n event ERC20TokenReady(address indexed contractOnMainnet, uint256 amount);\n\n event TransferDelayed(uint256 id, address receiver, address token, uint256 amount);\n\n event Escalated(uint256 id);\n\n /**\n * @dev Emitted when token transfer is skipped due to internal token error\n */\n event TransferSkipped(uint256 id);\n\n /**\n * @dev Emitted when big transfer threshold is changed\n */\n event BigTransferThresholdIsChanged(\n bytes32 indexed schainHash,\n address indexed token,\n uint256 oldValue,\n uint256 newValue\n );\n\n /**\n * @dev Emitted when big transfer delay is changed\n */\n event BigTransferDelayIsChanged(\n bytes32 indexed schainHash,\n uint256 oldValue,\n uint256 newValue\n );\n\n /**\n * @dev Emitted when arbitrage duration is changed\n */\n event ArbitrageDurationIsChanged(\n bytes32 indexed schainHash,\n uint256 oldValue,\n uint256 newValue\n );\n\n /**\n * @dev Allows `msg.sender` to send ERC20 token from mainnet to schain\n *\n * Requirements:\n *\n * - Schain name must not be `Mainnet`.\n * - Receiver account on schain cannot be null.\n * - Schain that receives tokens should not be killed.\n * - Receiver contract should be defined.\n * - `msg.sender` should approve their tokens for DepositBoxERC20 address.\n */\n function depositERC20(\n string calldata schainName,\n address erc20OnMainnet,\n uint256 amount\n )\n external\n override\n rightTransaction(schainName, msg.sender)\n whenNotKilled(_schainHash(schainName))\n {\n bytes32 schainHash = _schainHash(schainName);\n address contractReceiver = schainLinks[schainHash];\n require(contractReceiver != address(0), \"Unconnected chain\");\n require(\n IERC20MetadataUpgradeable(erc20OnMainnet).allowance(msg.sender, address(this)) >= amount,\n \"DepositBox was not approved for ERC20 token\"\n );\n bytes memory data = _receiveERC20(\n schainName,\n erc20OnMainnet,\n msg.sender,\n amount\n );\n _saveTransferredAmount(schainHash, erc20OnMainnet, amount);\n IERC20MetadataUpgradeable(erc20OnMainnet).safeTransferFrom(msg.sender, address(this), amount);\n messageProxy.postOutgoingMessage(\n schainHash,\n contractReceiver,\n data\n );\n }\n\n /**\n * @dev Allows MessageProxyForMainnet contract to execute transferring ERC20 token from schain to mainnet.\n *\n * Requirements:\n *\n * - Schain from which the tokens came should not be killed.\n * - Sender contract should be defined and schain name cannot be `Mainnet`.\n * - Amount of tokens on DepositBoxERC20 should be equal or more than transferred amount.\n */\n function postMessage(\n bytes32 schainHash,\n address sender,\n bytes calldata data\n )\n external\n override\n onlyMessageProxy\n whenNotKilled(schainHash)\n checkReceiverChain(schainHash, sender)\n {\n Messages.TransferErc20Message memory message = Messages.decodeTransferErc20Message(data);\n require(message.token.isContract(), \"Given address is not a contract\");\n require(\n IERC20MetadataUpgradeable(message.token).balanceOf(address(this)) >= message.amount,\n \"Not enough money\"\n );\n _removeTransferredAmount(schainHash, message.token, message.amount);\n\n uint256 delay = _delayConfig[schainHash].transferDelay;\n if (\n delay > 0\n && _delayConfig[schainHash].bigTransferThreshold[message.token] <= message.amount\n && !isReceiverTrusted(schainHash, message.receiver)\n ) {\n _createDelayedTransfer(schainHash, message, delay);\n } else {\n IERC20MetadataUpgradeable(message.token).safeTransfer(message.receiver, message.amount);\n }\n }\n\n /**\n * @dev Allows Schain owner to add an ERC20 token to DepositBoxERC20.\n *\n * Emits an {ERC20TokenAdded} event.\n *\n * Requirements:\n *\n * - Schain should not be killed.\n * - Only owner of the schain able to run function.\n */\n function addERC20TokenByOwner(string calldata schainName, address erc20OnMainnet)\n external\n override\n onlySchainOwner(schainName)\n whenNotKilled(_schainHash(schainName))\n {\n _addERC20ForSchain(schainName, erc20OnMainnet);\n }\n\n /**\n * @dev Allows Schain owner to return each user their tokens.\n * The Schain owner decides which tokens to send to which address,\n * since the contract on mainnet does not store information about which tokens belong to whom.\n *\n * Requirements:\n *\n * - Amount of tokens on schain should be equal or more than transferred amount.\n * - msg.sender should be an owner of schain\n * - IMA transfers Mainnet <-> schain should be killed\n */\n function getFunds(string calldata schainName, address erc20OnMainnet, address receiver, uint amount)\n external\n override\n onlySchainOwner(schainName)\n whenKilled(_schainHash(schainName))\n {\n bytes32 schainHash = _schainHash(schainName);\n require(transferredAmount[schainHash][erc20OnMainnet] >= amount, \"Incorrect amount\");\n _removeTransferredAmount(schainHash, erc20OnMainnet, amount);\n IERC20MetadataUpgradeable(erc20OnMainnet).safeTransfer(receiver, amount);\n }\n\n /**\n * @dev Set a threshold amount of tokens.\n * If amount of tokens that exits IMA is bigger than the threshold\n * the transfer is delayed for configurable amount of time\n * and can be canceled by a voting\n *\n * Requirements:\n *\n * - msg.sender should be an owner of schain\n */\n function setBigTransferValue(\n string calldata schainName,\n address token,\n uint256 value\n )\n external\n override\n onlySchainOwner(schainName)\n {\n bytes32 schainHash = _schainHash(schainName);\n emit BigTransferThresholdIsChanged(\n schainHash,\n token,\n _delayConfig[schainHash].bigTransferThreshold[token],\n value\n );\n _delayConfig[schainHash].bigTransferThreshold[token] = value;\n }\n\n /**\n * @dev Set a time delay.\n * If amount of tokens that exits IMA is bigger than a threshold\n * the transfer is delayed for set amount of time\n * and can be canceled by a voting\n *\n * Requirements:\n *\n * - msg.sender should be an owner of schain\n */\n function setBigTransferDelay(\n string calldata schainName,\n uint256 delayInSeconds\n )\n external\n override\n onlySchainOwner(schainName)\n {\n bytes32 schainHash = _schainHash(schainName);\n // need to restrict big delays to avoid overflow\n require(delayInSeconds < 1e8, \"Delay is too big\"); // no more then ~ 3 years\n emit BigTransferDelayIsChanged(schainHash, _delayConfig[schainHash].transferDelay, delayInSeconds);\n _delayConfig[schainHash].transferDelay = delayInSeconds;\n }\n\n /**\n * @dev Set an arbitrage.\n * After escalation the transfer is locked for provided period of time.\n *\n * Requirements:\n *\n * - msg.sender should be an owner of schain\n */\n function setArbitrageDuration(\n string calldata schainName,\n uint256 delayInSeconds\n )\n external\n override\n onlySchainOwner(schainName)\n {\n bytes32 schainHash = _schainHash(schainName);\n // need to restrict big delays to avoid overflow\n require(delayInSeconds < 1e8, \"Delay is too big\"); // no more then ~ 3 years\n emit ArbitrageDurationIsChanged(schainHash, _delayConfig[schainHash].arbitrageDuration, delayInSeconds);\n _delayConfig[schainHash].arbitrageDuration = delayInSeconds;\n }\n\n /**\n * @dev Add the address to a whitelist of addresses that can do big transfers without delaying\n * Requirements:\n *\n * - msg.sender should be an owner of schain\n * - the address must not be in the whitelist\n */\n function trustReceiver(\n string calldata schainName,\n address receiver\n )\n external\n override\n onlySchainOwner(schainName)\n {\n require(\n _delayConfig[_schainHash(schainName)].trustedReceivers.add(receiver),\n \"Receiver already is trusted\"\n );\n }\n\n /**\n * @dev Remove the address from a whitelist of addresses that can do big transfers without delaying\n * Requirements:\n *\n * - msg.sender should be an owner of schain\n * - the address must be in the whitelist\n */\n function stopTrustingReceiver(\n string calldata schainName,\n address receiver\n )\n external\n override\n onlySchainOwner(schainName)\n {\n require(_delayConfig[_schainHash(schainName)].trustedReceivers.remove(receiver), \"Receiver is not trusted\");\n }\n\n /**\n * @dev Transfers tokens that was locked for delay during exit process.\n * Must be called by a receiver.\n */\n function retrieve() external override {\n retrieveFor(msg.sender);\n }\n\n /**\n * @dev Initialize arbitrage of a suspicious big transfer\n *\n * Requirements:\n *\n * - msg.sender should be an owner of schain or have ARBITER_ROLE role\n * - transfer must be delayed and arbitrage must not be started\n */\n function escalate(uint256 transferId) external override {\n bytes32 schainHash = delayedTransfers[transferId].schainHash;\n require(\n hasRole(ARBITER_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash),\n \"Not enough permissions to request escalation\"\n );\n require(delayedTransfers[transferId].status == DelayedTransferStatus.DELAYED, \"The transfer has to be delayed\");\n delayedTransfers[transferId].status = DelayedTransferStatus.ARBITRAGE;\n delayedTransfers[transferId].untilTimestamp = MathUpgradeable.max(\n delayedTransfers[transferId].untilTimestamp,\n block.timestamp + _delayConfig[schainHash].arbitrageDuration\n );\n emit Escalated(transferId);\n }\n\n /**\n * @dev Approve a big transfer and immidiately transfer tokens during arbitrage\n *\n * Requirements:\n *\n * - msg.sender should be an owner of schain\n * - arbitrage of the transfer must be started\n */\n function validateTransfer(\n uint transferId\n )\n external\n override\n onlySchainOwnerByHash(delayedTransfers[transferId].schainHash)\n {\n DelayedTransfer storage transfer = delayedTransfers[transferId];\n require(transfer.status == DelayedTransferStatus.ARBITRAGE, \"Arbitrage has to be active\");\n transfer.status = DelayedTransferStatus.COMPLETED;\n delete transfer.untilTimestamp;\n IERC20MetadataUpgradeable(transfer.token).safeTransfer(transfer.receiver, transfer.amount);\n }\n\n /**\n * @dev Reject a big transfer and transfer tokens to SKALE chain owner during arbitrage\n *\n * Requirements:\n *\n * - msg.sender should be an owner of schain\n * - arbitrage of the transfer must be started\n */\n function rejectTransfer(\n uint transferId\n )\n external\n override\n onlySchainOwnerByHash(delayedTransfers[transferId].schainHash)\n {\n DelayedTransfer storage transfer = delayedTransfers[transferId];\n require(transfer.status == DelayedTransferStatus.ARBITRAGE, \"Arbitrage has to be active\");\n transfer.status = DelayedTransferStatus.COMPLETED;\n delete transfer.untilTimestamp;\n // msg.sender is schain owner\n IERC20MetadataUpgradeable(transfer.token).safeTransfer(msg.sender, transfer.amount);\n }\n\n function doTransfer(address token, address receiver, uint256 amount) external override {\n require(msg.sender == address(this), \"Internal use only\");\n IERC20Upgradeable(token).safeTransfer(receiver, amount);\n }\n\n /**\n * @dev Returns receiver of message.\n *\n * Requirements:\n *\n * - Sender contract should be defined and schain name cannot be `Mainnet`.\n */\n function gasPayer(\n bytes32 schainHash,\n address sender,\n bytes calldata data\n )\n external\n view\n override\n checkReceiverChain(schainHash, sender)\n returns (address)\n {\n Messages.TransferErc20Message memory message = Messages.decodeTransferErc20Message(data);\n return message.receiver;\n }\n\n /**\n * @dev Should return true if token was added by Schain owner or\n * added automatically after sending to schain if whitelist was turned off.\n */\n function getSchainToERC20(\n string calldata schainName,\n address erc20OnMainnet\n )\n external\n view\n override\n returns (bool)\n {\n return _schainToERC20[_schainHash(schainName)].contains(erc20OnMainnet);\n }\n\n /**\n * @dev Should return length of a set of all mapped tokens which were added by Schain owner\n * or added automatically after sending to schain if whitelist was turned off.\n */\n function getSchainToAllERC20Length(string calldata schainName) external view override returns (uint256) {\n return _schainToERC20[_schainHash(schainName)].length();\n }\n\n /**\n * @dev Should return an array of range of tokens were added by Schain owner\n * or added automatically after sending to schain if whitelist was turned off.\n */\n function getSchainToAllERC20(\n string calldata schainName,\n uint256 from,\n uint256 to\n )\n external\n view\n override\n returns (address[] memory tokensInRange)\n {\n require(\n from < to && to - from <= 10 && to <= _schainToERC20[_schainHash(schainName)].length(),\n \"Range is incorrect\"\n );\n tokensInRange = new address[](to - from);\n for (uint256 i = from; i < to; i++) {\n tokensInRange[i - from] = _schainToERC20[_schainHash(schainName)].at(i);\n }\n }\n\n /**\n * @dev Get amount of tokens that are delayed for specified receiver\n */\n function getDelayedAmount(address receiver, address token) external view override returns (uint256 value) {\n uint256 delayedTransfersAmount = delayedTransfersByReceiver[receiver].length();\n for (uint256 i = 0; i < delayedTransfersAmount; ++i) {\n DelayedTransfer storage transfer = delayedTransfers[uint256(delayedTransfersByReceiver[receiver].at(i))];\n DelayedTransferStatus status = transfer.status;\n if (transfer.token == token) {\n if (status == DelayedTransferStatus.DELAYED || status == DelayedTransferStatus.ARBITRAGE) {\n value += transfer.amount;\n }\n }\n }\n }\n\n /**\n * @dev Get timestamp of next unlock of tokens that are delayed for specified receiver\n */\n function getNextUnlockTimestamp(\n address receiver,\n address token\n )\n external\n view\n override\n returns (uint256 unlockTimestamp)\n {\n uint256 delayedTransfersAmount = delayedTransfersByReceiver[receiver].length();\n unlockTimestamp = type(uint256).max;\n for (uint256 i = 0; i < delayedTransfersAmount; ++i) {\n DelayedTransfer storage transfer = delayedTransfers[uint256(delayedTransfersByReceiver[receiver].at(i))];\n DelayedTransferStatus status = transfer.status;\n if (transfer.token == token) {\n if (status != DelayedTransferStatus.COMPLETED) {\n unlockTimestamp = MathUpgradeable.min(unlockTimestamp, transfer.untilTimestamp);\n }\n if (status == DelayedTransferStatus.DELAYED) {\n break;\n }\n }\n }\n }\n\n /**\n * @dev Get amount of addresses that are added to the whitelist\n */\n function getTrustedReceiversAmount(bytes32 schainHash) external view override returns (uint256) {\n return _delayConfig[schainHash].trustedReceivers.length();\n }\n\n /**\n * @dev Get i-th address of the whitelist\n */\n function getTrustedReceiver(string calldata schainName, uint256 index) external view override returns (address) {\n return _delayConfig[_schainHash(schainName)].trustedReceivers.at(index);\n }\n\n /**\n * @dev Get amount of tokens that are considered as a big transfer\n */\n function getBigTransferThreshold(bytes32 schainHash, address token) external view override returns (uint256) {\n return _delayConfig[schainHash].bigTransferThreshold[token];\n }\n\n /**\n * @dev Get time delay of big transfers\n */\n function getTimeDelay(bytes32 schainHash) external view override returns (uint256) {\n return _delayConfig[schainHash].transferDelay;\n }\n\n /**\n * @dev Get duration of an arbitrage\n */\n function getArbitrageDuration(bytes32 schainHash) external view override returns (uint256) {\n return _delayConfig[schainHash].arbitrageDuration;\n }\n\n /**\n * @dev Retrive tokens that were unlocked after delay for specified receiver\n */\n function retrieveFor(address receiver) public override {\n uint256 transfersAmount = MathUpgradeable.min(\n delayedTransfersByReceiver[receiver].length(),\n _QUEUE_PROCESSING_LIMIT\n );\n\n uint256 currentIndex = 0;\n bool retrieved = false;\n for (uint256 i = 0; i < transfersAmount; ++i) {\n uint256 transferId = uint256(delayedTransfersByReceiver[receiver].at(currentIndex));\n DelayedTransfer memory transfer = delayedTransfers[transferId];\n ++currentIndex;\n\n if (transfer.status != DelayedTransferStatus.COMPLETED) {\n if (block.timestamp < transfer.untilTimestamp) {\n // disable detector untill slither fixes false positive\n // https://github.com/crytic/slither/issues/778\n // slither-disable-next-line incorrect-equality\n if (transfer.status == DelayedTransferStatus.DELAYED) {\n break;\n } else {\n // status is ARBITRAGE\n continue;\n }\n } else {\n // it's time to unlock\n if (currentIndex == 1) {\n --currentIndex;\n _removeOldestDelayedTransfer(receiver);\n } else {\n delayedTransfers[transferId].status = DelayedTransferStatus.COMPLETED;\n }\n retrieved = true;\n try\n this.doTransfer(transfer.token, transfer.receiver, transfer.amount)\n // solhint-disable-next-line no-empty-blocks\n {}\n catch {\n emit TransferSkipped(transferId);\n }\n }\n } else {\n // status is COMPLETED\n if (currentIndex == 1) {\n --currentIndex;\n retrieved = true;\n _removeOldestDelayedTransfer(receiver);\n }\n }\n }\n require(retrieved, \"There are no transfers available for retrieving\");\n }\n\n /**\n * @dev Creates a new DepositBoxERC20 contract.\n */\n function initialize(\n IContractManager contractManagerOfSkaleManagerValue,\n ILinker linkerValue,\n IMessageProxyForMainnet messageProxyValue\n )\n public\n override(DepositBox, IDepositBox)\n initializer\n {\n DepositBox.initialize(contractManagerOfSkaleManagerValue, linkerValue, messageProxyValue);\n }\n\n /**\n * @dev Check if the receiver is in the delay whitelist\n */\n function isReceiverTrusted(bytes32 schainHash, address receiver) public view override returns (bool) {\n return _delayConfig[schainHash].trustedReceivers.contains(receiver);\n }\n\n // private\n\n /**\n * @dev Saves amount of tokens that was transferred to schain.\n */\n function _saveTransferredAmount(bytes32 schainHash, address erc20Token, uint256 amount) private {\n transferredAmount[schainHash][erc20Token] += amount;\n }\n\n /**\n * @dev Removes amount of tokens that was transferred from schain.\n */\n function _removeTransferredAmount(bytes32 schainHash, address erc20Token, uint256 amount) private {\n transferredAmount[schainHash][erc20Token] -= amount;\n }\n\n /**\n * @dev Allows DepositBoxERC20 to receive ERC20 tokens.\n *\n * Emits an {ERC20TokenReady} event.\n *\n * Requirements:\n *\n * - Amount must be less than or equal to the total supply of the ERC20 contract.\n * - Whitelist should be turned off for auto adding tokens to DepositBoxERC20.\n */\n function _receiveERC20(\n string calldata schainName,\n address erc20OnMainnet,\n address to,\n uint256 amount\n )\n private\n returns (bytes memory data)\n {\n bytes32 schainHash = _schainHash(schainName);\n IERC20MetadataUpgradeable erc20 = IERC20MetadataUpgradeable(erc20OnMainnet);\n uint256 totalSupply = erc20.totalSupply();\n require(amount <= totalSupply, \"Amount is incorrect\");\n bool isERC20AddedToSchain = _schainToERC20[schainHash].contains(erc20OnMainnet);\n if (!isERC20AddedToSchain) {\n require(!isWhitelisted(schainName), \"Whitelist is enabled\");\n _addERC20ForSchain(schainName, erc20OnMainnet);\n data = Messages.encodeTransferErc20AndTokenInfoMessage(\n erc20OnMainnet,\n to,\n amount,\n _getErc20TotalSupply(erc20),\n _getErc20TokenInfo(erc20)\n );\n } else {\n data = Messages.encodeTransferErc20AndTotalSupplyMessage(\n erc20OnMainnet,\n to,\n amount,\n _getErc20TotalSupply(erc20)\n );\n }\n emit ERC20TokenReady(erc20OnMainnet, amount);\n }\n\n /**\n * @dev Adds an ERC20 token to DepositBoxERC20.\n *\n * Emits an {ERC20TokenAdded} event.\n *\n * Requirements:\n *\n * - Given address should be contract.\n */\n function _addERC20ForSchain(string calldata schainName, address erc20OnMainnet) private {\n bytes32 schainHash = _schainHash(schainName);\n require(erc20OnMainnet.isContract(), \"Given address is not a contract\");\n require(!_schainToERC20[schainHash].contains(erc20OnMainnet), \"ERC20 Token was already added\");\n _schainToERC20[schainHash].add(erc20OnMainnet);\n emit ERC20TokenAdded(schainName, erc20OnMainnet);\n }\n\n /**\n * @dev Add delayed transfer to receiver specific queue\n */\n function _addToDelayedQueue(\n address receiver,\n uint256 id,\n uint256 until\n )\n private\n {\n _addToDelayedQueueWithPriority(delayedTransfersByReceiver[receiver], id, until, _QUEUE_PROCESSING_LIMIT);\n }\n\n /**\n * @dev Add delayed transfer to receiver specific queue at the position\n * that maintains order from earlier unlocked to later unlocked.\n * If the position is located further than depthLimit from the back\n * the element is added at back - depthLimit index\n */\n function _addToDelayedQueueWithPriority(\n DoubleEndedQueueUpgradeable.Bytes32Deque storage queue,\n uint256 id,\n uint256 until,\n uint256 depthLimit\n )\n private\n {\n if (depthLimit == 0 || queue.empty()) {\n queue.pushBack(bytes32(id));\n } else {\n if (delayedTransfers[uint256(queue.back())].untilTimestamp <= until) {\n queue.pushBack(bytes32(id));\n } else {\n bytes32 lowPriorityValue = queue.popBack();\n _addToDelayedQueueWithPriority(queue, id, until, depthLimit - 1);\n queue.pushBack(lowPriorityValue);\n }\n }\n }\n\n /**\n * Create instance of DelayedTransfer and initialize all auxiliary fields.\n */\n function _createDelayedTransfer(\n bytes32 schainHash,\n Messages.TransferErc20Message memory message,\n uint256 delay\n )\n private\n {\n uint256 delayId = delayedTransfersSize++;\n delayedTransfers[delayId] = DelayedTransfer({\n receiver: message.receiver,\n schainHash: schainHash,\n token: message.token,\n amount: message.amount,\n untilTimestamp: block.timestamp + delay,\n status: DelayedTransferStatus.DELAYED\n });\n _addToDelayedQueue(message.receiver, delayId, block.timestamp + delay);\n emit TransferDelayed(delayId, message.receiver, message.token, message.amount);\n }\n\n /**\n * Remove instance of DelayedTransfer and clean auxiliary fields.\n */\n function _removeOldestDelayedTransfer(address receiver) private {\n uint256 transferId = uint256(delayedTransfersByReceiver[receiver].popFront());\n // For most cases the loop will have only 1 iteration.\n // In worst case the amount of iterations is limited by _QUEUE_PROCESSING_LIMIT\n // slither-disable-next-line costly-loop\n delete delayedTransfers[transferId];\n }\n\n /**\n * @dev Returns total supply of ERC20 token.\n */\n function _getErc20TotalSupply(IERC20MetadataUpgradeable erc20Token) private view returns (uint256) {\n return erc20Token.totalSupply();\n }\n\n /**\n * @dev Returns info about ERC20 token such as token name, decimals, symbol.\n */\n function _getErc20TokenInfo(IERC20MetadataUpgradeable erc20Token)\n private\n view\n returns (Messages.Erc20TokenInfo memory)\n {\n return Messages.Erc20TokenInfo({\n name: erc20Token.name(),\n decimals: erc20Token.decimals(),\n symbol: erc20Token.symbol()\n });\n }\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/math/MathUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.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 MathUpgradeable {\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. It 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 // 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)`.\n // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.\n // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.\n // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a\n // good first aproximation of `sqrt(a)` with at least 1 correct bit.\n uint256 result = 1;\n uint256 x = a;\n if (x >> 128 > 0) {\n x >>= 128;\n result <<= 64;\n }\n if (x >> 64 > 0) {\n x >>= 64;\n result <<= 32;\n }\n if (x >> 32 > 0) {\n x >>= 32;\n result <<= 16;\n }\n if (x >> 16 > 0) {\n x >>= 16;\n result <<= 8;\n }\n if (x >> 8 > 0) {\n x >>= 8;\n result <<= 4;\n }\n if (x >> 4 > 0) {\n x >>= 4;\n result <<= 2;\n }\n if (x >> 2 > 0) {\n result <<= 1;\n }\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 uint256 result = sqrt(a);\n if (rounding == Rounding.Up && result * result < a) {\n result += 1;\n }\n return result;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/structs/DoubleEndedQueueUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.6.0) (utils/structs/DoubleEndedQueue.sol)\npragma solidity ^0.8.4;\n\nimport \"../math/SafeCastUpgradeable.sol\";\n\n/**\n * @dev A sequence of items with the ability to efficiently push and pop items (i.e. insert and remove) on both ends of\n * the sequence (called front and back). Among other access patterns, it can be used to implement efficient LIFO and\n * FIFO queues. Storage use is optimized, and all operations are O(1) constant time. This includes {clear}, given that\n * the existing queue contents are left in storage.\n *\n * The struct is called `Bytes32Deque`. Other types can be cast to and from `bytes32`. This data structure can only be\n * used in storage, and not in memory.\n * ```\n * DoubleEndedQueue.Bytes32Deque queue;\n * ```\n *\n * _Available since v4.6._\n */\nlibrary DoubleEndedQueueUpgradeable {\n /**\n * @dev An operation (e.g. {front}) couldn't be completed due to the queue being empty.\n */\n error Empty();\n\n /**\n * @dev An operation (e.g. {at}) couldn't be completed due to an index being out of bounds.\n */\n error OutOfBounds();\n\n /**\n * @dev Indices are signed integers because the queue can grow in any direction. They are 128 bits so begin and end\n * are packed in a single storage slot for efficient access. Since the items are added one at a time we can safely\n * assume that these 128-bit indices will not overflow, and use unchecked arithmetic.\n *\n * Struct members have an underscore prefix indicating that they are \"private\" and should not be read or written to\n * directly. Use the functions provided below instead. Modifying the struct manually may violate assumptions and\n * lead to unexpected behavior.\n *\n * Indices are in the range [begin, end) which means the first item is at data[begin] and the last item is at\n * data[end - 1].\n */\n struct Bytes32Deque {\n int128 _begin;\n int128 _end;\n mapping(int128 => bytes32) _data;\n }\n\n /**\n * @dev Inserts an item at the end of the queue.\n */\n function pushBack(Bytes32Deque storage deque, bytes32 value) internal {\n int128 backIndex = deque._end;\n deque._data[backIndex] = value;\n unchecked {\n deque._end = backIndex + 1;\n }\n }\n\n /**\n * @dev Removes the item at the end of the queue and returns it.\n *\n * Reverts with `Empty` if the queue is empty.\n */\n function popBack(Bytes32Deque storage deque) internal returns (bytes32 value) {\n if (empty(deque)) revert Empty();\n int128 backIndex;\n unchecked {\n backIndex = deque._end - 1;\n }\n value = deque._data[backIndex];\n delete deque._data[backIndex];\n deque._end = backIndex;\n }\n\n /**\n * @dev Inserts an item at the beginning of the queue.\n */\n function pushFront(Bytes32Deque storage deque, bytes32 value) internal {\n int128 frontIndex;\n unchecked {\n frontIndex = deque._begin - 1;\n }\n deque._data[frontIndex] = value;\n deque._begin = frontIndex;\n }\n\n /**\n * @dev Removes the item at the beginning of the queue and returns it.\n *\n * Reverts with `Empty` if the queue is empty.\n */\n function popFront(Bytes32Deque storage deque) internal returns (bytes32 value) {\n if (empty(deque)) revert Empty();\n int128 frontIndex = deque._begin;\n value = deque._data[frontIndex];\n delete deque._data[frontIndex];\n unchecked {\n deque._begin = frontIndex + 1;\n }\n }\n\n /**\n * @dev Returns the item at the beginning of the queue.\n *\n * Reverts with `Empty` if the queue is empty.\n */\n function front(Bytes32Deque storage deque) internal view returns (bytes32 value) {\n if (empty(deque)) revert Empty();\n int128 frontIndex = deque._begin;\n return deque._data[frontIndex];\n }\n\n /**\n * @dev Returns the item at the end of the queue.\n *\n * Reverts with `Empty` if the queue is empty.\n */\n function back(Bytes32Deque storage deque) internal view returns (bytes32 value) {\n if (empty(deque)) revert Empty();\n int128 backIndex;\n unchecked {\n backIndex = deque._end - 1;\n }\n return deque._data[backIndex];\n }\n\n /**\n * @dev Return the item at a position in the queue given by `index`, with the first item at 0 and last item at\n * `length(deque) - 1`.\n *\n * Reverts with `OutOfBounds` if the index is out of bounds.\n */\n function at(Bytes32Deque storage deque, uint256 index) internal view returns (bytes32 value) {\n // int256(deque._begin) is a safe upcast\n int128 idx = SafeCastUpgradeable.toInt128(int256(deque._begin) + SafeCastUpgradeable.toInt256(index));\n if (idx >= deque._end) revert OutOfBounds();\n return deque._data[idx];\n }\n\n /**\n * @dev Resets the queue back to being empty.\n *\n * NOTE: The current items are left behind in storage. This does not affect the functioning of the queue, but misses\n * out on potential gas refunds.\n */\n function clear(Bytes32Deque storage deque) internal {\n deque._begin = 0;\n deque._end = 0;\n }\n\n /**\n * @dev Returns the number of items in the queue.\n */\n function length(Bytes32Deque storage deque) internal view returns (uint256) {\n // The interface preserves the invariant that begin <= end so we assume this will not overflow.\n // We also assume there are at most int256.max items in the queue.\n unchecked {\n return uint256(int256(deque._end) - int256(deque._begin));\n }\n }\n\n /**\n * @dev Returns true if the queue is empty.\n */\n function empty(Bytes32Deque storage deque) internal view returns (bool) {\n return deque._end <= deque._begin;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/structs/EnumerableSet.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Library for managing\n * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive\n * types.\n *\n * Sets have the following properties:\n *\n * - Elements are added, removed, and checked for existence in constant time\n * (O(1)).\n * - Elements are enumerated in O(n). No guarantees are made on the ordering.\n *\n * ```\n * contract Example {\n * // Add the library methods\n * using EnumerableSet for EnumerableSet.AddressSet;\n *\n * // Declare a set state variable\n * EnumerableSet.AddressSet private mySet;\n * }\n * ```\n *\n * As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)\n * and `uint256` (`UintSet`) are supported.\n *\n * [WARNING]\n * ====\n * Trying to delete such a structure from storage will likely result in data corruption, rendering the structure unusable.\n * See https://github.com/ethereum/solidity/pull/11843[ethereum/solidity#11843] for more info.\n *\n * In order to clean an EnumerableSet, you can either remove all elements one by one or create a fresh instance using an array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSetUpgradeable {\n // To implement this library for multiple types with as little code\n // repetition as possible, we write it in terms of a generic Set type with\n // bytes32 values.\n // The Set implementation uses private functions, and user-facing\n // implementations (such as AddressSet) are just wrappers around the\n // underlying Set.\n // This means that we can only create new EnumerableSets for types that fit\n // in bytes32.\n\n struct Set {\n // Storage of set values\n bytes32[] _values;\n // Position of the value in the `values` array, plus 1 because index 0\n // means a value is not in the set.\n mapping(bytes32 => uint256) _indexes;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function _add(Set storage set, bytes32 value) private returns (bool) {\n if (!_contains(set, value)) {\n set._values.push(value);\n // The value is stored at length-1, but we add 1 to all indexes\n // and use 0 as a sentinel value\n set._indexes[value] = set._values.length;\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function _remove(Set storage set, bytes32 value) private returns (bool) {\n // We read and store the value's index to prevent multiple reads from the same storage slot\n uint256 valueIndex = set._indexes[value];\n\n if (valueIndex != 0) {\n // Equivalent to contains(set, value)\n // To delete an element from the _values array in O(1), we swap the element to delete with the last one in\n // the array, and then remove the last element (sometimes called as 'swap and pop').\n // This modifies the order of the array, as noted in {at}.\n\n uint256 toDeleteIndex = valueIndex - 1;\n uint256 lastIndex = set._values.length - 1;\n\n if (lastIndex != toDeleteIndex) {\n bytes32 lastValue = set._values[lastIndex];\n\n // Move the last value to the index where the value to delete is\n set._values[toDeleteIndex] = lastValue;\n // Update the index for the moved value\n set._indexes[lastValue] = valueIndex; // Replace lastValue's index to valueIndex\n }\n\n // Delete the slot where the moved value was stored\n set._values.pop();\n\n // Delete the index for the deleted slot\n delete set._indexes[value];\n\n return true;\n } else {\n return false;\n }\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function _contains(Set storage set, bytes32 value) private view returns (bool) {\n return set._indexes[value] != 0;\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function _length(Set storage set) private view returns (uint256) {\n return set._values.length;\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function _at(Set storage set, uint256 index) private view returns (bytes32) {\n return set._values[index];\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function _values(Set storage set) private view returns (bytes32[] memory) {\n return set._values;\n }\n\n // Bytes32Set\n\n struct Bytes32Set {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _add(set._inner, value);\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {\n return _remove(set._inner, value);\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {\n return _contains(set._inner, value);\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(Bytes32Set storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {\n return _at(set._inner, index);\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {\n return _values(set._inner);\n }\n\n // AddressSet\n\n struct AddressSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(AddressSet storage set, address value) internal returns (bool) {\n return _add(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(AddressSet storage set, address value) internal returns (bool) {\n return _remove(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(AddressSet storage set, address value) internal view returns (bool) {\n return _contains(set._inner, bytes32(uint256(uint160(value))));\n }\n\n /**\n * @dev Returns the number of values in the set. O(1).\n */\n function length(AddressSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(AddressSet storage set, uint256 index) internal view returns (address) {\n return address(uint160(uint256(_at(set._inner, index))));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(AddressSet storage set) internal view returns (address[] memory) {\n bytes32[] memory store = _values(set._inner);\n address[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\n\n // UintSet\n\n struct UintSet {\n Set _inner;\n }\n\n /**\n * @dev Add a value to a set. O(1).\n *\n * Returns true if the value was added to the set, that is if it was not\n * already present.\n */\n function add(UintSet storage set, uint256 value) internal returns (bool) {\n return _add(set._inner, bytes32(value));\n }\n\n /**\n * @dev Removes a value from a set. O(1).\n *\n * Returns true if the value was removed from the set, that is if it was\n * present.\n */\n function remove(UintSet storage set, uint256 value) internal returns (bool) {\n return _remove(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns true if the value is in the set. O(1).\n */\n function contains(UintSet storage set, uint256 value) internal view returns (bool) {\n return _contains(set._inner, bytes32(value));\n }\n\n /**\n * @dev Returns the number of values on the set. O(1).\n */\n function length(UintSet storage set) internal view returns (uint256) {\n return _length(set._inner);\n }\n\n /**\n * @dev Returns the value stored at position `index` in the set. O(1).\n *\n * Note that there are no guarantees on the ordering of values inside the\n * array, and it may change when more values are added or removed.\n *\n * Requirements:\n *\n * - `index` must be strictly less than {length}.\n */\n function at(UintSet storage set, uint256 index) internal view returns (uint256) {\n return uint256(_at(set._inner, index));\n }\n\n /**\n * @dev Return the entire set in an array\n *\n * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed\n * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that\n * this function has an unbounded cost, and using it as part of a state-changing function may render the function\n * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.\n */\n function values(UintSet storage set) internal view returns (uint256[] memory) {\n bytes32[] memory store = _values(set._inner);\n uint256[] memory result;\n\n /// @solidity memory-safe-assembly\n assembly {\n result := store\n }\n\n return result;\n }\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/token/ERC20/utils/SafeERC20Upgradeable.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 \"../IERC20Upgradeable.sol\";\nimport \"../extensions/draft-IERC20PermitUpgradeable.sol\";\nimport \"../../../utils/AddressUpgradeable.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 SafeERC20Upgradeable {\n using AddressUpgradeable for address;\n\n function safeTransfer(\n IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20Upgradeable 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 IERC20PermitUpgradeable 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(IERC20Upgradeable 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"
},
"@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxERC20.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * IDepositBoxERC20.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"../IDepositBox.sol\";\n\n\ninterface IDepositBoxERC20 is IDepositBox {\n function addERC20TokenByOwner(string calldata schainName, address erc20OnMainnet) external;\n function depositERC20(string calldata schainName, address erc20OnMainnet, uint256 amount) external;\n function doTransfer(address token, address receiver, uint256 amount) external;\n function escalate(uint256 transferId) external;\n function getFunds(string calldata schainName, address erc20OnMainnet, address receiver, uint amount) external;\n function rejectTransfer(uint transferId) external;\n function retrieve() external;\n function retrieveFor(address receiver) external;\n function setArbitrageDuration(string calldata schainName, uint256 delayInSeconds) external;\n function setBigTransferValue(string calldata schainName, address token, uint256 value) external;\n function setBigTransferDelay(string calldata schainName, uint256 delayInSeconds) external;\n function stopTrustingReceiver(string calldata schainName, address receiver) external;\n function trustReceiver(string calldata schainName, address receiver) external;\n function validateTransfer(uint transferId) external;\n function isReceiverTrusted(bytes32 schainHash, address receiver) external view returns (bool);\n function getArbitrageDuration(bytes32 schainHash) external view returns (uint256);\n function getBigTransferThreshold(bytes32 schainHash, address token) external view returns (uint256);\n function getDelayedAmount(address receiver, address token) external view returns (uint256 value);\n function getNextUnlockTimestamp(address receiver, address token) external view returns (uint256 unlockTimestamp);\n function getSchainToERC20(string calldata schainName, address erc20OnMainnet) external view returns (bool);\n function getSchainToAllERC20Length(string calldata schainName) external view returns (uint256);\n function getSchainToAllERC20(\n string calldata schainName,\n uint256 from,\n uint256 to\n )\n external\n view\n returns (address[] memory);\n function getTimeDelay(bytes32 schainHash) external view returns (uint256);\n function getTrustedReceiver(string calldata schainName, uint256 index) external view returns (address);\n function getTrustedReceiversAmount(bytes32 schainHash) external view returns (uint256);\n}"
},
"contracts/Messages.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * Messages.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity 0.8.16;\n\n\n/**\n * @title Messages\n * @dev Library for encoding and decoding messages\n * for transferring from Mainnet to Schain and vice versa.\n */\nlibrary Messages {\n\n /**\n * @dev Enumerator that describes all supported message types.\n */\n enum MessageType {\n EMPTY,\n TRANSFER_ETH,\n TRANSFER_ERC20,\n TRANSFER_ERC20_AND_TOTAL_SUPPLY,\n TRANSFER_ERC20_AND_TOKEN_INFO,\n TRANSFER_ERC721,\n TRANSFER_ERC721_AND_TOKEN_INFO,\n USER_STATUS,\n INTERCHAIN_CONNECTION,\n TRANSFER_ERC1155,\n TRANSFER_ERC1155_AND_TOKEN_INFO,\n TRANSFER_ERC1155_BATCH,\n TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,\n TRANSFER_ERC721_WITH_METADATA,\n TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO\n }\n\n /**\n * @dev Structure for base message.\n */\n struct BaseMessage {\n MessageType messageType;\n }\n\n /**\n * @dev Structure for describing ETH.\n */\n struct TransferEthMessage {\n BaseMessage message;\n address receiver;\n uint256 amount;\n }\n\n /**\n * @dev Structure for user status.\n */\n struct UserStatusMessage {\n BaseMessage message;\n address receiver;\n bool isActive;\n }\n\n /**\n * @dev Structure for describing ERC20 token.\n */\n struct TransferErc20Message {\n BaseMessage message;\n address token;\n address receiver;\n uint256 amount;\n }\n\n /**\n * @dev Structure for describing additional data for ERC20 token.\n */\n struct Erc20TokenInfo {\n string name;\n uint8 decimals;\n string symbol;\n }\n\n /**\n * @dev Structure for describing ERC20 with token supply.\n */\n struct TransferErc20AndTotalSupplyMessage {\n TransferErc20Message baseErc20transfer;\n uint256 totalSupply;\n }\n\n /**\n * @dev Structure for describing ERC20 with token info.\n */\n struct TransferErc20AndTokenInfoMessage {\n TransferErc20Message baseErc20transfer;\n uint256 totalSupply;\n Erc20TokenInfo tokenInfo;\n }\n\n /**\n * @dev Structure for describing base ERC721.\n */\n struct TransferErc721Message {\n BaseMessage message;\n address token;\n address receiver;\n uint256 tokenId;\n }\n\n /**\n * @dev Structure for describing base ERC721 with metadata.\n */\n struct TransferErc721MessageWithMetadata {\n TransferErc721Message erc721message;\n string tokenURI;\n }\n\n /**\n * @dev Structure for describing ERC20 with token info.\n */\n struct Erc721TokenInfo {\n string name;\n string symbol;\n }\n\n /**\n * @dev Structure for describing additional data for ERC721 token.\n */\n struct TransferErc721AndTokenInfoMessage {\n TransferErc721Message baseErc721transfer;\n Erc721TokenInfo tokenInfo;\n }\n\n /**\n * @dev Structure for describing additional data for ERC721 token with metadata.\n */\n struct TransferErc721WithMetadataAndTokenInfoMessage {\n TransferErc721MessageWithMetadata baseErc721transferWithMetadata;\n Erc721TokenInfo tokenInfo;\n }\n\n /**\n * @dev Structure for describing whether interchain connection is allowed.\n */\n struct InterchainConnectionMessage {\n BaseMessage message;\n bool isAllowed;\n }\n\n /**\n * @dev Structure for describing whether interchain connection is allowed.\n */\n struct TransferErc1155Message {\n BaseMessage message;\n address token;\n address receiver;\n uint256 id;\n uint256 amount;\n }\n\n /**\n * @dev Structure for describing ERC1155 token in batches.\n */\n struct TransferErc1155BatchMessage {\n BaseMessage message;\n address token;\n address receiver;\n uint256[] ids;\n uint256[] amounts;\n }\n\n /**\n * @dev Structure for describing ERC1155 token info.\n */\n struct Erc1155TokenInfo {\n string uri;\n }\n\n /**\n * @dev Structure for describing message for transferring ERC1155 token with info.\n */\n struct TransferErc1155AndTokenInfoMessage {\n TransferErc1155Message baseErc1155transfer;\n Erc1155TokenInfo tokenInfo;\n }\n\n /**\n * @dev Structure for describing message for transferring ERC1155 token in batches with info.\n */\n struct TransferErc1155BatchAndTokenInfoMessage {\n TransferErc1155BatchMessage baseErc1155Batchtransfer;\n Erc1155TokenInfo tokenInfo;\n }\n\n\n /**\n * @dev Returns type of message for encoded data.\n */\n function getMessageType(bytes calldata data) internal pure returns (MessageType) {\n uint256 firstWord = abi.decode(data, (uint256));\n if (firstWord % 32 == 0) {\n return getMessageType(data[firstWord:]);\n } else {\n return abi.decode(data, (Messages.MessageType));\n }\n }\n\n /**\n * @dev Encodes message for transferring ETH. Returns encoded message.\n */\n function encodeTransferEthMessage(address receiver, uint256 amount) internal pure returns (bytes memory) {\n TransferEthMessage memory message = TransferEthMessage(\n BaseMessage(MessageType.TRANSFER_ETH),\n receiver,\n amount\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ETH. Returns structure `TransferEthMessage`.\n */\n function decodeTransferEthMessage(\n bytes calldata data\n ) internal pure returns (TransferEthMessage memory) {\n require(getMessageType(data) == MessageType.TRANSFER_ETH, \"Message type is not ETH transfer\");\n return abi.decode(data, (TransferEthMessage));\n }\n\n /**\n * @dev Encodes message for transferring ETH. Returns encoded message.\n */\n function encodeTransferErc20Message(\n address token,\n address receiver,\n uint256 amount\n ) internal pure returns (bytes memory) {\n TransferErc20Message memory message = TransferErc20Message(\n BaseMessage(MessageType.TRANSFER_ERC20),\n token,\n receiver,\n amount\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Encodes message for transferring ERC20 with total supply. Returns encoded message.\n */\n function encodeTransferErc20AndTotalSupplyMessage(\n address token,\n address receiver,\n uint256 amount,\n uint256 totalSupply\n ) internal pure returns (bytes memory) {\n TransferErc20AndTotalSupplyMessage memory message = TransferErc20AndTotalSupplyMessage(\n TransferErc20Message(\n BaseMessage(MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY),\n token,\n receiver,\n amount\n ),\n totalSupply\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC20. Returns structure `TransferErc20Message`.\n */\n function decodeTransferErc20Message(\n bytes calldata data\n ) internal pure returns (TransferErc20Message memory) {\n require(getMessageType(data) == MessageType.TRANSFER_ERC20, \"Message type is not ERC20 transfer\");\n return abi.decode(data, (TransferErc20Message));\n }\n\n /**\n * @dev Decodes message for transferring ERC20 with total supply. \n * Returns structure `TransferErc20AndTotalSupplyMessage`.\n */\n function decodeTransferErc20AndTotalSupplyMessage(\n bytes calldata data\n ) internal pure returns (TransferErc20AndTotalSupplyMessage memory) {\n require(\n getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOTAL_SUPPLY,\n \"Message type is not ERC20 transfer and total supply\"\n );\n return abi.decode(data, (TransferErc20AndTotalSupplyMessage));\n }\n\n /**\n * @dev Encodes message for transferring ERC20 with token info. \n * Returns encoded message.\n */\n function encodeTransferErc20AndTokenInfoMessage(\n address token,\n address receiver,\n uint256 amount,\n uint256 totalSupply,\n Erc20TokenInfo memory tokenInfo\n ) internal pure returns (bytes memory) {\n TransferErc20AndTokenInfoMessage memory message = TransferErc20AndTokenInfoMessage(\n TransferErc20Message(\n BaseMessage(MessageType.TRANSFER_ERC20_AND_TOKEN_INFO),\n token,\n receiver,\n amount\n ),\n totalSupply,\n tokenInfo\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC20 with token info. \n * Returns structure `TransferErc20AndTokenInfoMessage`.\n */\n function decodeTransferErc20AndTokenInfoMessage(\n bytes calldata data\n ) internal pure returns (TransferErc20AndTokenInfoMessage memory) {\n require(\n getMessageType(data) == MessageType.TRANSFER_ERC20_AND_TOKEN_INFO,\n \"Message type is not ERC20 transfer with token info\"\n );\n return abi.decode(data, (TransferErc20AndTokenInfoMessage));\n }\n\n /**\n * @dev Encodes message for transferring ERC721. \n * Returns encoded message.\n */\n function encodeTransferErc721Message(\n address token,\n address receiver,\n uint256 tokenId\n ) internal pure returns (bytes memory) {\n TransferErc721Message memory message = TransferErc721Message(\n BaseMessage(MessageType.TRANSFER_ERC721),\n token,\n receiver,\n tokenId\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC721. \n * Returns structure `TransferErc721Message`.\n */\n function decodeTransferErc721Message(\n bytes calldata data\n ) internal pure returns (TransferErc721Message memory) {\n require(getMessageType(data) == MessageType.TRANSFER_ERC721, \"Message type is not ERC721 transfer\");\n return abi.decode(data, (TransferErc721Message));\n }\n\n /**\n * @dev Encodes message for transferring ERC721 with token info. \n * Returns encoded message.\n */\n function encodeTransferErc721AndTokenInfoMessage(\n address token,\n address receiver,\n uint256 tokenId,\n Erc721TokenInfo memory tokenInfo\n ) internal pure returns (bytes memory) {\n TransferErc721AndTokenInfoMessage memory message = TransferErc721AndTokenInfoMessage(\n TransferErc721Message(\n BaseMessage(MessageType.TRANSFER_ERC721_AND_TOKEN_INFO),\n token,\n receiver,\n tokenId\n ),\n tokenInfo\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC721 with token info. \n * Returns structure `TransferErc721AndTokenInfoMessage`.\n */\n function decodeTransferErc721AndTokenInfoMessage(\n bytes calldata data\n ) internal pure returns (TransferErc721AndTokenInfoMessage memory) {\n require(\n getMessageType(data) == MessageType.TRANSFER_ERC721_AND_TOKEN_INFO,\n \"Message type is not ERC721 transfer with token info\"\n );\n return abi.decode(data, (TransferErc721AndTokenInfoMessage));\n }\n\n /**\n * @dev Encodes message for transferring ERC721. \n * Returns encoded message.\n */\n function encodeTransferErc721MessageWithMetadata(\n address token,\n address receiver,\n uint256 tokenId,\n string memory tokenURI\n ) internal pure returns (bytes memory) {\n TransferErc721MessageWithMetadata memory message = TransferErc721MessageWithMetadata(\n TransferErc721Message(\n BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA),\n token,\n receiver,\n tokenId\n ),\n tokenURI\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC721. \n * Returns structure `TransferErc721MessageWithMetadata`.\n */\n function decodeTransferErc721MessageWithMetadata(\n bytes calldata data\n ) internal pure returns (TransferErc721MessageWithMetadata memory) {\n require(\n getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA,\n \"Message type is not ERC721 transfer\"\n );\n return abi.decode(data, (TransferErc721MessageWithMetadata));\n }\n\n /**\n * @dev Encodes message for transferring ERC721 with token info. \n * Returns encoded message.\n */\n function encodeTransferErc721WithMetadataAndTokenInfoMessage(\n address token,\n address receiver,\n uint256 tokenId,\n string memory tokenURI,\n Erc721TokenInfo memory tokenInfo\n ) internal pure returns (bytes memory) {\n TransferErc721WithMetadataAndTokenInfoMessage memory message = TransferErc721WithMetadataAndTokenInfoMessage(\n TransferErc721MessageWithMetadata(\n TransferErc721Message(\n BaseMessage(MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO),\n token,\n receiver,\n tokenId\n ),\n tokenURI\n ),\n tokenInfo\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC721 with token info. \n * Returns structure `TransferErc721WithMetadataAndTokenInfoMessage`.\n */\n function decodeTransferErc721WithMetadataAndTokenInfoMessage(\n bytes calldata data\n ) internal pure returns (TransferErc721WithMetadataAndTokenInfoMessage memory) {\n require(\n getMessageType(data) == MessageType.TRANSFER_ERC721_WITH_METADATA_AND_TOKEN_INFO,\n \"Message type is not ERC721 transfer with token info\"\n );\n return abi.decode(data, (TransferErc721WithMetadataAndTokenInfoMessage));\n }\n\n /**\n * @dev Encodes message for activating user on schain. \n * Returns encoded message.\n */\n function encodeActivateUserMessage(address receiver) internal pure returns (bytes memory){\n return _encodeUserStatusMessage(receiver, true);\n }\n\n /**\n * @dev Encodes message for locking user on schain. \n * Returns encoded message.\n */\n function encodeLockUserMessage(address receiver) internal pure returns (bytes memory){\n return _encodeUserStatusMessage(receiver, false);\n }\n\n /**\n * @dev Decodes message for user status. \n * Returns structure UserStatusMessage.\n */\n function decodeUserStatusMessage(bytes calldata data) internal pure returns (UserStatusMessage memory) {\n require(getMessageType(data) == MessageType.USER_STATUS, \"Message type is not User Status\");\n return abi.decode(data, (UserStatusMessage));\n }\n\n\n /**\n * @dev Encodes message for allowing interchain connection.\n * Returns encoded message.\n */\n function encodeInterchainConnectionMessage(bool isAllowed) internal pure returns (bytes memory) {\n InterchainConnectionMessage memory message = InterchainConnectionMessage(\n BaseMessage(MessageType.INTERCHAIN_CONNECTION),\n isAllowed\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for allowing interchain connection.\n * Returns structure `InterchainConnectionMessage`.\n */\n function decodeInterchainConnectionMessage(bytes calldata data)\n internal\n pure\n returns (InterchainConnectionMessage memory)\n {\n require(getMessageType(data) == MessageType.INTERCHAIN_CONNECTION, \"Message type is not Interchain connection\");\n return abi.decode(data, (InterchainConnectionMessage));\n }\n\n /**\n * @dev Encodes message for transferring ERC1155 token.\n * Returns encoded message.\n */\n function encodeTransferErc1155Message(\n address token,\n address receiver,\n uint256 id,\n uint256 amount\n ) internal pure returns (bytes memory) {\n TransferErc1155Message memory message = TransferErc1155Message(\n BaseMessage(MessageType.TRANSFER_ERC1155),\n token,\n receiver,\n id,\n amount\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC1155 token.\n * Returns structure `TransferErc1155Message`.\n */\n function decodeTransferErc1155Message(\n bytes calldata data\n ) internal pure returns (TransferErc1155Message memory) {\n require(getMessageType(data) == MessageType.TRANSFER_ERC1155, \"Message type is not ERC1155 transfer\");\n return abi.decode(data, (TransferErc1155Message));\n }\n\n /**\n * @dev Encodes message for transferring ERC1155 with token info.\n * Returns encoded message.\n */\n function encodeTransferErc1155AndTokenInfoMessage(\n address token,\n address receiver,\n uint256 id,\n uint256 amount,\n Erc1155TokenInfo memory tokenInfo\n ) internal pure returns (bytes memory) {\n TransferErc1155AndTokenInfoMessage memory message = TransferErc1155AndTokenInfoMessage(\n TransferErc1155Message(\n BaseMessage(MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO),\n token,\n receiver,\n id,\n amount\n ),\n tokenInfo\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC1155 with token info.\n * Returns structure `TransferErc1155AndTokenInfoMessage`.\n */\n function decodeTransferErc1155AndTokenInfoMessage(\n bytes calldata data\n ) internal pure returns (TransferErc1155AndTokenInfoMessage memory) {\n require(\n getMessageType(data) == MessageType.TRANSFER_ERC1155_AND_TOKEN_INFO,\n \"Message type is not ERC1155AndTokenInfo transfer\"\n );\n return abi.decode(data, (TransferErc1155AndTokenInfoMessage));\n }\n\n /**\n * @dev Encodes message for transferring ERC1155 token in batches.\n * Returns encoded message.\n */\n function encodeTransferErc1155BatchMessage(\n address token,\n address receiver,\n uint256[] memory ids,\n uint256[] memory amounts\n ) internal pure returns (bytes memory) {\n TransferErc1155BatchMessage memory message = TransferErc1155BatchMessage(\n BaseMessage(MessageType.TRANSFER_ERC1155_BATCH),\n token,\n receiver,\n ids,\n amounts\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC1155 token in batches.\n * Returns structure `TransferErc1155BatchMessage`.\n */\n function decodeTransferErc1155BatchMessage(\n bytes calldata data\n ) internal pure returns (TransferErc1155BatchMessage memory) {\n require(\n getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH,\n \"Message type is not ERC1155Batch transfer\"\n );\n return abi.decode(data, (TransferErc1155BatchMessage));\n }\n\n /**\n * @dev Encodes message for transferring ERC1155 token in batches with token info.\n * Returns encoded message.\n */\n function encodeTransferErc1155BatchAndTokenInfoMessage(\n address token,\n address receiver,\n uint256[] memory ids,\n uint256[] memory amounts,\n Erc1155TokenInfo memory tokenInfo\n ) internal pure returns (bytes memory) {\n TransferErc1155BatchAndTokenInfoMessage memory message = TransferErc1155BatchAndTokenInfoMessage(\n TransferErc1155BatchMessage(\n BaseMessage(MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO),\n token,\n receiver,\n ids,\n amounts\n ),\n tokenInfo\n );\n return abi.encode(message);\n }\n\n /**\n * @dev Decodes message for transferring ERC1155 token in batches with token info.\n * Returns structure `TransferErc1155BatchAndTokenInfoMessage`.\n */\n function decodeTransferErc1155BatchAndTokenInfoMessage(\n bytes calldata data\n ) internal pure returns (TransferErc1155BatchAndTokenInfoMessage memory) {\n require(\n getMessageType(data) == MessageType.TRANSFER_ERC1155_BATCH_AND_TOKEN_INFO,\n \"Message type is not ERC1155BatchAndTokenInfo transfer\"\n );\n return abi.decode(data, (TransferErc1155BatchAndTokenInfoMessage));\n }\n\n /**\n * @dev Encodes message for transferring user status on schain.\n * Returns encoded message.\n */\n function _encodeUserStatusMessage(address receiver, bool isActive) private pure returns (bytes memory) {\n UserStatusMessage memory message = UserStatusMessage(\n BaseMessage(MessageType.USER_STATUS),\n receiver,\n isActive\n );\n return abi.encode(message);\n }\n\n}"
},
"contracts/mainnet/DepositBox.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * DepositBox.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Artem Payvin\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity 0.8.16;\n\nimport \"@skalenetwork/ima-interfaces/mainnet/IDepositBox.sol\";\n\nimport \"./Twin.sol\";\n\n\n/**\n * @title DepositBox\n * @dev Abstract contracts for DepositBoxes on mainnet.\n */\nabstract contract DepositBox is IDepositBox, Twin {\n\n ILinker public linker;\n\n // schainHash => true if automatic deployment tokens on schain was enabled \n mapping(bytes32 => bool) private _automaticDeploy;\n\n bytes32 public constant DEPOSIT_BOX_MANAGER_ROLE = keccak256(\"DEPOSIT_BOX_MANAGER_ROLE\");\n\n /**\n * @dev Modifier for checking whether schain was not killed.\n */\n modifier whenNotKilled(bytes32 schainHash) {\n require(linker.isNotKilled(schainHash), \"Schain is killed\");\n _;\n }\n\n /**\n * @dev Modifier for checking whether schain was killed.\n */\n modifier whenKilled(bytes32 schainHash) {\n require(!linker.isNotKilled(schainHash), \"Schain is not killed\");\n _;\n }\n\n /**\n * @dev Modifier for checking whether schainName is not equal to `Mainnet` \n * and address of receiver is not equal to null before transferring funds from mainnet to schain.\n */\n modifier rightTransaction(string memory schainName, address to) {\n require(\n keccak256(abi.encodePacked(schainName)) != keccak256(abi.encodePacked(\"Mainnet\")),\n \"SKALE chain name cannot be Mainnet\"\n );\n require(to != address(0), \"Receiver address cannot be null\");\n _;\n }\n\n /**\n * @dev Modifier for checking whether schainHash is not equal to `Mainnet` \n * and sender contract was added as contract processor on schain.\n */\n modifier checkReceiverChain(bytes32 schainHash, address sender) {\n require(\n schainHash != keccak256(abi.encodePacked(\"Mainnet\")) &&\n sender == schainLinks[schainHash],\n \"Receiver chain is incorrect\"\n );\n _;\n }\n\n /**\n * @dev Allows Schain owner turn on whitelist of tokens.\n */\n function enableWhitelist(string memory schainName) external override onlySchainOwner(schainName) {\n _automaticDeploy[keccak256(abi.encodePacked(schainName))] = false;\n }\n\n /**\n * @dev Allows Schain owner turn off whitelist of tokens.\n */\n function disableWhitelist(string memory schainName) external override onlySchainOwner(schainName) {\n _automaticDeploy[keccak256(abi.encodePacked(schainName))] = true;\n }\n\n function initialize(\n IContractManager contractManagerOfSkaleManagerValue,\n ILinker newLinker,\n IMessageProxyForMainnet messageProxyValue\n )\n public\n override\n virtual\n initializer\n {\n Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);\n _setupRole(LINKER_ROLE, address(newLinker));\n linker = newLinker;\n }\n\n /**\n * @dev Returns is whitelist enabled on schain.\n */\n function isWhitelisted(string memory schainName) public view override returns (bool) {\n return !_automaticDeploy[keccak256(abi.encodePacked(schainName))];\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/math/SafeCastUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/SafeCast.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow\n * checks.\n *\n * Downcasting from uint256/int256 in Solidity does not revert on overflow. This can\n * easily result in undesired exploitation or bugs, since developers usually\n * assume that overflows raise errors. `SafeCast` restores this intuition by\n * reverting the transaction when such an operation overflows.\n *\n * Using this library instead of the unchecked operations eliminates an entire\n * class of bugs, so it's recommended to use it always.\n *\n * Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing\n * all math on `uint256` and `int256` and then downcasting.\n */\nlibrary SafeCastUpgradeable {\n /**\n * @dev Returns the downcasted uint248 from uint256, reverting on\n * overflow (when the input is greater than largest uint248).\n *\n * Counterpart to Solidity's `uint248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toUint248(uint256 value) internal pure returns (uint248) {\n require(value <= type(uint248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return uint248(value);\n }\n\n /**\n * @dev Returns the downcasted uint240 from uint256, reverting on\n * overflow (when the input is greater than largest uint240).\n *\n * Counterpart to Solidity's `uint240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toUint240(uint256 value) internal pure returns (uint240) {\n require(value <= type(uint240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return uint240(value);\n }\n\n /**\n * @dev Returns the downcasted uint232 from uint256, reverting on\n * overflow (when the input is greater than largest uint232).\n *\n * Counterpart to Solidity's `uint232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toUint232(uint256 value) internal pure returns (uint232) {\n require(value <= type(uint232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return uint232(value);\n }\n\n /**\n * @dev Returns the downcasted uint224 from uint256, reverting on\n * overflow (when the input is greater than largest uint224).\n *\n * Counterpart to Solidity's `uint224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.2._\n */\n function toUint224(uint256 value) internal pure returns (uint224) {\n require(value <= type(uint224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return uint224(value);\n }\n\n /**\n * @dev Returns the downcasted uint216 from uint256, reverting on\n * overflow (when the input is greater than largest uint216).\n *\n * Counterpart to Solidity's `uint216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toUint216(uint256 value) internal pure returns (uint216) {\n require(value <= type(uint216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return uint216(value);\n }\n\n /**\n * @dev Returns the downcasted uint208 from uint256, reverting on\n * overflow (when the input is greater than largest uint208).\n *\n * Counterpart to Solidity's `uint208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toUint208(uint256 value) internal pure returns (uint208) {\n require(value <= type(uint208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return uint208(value);\n }\n\n /**\n * @dev Returns the downcasted uint200 from uint256, reverting on\n * overflow (when the input is greater than largest uint200).\n *\n * Counterpart to Solidity's `uint200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toUint200(uint256 value) internal pure returns (uint200) {\n require(value <= type(uint200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return uint200(value);\n }\n\n /**\n * @dev Returns the downcasted uint192 from uint256, reverting on\n * overflow (when the input is greater than largest uint192).\n *\n * Counterpart to Solidity's `uint192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toUint192(uint256 value) internal pure returns (uint192) {\n require(value <= type(uint192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return uint192(value);\n }\n\n /**\n * @dev Returns the downcasted uint184 from uint256, reverting on\n * overflow (when the input is greater than largest uint184).\n *\n * Counterpart to Solidity's `uint184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toUint184(uint256 value) internal pure returns (uint184) {\n require(value <= type(uint184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return uint184(value);\n }\n\n /**\n * @dev Returns the downcasted uint176 from uint256, reverting on\n * overflow (when the input is greater than largest uint176).\n *\n * Counterpart to Solidity's `uint176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toUint176(uint256 value) internal pure returns (uint176) {\n require(value <= type(uint176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return uint176(value);\n }\n\n /**\n * @dev Returns the downcasted uint168 from uint256, reverting on\n * overflow (when the input is greater than largest uint168).\n *\n * Counterpart to Solidity's `uint168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toUint168(uint256 value) internal pure returns (uint168) {\n require(value <= type(uint168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return uint168(value);\n }\n\n /**\n * @dev Returns the downcasted uint160 from uint256, reverting on\n * overflow (when the input is greater than largest uint160).\n *\n * Counterpart to Solidity's `uint160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toUint160(uint256 value) internal pure returns (uint160) {\n require(value <= type(uint160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return uint160(value);\n }\n\n /**\n * @dev Returns the downcasted uint152 from uint256, reverting on\n * overflow (when the input is greater than largest uint152).\n *\n * Counterpart to Solidity's `uint152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toUint152(uint256 value) internal pure returns (uint152) {\n require(value <= type(uint152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return uint152(value);\n }\n\n /**\n * @dev Returns the downcasted uint144 from uint256, reverting on\n * overflow (when the input is greater than largest uint144).\n *\n * Counterpart to Solidity's `uint144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toUint144(uint256 value) internal pure returns (uint144) {\n require(value <= type(uint144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return uint144(value);\n }\n\n /**\n * @dev Returns the downcasted uint136 from uint256, reverting on\n * overflow (when the input is greater than largest uint136).\n *\n * Counterpart to Solidity's `uint136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toUint136(uint256 value) internal pure returns (uint136) {\n require(value <= type(uint136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return uint136(value);\n }\n\n /**\n * @dev Returns the downcasted uint128 from uint256, reverting on\n * overflow (when the input is greater than largest uint128).\n *\n * Counterpart to Solidity's `uint128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v2.5._\n */\n function toUint128(uint256 value) internal pure returns (uint128) {\n require(value <= type(uint128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return uint128(value);\n }\n\n /**\n * @dev Returns the downcasted uint120 from uint256, reverting on\n * overflow (when the input is greater than largest uint120).\n *\n * Counterpart to Solidity's `uint120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toUint120(uint256 value) internal pure returns (uint120) {\n require(value <= type(uint120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return uint120(value);\n }\n\n /**\n * @dev Returns the downcasted uint112 from uint256, reverting on\n * overflow (when the input is greater than largest uint112).\n *\n * Counterpart to Solidity's `uint112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toUint112(uint256 value) internal pure returns (uint112) {\n require(value <= type(uint112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return uint112(value);\n }\n\n /**\n * @dev Returns the downcasted uint104 from uint256, reverting on\n * overflow (when the input is greater than largest uint104).\n *\n * Counterpart to Solidity's `uint104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toUint104(uint256 value) internal pure returns (uint104) {\n require(value <= type(uint104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return uint104(value);\n }\n\n /**\n * @dev Returns the downcasted uint96 from uint256, reverting on\n * overflow (when the input is greater than largest uint96).\n *\n * Counterpart to Solidity's `uint96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.2._\n */\n function toUint96(uint256 value) internal pure returns (uint96) {\n require(value <= type(uint96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return uint96(value);\n }\n\n /**\n * @dev Returns the downcasted uint88 from uint256, reverting on\n * overflow (when the input is greater than largest uint88).\n *\n * Counterpart to Solidity's `uint88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toUint88(uint256 value) internal pure returns (uint88) {\n require(value <= type(uint88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return uint88(value);\n }\n\n /**\n * @dev Returns the downcasted uint80 from uint256, reverting on\n * overflow (when the input is greater than largest uint80).\n *\n * Counterpart to Solidity's `uint80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toUint80(uint256 value) internal pure returns (uint80) {\n require(value <= type(uint80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return uint80(value);\n }\n\n /**\n * @dev Returns the downcasted uint72 from uint256, reverting on\n * overflow (when the input is greater than largest uint72).\n *\n * Counterpart to Solidity's `uint72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toUint72(uint256 value) internal pure returns (uint72) {\n require(value <= type(uint72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return uint72(value);\n }\n\n /**\n * @dev Returns the downcasted uint64 from uint256, reverting on\n * overflow (when the input is greater than largest uint64).\n *\n * Counterpart to Solidity's `uint64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v2.5._\n */\n function toUint64(uint256 value) internal pure returns (uint64) {\n require(value <= type(uint64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return uint64(value);\n }\n\n /**\n * @dev Returns the downcasted uint56 from uint256, reverting on\n * overflow (when the input is greater than largest uint56).\n *\n * Counterpart to Solidity's `uint56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toUint56(uint256 value) internal pure returns (uint56) {\n require(value <= type(uint56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return uint56(value);\n }\n\n /**\n * @dev Returns the downcasted uint48 from uint256, reverting on\n * overflow (when the input is greater than largest uint48).\n *\n * Counterpart to Solidity's `uint48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toUint48(uint256 value) internal pure returns (uint48) {\n require(value <= type(uint48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return uint48(value);\n }\n\n /**\n * @dev Returns the downcasted uint40 from uint256, reverting on\n * overflow (when the input is greater than largest uint40).\n *\n * Counterpart to Solidity's `uint40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toUint40(uint256 value) internal pure returns (uint40) {\n require(value <= type(uint40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return uint40(value);\n }\n\n /**\n * @dev Returns the downcasted uint32 from uint256, reverting on\n * overflow (when the input is greater than largest uint32).\n *\n * Counterpart to Solidity's `uint32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v2.5._\n */\n function toUint32(uint256 value) internal pure returns (uint32) {\n require(value <= type(uint32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return uint32(value);\n }\n\n /**\n * @dev Returns the downcasted uint24 from uint256, reverting on\n * overflow (when the input is greater than largest uint24).\n *\n * Counterpart to Solidity's `uint24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toUint24(uint256 value) internal pure returns (uint24) {\n require(value <= type(uint24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return uint24(value);\n }\n\n /**\n * @dev Returns the downcasted uint16 from uint256, reverting on\n * overflow (when the input is greater than largest uint16).\n *\n * Counterpart to Solidity's `uint16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v2.5._\n */\n function toUint16(uint256 value) internal pure returns (uint16) {\n require(value <= type(uint16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return uint16(value);\n }\n\n /**\n * @dev Returns the downcasted uint8 from uint256, reverting on\n * overflow (when the input is greater than largest uint8).\n *\n * Counterpart to Solidity's `uint8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v2.5._\n */\n function toUint8(uint256 value) internal pure returns (uint8) {\n require(value <= type(uint8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return uint8(value);\n }\n\n /**\n * @dev Converts a signed int256 into an unsigned uint256.\n *\n * Requirements:\n *\n * - input must be greater than or equal to 0.\n *\n * _Available since v3.0._\n */\n function toUint256(int256 value) internal pure returns (uint256) {\n require(value >= 0, \"SafeCast: value must be positive\");\n return uint256(value);\n }\n\n /**\n * @dev Returns the downcasted int248 from int256, reverting on\n * overflow (when the input is less than smallest int248 or\n * greater than largest int248).\n *\n * Counterpart to Solidity's `int248` operator.\n *\n * Requirements:\n *\n * - input must fit into 248 bits\n *\n * _Available since v4.7._\n */\n function toInt248(int256 value) internal pure returns (int248) {\n require(value >= type(int248).min && value <= type(int248).max, \"SafeCast: value doesn't fit in 248 bits\");\n return int248(value);\n }\n\n /**\n * @dev Returns the downcasted int240 from int256, reverting on\n * overflow (when the input is less than smallest int240 or\n * greater than largest int240).\n *\n * Counterpart to Solidity's `int240` operator.\n *\n * Requirements:\n *\n * - input must fit into 240 bits\n *\n * _Available since v4.7._\n */\n function toInt240(int256 value) internal pure returns (int240) {\n require(value >= type(int240).min && value <= type(int240).max, \"SafeCast: value doesn't fit in 240 bits\");\n return int240(value);\n }\n\n /**\n * @dev Returns the downcasted int232 from int256, reverting on\n * overflow (when the input is less than smallest int232 or\n * greater than largest int232).\n *\n * Counterpart to Solidity's `int232` operator.\n *\n * Requirements:\n *\n * - input must fit into 232 bits\n *\n * _Available since v4.7._\n */\n function toInt232(int256 value) internal pure returns (int232) {\n require(value >= type(int232).min && value <= type(int232).max, \"SafeCast: value doesn't fit in 232 bits\");\n return int232(value);\n }\n\n /**\n * @dev Returns the downcasted int224 from int256, reverting on\n * overflow (when the input is less than smallest int224 or\n * greater than largest int224).\n *\n * Counterpart to Solidity's `int224` operator.\n *\n * Requirements:\n *\n * - input must fit into 224 bits\n *\n * _Available since v4.7._\n */\n function toInt224(int256 value) internal pure returns (int224) {\n require(value >= type(int224).min && value <= type(int224).max, \"SafeCast: value doesn't fit in 224 bits\");\n return int224(value);\n }\n\n /**\n * @dev Returns the downcasted int216 from int256, reverting on\n * overflow (when the input is less than smallest int216 or\n * greater than largest int216).\n *\n * Counterpart to Solidity's `int216` operator.\n *\n * Requirements:\n *\n * - input must fit into 216 bits\n *\n * _Available since v4.7._\n */\n function toInt216(int256 value) internal pure returns (int216) {\n require(value >= type(int216).min && value <= type(int216).max, \"SafeCast: value doesn't fit in 216 bits\");\n return int216(value);\n }\n\n /**\n * @dev Returns the downcasted int208 from int256, reverting on\n * overflow (when the input is less than smallest int208 or\n * greater than largest int208).\n *\n * Counterpart to Solidity's `int208` operator.\n *\n * Requirements:\n *\n * - input must fit into 208 bits\n *\n * _Available since v4.7._\n */\n function toInt208(int256 value) internal pure returns (int208) {\n require(value >= type(int208).min && value <= type(int208).max, \"SafeCast: value doesn't fit in 208 bits\");\n return int208(value);\n }\n\n /**\n * @dev Returns the downcasted int200 from int256, reverting on\n * overflow (when the input is less than smallest int200 or\n * greater than largest int200).\n *\n * Counterpart to Solidity's `int200` operator.\n *\n * Requirements:\n *\n * - input must fit into 200 bits\n *\n * _Available since v4.7._\n */\n function toInt200(int256 value) internal pure returns (int200) {\n require(value >= type(int200).min && value <= type(int200).max, \"SafeCast: value doesn't fit in 200 bits\");\n return int200(value);\n }\n\n /**\n * @dev Returns the downcasted int192 from int256, reverting on\n * overflow (when the input is less than smallest int192 or\n * greater than largest int192).\n *\n * Counterpart to Solidity's `int192` operator.\n *\n * Requirements:\n *\n * - input must fit into 192 bits\n *\n * _Available since v4.7._\n */\n function toInt192(int256 value) internal pure returns (int192) {\n require(value >= type(int192).min && value <= type(int192).max, \"SafeCast: value doesn't fit in 192 bits\");\n return int192(value);\n }\n\n /**\n * @dev Returns the downcasted int184 from int256, reverting on\n * overflow (when the input is less than smallest int184 or\n * greater than largest int184).\n *\n * Counterpart to Solidity's `int184` operator.\n *\n * Requirements:\n *\n * - input must fit into 184 bits\n *\n * _Available since v4.7._\n */\n function toInt184(int256 value) internal pure returns (int184) {\n require(value >= type(int184).min && value <= type(int184).max, \"SafeCast: value doesn't fit in 184 bits\");\n return int184(value);\n }\n\n /**\n * @dev Returns the downcasted int176 from int256, reverting on\n * overflow (when the input is less than smallest int176 or\n * greater than largest int176).\n *\n * Counterpart to Solidity's `int176` operator.\n *\n * Requirements:\n *\n * - input must fit into 176 bits\n *\n * _Available since v4.7._\n */\n function toInt176(int256 value) internal pure returns (int176) {\n require(value >= type(int176).min && value <= type(int176).max, \"SafeCast: value doesn't fit in 176 bits\");\n return int176(value);\n }\n\n /**\n * @dev Returns the downcasted int168 from int256, reverting on\n * overflow (when the input is less than smallest int168 or\n * greater than largest int168).\n *\n * Counterpart to Solidity's `int168` operator.\n *\n * Requirements:\n *\n * - input must fit into 168 bits\n *\n * _Available since v4.7._\n */\n function toInt168(int256 value) internal pure returns (int168) {\n require(value >= type(int168).min && value <= type(int168).max, \"SafeCast: value doesn't fit in 168 bits\");\n return int168(value);\n }\n\n /**\n * @dev Returns the downcasted int160 from int256, reverting on\n * overflow (when the input is less than smallest int160 or\n * greater than largest int160).\n *\n * Counterpart to Solidity's `int160` operator.\n *\n * Requirements:\n *\n * - input must fit into 160 bits\n *\n * _Available since v4.7._\n */\n function toInt160(int256 value) internal pure returns (int160) {\n require(value >= type(int160).min && value <= type(int160).max, \"SafeCast: value doesn't fit in 160 bits\");\n return int160(value);\n }\n\n /**\n * @dev Returns the downcasted int152 from int256, reverting on\n * overflow (when the input is less than smallest int152 or\n * greater than largest int152).\n *\n * Counterpart to Solidity's `int152` operator.\n *\n * Requirements:\n *\n * - input must fit into 152 bits\n *\n * _Available since v4.7._\n */\n function toInt152(int256 value) internal pure returns (int152) {\n require(value >= type(int152).min && value <= type(int152).max, \"SafeCast: value doesn't fit in 152 bits\");\n return int152(value);\n }\n\n /**\n * @dev Returns the downcasted int144 from int256, reverting on\n * overflow (when the input is less than smallest int144 or\n * greater than largest int144).\n *\n * Counterpart to Solidity's `int144` operator.\n *\n * Requirements:\n *\n * - input must fit into 144 bits\n *\n * _Available since v4.7._\n */\n function toInt144(int256 value) internal pure returns (int144) {\n require(value >= type(int144).min && value <= type(int144).max, \"SafeCast: value doesn't fit in 144 bits\");\n return int144(value);\n }\n\n /**\n * @dev Returns the downcasted int136 from int256, reverting on\n * overflow (when the input is less than smallest int136 or\n * greater than largest int136).\n *\n * Counterpart to Solidity's `int136` operator.\n *\n * Requirements:\n *\n * - input must fit into 136 bits\n *\n * _Available since v4.7._\n */\n function toInt136(int256 value) internal pure returns (int136) {\n require(value >= type(int136).min && value <= type(int136).max, \"SafeCast: value doesn't fit in 136 bits\");\n return int136(value);\n }\n\n /**\n * @dev Returns the downcasted int128 from int256, reverting on\n * overflow (when the input is less than smallest int128 or\n * greater than largest int128).\n *\n * Counterpart to Solidity's `int128` operator.\n *\n * Requirements:\n *\n * - input must fit into 128 bits\n *\n * _Available since v3.1._\n */\n function toInt128(int256 value) internal pure returns (int128) {\n require(value >= type(int128).min && value <= type(int128).max, \"SafeCast: value doesn't fit in 128 bits\");\n return int128(value);\n }\n\n /**\n * @dev Returns the downcasted int120 from int256, reverting on\n * overflow (when the input is less than smallest int120 or\n * greater than largest int120).\n *\n * Counterpart to Solidity's `int120` operator.\n *\n * Requirements:\n *\n * - input must fit into 120 bits\n *\n * _Available since v4.7._\n */\n function toInt120(int256 value) internal pure returns (int120) {\n require(value >= type(int120).min && value <= type(int120).max, \"SafeCast: value doesn't fit in 120 bits\");\n return int120(value);\n }\n\n /**\n * @dev Returns the downcasted int112 from int256, reverting on\n * overflow (when the input is less than smallest int112 or\n * greater than largest int112).\n *\n * Counterpart to Solidity's `int112` operator.\n *\n * Requirements:\n *\n * - input must fit into 112 bits\n *\n * _Available since v4.7._\n */\n function toInt112(int256 value) internal pure returns (int112) {\n require(value >= type(int112).min && value <= type(int112).max, \"SafeCast: value doesn't fit in 112 bits\");\n return int112(value);\n }\n\n /**\n * @dev Returns the downcasted int104 from int256, reverting on\n * overflow (when the input is less than smallest int104 or\n * greater than largest int104).\n *\n * Counterpart to Solidity's `int104` operator.\n *\n * Requirements:\n *\n * - input must fit into 104 bits\n *\n * _Available since v4.7._\n */\n function toInt104(int256 value) internal pure returns (int104) {\n require(value >= type(int104).min && value <= type(int104).max, \"SafeCast: value doesn't fit in 104 bits\");\n return int104(value);\n }\n\n /**\n * @dev Returns the downcasted int96 from int256, reverting on\n * overflow (when the input is less than smallest int96 or\n * greater than largest int96).\n *\n * Counterpart to Solidity's `int96` operator.\n *\n * Requirements:\n *\n * - input must fit into 96 bits\n *\n * _Available since v4.7._\n */\n function toInt96(int256 value) internal pure returns (int96) {\n require(value >= type(int96).min && value <= type(int96).max, \"SafeCast: value doesn't fit in 96 bits\");\n return int96(value);\n }\n\n /**\n * @dev Returns the downcasted int88 from int256, reverting on\n * overflow (when the input is less than smallest int88 or\n * greater than largest int88).\n *\n * Counterpart to Solidity's `int88` operator.\n *\n * Requirements:\n *\n * - input must fit into 88 bits\n *\n * _Available since v4.7._\n */\n function toInt88(int256 value) internal pure returns (int88) {\n require(value >= type(int88).min && value <= type(int88).max, \"SafeCast: value doesn't fit in 88 bits\");\n return int88(value);\n }\n\n /**\n * @dev Returns the downcasted int80 from int256, reverting on\n * overflow (when the input is less than smallest int80 or\n * greater than largest int80).\n *\n * Counterpart to Solidity's `int80` operator.\n *\n * Requirements:\n *\n * - input must fit into 80 bits\n *\n * _Available since v4.7._\n */\n function toInt80(int256 value) internal pure returns (int80) {\n require(value >= type(int80).min && value <= type(int80).max, \"SafeCast: value doesn't fit in 80 bits\");\n return int80(value);\n }\n\n /**\n * @dev Returns the downcasted int72 from int256, reverting on\n * overflow (when the input is less than smallest int72 or\n * greater than largest int72).\n *\n * Counterpart to Solidity's `int72` operator.\n *\n * Requirements:\n *\n * - input must fit into 72 bits\n *\n * _Available since v4.7._\n */\n function toInt72(int256 value) internal pure returns (int72) {\n require(value >= type(int72).min && value <= type(int72).max, \"SafeCast: value doesn't fit in 72 bits\");\n return int72(value);\n }\n\n /**\n * @dev Returns the downcasted int64 from int256, reverting on\n * overflow (when the input is less than smallest int64 or\n * greater than largest int64).\n *\n * Counterpart to Solidity's `int64` operator.\n *\n * Requirements:\n *\n * - input must fit into 64 bits\n *\n * _Available since v3.1._\n */\n function toInt64(int256 value) internal pure returns (int64) {\n require(value >= type(int64).min && value <= type(int64).max, \"SafeCast: value doesn't fit in 64 bits\");\n return int64(value);\n }\n\n /**\n * @dev Returns the downcasted int56 from int256, reverting on\n * overflow (when the input is less than smallest int56 or\n * greater than largest int56).\n *\n * Counterpart to Solidity's `int56` operator.\n *\n * Requirements:\n *\n * - input must fit into 56 bits\n *\n * _Available since v4.7._\n */\n function toInt56(int256 value) internal pure returns (int56) {\n require(value >= type(int56).min && value <= type(int56).max, \"SafeCast: value doesn't fit in 56 bits\");\n return int56(value);\n }\n\n /**\n * @dev Returns the downcasted int48 from int256, reverting on\n * overflow (when the input is less than smallest int48 or\n * greater than largest int48).\n *\n * Counterpart to Solidity's `int48` operator.\n *\n * Requirements:\n *\n * - input must fit into 48 bits\n *\n * _Available since v4.7._\n */\n function toInt48(int256 value) internal pure returns (int48) {\n require(value >= type(int48).min && value <= type(int48).max, \"SafeCast: value doesn't fit in 48 bits\");\n return int48(value);\n }\n\n /**\n * @dev Returns the downcasted int40 from int256, reverting on\n * overflow (when the input is less than smallest int40 or\n * greater than largest int40).\n *\n * Counterpart to Solidity's `int40` operator.\n *\n * Requirements:\n *\n * - input must fit into 40 bits\n *\n * _Available since v4.7._\n */\n function toInt40(int256 value) internal pure returns (int40) {\n require(value >= type(int40).min && value <= type(int40).max, \"SafeCast: value doesn't fit in 40 bits\");\n return int40(value);\n }\n\n /**\n * @dev Returns the downcasted int32 from int256, reverting on\n * overflow (when the input is less than smallest int32 or\n * greater than largest int32).\n *\n * Counterpart to Solidity's `int32` operator.\n *\n * Requirements:\n *\n * - input must fit into 32 bits\n *\n * _Available since v3.1._\n */\n function toInt32(int256 value) internal pure returns (int32) {\n require(value >= type(int32).min && value <= type(int32).max, \"SafeCast: value doesn't fit in 32 bits\");\n return int32(value);\n }\n\n /**\n * @dev Returns the downcasted int24 from int256, reverting on\n * overflow (when the input is less than smallest int24 or\n * greater than largest int24).\n *\n * Counterpart to Solidity's `int24` operator.\n *\n * Requirements:\n *\n * - input must fit into 24 bits\n *\n * _Available since v4.7._\n */\n function toInt24(int256 value) internal pure returns (int24) {\n require(value >= type(int24).min && value <= type(int24).max, \"SafeCast: value doesn't fit in 24 bits\");\n return int24(value);\n }\n\n /**\n * @dev Returns the downcasted int16 from int256, reverting on\n * overflow (when the input is less than smallest int16 or\n * greater than largest int16).\n *\n * Counterpart to Solidity's `int16` operator.\n *\n * Requirements:\n *\n * - input must fit into 16 bits\n *\n * _Available since v3.1._\n */\n function toInt16(int256 value) internal pure returns (int16) {\n require(value >= type(int16).min && value <= type(int16).max, \"SafeCast: value doesn't fit in 16 bits\");\n return int16(value);\n }\n\n /**\n * @dev Returns the downcasted int8 from int256, reverting on\n * overflow (when the input is less than smallest int8 or\n * greater than largest int8).\n *\n * Counterpart to Solidity's `int8` operator.\n *\n * Requirements:\n *\n * - input must fit into 8 bits\n *\n * _Available since v3.1._\n */\n function toInt8(int256 value) internal pure returns (int8) {\n require(value >= type(int8).min && value <= type(int8).max, \"SafeCast: value doesn't fit in 8 bits\");\n return int8(value);\n }\n\n /**\n * @dev Converts an unsigned uint256 into a signed int256.\n *\n * Requirements:\n *\n * - input must be less than or equal to maxInt256.\n *\n * _Available since v3.0._\n */\n function toInt256(uint256 value) internal pure returns (int256) {\n // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive\n require(value <= uint256(type(int256).max), \"SafeCast: value doesn't fit in an int256\");\n return int256(value);\n }\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/draft-IERC20PermitUpgradeable.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 IERC20PermitUpgradeable {\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"
},
"@skalenetwork/ima-interfaces/mainnet/IDepositBox.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * IDepositBox.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"@skalenetwork/skale-manager-interfaces/IContractManager.sol\";\n\nimport \"../IGasReimbursable.sol\";\nimport \"../IMessageReceiver.sol\";\nimport \"./ILinker.sol\";\nimport \"./IMessageProxyForMainnet.sol\";\nimport \"./ITwin.sol\";\n\n\ninterface IDepositBox is ITwin, IMessageReceiver, IGasReimbursable {\n function initialize(\n IContractManager contractManagerOfSkaleManagerValue,\n ILinker newLinker,\n IMessageProxyForMainnet messageProxyValue\n ) external;\n function enableWhitelist(string memory schainName) external;\n function disableWhitelist(string memory schainName) external;\n function isWhitelisted(string memory schainName) external view returns (bool);\n}"
},
"@skalenetwork/skale-manager-interfaces/IContractManager.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/*\n IContractManager.sol - SKALE Manager Interfaces\n Copyright (C) 2021-Present SKALE Labs\n @author Dmytro Stebaeiv\n\n SKALE Manager Interfaces is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as published\n by the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n SKALE Manager Interfaces is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with SKALE Manager Interfaces. If not, see .\n*/\n\npragma solidity >=0.6.10 <0.9.0;\n\ninterface IContractManager {\n /**\n * @dev Emitted when contract is upgraded.\n */\n event ContractUpgraded(string contractsName, address contractsAddress);\n\n function initialize() external;\n function setContractsAddress(string calldata contractsName, address newContractsAddress) external;\n function contracts(bytes32 nameHash) external view returns (address);\n function getDelegationPeriodManager() external view returns (address);\n function getBounty() external view returns (address);\n function getValidatorService() external view returns (address);\n function getTimeHelpers() external view returns (address);\n function getConstantsHolder() external view returns (address);\n function getSkaleToken() external view returns (address);\n function getTokenState() external view returns (address);\n function getPunisher() external view returns (address);\n function getContract(string calldata name) external view returns (address);\n}"
},
"@skalenetwork/ima-interfaces/IGasReimbursable.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * IGasReimbursable.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Artem Payvin\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"./IMessageReceiver.sol\";\n\n\ninterface IGasReimbursable is IMessageReceiver {\n function gasPayer(\n bytes32 schainHash,\n address sender,\n bytes calldata data\n )\n external\n returns (address);\n}"
},
"@skalenetwork/ima-interfaces/IMessageReceiver.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * IMessageReceiver.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\n\ninterface IMessageReceiver {\n function postMessage(\n bytes32 schainHash,\n address sender,\n bytes calldata data\n )\n external;\n}"
},
"@skalenetwork/ima-interfaces/mainnet/ILinker.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * ILinker.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"./ITwin.sol\";\n\n\ninterface ILinker is ITwin {\n function registerMainnetContract(address newMainnetContract) external;\n function removeMainnetContract(address mainnetContract) external;\n function connectSchain(string calldata schainName, address[] calldata schainContracts) external;\n function kill(string calldata schainName) external;\n function disconnectSchain(string calldata schainName) external;\n function isNotKilled(bytes32 schainHash) external view returns (bool);\n function hasMainnetContract(address mainnetContract) external view returns (bool);\n function hasSchain(string calldata schainName) external view returns (bool connected);\n}"
},
"@skalenetwork/ima-interfaces/mainnet/IMessageProxyForMainnet.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * IMessageProxyForMainnet.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"../IMessageProxy.sol\";\nimport \"./ICommunityPool.sol\";\n\ninterface IMessageProxyForMainnet is IMessageProxy {\n function setCommunityPool(ICommunityPool newCommunityPoolAddress) external;\n function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external;\n function setNewMessageGasCost(uint256 newMessageGasCost) external;\n function pause(string calldata schainName) external;\n function resume(string calldata schainName) external;\n function messageInProgress() external view returns (bool);\n function isPaused(bytes32 schainHash) external view returns (bool);\n}"
},
"@skalenetwork/ima-interfaces/mainnet/ITwin.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * ITwin.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"./ISkaleManagerClient.sol\";\n\ninterface ITwin is ISkaleManagerClient {\n function addSchainContract(string calldata schainName, address contractReceiver) external;\n function removeSchainContract(string calldata schainName) external;\n function hasSchainContract(string calldata schainName) external view returns (bool);\n}"
},
"@skalenetwork/ima-interfaces/mainnet/ISkaleManagerClient.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * ISkaleManagerClient.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"@skalenetwork/skale-manager-interfaces/IContractManager.sol\";\n\n\ninterface ISkaleManagerClient {\n function initialize(IContractManager newContractManagerOfSkaleManager) external;\n function isSchainOwner(address sender, bytes32 schainHash) external view returns (bool);\n function isAgentAuthorized(bytes32 schainHash, address sender) external view returns (bool);\n}"
},
"@skalenetwork/ima-interfaces/IMessageProxy.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * IMessageProxy.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\n\ninterface IMessageProxy {\n\n /**\n * @dev Structure that describes message. Should contain sender of message,\n * destination contract on schain that will receiver message,\n * data that contains all needed info about token or ETH.\n */\n struct Message {\n address sender;\n address destinationContract;\n bytes data;\n }\n\n /**\n * @dev Structure that contains fields for bls signature.\n */\n struct Signature {\n uint256[2] blsSignature;\n uint256 hashA;\n uint256 hashB;\n uint256 counter;\n }\n\n function addConnectedChain(string calldata schainName) external;\n function postIncomingMessages(\n string calldata fromSchainName,\n uint256 startingCounter,\n Message[] calldata messages,\n Signature calldata sign\n ) external;\n function setNewGasLimit(uint256 newGasLimit) external;\n function registerExtraContractForAll(address extraContract) external;\n function removeExtraContractForAll(address extraContract) external; \n function removeConnectedChain(string memory schainName) external;\n function postOutgoingMessage(\n bytes32 targetChainHash,\n address targetContract,\n bytes memory data\n ) external;\n function registerExtraContract(string memory chainName, address extraContract) external;\n function removeExtraContract(string memory schainName, address extraContract) external;\n function setVersion(string calldata newVersion) external;\n function isContractRegistered(\n bytes32 schainHash,\n address contractAddress\n ) external view returns (bool);\n function getContractRegisteredLength(bytes32 schainHash) external view returns (uint256);\n function getContractRegisteredRange(\n bytes32 schainHash,\n uint256 from,\n uint256 to\n )\n external\n view\n returns (address[] memory);\n function getOutgoingMessagesCounter(string calldata targetSchainName) external view returns (uint256);\n function getIncomingMessagesCounter(string calldata fromSchainName) external view returns (uint256);\n function isConnectedChain(string memory schainName) external view returns (bool);\n}"
},
"@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * ICommunityPool.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"@skalenetwork/skale-manager-interfaces/IContractManager.sol\";\n\n\nimport \"./ILinker.sol\";\nimport \"./IMessageProxyForMainnet.sol\";\nimport \"./ITwin.sol\";\n\n\ninterface ICommunityPool is ITwin {\n function initialize(\n IContractManager contractManagerOfSkaleManagerValue,\n ILinker linker,\n IMessageProxyForMainnet messageProxyValue\n ) external;\n function refundGasByUser(bytes32 schainHash, address payable node, address user, uint gas) external returns (uint);\n function rechargeUserWallet(string calldata schainName, address user) external payable;\n function withdrawFunds(string calldata schainName, uint amount) external;\n function setMinTransactionGas(uint newMinTransactionGas) external;\n function setMultiplier(uint newMultiplierNumerator, uint newMultiplierDivider) external;\n function refundGasBySchainWallet(\n bytes32 schainHash,\n address payable node,\n uint gas\n ) external returns (bool);\n function getBalance(address user, string calldata schainName) external view returns (uint);\n function checkUserBalance(bytes32 schainHash, address receiver) external view returns (bool);\n function getRecommendedRechargeAmount(bytes32 schainHash, address receiver) external view returns (uint256);\n}"
},
"contracts/mainnet/Twin.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * Twin.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Artem Payvin\n * @author Dmytro Stebaiev\n * @author Vadim Yavorsky\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity 0.8.16;\n\nimport \"@skalenetwork/ima-interfaces/mainnet/ITwin.sol\";\n\nimport \"./MessageProxyForMainnet.sol\";\nimport \"./SkaleManagerClient.sol\";\n\n/**\n * @title Twin\n * @dev Runs on Mainnet,\n * contains logic for connecting paired contracts on Mainnet and on Schain.\n */\nabstract contract Twin is SkaleManagerClient, ITwin {\n\n IMessageProxyForMainnet public messageProxy;\n mapping(bytes32 => address) public schainLinks;\n bytes32 public constant LINKER_ROLE = keccak256(\"LINKER_ROLE\");\n\n /**\n * @dev Modifier for checking whether caller is MessageProxy contract.\n */\n modifier onlyMessageProxy() {\n require(msg.sender == address(messageProxy), \"Sender is not a MessageProxy\");\n _;\n }\n\n /**\n * @dev Binds a contract on mainnet with their twin on schain.\n *\n * Requirements:\n *\n * - `msg.sender` must be schain owner or has required role.\n * - SKALE chain must not already be added.\n * - Address of contract on schain must be non-zero.\n */\n function addSchainContract(string calldata schainName, address contractReceiver) external override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(\n hasRole(LINKER_ROLE, msg.sender) ||\n isSchainOwner(msg.sender, schainHash), \"Not authorized caller\"\n );\n require(schainLinks[schainHash] == address(0), \"SKALE chain is already set\");\n require(contractReceiver != address(0), \"Incorrect address of contract receiver on Schain\");\n schainLinks[schainHash] = contractReceiver;\n }\n\n /**\n * @dev Removes connection with contract on schain.\n *\n * Requirements:\n *\n * - `msg.sender` must be schain owner or has required role.\n * - SKALE chain must already be set.\n */\n function removeSchainContract(string calldata schainName) external override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(\n hasRole(LINKER_ROLE, msg.sender) ||\n isSchainOwner(msg.sender, schainHash), \"Not authorized caller\"\n );\n require(schainLinks[schainHash] != address(0), \"SKALE chain is not set\");\n delete schainLinks[schainHash];\n }\n\n /**\n * @dev Returns true if mainnet contract and schain contract are connected together for transferring messages.\n */\n function hasSchainContract(string calldata schainName) external view override returns (bool) {\n return schainLinks[keccak256(abi.encodePacked(schainName))] != address(0);\n }\n \n function initialize(\n IContractManager contractManagerOfSkaleManagerValue,\n IMessageProxyForMainnet newMessageProxy\n )\n public\n virtual\n initializer\n {\n SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);\n messageProxy = newMessageProxy;\n }\n}\n"
},
"contracts/mainnet/MessageProxyForMainnet.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * MessageProxyForMainnet.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2019-Present SKALE Labs\n * @author Artem Payvin\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity 0.8.16;\n\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@skalenetwork/skale-manager-interfaces/IWallets.sol\";\nimport \"@skalenetwork/skale-manager-interfaces/ISchains.sol\";\nimport \"@skalenetwork/ima-interfaces/mainnet/IMessageProxyForMainnet.sol\";\nimport \"@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol\";\nimport \"@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol\";\n\n\nimport \"../MessageProxy.sol\";\nimport \"./SkaleManagerClient.sol\";\nimport \"./CommunityPool.sol\";\n\n\n/**\n * @title Message Proxy for Mainnet\n * @dev Runs on Mainnet, contains functions to manage the incoming messages from\n * `targetSchainName` and outgoing messages to `fromSchainName`. Every SKALE chain with\n * IMA is therefore connected to MessageProxyForMainnet.\n *\n * Messages from SKALE chains are signed using BLS threshold signatures from the\n * nodes in the chain. Since Ethereum Mainnet has no BLS public key, mainnet\n * messages do not need to be signed.\n */\ncontract MessageProxyForMainnet is SkaleManagerClient, MessageProxy, IMessageProxyForMainnet {\n\n using AddressUpgradeable for address;\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n\n struct Pause {\n bool paused;\n }\n\n bytes32 public constant PAUSABLE_ROLE = keccak256(abi.encodePacked(\"PAUSABLE_ROLE\"));\n\n /**\n * 16 Agents\n * Synchronize time with time.nist.gov\n * Every agent checks if it is their time slot\n * Time slots are in increments of 10 seconds\n * At the start of their slot each agent:\n * For each connected schain:\n * Read incoming counter on the dst chain\n * Read outgoing counter on the src chain\n * Calculate the difference outgoing - incoming\n * Call postIncomingMessages function passing (un)signed message array\n * ID of this schain, Chain 0 represents ETH mainnet,\n */\n\n ICommunityPool public communityPool;\n\n uint256 public headerMessageGasCost;\n uint256 public messageGasCost;\n\n // disable detector until slither will fix this issue\n // https://github.com/crytic/slither/issues/456\n // slither-disable-next-line uninitialized-state\n mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _registryContracts;\n string public version;\n bool public override messageInProgress;\n\n // schainHash => Pause structure\n mapping(bytes32 => Pause) public pauseInfo;\n\n /**\n * @dev Emitted when gas cost for message header was changed.\n */\n event GasCostMessageHeaderWasChanged(\n uint256 oldValue,\n uint256 newValue\n );\n\n /**\n * @dev Emitted when gas cost for message was changed.\n */\n event GasCostMessageWasChanged(\n uint256 oldValue,\n uint256 newValue\n );\n\n /**\n * @dev Emitted when the schain is paused\n */\n event SchainPaused(\n bytes32 indexed schainHash\n );\n\n /**\n * @dev Emitted when the schain is resumed\n */\n event SchainResumed(\n bytes32 indexed schainHash\n );\n\n /**\n * @dev Reentrancy guard for postIncomingMessages.\n */\n modifier messageInProgressLocker() {\n require(!messageInProgress, \"Message is in progress\");\n messageInProgress = true;\n _;\n messageInProgress = false;\n }\n\n modifier whenNotPaused(bytes32 schainHash) {\n require(!isPaused(schainHash), \"IMA is paused\");\n _;\n }\n\n /**\n * @dev Allows `msg.sender` to connect schain with MessageProxyOnMainnet for transferring messages.\n *\n * Requirements:\n *\n * - Schain name must not be `Mainnet`.\n */\n function addConnectedChain(string calldata schainName) external override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(ISchainsInternal(\n contractManagerOfSkaleManager.getContract(\"SchainsInternal\")\n ).isSchainExist(schainHash), \"SKALE chain must exist\");\n _addConnectedChain(schainHash);\n }\n\n /**\n * @dev Allows owner of the contract to set CommunityPool address for gas reimbursement.\n *\n * Requirements:\n *\n * - `msg.sender` must be granted as DEFAULT_ADMIN_ROLE.\n * - Address of CommunityPool contract must not be null.\n */\n function setCommunityPool(ICommunityPool newCommunityPoolAddress) external override {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"Not authorized caller\");\n require(address(newCommunityPoolAddress) != address(0), \"CommunityPool address has to be set\");\n communityPool = newCommunityPoolAddress;\n }\n\n /**\n * @dev Allows `msg.sender` to register extra contract for being able to transfer messages from custom contracts.\n *\n * Requirements:\n *\n * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.\n * - Schain name must not be `Mainnet`.\n */\n function registerExtraContract(string memory schainName, address extraContract) external override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(\n hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||\n isSchainOwner(msg.sender, schainHash),\n \"Not enough permissions to register extra contract\"\n );\n require(schainHash != MAINNET_HASH, \"Schain hash can not be equal Mainnet\");\n _registerExtraContract(schainHash, extraContract);\n }\n\n /**\n * @dev Allows `msg.sender` to remove extra contract,\n * thus `extraContract` will no longer be available to transfer messages from mainnet to schain.\n *\n * Requirements:\n *\n * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.\n * - Schain name must not be `Mainnet`.\n */\n function removeExtraContract(string memory schainName, address extraContract) external override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(\n hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender) ||\n isSchainOwner(msg.sender, schainHash),\n \"Not enough permissions to register extra contract\"\n );\n require(schainHash != MAINNET_HASH, \"Schain hash can not be equal Mainnet\");\n _removeExtraContract(schainHash, extraContract);\n }\n\n /**\n * @dev Posts incoming message from `fromSchainName`.\n *\n * Requirements:\n *\n * - `msg.sender` must be authorized caller.\n * - `fromSchainName` must be initialized.\n * - `startingCounter` must be equal to the chain's incoming message counter.\n * - If destination chain is Mainnet, message signature must be valid.\n */\n function postIncomingMessages(\n string calldata fromSchainName,\n uint256 startingCounter,\n Message[] calldata messages,\n Signature calldata sign\n )\n external\n override(IMessageProxy, MessageProxy)\n messageInProgressLocker\n whenNotPaused(keccak256(abi.encodePacked(fromSchainName)))\n {\n uint256 gasTotal = gasleft();\n bytes32 fromSchainHash = keccak256(abi.encodePacked(fromSchainName));\n require(isAgentAuthorized(fromSchainHash, msg.sender), \"Agent is not authorized\");\n require(_checkSchainBalance(fromSchainHash), \"Schain wallet has not enough funds\");\n require(connectedChains[fromSchainHash].inited, \"Chain is not initialized\");\n require(messages.length <= MESSAGES_LENGTH, \"Too many messages\");\n require(\n startingCounter == connectedChains[fromSchainHash].incomingMessageCounter,\n \"Starting counter is not equal to incoming message counter\");\n\n require(_verifyMessages(\n fromSchainName,\n _hashedArray(messages, startingCounter, fromSchainName), sign),\n \"Signature is not verified\");\n uint additionalGasPerMessage =\n (gasTotal - gasleft() + headerMessageGasCost + messages.length * messageGasCost) / messages.length;\n uint notReimbursedGas = 0;\n connectedChains[fromSchainHash].incomingMessageCounter += messages.length;\n for (uint256 i = 0; i < messages.length; i++) {\n gasTotal = gasleft();\n if (isContractRegistered(bytes32(0), messages[i].destinationContract)) {\n address receiver = _getGasPayer(fromSchainHash, messages[i], startingCounter + i);\n _callReceiverContract(fromSchainHash, messages[i], startingCounter + i);\n notReimbursedGas += communityPool.refundGasByUser(\n fromSchainHash,\n payable(msg.sender),\n receiver,\n gasTotal - gasleft() + additionalGasPerMessage\n );\n } else {\n _callReceiverContract(fromSchainHash, messages[i], startingCounter + i);\n notReimbursedGas += gasTotal - gasleft() + additionalGasPerMessage;\n }\n }\n communityPool.refundGasBySchainWallet(fromSchainHash, payable(msg.sender), notReimbursedGas);\n }\n\n /**\n * @dev Sets headerMessageGasCost to a new value.\n *\n * Requirements:\n *\n * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.\n */\n function setNewHeaderMessageGasCost(uint256 newHeaderMessageGasCost) external override onlyConstantSetter {\n emit GasCostMessageHeaderWasChanged(headerMessageGasCost, newHeaderMessageGasCost);\n headerMessageGasCost = newHeaderMessageGasCost;\n }\n\n /**\n * @dev Sets messageGasCost to a new value.\n *\n * Requirements:\n *\n * - `msg.sender` must be granted as CONSTANT_SETTER_ROLE.\n */\n function setNewMessageGasCost(uint256 newMessageGasCost) external override onlyConstantSetter {\n emit GasCostMessageWasChanged(messageGasCost, newMessageGasCost);\n messageGasCost = newMessageGasCost;\n }\n\n /**\n * @dev Sets new version of contracts on mainnet\n *\n * Requirements:\n *\n * - `msg.sender` must be granted DEFAULT_ADMIN_ROLE.\n */\n function setVersion(string calldata newVersion) external override {\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), \"DEFAULT_ADMIN_ROLE is required\");\n emit VersionUpdated(version, newVersion);\n version = newVersion;\n }\n\n /**\n * @dev Allows PAUSABLE_ROLE to pause IMA bridge unlimited\n * or DEFAULT_ADMIN_ROLE to pause for 4 hours\n * or schain owner to pause unlimited after DEFAULT_ADMIN_ROLE pause it\n *\n * Requirements:\n *\n * - IMA bridge to current schain was not paused\n * - Sender should be PAUSABLE_ROLE, DEFAULT_ADMIN_ROLE or schain owner\n */\n function pause(string calldata schainName) external override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(hasRole(PAUSABLE_ROLE, msg.sender), \"Incorrect sender\");\n require(!pauseInfo[schainHash].paused, \"Already paused\");\n pauseInfo[schainHash].paused = true;\n emit SchainPaused(schainHash);\n }\n\n/**\n * @dev Allows DEFAULT_ADMIN_ROLE or schain owner to resume IMA bridge\n *\n * Requirements:\n *\n * - IMA bridge to current schain was paused\n * - Sender should be DEFAULT_ADMIN_ROLE or schain owner\n */\n function resume(string calldata schainName) external override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || isSchainOwner(msg.sender, schainHash), \"Incorrect sender\");\n require(pauseInfo[schainHash].paused, \"Already unpaused\");\n pauseInfo[schainHash].paused = false;\n emit SchainResumed(schainHash);\n }\n\n /**\n * @dev Creates a new MessageProxyForMainnet contract.\n */\n function initialize(IContractManager contractManagerOfSkaleManagerValue) public virtual override initializer {\n SkaleManagerClient.initialize(contractManagerOfSkaleManagerValue);\n MessageProxy.initializeMessageProxy(1e6);\n headerMessageGasCost = 92251;\n messageGasCost = 9000;\n }\n\n /**\n * @dev PostOutgoingMessage function with whenNotPaused modifier\n */\n function postOutgoingMessage(\n bytes32 targetChainHash,\n address targetContract,\n bytes memory data\n )\n public\n override(IMessageProxy, MessageProxy)\n whenNotPaused(targetChainHash)\n {\n super.postOutgoingMessage(targetChainHash, targetContract, data);\n }\n\n /**\n * @dev Checks whether chain is currently connected.\n *\n * Note: Mainnet chain does not have a public key, and is implicitly\n * connected to MessageProxy.\n *\n * Requirements:\n *\n * - `schainName` must not be Mainnet.\n */\n function isConnectedChain(\n string memory schainName\n )\n public\n view\n override(IMessageProxy, MessageProxy)\n returns (bool)\n {\n require(keccak256(abi.encodePacked(schainName)) != MAINNET_HASH, \"Schain id can not be equal Mainnet\");\n return super.isConnectedChain(schainName);\n }\n\n /**\n * @dev Returns true if IMA to schain is paused.\n */\n function isPaused(bytes32 schainHash) public view override returns (bool) {\n return pauseInfo[schainHash].paused;\n }\n\n // private\n\n function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view override {\n require(\n isContractRegistered(bytes32(0), msg.sender)\n || isContractRegistered(targetChainHash, msg.sender)\n || isSchainOwner(msg.sender, targetChainHash),\n \"Sender contract is not registered\"\n );\n }\n\n /**\n * @dev Converts calldata structure to memory structure and checks\n * whether message BLS signature is valid.\n */\n function _verifyMessages(\n string calldata fromSchainName,\n bytes32 hashedMessages,\n MessageProxyForMainnet.Signature calldata sign\n )\n internal\n view\n returns (bool)\n {\n return ISchains(\n contractManagerOfSkaleManager.getContract(\"Schains\")\n ).verifySchainSignature(\n sign.blsSignature[0],\n sign.blsSignature[1],\n hashedMessages,\n sign.counter,\n sign.hashA,\n sign.hashB,\n fromSchainName\n );\n }\n\n /**\n * @dev Checks whether balance of schain wallet is sufficient for\n * for reimbursement custom message.\n */\n function _checkSchainBalance(bytes32 schainHash) internal view returns (bool) {\n return IWallets(\n payable(contractManagerOfSkaleManager.getContract(\"Wallets\"))\n ).getSchainBalance(schainHash) >= (MESSAGES_LENGTH + 1) * gasLimit * tx.gasprice;\n }\n\n /**\n * @dev Returns list of registered custom extra contracts.\n */\n function _getRegistryContracts()\n internal\n view\n override\n returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage)\n {\n return _registryContracts;\n }\n}\n"
},
"contracts/mainnet/SkaleManagerClient.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * SkaleManagerClient.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Artem Payvin\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity 0.8.16;\n\nimport \"@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol\";\nimport \"@skalenetwork/skale-manager-interfaces/IContractManager.sol\";\nimport \"@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol\";\nimport \"@skalenetwork/ima-interfaces/mainnet/ISkaleManagerClient.sol\";\n\n\n/**\n * @title SkaleManagerClient - contract that knows ContractManager\n * and makes calls to SkaleManager contracts.\n */\ncontract SkaleManagerClient is Initializable, AccessControlEnumerableUpgradeable, ISkaleManagerClient {\n\n IContractManager public contractManagerOfSkaleManager;\n\n /**\n * @dev Modifier for checking whether caller is owner of SKALE chain.\n */\n modifier onlySchainOwner(string memory schainName) {\n require(\n isSchainOwner(msg.sender, _schainHash(schainName)),\n \"Sender is not an Schain owner\"\n );\n _;\n }\n\n /**\n * @dev Modifier for checking whether caller is owner of SKALE chain.\n */\n modifier onlySchainOwnerByHash(bytes32 schainHash) {\n require(\n isSchainOwner(msg.sender, schainHash),\n \"Sender is not an Schain owner\"\n );\n _;\n }\n\n /**\n * @dev initialize - sets current address of ContractManager of SkaleManager.\n * @param newContractManagerOfSkaleManager - current address of ContractManager of SkaleManager.\n */\n function initialize(\n IContractManager newContractManagerOfSkaleManager\n )\n public\n override\n virtual\n initializer\n {\n AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();\n _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);\n contractManagerOfSkaleManager = newContractManagerOfSkaleManager;\n }\n\n /**\n * @dev Checks whether sender is owner of SKALE chain\n */\n function isSchainOwner(address sender, bytes32 schainHash) public view override returns (bool) {\n address skaleChainsInternal = contractManagerOfSkaleManager.getContract(\"SchainsInternal\");\n return ISchainsInternal(skaleChainsInternal).isOwnerAddress(sender, schainHash);\n }\n\n function isAgentAuthorized(bytes32 schainHash, address sender) public view override returns (bool) {\n address skaleChainsInternal = contractManagerOfSkaleManager.getContract(\"SchainsInternal\");\n return ISchainsInternal(skaleChainsInternal).isNodeAddressesInGroup(schainHash, sender);\n }\n\n function _schainHash(string memory schainName) internal pure returns (bytes32) {\n return keccak256(abi.encodePacked(schainName));\n }\n}\n"
},
"@skalenetwork/skale-manager-interfaces/IWallets.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/*\n IWallets - SKALE Manager Interfaces\n Copyright (C) 2021-Present SKALE Labs\n @author Dmytro Stebaeiv\n\n SKALE Manager Interfaces is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as published\n by the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n SKALE Manager Interfaces is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with SKALE Manager Interfaces. If not, see .\n*/\n\npragma solidity >=0.6.10 <0.9.0;\n\ninterface IWallets {\n /**\n * @dev Emitted when the validator wallet was funded\n */\n event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId);\n\n /**\n * @dev Emitted when the schain wallet was funded\n */\n event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash);\n\n /**\n * @dev Emitted when the node received a refund from validator to its wallet\n */\n event NodeRefundedByValidator(address node, uint validatorId, uint amount);\n\n /**\n * @dev Emitted when the node received a refund from schain to its wallet\n */\n event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount);\n\n /**\n * @dev Emitted when the validator withdrawn funds from validator wallet\n */\n event WithdrawFromValidatorWallet(uint indexed validatorId, uint amount);\n\n /**\n * @dev Emitted when the schain owner withdrawn funds from schain wallet\n */\n event WithdrawFromSchainWallet(bytes32 indexed schainHash, uint amount);\n\n receive() external payable;\n function refundGasByValidator(uint validatorId, address payable spender, uint spentGas) external;\n function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external;\n function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external;\n function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external;\n function withdrawFundsFromValidatorWallet(uint amount) external;\n function rechargeValidatorWallet(uint validatorId) external payable;\n function rechargeSchainWallet(bytes32 schainId) external payable;\n function getSchainBalance(bytes32 schainHash) external view returns (uint);\n function getValidatorBalance(uint validatorId) external view returns (uint);\n}\n"
},
"@skalenetwork/skale-manager-interfaces/ISchains.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/*\n ISchains.sol - SKALE Manager Interfaces\n Copyright (C) 2021-Present SKALE Labs\n @author Dmytro Stebaeiv\n\n SKALE Manager Interfaces is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as published\n by the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n SKALE Manager Interfaces is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with SKALE Manager Interfaces. If not, see .\n*/\n\npragma solidity >=0.6.10 <0.9.0;\n\ninterface ISchains {\n\n struct SchainOption {\n string name;\n bytes value;\n }\n \n /**\n * @dev Emitted when an schain is created.\n */\n event SchainCreated(\n string name,\n address owner,\n uint partOfNode,\n uint lifetime,\n uint numberOfNodes,\n uint deposit,\n uint16 nonce,\n bytes32 schainHash\n );\n\n /**\n * @dev Emitted when an schain is deleted.\n */\n event SchainDeleted(\n address owner,\n string name,\n bytes32 indexed schainHash\n );\n\n /**\n * @dev Emitted when a node in an schain is rotated.\n */\n event NodeRotated(\n bytes32 schainHash,\n uint oldNode,\n uint newNode\n );\n\n /**\n * @dev Emitted when a node is added to an schain.\n */\n event NodeAdded(\n bytes32 schainHash,\n uint newNode\n );\n\n /**\n * @dev Emitted when a group of nodes is created for an schain.\n */\n event SchainNodes(\n string name,\n bytes32 schainHash,\n uint[] nodesInGroup\n );\n\n function addSchain(address from, uint deposit, bytes calldata data) external;\n function addSchainByFoundation(\n uint lifetime,\n uint8 typeOfSchain,\n uint16 nonce,\n string calldata name,\n address schainOwner,\n address schainOriginator,\n SchainOption[] calldata options\n )\n external\n payable;\n function deleteSchain(address from, string calldata name) external;\n function deleteSchainByRoot(string calldata name) external;\n function restartSchainCreation(string calldata name) external;\n function verifySchainSignature(\n uint256 signA,\n uint256 signB,\n bytes32 hash,\n uint256 counter,\n uint256 hashA,\n uint256 hashB,\n string calldata schainName\n )\n external\n view\n returns (bool);\n function getSchainPrice(uint typeOfSchain, uint lifetime) external view returns (uint);\n function getOption(bytes32 schainHash, string calldata optionName) external view returns (bytes memory);\n function getOptions(bytes32 schainHash) external view returns (SchainOption[] memory);\n}"
},
"@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/*\n ISchainsInternal - SKALE Manager Interfaces\n Copyright (C) 2021-Present SKALE Labs\n @author Dmytro Stebaeiv\n\n SKALE Manager Interfaces is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as published\n by the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n SKALE Manager Interfaces is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with SKALE Manager Interfaces. If not, see .\n*/\n\npragma solidity >=0.6.10 <0.9.0;\n\ninterface ISchainsInternal {\n struct Schain {\n string name;\n address owner;\n uint indexInOwnerList;\n uint8 partOfNode;\n uint lifetime;\n uint startDate;\n uint startBlock;\n uint deposit;\n uint64 index;\n uint generation;\n address originator;\n }\n\n struct SchainType {\n uint8 partOfNode;\n uint numberOfNodes;\n }\n\n /**\n * @dev Emitted when schain type added.\n */\n event SchainTypeAdded(uint indexed schainType, uint partOfNode, uint numberOfNodes);\n\n /**\n * @dev Emitted when schain type removed.\n */\n event SchainTypeRemoved(uint indexed schainType);\n\n function initializeSchain(\n string calldata name,\n address from,\n address originator,\n uint lifetime,\n uint deposit) external;\n function createGroupForSchain(\n bytes32 schainHash,\n uint numberOfNodes,\n uint8 partOfNode\n )\n external\n returns (uint[] memory);\n function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external;\n function removeSchain(bytes32 schainHash, address from) external;\n function removeNodeFromSchain(uint nodeIndex, bytes32 schainHash) external;\n function deleteGroup(bytes32 schainHash) external;\n function setException(bytes32 schainHash, uint nodeIndex) external;\n function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external;\n function removeHolesForSchain(bytes32 schainHash) external;\n function addSchainType(uint8 partOfNode, uint numberOfNodes) external;\n function removeSchainType(uint typeOfSchain) external;\n function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external;\n function removeNodeFromAllExceptionSchains(uint nodeIndex) external;\n function removeAllNodesFromSchainExceptions(bytes32 schainHash) external;\n function makeSchainNodesInvisible(bytes32 schainHash) external;\n function makeSchainNodesVisible(bytes32 schainHash) external;\n function newGeneration() external;\n function addSchainForNode(uint nodeIndex, bytes32 schainHash) external;\n function removeSchainForNode(uint nodeIndex, uint schainIndex) external;\n function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external;\n function isSchainActive(bytes32 schainHash) external view returns (bool);\n function schainsAtSystem(uint index) external view returns (bytes32);\n function numberOfSchains() external view returns (uint64);\n function getSchains() external view returns (bytes32[] memory);\n function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8);\n function getSchainListSize(address from) external view returns (uint);\n function getSchainHashesByAddress(address from) external view returns (bytes32[] memory);\n function getSchainIdsByAddress(address from) external view returns (bytes32[] memory);\n function getSchainHashesForNode(uint nodeIndex) external view returns (bytes32[] memory);\n function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory);\n function getSchainOwner(bytes32 schainHash) external view returns (address);\n function getSchainOriginator(bytes32 schainHash) external view returns (address);\n function isSchainNameAvailable(string calldata name) external view returns (bool);\n function isTimeExpired(bytes32 schainHash) external view returns (bool);\n function isOwnerAddress(address from, bytes32 schainId) external view returns (bool);\n function getSchainName(bytes32 schainHash) external view returns (string memory);\n function getActiveSchain(uint nodeIndex) external view returns (bytes32);\n function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains);\n function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint);\n function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory);\n function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool);\n function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint);\n function isAnyFreeNode(bytes32 schainHash) external view returns (bool);\n function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool);\n function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool);\n function checkSchainOnNode(uint nodeIndex, bytes32 schainHash) external view returns (bool);\n function getSchainType(uint typeOfSchain) external view returns(uint8, uint);\n function getGeneration(bytes32 schainHash) external view returns (uint);\n function isSchainExist(bytes32 schainHash) external view returns (bool);\n}"
},
"contracts/MessageProxy.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * MessageProxy.sol - SKALE Interchain Messaging Agent\n * Copyright (C) 2021-Present SKALE Labs\n * @author Dmytro Stebaiev\n *\n * SKALE IMA is free software: you can redistribute it and/or modify\n * it under the terms of the GNU Affero General Public License as published\n * by the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * SKALE IMA is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with SKALE IMA. If not, see .\n */\n\npragma solidity 0.8.16;\n\nimport \"@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"@skalenetwork/ima-interfaces/IGasReimbursable.sol\";\nimport \"@skalenetwork/ima-interfaces/IMessageProxy.sol\";\nimport \"@skalenetwork/ima-interfaces/IMessageReceiver.sol\";\n\n\n/**\n * @title MessageProxy\n * @dev Abstract contract for MessageProxyForMainnet and MessageProxyForSchain.\n */\nabstract contract MessageProxy is AccessControlEnumerableUpgradeable, IMessageProxy {\n using AddressUpgradeable for address;\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n\n /**\n * @dev Structure that stores counters for outgoing and incoming messages.\n */\n struct ConnectedChainInfo {\n // message counters start with 0\n uint256 incomingMessageCounter;\n uint256 outgoingMessageCounter;\n bool inited;\n }\n\n bytes32 public constant MAINNET_HASH = keccak256(abi.encodePacked(\"Mainnet\"));\n bytes32 public constant CHAIN_CONNECTOR_ROLE = keccak256(\"CHAIN_CONNECTOR_ROLE\");\n bytes32 public constant EXTRA_CONTRACT_REGISTRAR_ROLE = keccak256(\"EXTRA_CONTRACT_REGISTRAR_ROLE\");\n bytes32 public constant CONSTANT_SETTER_ROLE = keccak256(\"CONSTANT_SETTER_ROLE\");\n uint256 public constant MESSAGES_LENGTH = 10;\n uint256 public constant REVERT_REASON_LENGTH = 64;\n\n // schainHash => ConnectedChainInfo\n mapping(bytes32 => ConnectedChainInfo) public connectedChains;\n // schainHash => contract address => allowed\n // solhint-disable-next-line private-vars-leading-underscore\n mapping(bytes32 => mapping(address => bool)) internal deprecatedRegistryContracts;\n\n uint256 public gasLimit;\n\n /**\n * @dev Emitted for every outgoing message to schain.\n */\n event OutgoingMessage(\n bytes32 indexed dstChainHash,\n uint256 indexed msgCounter,\n address indexed srcContract,\n address dstContract,\n bytes data\n );\n\n /**\n * @dev Emitted when function `postMessage` returns revert.\n * Used to prevent stuck loop inside function `postIncomingMessages`.\n */\n event PostMessageError(\n uint256 indexed msgCounter,\n bytes message\n );\n\n /**\n * @dev Emitted when gas limit per one call of `postMessage` was changed.\n */\n event GasLimitWasChanged(\n uint256 oldValue,\n uint256 newValue\n );\n\n /**\n * @dev Emitted when the version was updated\n */\n event VersionUpdated(string oldVersion, string newVersion);\n\n /**\n * @dev Emitted when extra contract was added.\n */\n event ExtraContractRegistered(\n bytes32 indexed chainHash,\n address contractAddress\n );\n\n /**\n * @dev Emitted when extra contract was removed.\n */\n event ExtraContractRemoved(\n bytes32 indexed chainHash,\n address contractAddress\n );\n\n /**\n * @dev Modifier to make a function callable only if caller is granted with {CHAIN_CONNECTOR_ROLE}.\n */\n modifier onlyChainConnector() {\n require(hasRole(CHAIN_CONNECTOR_ROLE, msg.sender), \"CHAIN_CONNECTOR_ROLE is required\");\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only if caller is granted with {EXTRA_CONTRACT_REGISTRAR_ROLE}.\n */\n modifier onlyExtraContractRegistrar() {\n require(hasRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender), \"EXTRA_CONTRACT_REGISTRAR_ROLE is required\");\n _;\n }\n\n /**\n * @dev Modifier to make a function callable only if caller is granted with {CONSTANT_SETTER_ROLE}.\n */\n modifier onlyConstantSetter() {\n require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), \"Not enough permissions to set constant\");\n _;\n } \n\n /**\n * @dev Sets gasLimit to a new value.\n * \n * Requirements:\n * \n * - `msg.sender` must be granted CONSTANT_SETTER_ROLE.\n */\n function setNewGasLimit(uint256 newGasLimit) external override onlyConstantSetter {\n emit GasLimitWasChanged(gasLimit, newGasLimit);\n gasLimit = newGasLimit;\n }\n\n /**\n * @dev Virtual function for `postIncomingMessages`.\n */\n function postIncomingMessages(\n string calldata fromSchainName,\n uint256 startingCounter,\n Message[] calldata messages,\n Signature calldata sign\n )\n external\n virtual\n override;\n\n /**\n * @dev Allows `msg.sender` to register extra contract for all schains\n * for being able to transfer messages from custom contracts.\n * \n * Requirements:\n * \n * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.\n * - Passed address should be contract.\n * - Extra contract must not be registered.\n */\n function registerExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar {\n require(extraContract.isContract(), \"Given address is not a contract\");\n require(!_getRegistryContracts()[bytes32(0)].contains(extraContract), \"Extra contract is already registered\");\n _getRegistryContracts()[bytes32(0)].add(extraContract);\n emit ExtraContractRegistered(bytes32(0), extraContract);\n }\n\n /**\n * @dev Allows `msg.sender` to remove extra contract for all schains.\n * Extra contract will no longer be able to send messages through MessageProxy.\n * \n * Requirements:\n * \n * - `msg.sender` must be granted as EXTRA_CONTRACT_REGISTRAR_ROLE.\n */\n function removeExtraContractForAll(address extraContract) external override onlyExtraContractRegistrar {\n require(_getRegistryContracts()[bytes32(0)].contains(extraContract), \"Extra contract is not registered\");\n _getRegistryContracts()[bytes32(0)].remove(extraContract);\n emit ExtraContractRemoved(bytes32(0), extraContract);\n }\n\n /**\n * @dev Should return length of contract registered by schainHash.\n */\n function getContractRegisteredLength(bytes32 schainHash) external view override returns (uint256) {\n return _getRegistryContracts()[schainHash].length();\n }\n\n /**\n * @dev Should return a range of contracts registered by schainHash.\n * \n * Requirements:\n * range should be less or equal 10 contracts\n */\n function getContractRegisteredRange(\n bytes32 schainHash,\n uint256 from,\n uint256 to\n )\n external\n view\n override\n returns (address[] memory contractsInRange)\n {\n require(\n from < to && to - from <= 10 && to <= _getRegistryContracts()[schainHash].length(),\n \"Range is incorrect\"\n );\n contractsInRange = new address[](to - from);\n for (uint256 i = from; i < to; i++) {\n contractsInRange[i - from] = _getRegistryContracts()[schainHash].at(i);\n }\n }\n\n /**\n * @dev Returns number of outgoing messages.\n * \n * Requirements:\n * \n * - Target schain must be initialized.\n */\n function getOutgoingMessagesCounter(string calldata targetSchainName)\n external\n view\n override\n returns (uint256)\n {\n bytes32 dstChainHash = keccak256(abi.encodePacked(targetSchainName));\n require(connectedChains[dstChainHash].inited, \"Destination chain is not initialized\");\n return connectedChains[dstChainHash].outgoingMessageCounter;\n }\n\n /**\n * @dev Returns number of incoming messages.\n * \n * Requirements:\n * \n * - Source schain must be initialized.\n */\n function getIncomingMessagesCounter(string calldata fromSchainName)\n external\n view\n override\n returns (uint256)\n {\n bytes32 srcChainHash = keccak256(abi.encodePacked(fromSchainName));\n require(connectedChains[srcChainHash].inited, \"Source chain is not initialized\");\n return connectedChains[srcChainHash].incomingMessageCounter;\n }\n\n function initializeMessageProxy(uint newGasLimit) public initializer {\n AccessControlEnumerableUpgradeable.__AccessControlEnumerable_init();\n _setupRole(DEFAULT_ADMIN_ROLE, msg.sender);\n _setupRole(CHAIN_CONNECTOR_ROLE, msg.sender);\n _setupRole(EXTRA_CONTRACT_REGISTRAR_ROLE, msg.sender);\n _setupRole(CONSTANT_SETTER_ROLE, msg.sender);\n gasLimit = newGasLimit;\n }\n\n /**\n * @dev Posts message from this contract to `targetChainHash` MessageProxy contract.\n * This is called by a smart contract to make a cross-chain call.\n * \n * Emits an {OutgoingMessage} event.\n *\n * Requirements:\n * \n * - Target chain must be initialized.\n * - Target chain must be registered as external contract.\n */\n function postOutgoingMessage(\n bytes32 targetChainHash,\n address targetContract,\n bytes memory data\n )\n public\n override\n virtual\n {\n require(connectedChains[targetChainHash].inited, \"Destination chain is not initialized\");\n _authorizeOutgoingMessageSender(targetChainHash);\n \n emit OutgoingMessage(\n targetChainHash,\n connectedChains[targetChainHash].outgoingMessageCounter,\n msg.sender,\n targetContract,\n data\n );\n\n connectedChains[targetChainHash].outgoingMessageCounter += 1;\n }\n\n /**\n * @dev Allows CHAIN_CONNECTOR_ROLE to remove connected chain from this contract.\n * \n * Requirements:\n * \n * - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.\n * - `schainName` must be initialized.\n */\n function removeConnectedChain(string memory schainName) public virtual override onlyChainConnector {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(connectedChains[schainHash].inited, \"Chain is not initialized\");\n delete connectedChains[schainHash];\n } \n\n /**\n * @dev Checks whether chain is currently connected.\n */\n function isConnectedChain(\n string memory schainName\n )\n public\n view\n virtual\n override\n returns (bool)\n {\n return connectedChains[keccak256(abi.encodePacked(schainName))].inited;\n }\n\n /**\n * @dev Checks whether contract is currently registered as extra contract.\n */\n function isContractRegistered(\n bytes32 schainHash,\n address contractAddress\n )\n public\n view\n override\n returns (bool)\n {\n return _getRegistryContracts()[schainHash].contains(contractAddress);\n }\n\n /**\n * @dev Allows MessageProxy to register extra contract for being able to transfer messages from custom contracts.\n * \n * Requirements:\n * \n * - Extra contract address must be contract.\n * - Extra contract must not be registered.\n * - Extra contract must not be registered for all chains.\n */\n function _registerExtraContract(\n bytes32 chainHash,\n address extraContract\n )\n internal\n { \n require(extraContract.isContract(), \"Given address is not a contract\");\n require(!_getRegistryContracts()[chainHash].contains(extraContract), \"Extra contract is already registered\");\n require(\n !_getRegistryContracts()[bytes32(0)].contains(extraContract),\n \"Extra contract is already registered for all chains\"\n );\n \n _getRegistryContracts()[chainHash].add(extraContract);\n emit ExtraContractRegistered(chainHash, extraContract);\n }\n\n /**\n * @dev Allows MessageProxy to remove extra contract,\n * thus `extraContract` will no longer be available to transfer messages from mainnet to schain.\n * \n * Requirements:\n * \n * - Extra contract must be registered.\n */\n function _removeExtraContract(\n bytes32 chainHash,\n address extraContract\n )\n internal\n {\n require(_getRegistryContracts()[chainHash].contains(extraContract), \"Extra contract is not registered\");\n _getRegistryContracts()[chainHash].remove(extraContract);\n emit ExtraContractRemoved(chainHash, extraContract);\n }\n\n /**\n * @dev Allows MessageProxy to connect schain with MessageProxyOnMainnet for transferring messages.\n * \n * Requirements:\n * \n * - `msg.sender` must be granted CHAIN_CONNECTOR_ROLE.\n * - SKALE chain must not be connected.\n */\n function _addConnectedChain(bytes32 schainHash) internal onlyChainConnector {\n require(!connectedChains[schainHash].inited,\"Chain is already connected\");\n connectedChains[schainHash] = ConnectedChainInfo({\n incomingMessageCounter: 0,\n outgoingMessageCounter: 0,\n inited: true\n });\n }\n\n /**\n * @dev Allows MessageProxy to send messages from schain to mainnet.\n * Destination contract must implement `postMessage` method.\n */\n function _callReceiverContract(\n bytes32 schainHash,\n Message calldata message,\n uint counter\n )\n internal\n {\n if (!message.destinationContract.isContract()) {\n emit PostMessageError(\n counter,\n \"Destination contract is not a contract\"\n );\n return;\n }\n try IMessageReceiver(message.destinationContract).postMessage{gas: gasLimit}(\n schainHash,\n message.sender,\n message.data\n ) {\n return;\n } catch Error(string memory reason) {\n emit PostMessageError(\n counter,\n _getSlice(bytes(reason), REVERT_REASON_LENGTH)\n );\n } catch Panic(uint errorCode) {\n emit PostMessageError(\n counter,\n abi.encodePacked(errorCode)\n );\n } catch (bytes memory revertData) {\n emit PostMessageError(\n counter,\n _getSlice(revertData, REVERT_REASON_LENGTH)\n );\n }\n }\n\n /**\n * @dev Returns receiver of message.\n */\n function _getGasPayer(\n bytes32 schainHash,\n Message calldata message,\n uint counter\n )\n internal\n returns (address)\n {\n try IGasReimbursable(message.destinationContract).gasPayer{gas: gasLimit}(\n schainHash,\n message.sender,\n message.data\n ) returns (address receiver) {\n return receiver;\n } catch Error(string memory reason) {\n emit PostMessageError(\n counter,\n _getSlice(bytes(reason), REVERT_REASON_LENGTH)\n );\n return address(0);\n } catch Panic(uint errorCode) {\n emit PostMessageError(\n counter,\n abi.encodePacked(errorCode)\n );\n return address(0);\n } catch (bytes memory revertData) {\n emit PostMessageError(\n counter,\n _getSlice(revertData, REVERT_REASON_LENGTH)\n );\n return address(0);\n }\n }\n\n /**\n * @dev Checks whether msg.sender is registered as custom extra contract.\n */\n function _authorizeOutgoingMessageSender(bytes32 targetChainHash) internal view virtual {\n require(\n isContractRegistered(bytes32(0), msg.sender) || isContractRegistered(targetChainHash, msg.sender),\n \"Sender contract is not registered\"\n ); \n }\n\n /**\n * @dev Returns list of registered custom extra contracts.\n */\n function _getRegistryContracts()\n internal\n view\n virtual\n returns (mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) storage);\n\n /**\n * @dev Returns hash of message array.\n */\n function _hashedArray(\n Message[] calldata messages,\n uint256 startingCounter,\n string calldata fromChainName\n )\n internal\n pure\n returns (bytes32)\n {\n bytes32 sourceHash = keccak256(abi.encodePacked(fromChainName));\n bytes32 hash = keccak256(abi.encodePacked(sourceHash, bytes32(startingCounter)));\n for (uint256 i = 0; i < messages.length; i++) {\n hash = keccak256(\n abi.encodePacked(\n abi.encode(\n hash,\n messages[i].sender,\n messages[i].destinationContract\n ),\n messages[i].data\n )\n );\n }\n return hash;\n }\n\n function _getSlice(bytes memory text, uint end) private pure returns (bytes memory) {\n uint slicedEnd = end < text.length ? end : text.length;\n bytes memory sliced = new bytes(slicedEnd);\n for(uint i = 0; i < slicedEnd; i++){\n sliced[i] = text[i];\n }\n return sliced; \n }\n}\n"
},
"contracts/mainnet/CommunityPool.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/*\n CommunityPool.sol - SKALE Manager\n Copyright (C) 2021-Present SKALE Labs\n @author Dmytro Stebaiev\n @author Artem Payvin\n @author Vadim Yavorsky\n\n SKALE Manager is free software: you can redistribute it and/or modify\n it under the terms of the GNU Affero General Public License as published\n by the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n SKALE Manager is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with SKALE Manager. If not, see .\n*/\n\npragma solidity 0.8.16;\n\nimport \"@skalenetwork/ima-interfaces/mainnet/ICommunityPool.sol\";\nimport \"@skalenetwork/skale-manager-interfaces/IWallets.sol\";\n\nimport \"../Messages.sol\";\nimport \"./Twin.sol\";\n\n\n/**\n * @title CommunityPool\n * @dev Contract contains logic to perform automatic self-recharging ETH for nodes.\n */\ncontract CommunityPool is Twin, ICommunityPool {\n\n using AddressUpgradeable for address payable;\n\n bytes32 public constant CONSTANT_SETTER_ROLE = keccak256(\"CONSTANT_SETTER_ROLE\");\n\n // address of user => schainHash => balance of gas wallet in ETH\n mapping(address => mapping(bytes32 => uint)) private _userWallets;\n\n // address of user => schainHash => true if unlocked for transferring\n mapping(address => mapping(bytes32 => bool)) public activeUsers;\n\n uint public minTransactionGas;\n\n uint public multiplierNumerator;\n uint public multiplierDivider;\n\n /**\n * @dev Emitted when minimal value in gas for transactions from schain to mainnet was changed \n */\n event MinTransactionGasWasChanged(\n uint oldValue,\n uint newValue\n );\n\n /**\n * @dev Emitted when basefee multiplier was changed \n */\n event MultiplierWasChanged(\n uint oldMultiplierNumerator,\n uint oldMultiplierDivider,\n uint newMultiplierNumerator,\n uint newMultiplierDivider\n );\n\n function initialize(\n IContractManager contractManagerOfSkaleManagerValue,\n ILinker linker,\n IMessageProxyForMainnet messageProxyValue\n )\n external\n override\n initializer\n {\n Twin.initialize(contractManagerOfSkaleManagerValue, messageProxyValue);\n _setupRole(LINKER_ROLE, address(linker));\n minTransactionGas = 1e6;\n multiplierNumerator = 3;\n multiplierDivider = 2;\n }\n\n /**\n * @dev Allows MessageProxyForMainnet to reimburse gas for transactions \n * that transfer funds from schain to mainnet.\n * \n * Requirements:\n * \n * - User that receives funds should have enough funds in their gas wallet.\n * - Address that should be reimbursed for executing transaction must not be null.\n */\n function refundGasByUser(\n bytes32 schainHash,\n address payable node,\n address user,\n uint gas\n )\n external\n override\n onlyMessageProxy\n returns (uint)\n {\n require(node != address(0), \"Node address must be set\");\n if (!activeUsers[user][schainHash]) {\n return gas;\n }\n uint amount = tx.gasprice * gas;\n if (amount > _userWallets[user][schainHash]) {\n amount = _userWallets[user][schainHash];\n }\n _userWallets[user][schainHash] = _userWallets[user][schainHash] - amount;\n if (!_balanceIsSufficient(schainHash, user, 0)) {\n activeUsers[user][schainHash] = false;\n messageProxy.postOutgoingMessage(\n schainHash,\n schainLinks[schainHash],\n Messages.encodeLockUserMessage(user)\n );\n }\n node.sendValue(amount);\n return (tx.gasprice * gas - amount) / tx.gasprice;\n }\n\n function refundGasBySchainWallet(\n bytes32 schainHash,\n address payable node,\n uint gas\n )\n external\n override\n onlyMessageProxy\n returns (bool)\n {\n if (gas > 0) {\n\n IWallets(payable(contractManagerOfSkaleManager.getContract(\"Wallets\"))).refundGasBySchain(\n schainHash,\n node,\n gas,\n false\n );\n }\n return true;\n }\n\n /**\n * @dev Allows `msg.sender` to recharge their wallet for further gas reimbursement.\n * \n * Requirements:\n * \n * - 'msg.sender` should recharge their gas wallet for amount that enough to reimburse any \n * transaction from schain to mainnet.\n */\n function rechargeUserWallet(string calldata schainName, address user) external payable override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(\n _balanceIsSufficient(schainHash, user, msg.value),\n \"Not enough ETH for transaction\"\n );\n _userWallets[user][schainHash] = _userWallets[user][schainHash] + msg.value;\n if (!activeUsers[user][schainHash]) {\n activeUsers[user][schainHash] = true;\n messageProxy.postOutgoingMessage(\n schainHash,\n schainLinks[schainHash],\n Messages.encodeActivateUserMessage(user)\n );\n }\n }\n\n /**\n * @dev Allows `msg.sender` to withdraw funds from their gas wallet.\n * If `msg.sender` withdraws too much funds,\n * then he will no longer be able to transfer their tokens on ETH from schain to mainnet.\n * \n * Requirements:\n * \n * - 'msg.sender` must have sufficient amount of ETH on their gas wallet.\n */\n function withdrawFunds(string calldata schainName, uint amount) external override {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(amount <= _userWallets[msg.sender][schainHash], \"Balance is too low\");\n require(!messageProxy.messageInProgress(), \"Message is in progress\");\n _userWallets[msg.sender][schainHash] = _userWallets[msg.sender][schainHash] - amount;\n if (\n !_balanceIsSufficient(schainHash, msg.sender, 0) &&\n activeUsers[msg.sender][schainHash]\n ) {\n activeUsers[msg.sender][schainHash] = false;\n messageProxy.postOutgoingMessage(\n schainHash,\n schainLinks[schainHash],\n Messages.encodeLockUserMessage(msg.sender)\n );\n }\n payable(msg.sender).sendValue(amount);\n }\n\n /**\n * @dev Allows `msg.sender` set the amount of gas that should be \n * enough for reimbursing any transaction from schain to mainnet.\n * \n * Requirements:\n * \n * - 'msg.sender` must have sufficient amount of ETH on their gas wallet.\n */\n function setMinTransactionGas(uint newMinTransactionGas) external override {\n require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), \"CONSTANT_SETTER_ROLE is required\");\n emit MinTransactionGasWasChanged(minTransactionGas, newMinTransactionGas);\n minTransactionGas = newMinTransactionGas;\n }\n\n /**\n * @dev Allows `msg.sender` set the amount of gas that should be \n * enough for reimbursing any transaction from schain to mainnet.\n * \n * Requirements:\n * \n * - 'msg.sender` must have sufficient amount of ETH on their gas wallet.\n */\n function setMultiplier(uint newMultiplierNumerator, uint newMultiplierDivider) external override {\n require(hasRole(CONSTANT_SETTER_ROLE, msg.sender), \"CONSTANT_SETTER_ROLE is required\");\n require(newMultiplierDivider > 0, \"Divider is zero\");\n emit MultiplierWasChanged(\n multiplierNumerator,\n multiplierDivider,\n newMultiplierNumerator,\n newMultiplierDivider\n );\n multiplierNumerator = newMultiplierNumerator;\n multiplierDivider = newMultiplierDivider;\n }\n\n /**\n * @dev Returns the amount of ETH on gas wallet for particular user.\n */\n function getBalance(address user, string calldata schainName) external view override returns (uint) {\n return _userWallets[user][keccak256(abi.encodePacked(schainName))];\n }\n\n /**\n * @dev Checks whether user is active and wallet was recharged for sufficient amount.\n */\n function checkUserBalance(bytes32 schainHash, address receiver) external view override returns (bool) {\n return activeUsers[receiver][schainHash] && _balanceIsSufficient(schainHash, receiver, 0);\n }\n\n /**\n * @dev Checks whether passed amount is enough to recharge user wallet with current basefee.\n */\n function getRecommendedRechargeAmount(\n bytes32 schainHash,\n address receiver\n )\n external\n view\n override\n returns (uint256)\n {\n uint256 currentValue = _multiplyOnAdaptedBaseFee(minTransactionGas);\n if (currentValue <= _userWallets[receiver][schainHash]) {\n return 0;\n }\n return currentValue - _userWallets[receiver][schainHash];\n }\n\n /**\n * @dev Checks whether user wallet was recharged for sufficient amount.\n */\n function _balanceIsSufficient(bytes32 schainHash, address receiver, uint256 delta) private view returns (bool) {\n return delta + _userWallets[receiver][schainHash] >= minTransactionGas * tx.gasprice;\n }\n\n function _multiplyOnAdaptedBaseFee(uint256 value) private view returns (uint256) {\n return value * block.basefee * multiplierNumerator / multiplierDivider;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/access/AccessControlEnumerableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlEnumerableUpgradeable.sol\";\nimport \"./AccessControlUpgradeable.sol\";\nimport \"../utils/structs/EnumerableSetUpgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Extension of {AccessControl} that allows enumerating the members of each role.\n */\nabstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable {\n function __AccessControlEnumerable_init() internal onlyInitializing {\n }\n\n function __AccessControlEnumerable_init_unchained() internal onlyInitializing {\n }\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n\n mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers;\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) public view virtual override returns (address) {\n return _roleMembers[role].at(index);\n }\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) public view virtual override returns (uint256) {\n return _roleMembers[role].length();\n }\n\n /**\n * @dev Overload {_grantRole} to track enumerable memberships\n */\n function _grantRole(bytes32 role, address account) internal virtual override {\n super._grantRole(role, account);\n _roleMembers[role].add(account);\n }\n\n /**\n * @dev Overload {_revokeRole} to track enumerable memberships\n */\n function _revokeRole(bytes32 role, address account) internal virtual override {\n super._revokeRole(role, account);\n _roleMembers[role].remove(account);\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/access/IAccessControlEnumerableUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlUpgradeable.sol\";\n\n/**\n * @dev External interface of AccessControlEnumerable declared to support ERC165 detection.\n */\ninterface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable {\n /**\n * @dev Returns one of the accounts that have `role`. `index` must be a\n * value between 0 and {getRoleMemberCount}, non-inclusive.\n *\n * Role bearers are not sorted in any particular way, and their ordering may\n * change at any point.\n *\n * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure\n * you perform all queries on the same block. See the following\n * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]\n * for more information.\n */\n function getRoleMember(bytes32 role, uint256 index) external view returns (address);\n\n /**\n * @dev Returns the number of accounts that have `role`. Can be used\n * together with {getRoleMember} to enumerate all bearers of a role.\n */\n function getRoleMemberCount(bytes32 role) external view returns (uint256);\n}\n"
},
"@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (access/AccessControl.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IAccessControlUpgradeable.sol\";\nimport \"../utils/ContextUpgradeable.sol\";\nimport \"../utils/StringsUpgradeable.sol\";\nimport \"../utils/introspection/ERC165Upgradeable.sol\";\nimport \"../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Contract module that allows children to implement role-based access\n * control mechanisms. This is a lightweight version that doesn't allow enumerating role\n * members except through off-chain means by accessing the contract event logs. Some\n * applications may benefit from on-chain enumerability, for those cases see\n * {AccessControlEnumerable}.\n *\n * Roles are referred to by their `bytes32` identifier. These should be exposed\n * in the external API and be unique. The best way to achieve this is by\n * using `public constant` hash digests:\n *\n * ```\n * bytes32 public constant MY_ROLE = keccak256(\"MY_ROLE\");\n * ```\n *\n * Roles can be used to represent a set of permissions. To restrict access to a\n * function call, use {hasRole}:\n *\n * ```\n * function foo() public {\n * require(hasRole(MY_ROLE, msg.sender));\n * ...\n * }\n * ```\n *\n * Roles can be granted and revoked dynamically via the {grantRole} and\n * {revokeRole} functions. Each role has an associated admin role, and only\n * accounts that have a role's admin role can call {grantRole} and {revokeRole}.\n *\n * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means\n * that only accounts with this role will be able to grant or revoke other\n * roles. More complex role relationships can be created by using\n * {_setRoleAdmin}.\n *\n * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to\n * grant and revoke this role. Extra precautions should be taken to secure\n * accounts that have been granted it.\n */\nabstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {\n function __AccessControl_init() internal onlyInitializing {\n }\n\n function __AccessControl_init_unchained() internal onlyInitializing {\n }\n struct RoleData {\n mapping(address => bool) members;\n bytes32 adminRole;\n }\n\n mapping(bytes32 => RoleData) private _roles;\n\n bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;\n\n /**\n * @dev Modifier that checks that an account has a specific role. Reverts\n * with a standardized message including the required role.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n *\n * _Available since v4.1._\n */\n modifier onlyRole(bytes32 role) {\n _checkRole(role);\n _;\n }\n\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);\n }\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) public view virtual override returns (bool) {\n return _roles[role].members[account];\n }\n\n /**\n * @dev Revert with a standard message if `_msgSender()` is missing `role`.\n * Overriding this function changes the behavior of the {onlyRole} modifier.\n *\n * Format of the revert message is described in {_checkRole}.\n *\n * _Available since v4.6._\n */\n function _checkRole(bytes32 role) internal view virtual {\n _checkRole(role, _msgSender());\n }\n\n /**\n * @dev Revert with a standard message if `account` is missing `role`.\n *\n * The format of the revert reason is given by the following regular expression:\n *\n * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/\n */\n function _checkRole(bytes32 role, address account) internal view virtual {\n if (!hasRole(role, account)) {\n revert(\n string(\n abi.encodePacked(\n \"AccessControl: account \",\n StringsUpgradeable.toHexString(uint160(account), 20),\n \" is missing role \",\n StringsUpgradeable.toHexString(uint256(role), 32)\n )\n )\n );\n }\n }\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) {\n return _roles[role].adminRole;\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleGranted} event.\n */\n function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _grantRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n *\n * May emit a {RoleRevoked} event.\n */\n function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {\n _revokeRole(role, account);\n }\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been revoked `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n *\n * May emit a {RoleRevoked} event.\n */\n function renounceRole(bytes32 role, address account) public virtual override {\n require(account == _msgSender(), \"AccessControl: can only renounce roles for self\");\n\n _revokeRole(role, account);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event. Note that unlike {grantRole}, this function doesn't perform any\n * checks on the calling account.\n *\n * May emit a {RoleGranted} event.\n *\n * [WARNING]\n * ====\n * This function should only be called from the constructor when setting\n * up the initial roles for the system.\n *\n * Using this function in any other way is effectively circumventing the admin\n * system imposed by {AccessControl}.\n * ====\n *\n * NOTE: This function is deprecated in favor of {_grantRole}.\n */\n function _setupRole(bytes32 role, address account) internal virtual {\n _grantRole(role, account);\n }\n\n /**\n * @dev Sets `adminRole` as ``role``'s admin role.\n *\n * Emits a {RoleAdminChanged} event.\n */\n function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {\n bytes32 previousAdminRole = getRoleAdmin(role);\n _roles[role].adminRole = adminRole;\n emit RoleAdminChanged(role, previousAdminRole, adminRole);\n }\n\n /**\n * @dev Grants `role` to `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleGranted} event.\n */\n function _grantRole(bytes32 role, address account) internal virtual {\n if (!hasRole(role, account)) {\n _roles[role].members[account] = true;\n emit RoleGranted(role, account, _msgSender());\n }\n }\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * Internal function without access restriction.\n *\n * May emit a {RoleRevoked} event.\n */\n function _revokeRole(bytes32 role, address account) internal virtual {\n if (hasRole(role, account)) {\n _roles[role].members[account] = false;\n emit RoleRevoked(role, account, _msgSender());\n }\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/access/IAccessControlUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev External interface of AccessControl declared to support ERC165 detection.\n */\ninterface IAccessControlUpgradeable {\n /**\n * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`\n *\n * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite\n * {RoleAdminChanged} not being emitted signaling this.\n *\n * _Available since v3.1._\n */\n event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);\n\n /**\n * @dev Emitted when `account` is granted `role`.\n *\n * `sender` is the account that originated the contract call, an admin role\n * bearer except when using {AccessControl-_setupRole}.\n */\n event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Emitted when `account` is revoked `role`.\n *\n * `sender` is the account that originated the contract call:\n * - if using `revokeRole`, it is the admin role bearer\n * - if using `renounceRole`, it is the role bearer (i.e. `account`)\n */\n event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);\n\n /**\n * @dev Returns `true` if `account` has been granted `role`.\n */\n function hasRole(bytes32 role, address account) external view returns (bool);\n\n /**\n * @dev Returns the admin role that controls `role`. See {grantRole} and\n * {revokeRole}.\n *\n * To change a role's admin, use {AccessControl-_setRoleAdmin}.\n */\n function getRoleAdmin(bytes32 role) external view returns (bytes32);\n\n /**\n * @dev Grants `role` to `account`.\n *\n * If `account` had not been already granted `role`, emits a {RoleGranted}\n * event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function grantRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from `account`.\n *\n * If `account` had been granted `role`, emits a {RoleRevoked} event.\n *\n * Requirements:\n *\n * - the caller must have ``role``'s admin role.\n */\n function revokeRole(bytes32 role, address account) external;\n\n /**\n * @dev Revokes `role` from the calling account.\n *\n * Roles are often managed via {grantRole} and {revokeRole}: this function's\n * purpose is to provide a mechanism for accounts to lose their privileges\n * if they are compromised (such as when a trusted device is misplaced).\n *\n * If the calling account had been granted `role`, emits a {RoleRevoked}\n * event.\n *\n * Requirements:\n *\n * - the caller must be `account`.\n */\n function renounceRole(bytes32 role, address account) external;\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-upgradeable/utils/StringsUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev String operations.\n */\nlibrary StringsUpgradeable {\n bytes16 private constant _HEX_SYMBOLS = \"0123456789abcdef\";\n uint8 private constant _ADDRESS_LENGTH = 20;\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` decimal representation.\n */\n function toString(uint256 value) internal pure returns (string memory) {\n // Inspired by OraclizeAPI's implementation - MIT licence\n // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol\n\n if (value == 0) {\n return \"0\";\n }\n uint256 temp = value;\n uint256 digits;\n while (temp != 0) {\n digits++;\n temp /= 10;\n }\n bytes memory buffer = new bytes(digits);\n while (value != 0) {\n digits -= 1;\n buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));\n value /= 10;\n }\n return string(buffer);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.\n */\n function toHexString(uint256 value) internal pure returns (string memory) {\n if (value == 0) {\n return \"0x00\";\n }\n uint256 temp = value;\n uint256 length = 0;\n while (temp != 0) {\n length++;\n temp >>= 8;\n }\n return toHexString(value, length);\n }\n\n /**\n * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.\n */\n function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {\n bytes memory buffer = new bytes(2 * length + 2);\n buffer[0] = \"0\";\n buffer[1] = \"x\";\n for (uint256 i = 2 * length + 1; i > 1; --i) {\n buffer[i] = _HEX_SYMBOLS[value & 0xf];\n value >>= 4;\n }\n require(value == 0, \"Strings: hex length insufficient\");\n return string(buffer);\n }\n\n /**\n * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.\n */\n function toHexString(address addr) internal pure returns (string memory) {\n return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./IERC165Upgradeable.sol\";\nimport \"../../proxy/utils/Initializable.sol\";\n\n/**\n * @dev Implementation of the {IERC165} interface.\n *\n * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check\n * for the additional interface id that will be supported. For example:\n *\n * ```solidity\n * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);\n * }\n * ```\n *\n * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.\n */\nabstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {\n function __ERC165_init() internal onlyInitializing {\n }\n\n function __ERC165_init_unchained() internal onlyInitializing {\n }\n /**\n * @dev See {IERC165-supportsInterface}.\n */\n function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {\n return interfaceId == type(IERC165Upgradeable).interfaceId;\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/utils/introspection/IERC165Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Interface of the ERC165 standard, as defined in the\n * https://eips.ethereum.org/EIPS/eip-165[EIP].\n *\n * Implementers can declare support of contract interfaces, which can then be\n * queried by others ({ERC165Checker}).\n *\n * For an implementation, see {ERC165}.\n */\ninterface IERC165Upgradeable {\n /**\n * @dev Returns true if this contract implements the interface defined by\n * `interfaceId`. See the corresponding\n * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]\n * to learn more about how these ids are created.\n *\n * This function call must use less than 30 000 gas.\n */\n function supportsInterface(bytes4 interfaceId) external view returns (bool);\n}\n"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}