creation_sourcecode: {{
    "language": "Solidity",
    "sources": {
      "@openzeppelin/contracts/utils/Counters.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @title Counters\n * @author Matt Condon (@shrugs)\n * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number\n * of elements in a mapping, issuing ERC721 ids, or counting request ids.\n *\n * Include with `using Counters for Counters.Counter;`\n */\nlibrary Counters {\n    struct Counter {\n        // This variable should never be directly accessed by users of the library: interactions must be restricted to\n        // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add\n        // this feature: see https://github.com/ethereum/solidity/issues/4637\n        uint256 _value; // default: 0\n    }\n\n    function current(Counter storage counter) internal view returns (uint256) {\n        return counter._value;\n    }\n\n    function increment(Counter storage counter) internal {\n        unchecked {\n            counter._value += 1;\n        }\n    }\n\n    function decrement(Counter storage counter) internal {\n        uint256 value = counter._value;\n        require(value > 0, \"Counter: decrement overflow\");\n        unchecked {\n            counter._value = value - 1;\n        }\n    }\n\n    function reset(Counter storage counter) internal {\n        counter._value = 0;\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/cryptography/ECDSA.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/cryptography/ECDSA.sol)\n\npragma solidity ^0.8.0;\n\nimport \"../Strings.sol\";\n\n/**\n * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.\n *\n * These functions can be used to verify that a message was signed by the holder\n * of the private keys of a given address.\n */\nlibrary ECDSA {\n    enum RecoverError {\n        NoError,\n        InvalidSignature,\n        InvalidSignatureLength,\n        InvalidSignatureS,\n        InvalidSignatureV // Deprecated in v4.8\n    }\n\n    function _throwError(RecoverError error) private pure {\n        if (error == RecoverError.NoError) {\n            return; // no error: do nothing\n        } else if (error == RecoverError.InvalidSignature) {\n            revert(\"ECDSA: invalid signature\");\n        } else if (error == RecoverError.InvalidSignatureLength) {\n            revert(\"ECDSA: invalid signature length\");\n        } else if (error == RecoverError.InvalidSignatureS) {\n            revert(\"ECDSA: invalid signature 's' value\");\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature` or error string. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     *\n     * Documentation for signature generation:\n     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]\n     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {\n        if (signature.length == 65) {\n            bytes32 r;\n            bytes32 s;\n            uint8 v;\n            // ecrecover takes the signature parameters, and the only way to get them\n            // currently is to use assembly.\n            /// @solidity memory-safe-assembly\n            assembly {\n                r := mload(add(signature, 0x20))\n                s := mload(add(signature, 0x40))\n                v := byte(0, mload(add(signature, 0x60)))\n            }\n            return tryRecover(hash, v, r, s);\n        } else {\n            return (address(0), RecoverError.InvalidSignatureLength);\n        }\n    }\n\n    /**\n     * @dev Returns the address that signed a hashed message (`hash`) with\n     * `signature`. This address can then be used for verification purposes.\n     *\n     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:\n     * this function rejects them by requiring the `s` value to be in the lower\n     * half order, and the `v` value to be either 27 or 28.\n     *\n     * IMPORTANT: `hash` _must_ be the result of a hash operation for the\n     * verification to be secure: it is possible to craft signatures that\n     * recover to arbitrary addresses for non-hashed data. A safe way to ensure\n     * this is by receiving a hash of the original message (which may otherwise\n     * be too long), and then calling {toEthSignedMessageHash} on it.\n     */\n    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, signature);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.\n     *\n     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address, RecoverError) {\n        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);\n        uint8 v = uint8((uint256(vs) >> 255) + 27);\n        return tryRecover(hash, v, r, s);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.\n     *\n     * _Available since v4.2._\n     */\n    function recover(bytes32 hash, bytes32 r, bytes32 vs) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, r, vs);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     *\n     * _Available since v4.3._\n     */\n    function tryRecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address, RecoverError) {\n        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature\n        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines\n        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most\n        // signatures from current libraries generate a unique signature with an s-value in the lower half order.\n        //\n        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value\n        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or\n        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept\n        // these malleable signatures as well.\n        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {\n            return (address(0), RecoverError.InvalidSignatureS);\n        }\n\n        // If the signature is valid (and not malleable), return the signer address\n        address signer = ecrecover(hash, v, r, s);\n        if (signer == address(0)) {\n            return (address(0), RecoverError.InvalidSignature);\n        }\n\n        return (signer, RecoverError.NoError);\n    }\n\n    /**\n     * @dev Overload of {ECDSA-recover} that receives the `v`,\n     * `r` and `s` signature fields separately.\n     */\n    function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {\n        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);\n        _throwError(error);\n        return recovered;\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from a `hash`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32 message) {\n        // 32 is the length in bytes of hash,\n        // enforced by the type signature above\n        /// @solidity memory-safe-assembly\n        assembly {\n            mstore(0x00, \"\\x19Ethereum Signed Message:\\n32\")\n            mstore(0x1c, hash)\n            message := keccak256(0x00, 0x3c)\n        }\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Message, created from `s`. This\n     * produces hash corresponding to the one signed with the\n     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]\n     * JSON-RPC method as part of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19Ethereum Signed Message:\\n\", Strings.toString(s.length), s));\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Typed Data, created from a\n     * `domainSeparator` and a `structHash`. This produces hash corresponding\n     * to the one signed with the\n     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]\n     * JSON-RPC method as part of EIP-712.\n     *\n     * See {recover}.\n     */\n    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32 data) {\n        /// @solidity memory-safe-assembly\n        assembly {\n            let ptr := mload(0x40)\n            mstore(ptr, \"\\x19\\x01\")\n            mstore(add(ptr, 0x02), domainSeparator)\n            mstore(add(ptr, 0x22), structHash)\n            data := keccak256(ptr, 0x42)\n        }\n    }\n\n    /**\n     * @dev Returns an Ethereum Signed Data with intended validator, created from a\n     * `validator` and `data` according to the version 0 of EIP-191.\n     *\n     * See {recover}.\n     */\n    function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) {\n        return keccak256(abi.encodePacked(\"\\x19\\x00\", validator, data));\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/Math.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/math/Math.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard math utilities missing in the Solidity language.\n */\nlibrary Math {\n    enum Rounding {\n        Down, // Toward negative infinity\n        Up, // Toward infinity\n        Zero // Toward zero\n    }\n\n    /**\n     * @dev Returns the largest of two numbers.\n     */\n    function max(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two numbers.\n     */\n    function min(uint256 a, uint256 b) internal pure returns (uint256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two numbers. The result is rounded towards\n     * zero.\n     */\n    function average(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b) / 2 can overflow.\n        return (a & b) + (a ^ b) / 2;\n    }\n\n    /**\n     * @dev Returns the ceiling of the division of two numbers.\n     *\n     * This differs from standard division with `/` in that it rounds up instead\n     * of rounding down.\n     */\n    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {\n        // (a + b - 1) / b can overflow on addition, so we distribute.\n        return a == 0 ? 0 : (a - 1) / b + 1;\n    }\n\n    /**\n     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0\n     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)\n     * with further edits by Uniswap Labs also under MIT license.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator) internal pure returns (uint256 result) {\n        unchecked {\n            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use\n            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256\n            // variables such that product = prod1 * 2^256 + prod0.\n            uint256 prod0; // Least significant 256 bits of the product\n            uint256 prod1; // Most significant 256 bits of the product\n            assembly {\n                let mm := mulmod(x, y, not(0))\n                prod0 := mul(x, y)\n                prod1 := sub(sub(mm, prod0), lt(mm, prod0))\n            }\n\n            // Handle non-overflow cases, 256 by 256 division.\n            if (prod1 == 0) {\n                // Solidity will revert if denominator == 0, unlike the div opcode on its own.\n                // The surrounding unchecked block does not change this fact.\n                // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic.\n                return prod0 / denominator;\n            }\n\n            // Make sure the result is less than 2^256. Also prevents denominator == 0.\n            require(denominator > prod1, \"Math: mulDiv overflow\");\n\n            ///////////////////////////////////////////////\n            // 512 by 256 division.\n            ///////////////////////////////////////////////\n\n            // Make division exact by subtracting the remainder from [prod1 prod0].\n            uint256 remainder;\n            assembly {\n                // Compute remainder using mulmod.\n                remainder := mulmod(x, y, denominator)\n\n                // Subtract 256 bit number from 512 bit number.\n                prod1 := sub(prod1, gt(remainder, prod0))\n                prod0 := sub(prod0, remainder)\n            }\n\n            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.\n            // See https://cs.stackexchange.com/q/138556/92363.\n\n            // Does not overflow because the denominator cannot be zero at this stage in the function.\n            uint256 twos = denominator & (~denominator + 1);\n            assembly {\n                // Divide denominator by twos.\n                denominator := div(denominator, twos)\n\n                // Divide [prod1 prod0] by twos.\n                prod0 := div(prod0, twos)\n\n                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.\n                twos := add(div(sub(0, twos), twos), 1)\n            }\n\n            // Shift in bits from prod1 into prod0.\n            prod0 |= prod1 * twos;\n\n            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such\n            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for\n            // four bits. That is, denominator * inv = 1 mod 2^4.\n            uint256 inverse = (3 * denominator) ^ 2;\n\n            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works\n            // in modular arithmetic, doubling the correct bits in each step.\n            inverse *= 2 - denominator * inverse; // inverse mod 2^8\n            inverse *= 2 - denominator * inverse; // inverse mod 2^16\n            inverse *= 2 - denominator * inverse; // inverse mod 2^32\n            inverse *= 2 - denominator * inverse; // inverse mod 2^64\n            inverse *= 2 - denominator * inverse; // inverse mod 2^128\n            inverse *= 2 - denominator * inverse; // inverse mod 2^256\n\n            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.\n            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is\n            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1\n            // is no longer required.\n            result = prod0 * inverse;\n            return result;\n        }\n    }\n\n    /**\n     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.\n     */\n    function mulDiv(uint256 x, uint256 y, uint256 denominator, Rounding rounding) internal pure returns (uint256) {\n        uint256 result = mulDiv(x, y, denominator);\n        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {\n            result += 1;\n        }\n        return result;\n    }\n\n    /**\n     * @dev Returns the square root of a number. If the number is not a perfect square, the value is rounded down.\n     *\n     * Inspired by Henry S. Warren, Jr.'s \"Hacker's Delight\" (Chapter 11).\n     */\n    function sqrt(uint256 a) internal pure returns (uint256) {\n        if (a == 0) {\n            return 0;\n        }\n\n        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.\n        //\n        // We know that the \"msb\" (most significant bit) of our target number `a` is a power of 2 such that we have\n        // `msb(a) <= a < 2*msb(a)`. This value can be written `msb(a)=2**k` with `k=log2(a)`.\n        //\n        // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)`\n        // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))`\n        // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)`\n        //\n        // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit.\n        uint256 result = 1 << (log2(a) >> 1);\n\n        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,\n        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at\n        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision\n        // into the expected uint128 result.\n        unchecked {\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            result = (result + a / result) >> 1;\n            return min(result, a / result);\n        }\n    }\n\n    /**\n     * @notice Calculates sqrt(a), following the selected rounding direction.\n     */\n    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = sqrt(a);\n            return result + (rounding == Rounding.Up && result * result < a ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 2, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 128;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 64;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 32;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 16;\n            }\n            if (value >> 8 > 0) {\n                value >>= 8;\n                result += 8;\n            }\n            if (value >> 4 > 0) {\n                value >>= 4;\n                result += 4;\n            }\n            if (value >> 2 > 0) {\n                value >>= 2;\n                result += 2;\n            }\n            if (value >> 1 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 2, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log2(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log2(value);\n            return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 10, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >= 10 ** 64) {\n                value /= 10 ** 64;\n                result += 64;\n            }\n            if (value >= 10 ** 32) {\n                value /= 10 ** 32;\n                result += 32;\n            }\n            if (value >= 10 ** 16) {\n                value /= 10 ** 16;\n                result += 16;\n            }\n            if (value >= 10 ** 8) {\n                value /= 10 ** 8;\n                result += 8;\n            }\n            if (value >= 10 ** 4) {\n                value /= 10 ** 4;\n                result += 4;\n            }\n            if (value >= 10 ** 2) {\n                value /= 10 ** 2;\n                result += 2;\n            }\n            if (value >= 10 ** 1) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 10, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log10(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log10(value);\n            return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0);\n        }\n    }\n\n    /**\n     * @dev Return the log in base 256, rounded down, of a positive value.\n     * Returns 0 if given 0.\n     *\n     * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string.\n     */\n    function log256(uint256 value) internal pure returns (uint256) {\n        uint256 result = 0;\n        unchecked {\n            if (value >> 128 > 0) {\n                value >>= 128;\n                result += 16;\n            }\n            if (value >> 64 > 0) {\n                value >>= 64;\n                result += 8;\n            }\n            if (value >> 32 > 0) {\n                value >>= 32;\n                result += 4;\n            }\n            if (value >> 16 > 0) {\n                value >>= 16;\n                result += 2;\n            }\n            if (value >> 8 > 0) {\n                result += 1;\n            }\n        }\n        return result;\n    }\n\n    /**\n     * @dev Return the log in base 256, following the selected rounding direction, of a positive value.\n     * Returns 0 if given 0.\n     */\n    function log256(uint256 value, Rounding rounding) internal pure returns (uint256) {\n        unchecked {\n            uint256 result = log256(value);\n            return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/math/SignedMath.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol)\n\npragma solidity ^0.8.0;\n\n/**\n * @dev Standard signed math utilities missing in the Solidity language.\n */\nlibrary SignedMath {\n    /**\n     * @dev Returns the largest of two signed numbers.\n     */\n    function max(int256 a, int256 b) internal pure returns (int256) {\n        return a > b ? a : b;\n    }\n\n    /**\n     * @dev Returns the smallest of two signed numbers.\n     */\n    function min(int256 a, int256 b) internal pure returns (int256) {\n        return a < b ? a : b;\n    }\n\n    /**\n     * @dev Returns the average of two signed numbers without overflow.\n     * The result is rounded towards zero.\n     */\n    function average(int256 a, int256 b) internal pure returns (int256) {\n        // Formula from the book \"Hacker's Delight\"\n        int256 x = (a & b) + ((a ^ b) >> 1);\n        return x + (int256(uint256(x) >> 255) & (a ^ b));\n    }\n\n    /**\n     * @dev Returns the absolute unsigned value of a signed value.\n     */\n    function abs(int256 n) internal pure returns (uint256) {\n        unchecked {\n            // must be unchecked in order to support `n = type(int256).min`\n            return uint256(n >= 0 ? n : -n);\n        }\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/Strings.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol)\n\npragma solidity ^0.8.0;\n\nimport \"./math/Math.sol\";\nimport \"./math/SignedMath.sol\";\n\n/**\n * @dev String operations.\n */\nlibrary Strings {\n    bytes16 private constant _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        unchecked {\n            uint256 length = Math.log10(value) + 1;\n            string memory buffer = new string(length);\n            uint256 ptr;\n            /// @solidity memory-safe-assembly\n            assembly {\n                ptr := add(buffer, add(32, length))\n            }\n            while (true) {\n                ptr--;\n                /// @solidity memory-safe-assembly\n                assembly {\n                    mstore8(ptr, byte(mod(value, 10), _SYMBOLS))\n                }\n                value /= 10;\n                if (value == 0) break;\n            }\n            return buffer;\n        }\n    }\n\n    /**\n     * @dev Converts a `int256` to its ASCII `string` decimal representation.\n     */\n    function toString(int256 value) internal pure returns (string memory) {\n        return string(abi.encodePacked(value < 0 ? \"-\" : \"\", toString(SignedMath.abs(value))));\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        unchecked {\n            return toHexString(value, Math.log256(value) + 1);\n        }\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] = _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    /**\n     * @dev Returns true if the two strings are equal.\n     */\n    function equal(string memory a, string memory b) internal pure returns (bool) {\n        return keccak256(bytes(a)) == keccak256(bytes(b));\n    }\n}\n"
      },
      "@openzeppelin/contracts/utils/structs/EnumerableSet.sol": {
        "content": "// SPDX-License-Identifier: MIT\n// OpenZeppelin Contracts (last updated v4.9.0) (utils/structs/EnumerableSet.sol)\n// This file was procedurally generated from scripts/generate/templates/EnumerableSet.js.\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 * ```solidity\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\n * 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\n * array of EnumerableSet.\n * ====\n */\nlibrary EnumerableSet {\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        bytes32[] memory store = _values(set._inner);\n        bytes32[] memory result;\n\n        /// @solidity memory-safe-assembly\n        assembly {\n            result := store\n        }\n\n        return result;\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 in 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/facets/TeleportFacet.sol": {
        "content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\nimport {ITeleport} from \"../interfaces/ITeleport.sol\";\nimport {IProvider} from \"../interfaces/IProvider.sol\";\nimport {IProviderSelector} from \"../interfaces/IProviderSelector.sol\";\nimport {ITeleportDApp} from \"../interfaces/ITeleportDApp.sol\";\nimport {LibTeleport} from \"../libraries/LibTeleport.sol\";\nimport {LibGovernance, ECDSA, Counters} from \"../libraries/LibGovernance.sol\";\nimport {LibFeeCalculator} from \"../libraries/LibFeeCalculator.sol\";\nimport {Governable} from \"../Governable.sol\";\nimport {ICommonErrors, ITeleportFacetErrors} from \"../interfaces/IDiamondErrors.sol\";\n\ncontract TeleportFacet is ITeleport, Governable, ITeleportFacetErrors {\n    using Counters for Counters.Counter;\n    address private immutable _SELF = address(this);\n\n    // Modifier to restrict access to functions only to valid providers\n    modifier onlyValidProvider() {\n        if (!IProviderSelector(LibTeleport.teleportStorage().providerSelector).isValidProvider(msg.sender))\n            revert OnlyValidProviderCalls();\n        _;\n    }\n\n    /**\n     * @notice sets the state for the TeleportFacet\n     * @dev This method is never attached on the diamond\n     */\n    function state(bytes memory data_) external {\n        if (address(this) == _SELF) {\n            revert ICommonErrors.NoDirectCall();\n        }\n\n        LibTeleport.Storage storage ts = LibTeleport.teleportStorage();\n        (ts.chainId, ts.providerSelector) = abi.decode(data_, (uint8, address));\n    }\n\n    /*********************************** PUBLIC INTERFACE *********************************/\n\n    /**\n     * @notice Selects a provider to bridge the message to the target chain\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     */\n    function transmit(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_\n    ) external payable override {\n        _transmitWithArgs(targetChainId_, transmissionReceiver_, dAppId_, payload_, bytes(\"\"));\n    }\n\n    /**\n     * @notice Selects a provider to bridge the message to the target chain\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param extraOptionalArgs_ Extra optional arguments to be passed to the provider. This allow for specific provider configurations. Send bytes('') if not needed\n     */\n    function transmitWithArgs(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external payable override {\n        _transmitWithArgs(targetChainId_, transmissionReceiver_, dAppId_, payload_, extraOptionalArgs_);\n    }\n\n    /**\n     * @notice Selects a provider to bridge the message to the target chain\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param providerAddress_ The provider to be used for the transmission\n     * @param extraOptionalArgs_ Extra arguments to be passed to the provider. This allow for specific provider configurations\n     * */\n    function transmitWithProvider(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        address providerAddress_,\n        bytes calldata extraOptionalArgs_\n    ) external payable {\n        // Check if the provider exists\n        if (providerAddress_ == address(0)) revert ProviderCannotBeZeroAddress();\n\n        // Validate that the given provider is a valid one according to the provider selector\n        if (!IProviderSelector(LibTeleport.teleportStorage().providerSelector).isValidProvider(providerAddress_))\n            revert InvalidProvider();\n\n        _transmitWithProvider(\n            targetChainId_,\n            transmissionReceiver_,\n            dAppId_,\n            payload_,\n            providerAddress_,\n            extraOptionalArgs_\n        );\n    }\n\n    /**\n     * @dev Returns the teleport fee charged by the teleport contract.\n     * @return The teleport fee amount in wei.\n     */\n    function teleportFee() external view override returns (uint256) {\n        return LibFeeCalculator.feeCalculatorStorage().serviceFee;\n    }\n\n    /**\n     * @dev Returns the provider fee charged by the provider contract.\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param extraOptionalArgs_ Extra optional arguments to be passed to the provider. This allow for specific provider configurations. Send bytes('') if not needed\n     * @return The provider fee amount in wei.\n     */\n    function providerFee(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external view override returns (uint256) {\n        // Get the correct provider from provider selector\n        address providerAddress_ = IProviderSelector(LibTeleport.teleportStorage().providerSelector).getProvider(\n            targetChainId_,\n            transmissionReceiver_,\n            dAppId_,\n            payload_\n        );\n\n        if (providerAddress_ == address(0)) revert TransmissionNotSupportedByAnyProvider();\n\n        return\n            _providerFee(\n                providerAddress_,\n                targetChainId_,\n                transmissionReceiver_,\n                dAppId_,\n                payload_,\n                extraOptionalArgs_\n            );\n    }\n\n    /**\n     * @dev Returns the provider fee charged by the provider contract.\n     * @param providerAddress_ The provider to be used for the transmission\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param extraOptionalArgs_ Extra optional arguments to be passed to the provider. This allow for specific provider configurations. Send bytes('') if not needed\n     * @return The provider fee amount in wei.\n     */\n    function providerFee(\n        address providerAddress_,\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external view override returns (uint256) {\n        if (providerAddress_ == address(0)) revert ProviderCannotBeZeroAddress();\n\n        return\n            _providerFee(\n                providerAddress_,\n                targetChainId_,\n                transmissionReceiver_,\n                dAppId_,\n                payload_,\n                extraOptionalArgs_\n            );\n    }\n\n    /**\n     * @dev Returns the service fee charged by the teleport and the provider contracts.\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param extraOptionalArgs_ Extra optional arguments to be passed to the provider. This allow for specific provider configurations. Send bytes('') if not needed\n     * @return The service fee amount in wei.\n     */\n    function serviceFee(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external view override returns (uint256) {\n        // Get the correct provider from provider selector\n        address providerAddress_ = IProviderSelector(LibTeleport.teleportStorage().providerSelector).getProvider(\n            targetChainId_,\n            transmissionReceiver_,\n            dAppId_,\n            payload_\n        );\n\n        if (providerAddress_ == address(0)) revert TransmissionNotSupportedByAnyProvider();\n\n        return\n            LibFeeCalculator.feeCalculatorStorage().serviceFee +\n            _providerFee(\n                providerAddress_,\n                targetChainId_,\n                transmissionReceiver_,\n                dAppId_,\n                payload_,\n                extraOptionalArgs_\n            );\n    }\n\n    /**\n     * @dev Returns the service fee charged by the teleport and the provider contracts.\n     * @param providerAddress_ The provider to be used for the transmission\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param extraOptionalArgs_ Extra optional arguments to be passed to the provider. This allow for specific provider configurations. Send bytes('') if not needed\n     * @return The service fee amount in wei.\n     */\n    function serviceFee(\n        address providerAddress_,\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external view override returns (uint256) {\n        // Get the correct provider from provider selector\n        if (providerAddress_ == address(0)) revert ProviderCannotBeZeroAddress();\n\n        return\n            LibFeeCalculator.feeCalculatorStorage().serviceFee +\n            _providerFee(\n                providerAddress_,\n                targetChainId_,\n                transmissionReceiver_,\n                dAppId_,\n                payload_,\n                extraOptionalArgs_\n            );\n    }\n\n    /**\n     * @dev Delivers a message using the provided provider. This might not be supported by all providers.\n     * @param providerAddress The address of the provider contract.\n     * @param args The arguments to be passed to the provider contract.\n     */\n    function deliver(address providerAddress, bytes calldata args) external override {\n        // Check if the provider exists\n        if (providerAddress == address(0)) revert ProviderCannotBeZeroAddress();\n\n        // Validate that the given provider is a valid one according to the provider selector\n        if (!IProviderSelector(LibTeleport.teleportStorage().providerSelector).isValidProvider(providerAddress))\n            revert InvalidProvider();\n\n        // Call deliver method on provider\n        IProvider(providerAddress).manualClaim(args);\n    }\n\n    /**\n     * @dev Function called when a provider receives a transmission from another chain's teleport.\n     * @param args The DappTransmissionReceive struct containing the transmission data.\n     */\n    function onProviderReceive(DappTransmissionReceive calldata args) external override onlyValidProvider {\n        bytes memory sourceChainTeleportSender = LibTeleport.teleportStorage().teleportAddressByChainId[\n            args.sourceChainId\n        ];\n\n        if (sourceChainTeleportSender.length == 0) revert SourceChainNotSupported();\n\n        // check the sender is the teleport contract of the source chain\n        if (keccak256(sourceChainTeleportSender) != keccak256(args.teleportSender)) revert InvalidTeleportSender();\n\n        ITeleportDApp(args.dappTransmissionReceiver).onTeleportMessage(\n            args.sourceChainId,\n            args.dappTransmissionSender,\n            args.dAppId,\n            args.payload\n        );\n    }\n\n    /*********************************** GOVERNANCE SECTION *********************************/\n\n    function configProviderSelector(\n        bytes calldata configData,\n        bytes[] calldata signatures_\n    ) external override onlyConsensusNonce(computeConfigProviderSelector(configData), signatures_) {\n        IProviderSelector(LibTeleport.teleportStorage().providerSelector).config(configData);\n    }\n\n    /// @notice Computes the bytes32 ethereum signed message hash of the call to config the provider selector message\n    function computeConfigProviderSelector(bytes calldata configData) internal view returns (bytes32) {\n        return\n            ECDSA.toEthSignedMessageHash(\n                keccak256(\n                    abi.encode(\n                        LibTeleport.teleportStorage().chainId,\n                        \"computeConfigProviderSelector\",\n                        configData,\n                        LibGovernance.governanceStorage().administrativeNonce.current()\n                    )\n                )\n            );\n    }\n\n    function configProvider(\n        bytes calldata configData,\n        address providerAddress,\n        bytes[] calldata signatures_\n    ) external override onlyConsensusNonce(computeConfigProvider(configData, providerAddress), signatures_) {\n        // Check if the provider exists\n        if (providerAddress == address(0)) revert ProviderCannotBeZeroAddress();\n\n        // Validate that the given provider is a valid one according to the provider selector\n        if (!IProviderSelector(LibTeleport.teleportStorage().providerSelector).isValidProvider(providerAddress))\n            revert InvalidProvider();\n\n        IProvider(providerAddress).config(configData);\n    }\n\n    /// @notice Computes the bytes32 ethereum signed message hash of the call to the config a provider message\n    function computeConfigProvider(bytes calldata configData, address providerAddress) internal view returns (bytes32) {\n        return\n            ECDSA.toEthSignedMessageHash(\n                keccak256(\n                    abi.encode(\n                        LibTeleport.teleportStorage().chainId,\n                        \"computeConfigProvider\",\n                        configData,\n                        providerAddress,\n                        LibGovernance.governanceStorage().administrativeNonce.current()\n                    )\n                )\n            );\n    }\n\n    /*********************************** PRIVATE SECTION *********************************/\n\n    /**\n     * @notice internal function to transmit the message to the target chain using the given provider\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param dappTransmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param providerAddress_ The provider to be used for the transmission\n     * @param extraOptionalArgs_ Extra arguments to be passed to the provider. This allow for specific provider configurations\n     * */\n    function _transmitWithProvider(\n        uint8 targetChainId_,\n        bytes calldata dappTransmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        address providerAddress_,\n        bytes memory extraOptionalArgs_\n    ) private {\n        uint256 remainingValue = LibFeeCalculator.accrueReward(msg.value);\n\n        emit TransmissionFees(msg.value - remainingValue);\n\n        bytes memory targetChainTeleportReceiver = LibTeleport.teleportStorage().teleportAddressByChainId[\n            targetChainId_\n        ];\n\n        if (targetChainTeleportReceiver.length == 0) revert TargetChainNotSupported();\n\n        // Call the provider to transmit the message\n        IProvider(providerAddress_).sendMsg{value: remainingValue}(\n            targetChainId_,\n            targetChainTeleportReceiver,\n            IProvider.DappTransmissionInfo(_addressToBytes(msg.sender), dappTransmissionReceiver_, dAppId_, payload_),\n            extraOptionalArgs_\n        );\n    }\n\n    /**\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param extraOptionalArgs_ Extra optional arguments to be passed to the provider. This allow for specific provider configurations. Send bytes('') if not needed\n     */\n    function _transmitWithArgs(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes memory extraOptionalArgs_\n    ) private {\n        // Get the correct provider from provider selector\n        address provider = IProviderSelector(LibTeleport.teleportStorage().providerSelector).getProvider(\n            targetChainId_,\n            transmissionReceiver_,\n            dAppId_,\n            payload_\n        );\n\n        if (provider == address(0)) revert TransmissionNotSupportedByAnyProvider();\n\n        //Call the transmitWithProvider with the gotten providerId to transmit the message\n        _transmitWithProvider(targetChainId_, transmissionReceiver_, dAppId_, payload_, provider, extraOptionalArgs_);\n    }\n\n    /**\n     * @dev Returns the provider fee charged by the provider contract.\n     * @param providerAddress_ The provider to be used for the transmission\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param extraOptionalArgs_ Extra optional arguments to be passed to the provider. This allow for specific provider configurations. Send bytes('') if not needed\n     * @return The provider fee amount in wei.\n     */\n    function _providerFee(\n        address providerAddress_,\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) internal view returns (uint256) {\n        bytes memory targetChainTeleportReceiver = LibTeleport.teleportStorage().teleportAddressByChainId[\n            targetChainId_\n        ];\n\n        if (targetChainTeleportReceiver.length == 0) revert TargetChainNotSupported();\n\n        return\n            IProvider(providerAddress_).fee(\n                targetChainId_,\n                targetChainTeleportReceiver,\n                IProvider.DappTransmissionInfo(_addressToBytes(msg.sender), transmissionReceiver_, dAppId_, payload_),\n                extraOptionalArgs_\n            );\n    }\n\n    /*********************************** UTILS *********************************/\n\n    /**\n     *  @param addr value of type address\n     *  @return addr value converted to type bytes\n     */\n    function _addressToBytes(address addr) internal pure returns (bytes memory) {\n        return abi.encodePacked(addr);\n    }\n}\n"
      },
      "contracts/Governable.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\nimport {LibGovernance, Counters, ECDSA} from \"./libraries/LibGovernance.sol\";\nimport {IGovernanceFacetErrors} from \"./interfaces/IDiamondErrors.sol\";\n\n/**\n * @notice Provides modifiers for securing methods behind a governance vote\n */\nabstract contract Governable {\n    using Counters for Counters.Counter;\n    using LibGovernance for LibGovernance.Storage;\n\n    /**\n     * @notice Verifies the message hash against the signatures. Requires a majority.\n     * @param _ethHash hash to verify\n     * @param _signatures governance hash signatures\n     */\n    function onlyConsensus(LibGovernance.Storage storage gs, bytes32 _ethHash, bytes[] memory _signatures) internal view {\n        uint256 members = gs.membersCount();\n        if (_signatures.length > members || _signatures.length <= (members / 2)) {\n            revert IGovernanceFacetErrors.InvalidNumberOfSignatures();\n        }\n\n        address lastSigner;\n        for (uint256 i = 0; i < _signatures.length; ) {\n            address signer = ECDSA.recover(_ethHash, _signatures[i]);\n\n            if (!gs.isMember(signer)) {\n                revert IGovernanceFacetErrors.InvalidSigner();\n            }\n            if (signer <= lastSigner) {\n                revert IGovernanceFacetErrors.WrongSignersOrder();\n            }\n            lastSigner = signer;\n\n            unchecked {\n                ++i;\n            }\n        }\n    }\n\n    /**\n     * @notice Verifies the message hash against the signatures. Requires a majority. Burns a nonce.\n     * @param _ethHash hash to verify\n     * @param _signatures governance hash signatures\n     */\n    modifier onlyConsensusNonce(bytes32 _ethHash, bytes[] calldata _signatures) {\n        LibGovernance.Storage storage gs = LibGovernance.governanceStorage();\n        onlyConsensus(gs, _ethHash, _signatures);\n        gs.administrativeNonce.increment();\n        _;\n    }\n\n    /**\n     * @notice Verifies the message hash against the signatures. Requires a majority. Burns the hash.\n     * @param _ethHash hash to verify\n     * @param _signatures governance hash signatures\n     */\n    modifier onlyConsensusHash(bytes32 _ethHash, bytes[] memory _signatures) {\n        LibGovernance.Storage storage gs = LibGovernance.governanceStorage();\n\n        if (gs.hashesUsed[_ethHash]) {\n            revert IGovernanceFacetErrors.HashAlreadyUsed();\n        }\n        gs.hashesUsed[_ethHash] = true;\n        onlyConsensus(gs, _ethHash, _signatures);\n        _;\n    }\n}\n"
      },
      "contracts/interfaces/IDiamondErrors.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\ninterface ICommonErrors {\n    error NoDirectCall();\n\n    error TransferFailed(string message);\n\n    error AccountIsAddressZero();\n\n    error NoValueAllowed();\n}\n\ninterface IDiamondLoupeFacetErrors {\n    error ExceededMaxFacets();\n}\n\ninterface ILibDiamondErrors {\n    // \"Diamond: Function does not exist\"\n    error FunctionDoesNotExist();\n\n    // LibDiamondCut: No selectors in facet to cut\n    error NoSelectorsInFacetToCut();\n\n    // LibDiamondCut: Can't add function that already exists\n    error FunctionAlreadyExists();\n\n    // LibDiamondCut: Can't replace immutable function\n    error CantReplaceImmutableFn();\n\n    // LibDiamondCut: Can't replace function with same function\n    error CantReplaceWithSameFn();\n\n    // LibDiamondCut: Can't replace function that doesn't exist\n    error CantReplaceNonexistentFn();\n\n    // LibDiamondCut: Remove facet address must be address(0)\n    error RemoveFacetAddressMustBeZero();\n\n    // LibDiamondCut: Can't remove function that doesn't exist\n    error CantRemoveNonexistentFn();\n\n    // LibDiamondCut: Can't remove immutable function\n    error CantRemoveImmutableFn();\n\n    // LibDiamondCut: Incorrect FacetCutAction\n    error IncorrectFacetCutAction();\n\n    // LibDiamondCut: _init is address(0) but_calldata is not empty\n    error InitIsAddress0AndCalldataNotEmpty();\n\n    // LibDiamondCut: _calldata is empty but _init is not address(0)\n    error CalldataIsEmpty();\n\n    // LibDiamondCut: _init function reverted\n    error InitFunctionReverted();\n\n    // either \"LibDiamondCut: Add facet has no code\" or \"LibDiamondCut: Replace facet has no code\" or \"LibDiamondCut: _init address has no code\"\n    error ContractHasNoCode(string checkCase);\n\n    error LibDiamond__InitIsNotFacet();\n}\n\ninterface ITeleportFacetErrors {\n    /**\n     * @dev Used to make sure the function is only called by the teleport contract.\n     */\n    error OnlyValidProviderCalls();\n\n    /**\n     * @dev Used when there's not provider that supports the specified transmission.\n     */\n    error TransmissionNotSupportedByAnyProvider();\n\n    /**\n     * @dev Used when the provided provider address is the zero address.\n     */\n    error ProviderCannotBeZeroAddress();\n\n    /**\n     * @dev Used when the provided provider address is not supported by the provider selector.\n     */\n    error InvalidProvider();\n\n    /**\n     * @dev Thrown when a message is received from an unknown source chain.\n     */\n    error SourceChainNotSupported();\n\n    /**\n     * @dev Thrown when a message is received from an invalid teleport sender.\n     */\n    error InvalidTeleportSender();\n\n    /**\n     * @dev Thrown when a message is being send to an unknown target chain.\n     */\n    error TargetChainNotSupported();\n\n    // LibTeleport: INVALID_CHAIN_ID\n    error InvalidChainId();\n\n    // LibTeleport: INVALID_SENDER_ADDRESS\n    error InvalidSenderAddress();\n\n    // LibTeleport: DUPLICATE_CHAIN_ID\n    error DuplicateChainId();\n}\n\ninterface IFeeCalculatorFacetErrors {\n    // FeeCalculator: nothing to claim\n    error NothingToClaim();\n\n    // FeeCalculator: insufficient fee amount\n    error InsufficientFeeAmount();\n}\n\ninterface IGovernanceFacetErrors {\n    // Governance: msg.sender is not a member\n    error NotAValidMember();\n\n    // Governance: member list empty\n    error MemberListEmpty();\n\n    // Governance: Account already added\n    error AccountAlreadyAdded();\n\n    // Governance: Would become memberless\n    error WouldBecomeMemberless();\n\n    // Governance: Invalid number of signatures\n    error InvalidNumberOfSignatures();\n\n    // Governance: invalid signer\n    error InvalidSigner();\n\n    // Governance: signers must be in ascending order and uniques\n    error WrongSignersOrder();\n\n    // Governance: message hash already used\n    error HashAlreadyUsed();\n}\n\n// solhint-disable no-empty-blocks\ninterface IDiamondErrors is\n    ICommonErrors,\n    IDiamondLoupeFacetErrors,\n    ILibDiamondErrors,\n    ITeleportFacetErrors,\n    IFeeCalculatorFacetErrors,\n    IGovernanceFacetErrors\n{\n    // We just combine all the interfaces into one to simplify the import from the ITeleportDiamond and generate the ABI\n}\n"
      },
      "contracts/interfaces/IProvider.sol": {
        "content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\ninterface IProvider {\n    /**\n     * @dev Used to make sure the function is only called by the teleport contract.\n     */\n    error OnlyTeleportCalls();\n\n    /// @notice emitted when transmitting a payload\n    event Transmission(\n        bytes transmissionSender,\n        uint8 targetChainId,\n        bytes transmissionReceiver,\n        bytes32 dAppId,\n        bytes payload\n    );\n    /// @notice emitted when delivering a payload\n    event Delivery(bytes32 transmissionId);\n\n    struct DappTransmissionInfo {\n        bytes dappTransmissionSender;\n        bytes dappTransmissionReceiver;\n        bytes32 dAppId;\n        bytes dappPayload;\n    }\n\n    function supportedChains(uint256 index) external view returns (uint8);\n\n    function supportedChainsCount() external view returns (uint256);\n\n    /// @return The currently set service fee\n    function fee(\n        uint8 targetChainId,\n        bytes calldata transmissionTeleportReceiver,\n        DappTransmissionInfo calldata dappTranmissionInfo,\n        bytes calldata extraOptionalArgs\n    ) external view returns (uint256);\n\n    function sendMsg(\n        uint8 targetChainId,\n        bytes calldata transmissionTeleportReceiver,\n        DappTransmissionInfo calldata dappTranmissionInfo,\n        bytes calldata extraOptionalArgs\n    ) external payable;\n\n    function manualClaim(bytes calldata args) external;\n\n    function config(bytes calldata configData) external;\n}\n"
      },
      "contracts/interfaces/IProviderSelector.sol": {
        "content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\ninterface IProviderSelector {\n    /**\n     * @dev Used to make sure the function is only called by the teleport contract.\n     */\n    error OnlyTeleportCalls();\n\n    function isValidProvider(address provider) external returns (bool);\n\n    function getProvider(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_\n    ) external view returns (address);\n\n    function config(bytes calldata configData) external;\n}\n"
      },
      "contracts/interfaces/ITeleport.sol": {
        "content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\n/**\n * @title ITeleport\n * @dev Interface for the Teleport contract, which allows for cross-chain communication and messages transfer using different providers.\n */\ninterface ITeleport {\n    /**\n     * @notice Emitted when collecting fees\n     * @param serviceFee The amount of service fee collected\n     */\n    event TransmissionFees(uint256 serviceFee);\n\n    /**\n     * @dev Transmits a message to the specified target chain ID. The message will be delivered using the most suitable provider.\n     * @param targetChainId The ID of the target chain\n     * @param transmissionReceiver The address of the receiver on the target chain\n     * @param dAppId The ID of the dApp on the target chain\n     * @param payload The message payload\n     */\n    function transmit(\n        uint8 targetChainId,\n        bytes calldata transmissionReceiver,\n        bytes32 dAppId,\n        bytes calldata payload\n    ) external payable;\n\n    /**\n     * @notice Selects a provider to bridge the message to the target chain\n     * @param targetChainId_ The chainID where the message should be delivered to\n     * @param transmissionReceiver_ The address of the contract in the target chain to receive the transmission\n     * @param dAppId_ ID for the dApp that the message belongs to\n     * @param payload_ The dApp-specific message data\n     * @param extraOptionalArgs_ Extra optional arguments to be passed to the provider. This allow for specific provider configurations. Send bytes('') if not needed\n     */\n    function transmitWithArgs(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external payable;\n\n    /**\n     * @dev Transmits a message to the specified target chain ID. The message will be delivered using the specified provider.\n     * @param targetChainId The ID of the target chain\n     * @param transmissionReceiver The address of the receiver on the target chain\n     * @param dAppId The ID of the dApp on the target chain\n     * @param payload The message payload\n     * @param providerAddress The address of the provider to use\n     */\n    function transmitWithProvider(\n        uint8 targetChainId,\n        bytes calldata transmissionReceiver,\n        bytes32 dAppId,\n        bytes calldata payload,\n        address providerAddress,\n        bytes memory extraOptionalArgs_\n    ) external payable;\n\n    /**\n     * @dev Delivers a message to this chain.\n     * @param args The message arguments, which depend on the provider. See the provider's documentation for more information.\n     */\n    function deliver(address providerAddress, bytes calldata args) external;\n\n    /**\n     * @dev Returns the currently set teleport fee.\n     * @return The teleport fee amount\n     */\n    function teleportFee() external view returns (uint256);\n\n    /**\n     * @dev Returns the fee for the automatic selected provider.\n     * @return The provider fee amount\n     */\n    function providerFee(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external view returns (uint256);\n\n    /**\n     * @dev Returns the fee for the stated provider.\n     * @return The provider fee amount\n     */\n    function providerFee(\n        address providerAddress_,\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external view returns (uint256);\n\n    /**\n     * @dev Returns the currently set service fee.\n     * @return The service fee amount\n     */\n    function serviceFee(\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external view returns (uint256);\n\n    /**\n     * @dev Returns the currently set service fee.\n     * @return The service fee amount\n     */\n    function serviceFee(\n        address providerAddress_,\n        uint8 targetChainId_,\n        bytes calldata transmissionReceiver_,\n        bytes32 dAppId_,\n        bytes calldata payload_,\n        bytes calldata extraOptionalArgs_\n    ) external view returns (uint256);\n\n    struct DappTransmissionReceive {\n        bytes teleportSender;\n        uint8 sourceChainId;\n        bytes dappTransmissionSender;\n        address dappTransmissionReceiver;\n        bytes32 dAppId;\n        bytes payload;\n    }\n\n    /**\n     * @dev Notifies the teleport that the provider has received a new message. Teleport should invoke the related dapps.\n     * @param args The arguments of the message.\n     */\n    function onProviderReceive(DappTransmissionReceive calldata args) external;\n\n    function configProviderSelector(bytes calldata configData, bytes[] calldata signatures_) external;\n\n    function configProvider(bytes calldata configData, address providerAddress, bytes[] calldata signatures_) external;\n}\n"
      },
      "contracts/interfaces/ITeleportDApp.sol": {
        "content": "//SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\ninterface ITeleportDApp {\n    /**\n     * @notice Called by a Teleport contract to deliver a verified payload to a dApp\n     * @param _sourceChainId The chainID where the transmission originated\n     * @param _transmissionSender The address that invoked `transmit()` on the source chain\n     * @param _dAppId an identifier for the dApp\n     * @param _payload a dApp-specific byte array with the message data\n     */\n    function onTeleportMessage(\n        uint8 _sourceChainId,\n        bytes calldata _transmissionSender,\n        bytes32 _dAppId,\n        bytes calldata _payload\n    ) external;\n}\n"
      },
      "contracts/interfaces/IUtility.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\ninterface IUtility {\n    event TeleportSenderSet(TeleportSender[] senders_);\n    event ProviderSelectorSet(address providerSelector_);\n\n    struct Subroutine {\n        address contractAddress;\n        bytes callParams;\n    }\n\n    /**\n     * @dev Struct with the information of the teleport sender of a specific chain with the defined MPCId chainId.\n     */\n    struct TeleportSender {\n        // The MPCId of the sender teleport\n        uint8 chainId;\n        // The actual teleport sender address\n        bytes senderAddress;\n    }\n\n    /// @return The internal Teleport chain Id\n    function chainId() external view returns (uint8);\n\n    /**\n     * @dev Returns the address of the provider selector.\n     */\n    function providerSelector() external view returns (address);\n\n    /**\n     * @dev Returns the teleport sender address for a given chainId.\n     * @param _chainId The chainId of the teleport sender.\n     * @return The teleport sender address.\n     */\n    function getTeleportSender(uint8 _chainId) external view returns (bytes memory);\n\n    /**\n     * @dev Sets the teleport senders that are allowed to send messaged from another chains.\n     * @param senders_ An array of `TeleportSender` structs representing the teleport senders.\n     * @param signatures_ An array of bytes representing the governance signatures that allow this change.\n     */\n    function setTeleportSenders(TeleportSender[] calldata senders_, bytes[] calldata signatures_) external;\n\n    /**\n     * @dev Sets the provider selector.\n     * @param providerSelector_ The address of the provider selector contract.\n     * @param signatures_ The array of governance members signatures that allow the change.\n     */\n    function setProviderSelector(address providerSelector_, bytes[] calldata signatures_) external;\n}\n"
      },
      "contracts/libraries/LibFeeCalculator.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\nimport {LibGovernance} from \"./LibGovernance.sol\";\nimport {IFeeCalculatorFacetErrors} from \"../interfaces/IDiamondErrors.sol\";\n\nlibrary LibFeeCalculator {\n    bytes32 private constant STORAGE_POSITION = keccak256(\"fee.calculator.storage\");\n    using LibGovernance for LibGovernance.Storage;\n\n    struct Storage {\n        // The current service fee\n        uint256 serviceFee;\n        // Total fees accrued since contract deployment\n        uint256 feesAccrued;\n        // Total fees accrued up to the last point a member claimed rewards\n        uint256 previousAccrued;\n        // Accumulates rewards on a per-member basis\n        uint256 accumulator;\n        // Total rewards claimed per member\n        mapping(address => uint256) claimedRewardsPerAccount;\n    }\n\n    function feeCalculatorStorage() internal pure returns (Storage storage ds) {\n        bytes32 position = STORAGE_POSITION;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            ds.slot := position\n        }\n    }\n\n    /**\n     * @notice addNewMember Sets the initial claimed rewards for new members\n     * @param account_ The address of the new member\n     */\n    function addNewMember(address account_) internal {\n        LibFeeCalculator.Storage storage fcs = feeCalculatorStorage();\n\n        uint256 diff = fcs.feesAccrued - fcs.previousAccrued;\n        if (diff > 0) {\n            fcs.accumulator += diff / LibGovernance.governanceStorage().membersCount();\n            fcs.previousAccrued = fcs.feesAccrued;\n        }\n\n        fcs.claimedRewardsPerAccount[account_] = fcs.accumulator;\n    }\n\n    /**\n     * @notice claimReward Make calculations based on fee distribution and returns the claimable amount\n     * @param claimer_ The address of the claimer\n     */\n    function claimReward(address claimer_) internal returns (uint256) {\n        LibFeeCalculator.Storage storage fcs = feeCalculatorStorage();\n\n        uint256 diff = fcs.feesAccrued - fcs.previousAccrued;\n        if (diff > 0) {\n            uint256 gain = diff / LibGovernance.governanceStorage().membersCount();\n            fcs.previousAccrued = fcs.feesAccrued;\n            fcs.accumulator += gain;\n        }\n\n        uint256 claimableAmount = fcs.accumulator - fcs.claimedRewardsPerAccount[claimer_];\n\n        fcs.claimedRewardsPerAccount[claimer_] = fcs.accumulator;\n\n        return claimableAmount;\n    }\n\n    /**\n     * @notice Accrue reward to be later distributed to members\n     */\n    function accrueReward(uint256 amount_) internal returns (uint256) {\n        LibFeeCalculator.Storage storage fcs = feeCalculatorStorage();\n\n        if (amount_ < fcs.serviceFee) {\n            revert IFeeCalculatorFacetErrors.InsufficientFeeAmount();\n        }\n        fcs.feesAccrued += fcs.serviceFee;\n\n        return amount_ - fcs.serviceFee;\n    }\n}\n"
      },
      "contracts/libraries/LibGovernance.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\nimport {EnumerableSet} from \"@openzeppelin/contracts/utils/structs/EnumerableSet.sol\";\nimport {Counters} from \"@openzeppelin/contracts/utils/Counters.sol\";\n// solhint-disable-next-line no-unused-import\nimport {ECDSA} from \"@openzeppelin/contracts/utils/cryptography/ECDSA.sol\"; // We will use this from consumers of this library\nimport {IGovernanceFacetErrors} from \"../interfaces/IDiamondErrors.sol\";\n\nlibrary LibGovernance {\n    using EnumerableSet for EnumerableSet.AddressSet;\n    bytes32 private constant STORAGE_POSITION = keccak256(\"diamond.standard.governance.storage\");\n\n    struct Storage {\n        // nonce used for making administrative changes\n        Counters.Counter administrativeNonce;\n        // the set of active validators\n        EnumerableSet.AddressSet membersSet;\n        // governance message hashes we've executed\n        mapping(bytes32 => bool) hashesUsed;\n    }\n\n    function governanceStorage() internal pure returns (Storage storage gs) {\n        bytes32 position = STORAGE_POSITION;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            gs.slot := position\n        }\n    }\n\n    /// @notice Adds/removes a validator from the member set\n    function updateMember(Storage storage gs, address account_, bool status_) internal {\n        if (status_) {\n            if (!gs.membersSet.add(account_)) {\n                revert IGovernanceFacetErrors.AccountAlreadyAdded();\n            }\n        } else if (!status_) {\n            if (gs.membersSet.length() <= 1) {\n                revert IGovernanceFacetErrors.WouldBecomeMemberless();\n            }\n            if (!gs.membersSet.remove(account_)) {\n                revert IGovernanceFacetErrors.NotAValidMember();\n            }\n        }\n    }\n\n    /// @notice Returns true/false depending on whether a given address is member or not\n    function isMember(Storage storage gs, address member_) internal view returns (bool) {\n        return gs.membersSet.contains(member_);\n    }\n\n    /// @notice Returns the count of the members\n    function membersCount(Storage storage gs) internal view returns (uint256) {\n        return gs.membersSet.length();\n    }\n\n    /// @notice Returns the address of a member at a given index\n    function memberAt(Storage storage gs, uint256 index_) internal view returns (address) {\n        return gs.membersSet.at(index_);\n    }\n}\n"
      },
      "contracts/libraries/LibTeleport.sol": {
        "content": "// SPDX-License-Identifier: Unlicense\npragma solidity 0.8.9;\n\nimport {IUtility} from \"../interfaces/IUtility.sol\";\nimport {ICommonErrors, ITeleportFacetErrors} from \"../interfaces/IDiamondErrors.sol\";\n\nlibrary LibTeleport {\n    bytes32 private constant STORAGE_POSITION = keccak256(\"message.teleport.storage\");\n\n    struct Storage {\n        /// The Id of the current chain\n        uint8 chainId;\n        address providerSelector;\n        // Who is allowed to send us teleport messages by MPCId\n        mapping(uint8 => bytes) teleportAddressByChainId;\n        uint8[] supportedChainIds;\n    }\n\n    /// @notice Returns the Teleport Storage object at the correct slot\n    function teleportStorage() internal pure returns (Storage storage mts) {\n        bytes32 position = STORAGE_POSITION;\n        // solhint-disable-next-line no-inline-assembly\n        assembly {\n            mts.slot := position\n        }\n    }\n\n    /// @notice Sets the teleports' addresses on all supported chains\n    function updateTeleportSenders(IUtility.TeleportSender[] calldata senders_) internal {\n        LibTeleport.Storage storage ts = teleportStorage();\n        // reset teleportAddressByChainId\n        for (uint256 i = 0; i < ts.supportedChainIds.length; ) {\n            delete ts.teleportAddressByChainId[ts.supportedChainIds[i]];\n            unchecked {\n                ++i;\n            }\n        }\n        // reset supportedChainIds\n        delete ts.supportedChainIds;\n        for (uint256 i = 0; i < senders_.length; ) {\n            if (senders_[i].chainId == 0) {\n                revert ITeleportFacetErrors.InvalidChainId();\n            }\n            if (senders_[i].senderAddress.length != 20) {\n                revert ITeleportFacetErrors.InvalidSenderAddress();\n            }\n            if (keccak256(abi.encodePacked(senders_[i].senderAddress)) == keccak256(abi.encodePacked(address(0)))) {\n                revert ICommonErrors.AccountIsAddressZero();\n            }\n            if (keccak256(ts.teleportAddressByChainId[senders_[i].chainId]) != keccak256(bytes(\"\"))) {\n                revert ITeleportFacetErrors.DuplicateChainId();\n            }\n            ts.teleportAddressByChainId[senders_[i].chainId] = senders_[i].senderAddress;\n            ts.supportedChainIds.push(senders_[i].chainId);\n            unchecked {\n                ++i;\n            }\n        }\n    }\n}\n"
      }
    },
    "settings": {
      "optimizer": {
        "enabled": true,
        "runs": 200
      },
      "outputSelection": {
        "*": {
          "*": [
            "evm.bytecode",
            "evm.deployedBytecode",
            "devdoc",
            "userdoc",
            "metadata",
            "abi"
          ]
        }
      },
      "libraries": {}
    }
  }}