zellic-audit
Initial commit
f998fcd
raw
history blame
181 kB
{
"language": "Solidity",
"sources": {
"contracts/mainnet/DepositBoxes/DepositBoxERC721.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * DepositBoxERC721.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 <https://www.gnu.org/licenses/>.\n */\n\npragma solidity 0.8.16;\n\nimport \"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol\";\nimport \"@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxERC721.sol\";\nimport \"@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol\";\n\nimport \"../DepositBox.sol\";\nimport \"../../Messages.sol\";\n\n\n/**\n * @title DepositBoxERC721\n * @dev Runs on mainnet,\n * accepts messages from schain,\n * stores deposits of ERC721.\n */\ncontract DepositBoxERC721 is DepositBox, IDepositBoxERC721 {\n using AddressUpgradeable for address;\n using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;\n\n // schainHash => address of ERC on Mainnet\n // Deprecated\n // slither-disable-next-line unused-state\n mapping(bytes32 => mapping(address => bool)) private _deprecatedSchainToERC721;\n mapping(address => mapping(uint256 => bytes32)) public transferredAmount;\n mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _schainToERC721;\n\n /**\n * @dev Emitted when token is mapped in DepositBoxERC721.\n */\n event ERC721TokenAdded(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 ERC721TokenReady(address indexed contractOnMainnet, uint256 tokenId);\n\n /**\n * @dev Allows `msg.sender` to send ERC721 token from mainnet to schain.\n * \n * Requirements:\n * \n * - Receiver contract should be defined.\n * - `msg.sender` should approve their token for DepositBoxERC721 address.\n */\n function depositERC721(\n string calldata schainName,\n address erc721OnMainnet,\n uint256 tokenId\n )\n external\n override\n rightTransaction(schainName, msg.sender)\n whenNotKilled(keccak256(abi.encodePacked(schainName)))\n {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n address contractReceiver = schainLinks[schainHash];\n require(contractReceiver != address(0), \"Unconnected chain\");\n require(\n IERC721Upgradeable(erc721OnMainnet).getApproved(tokenId) == address(this),\n \"DepositBox was not approved for ERC721 token\"\n );\n bytes memory data = _receiveERC721(\n schainName,\n erc721OnMainnet,\n msg.sender,\n tokenId\n );\n _saveTransferredAmount(schainHash, erc721OnMainnet, tokenId);\n IERC721Upgradeable(erc721OnMainnet).transferFrom(msg.sender, address(this), tokenId);\n messageProxy.postOutgoingMessage(\n schainHash,\n contractReceiver,\n data\n );\n }\n\n /**\n * @dev Allows MessageProxyForMainnet contract to execute transferring ERC721 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 * - DepositBoxERC721 contract should own token.\n */\n function postMessage(\n bytes32 schainHash,\n address sender,\n bytes calldata data\n )\n external\n virtual\n override\n onlyMessageProxy\n whenNotKilled(schainHash)\n checkReceiverChain(schainHash, sender)\n {\n Messages.TransferErc721Message memory message = Messages.decodeTransferErc721Message(data);\n require(message.token.isContract(), \"Given address is not a contract\");\n require(IERC721Upgradeable(message.token).ownerOf(message.tokenId) == address(this), \"Incorrect tokenId\");\n _removeTransferredAmount(message.token, message.tokenId);\n IERC721Upgradeable(message.token).transferFrom(address(this), message.receiver, message.tokenId);\n }\n\n /**\n * @dev Allows Schain owner to add an ERC721 token to DepositBoxERC721.\n * \n * Emits an {ERC721TokenAdded} event.\n * \n * Requirements:\n * \n * - Schain should not be killed.\n * - Only owner of the schain able to run function.\n */\n function addERC721TokenByOwner(string calldata schainName, address erc721OnMainnet)\n external\n override\n onlySchainOwner(schainName)\n whenNotKilled(keccak256(abi.encodePacked(schainName)))\n {\n _addERC721ForSchain(schainName, erc721OnMainnet);\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 * - DepositBoxERC721 contract should own such token.\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 erc721OnMainnet, address receiver, uint tokenId)\n external\n override\n onlySchainOwner(schainName)\n whenKilled(keccak256(abi.encodePacked(schainName)))\n {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(transferredAmount[erc721OnMainnet][tokenId] == schainHash, \"Incorrect tokenId\");\n _removeTransferredAmount(erc721OnMainnet, tokenId);\n IERC721Upgradeable(erc721OnMainnet).transferFrom(address(this), receiver, tokenId);\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 virtual\n override\n checkReceiverChain(schainHash, sender)\n returns (address)\n {\n Messages.TransferErc721Message memory message = Messages.decodeTransferErc721Message(data);\n return message.receiver;\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 getSchainToAllERC721Length(string calldata schainName) external view override returns (uint256) {\n return _schainToERC721[keccak256(abi.encodePacked(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 getSchainToAllERC721(\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 <= _schainToERC721[keccak256(abi.encodePacked(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] = _schainToERC721[keccak256(abi.encodePacked(schainName))].at(i);\n }\n }\n\n /**\n * @dev Creates a new DepositBoxERC721 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 Should return true if token was added by Schain owner or \n * automatically added after sending to schain if whitelist was turned off.\n */\n function getSchainToERC721(\n string calldata schainName,\n address erc721OnMainnet\n )\n public\n view\n override\n returns (bool)\n {\n return _schainToERC721[keccak256(abi.encodePacked(schainName))].contains(erc721OnMainnet);\n }\n\n /**\n * @dev Removes the ids of tokens that was transferred from schain.\n */\n function _removeTransferredAmount(address erc721Token, uint256 tokenId) internal {\n transferredAmount[erc721Token][tokenId] = bytes32(0);\n }\n\n /**\n * @dev Allows DepositBoxERC721 to receive ERC721 tokens.\n * \n * Emits an {ERC721TokenReady} event.\n * \n * Requirements:\n * \n * - Whitelist should be turned off for auto adding tokens to DepositBoxERC721.\n */\n function _receiveERC721(\n string calldata schainName,\n address erc721OnMainnet,\n address to,\n uint256 tokenId\n )\n internal\n virtual\n returns (bytes memory data)\n {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n bool isERC721AddedToSchain = _schainToERC721[schainHash].contains(erc721OnMainnet);\n if (!isERC721AddedToSchain) {\n require(!isWhitelisted(schainName), \"Whitelist is enabled\");\n _addERC721ForSchain(schainName, erc721OnMainnet);\n data = Messages.encodeTransferErc721AndTokenInfoMessage(\n erc721OnMainnet,\n to,\n tokenId,\n _getTokenInfo(IERC721MetadataUpgradeable(erc721OnMainnet))\n );\n } else {\n data = Messages.encodeTransferErc721Message(erc721OnMainnet, to, tokenId);\n }\n emit ERC721TokenReady(erc721OnMainnet, tokenId);\n }\n\n /**\n * @dev Adds an ERC721 token to DepositBoxERC721.\n * \n * Emits an {ERC721TokenAdded} event.\n * \n * Requirements:\n * \n * - Given address should be contract.\n */\n function _addERC721ForSchain(string calldata schainName, address erc721OnMainnet) internal {\n bytes32 schainHash = keccak256(abi.encodePacked(schainName));\n require(erc721OnMainnet.isContract(), \"Given address is not a contract\");\n require(!_schainToERC721[schainHash].contains(erc721OnMainnet), \"ERC721 Token was already added\");\n _schainToERC721[schainHash].add(erc721OnMainnet);\n emit ERC721TokenAdded(schainName, erc721OnMainnet);\n }\n\n /**\n * @dev Returns info about ERC721 token such as token name, symbol.\n */\n function _getTokenInfo(IERC721MetadataUpgradeable erc721) internal view returns (Messages.Erc721TokenInfo memory) {\n return Messages.Erc721TokenInfo({\n name: erc721.name(),\n symbol: erc721.symbol()\n });\n }\n\n /**\n * @dev Saves the ids of tokens that was transferred to schain.\n */\n function _saveTransferredAmount(bytes32 schainHash, address erc721Token, uint256 tokenId) private {\n transferredAmount[erc721Token][tokenId] = schainHash;\n }\n}\n"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../IERC721Upgradeable.sol\";\n\n/**\n * @title ERC-721 Non-Fungible Token Standard, optional metadata extension\n * @dev See https://eips.ethereum.org/EIPS/eip-721\n */\ninterface IERC721MetadataUpgradeable is IERC721Upgradeable {\n /**\n * @dev Returns the token collection name.\n */\n function name() external view returns (string memory);\n\n /**\n * @dev Returns the token collection symbol.\n */\n function symbol() external view returns (string memory);\n\n /**\n * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.\n */\n function tokenURI(uint256 tokenId) external view returns (string memory);\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"
},
"@skalenetwork/ima-interfaces/mainnet/DepositBoxes/IDepositBoxERC721.sol": {
"content": "// SPDX-License-Identifier: AGPL-3.0-only\n\n/**\n * IDepositBoxERC721.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 <https://www.gnu.org/licenses/>.\n */\n\npragma solidity >=0.6.10 <0.9.0;\n\nimport \"../IDepositBox.sol\";\n\n\ninterface IDepositBoxERC721 is IDepositBox {\n function depositERC721(string calldata schainName, address erc721OnMainnet, uint256 tokenId) external;\n function addERC721TokenByOwner(string calldata schainName, address erc721OnMainnet) external;\n function getFunds(string calldata schainName, address erc721OnMainnet, address receiver, uint tokenId) external;\n function getSchainToERC721(string calldata schainName, address erc721OnMainnet) external view returns (bool);\n function getSchainToAllERC721Length(string calldata schainName) external view returns (uint256);\n function getSchainToAllERC721(\n string calldata schainName,\n uint256 from,\n uint256 to\n )\n external\n view\n returns (address[] memory);\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"
},
"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 <https://www.gnu.org/licenses/>.\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"
},
"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 <https://www.gnu.org/licenses/>.\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}"
},
"@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol": {
"content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.7.0) (token/ERC721/IERC721.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../../utils/introspection/IERC165Upgradeable.sol\";\n\n/**\n * @dev Required interface of an ERC721 compliant contract.\n */\ninterface IERC721Upgradeable is IERC165Upgradeable {\n /**\n * @dev Emitted when `tokenId` token is transferred from `from` to `to`.\n */\n event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.\n */\n event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);\n\n /**\n * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.\n */\n event ApprovalForAll(address indexed owner, address indexed operator, bool approved);\n\n /**\n * @dev Returns the number of tokens in ``owner``'s account.\n */\n function balanceOf(address owner) external view returns (uint256 balance);\n\n /**\n * @dev Returns the owner of the `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function ownerOf(uint256 tokenId) external view returns (address owner);\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId,\n bytes calldata data\n ) external;\n\n /**\n * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients\n * are aware of the ERC721 protocol to prevent tokens from being forever locked.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must exist and be owned by `from`.\n * - If the caller is not `from`, it must have been allowed to move this token by either {approve} or {setApprovalForAll}.\n * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.\n *\n * Emits a {Transfer} event.\n */\n function safeTransferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Transfers `tokenId` token from `from` to `to`.\n *\n * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.\n *\n * Requirements:\n *\n * - `from` cannot be the zero address.\n * - `to` cannot be the zero address.\n * - `tokenId` token must be owned by `from`.\n * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.\n *\n * Emits a {Transfer} event.\n */\n function transferFrom(\n address from,\n address to,\n uint256 tokenId\n ) external;\n\n /**\n * @dev Gives permission to `to` to transfer `tokenId` token to another account.\n * The approval is cleared when the token is transferred.\n *\n * Only a single account can be approved at a time, so approving the zero address clears previous approvals.\n *\n * Requirements:\n *\n * - The caller must own the token or be an approved operator.\n * - `tokenId` must exist.\n *\n * Emits an {Approval} event.\n */\n function approve(address to, uint256 tokenId) external;\n\n /**\n * @dev Approve or remove `operator` as an operator for the caller.\n * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.\n *\n * Requirements:\n *\n * - The `operator` cannot be the caller.\n *\n * Emits an {ApprovalForAll} event.\n */\n function setApprovalForAll(address operator, bool _approved) external;\n\n /**\n * @dev Returns the account approved for `tokenId` token.\n *\n * Requirements:\n *\n * - `tokenId` must exist.\n */\n function getApproved(uint256 tokenId) external view returns (address operator);\n\n /**\n * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.\n *\n * See {setApprovalForAll}\n */\n function isApprovedForAll(address owner, address operator) external view returns (bool);\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"
},
"@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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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 <https://www.gnu.org/licenses/>.\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"
}
},
"settings": {
"optimizer": {
"enabled": true,
"runs": 200
},
"outputSelection": {
"*": {
"*": [
"evm.bytecode",
"evm.deployedBytecode",
"devdoc",
"userdoc",
"metadata",
"abi"
]
}
},
"libraries": {}
}
}