Skip to content
Verified contractExactUNLICENSED

OLinxMessageVerifier

Address0x55ffafc4671629a6fca88db239d7f7bf654f8385
Balance

0 ETH

 

Transactions

1

 

Compiler

solc 0.8.17

 

Same code

4 more contracts

 

Details

Compiler
solc 0.8.17+commit.8df45f5f
Language
solidity
Optimization
Yes, 200 runs
EVM version
london
Via IR
yes
License
UNLICENSED
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
26,267,849
Creation transaction
0x3e4d4bc7a1…52462c69bb

project/contracts/v9/OLinxMessageVerifier.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.17;
import "@openzeppelin/contracts/utils/cryptography/draft-EIP712.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "./OLinxExchangeTypes.sol";
import "./IOLinxTransport.sol";

// v9 transport (messages v3, with the payee): a numbered set of OLinx validators signing EIP-712 exchange messages. The set has
// its own size (at least four) and quorum (more than two thirds). Only a quorum of the current set
// can replace it; the change is announced, waits `changeDelay`, and can be withdrawn the same way.
// No admin exists here.
contract OLinxMessageVerifier is EIP712, IOLinxTransport {
    struct ValidatorSet {
        bytes32 id;
        uint16 quorum;
        uint16 size;
    }

    uint256 public constant MIN_VALIDATORS = 4;
    uint256 public constant MAX_VALIDATORS = 100;
    uint256 public constant MAX_GRACE = 7 days;
    uint256 public constant MAX_CHANGE_DELAY = 30 days;
    // An announced set that has waited must be activated within this time, or be proposed again.
    uint256 public constant APPLY_WINDOW = 14 days;
    bytes32 public constant TYPEHASH = keccak256(
        "Message(bytes32 protocolVersion,bytes32 environment,bytes32 validatorSetId,uint256 originChain,address originContract,uint256 targetChain,address targetContract,uint8 action,bytes32 takeId,bytes32 offerId,bytes32 transactionHash,uint256 logIndex,uint256 blockNumber,bytes32 blockHash,address token,uint256 fillAmount,uint256 filledAmount,uint256 payAmount,address beneficiary,bool allowPartial,address payee)"
    );
    // An empty `validators` withdraws the change that is waiting.
    bytes32 public constant CHANGE_TYPEHASH = keccak256("ValidatorChange(uint64 setNumber,address[] validators,uint16 quorum,uint64 grace,uint256 nonce)");

    // The fewest blocks an event must be deep before a validator certifies it, once the validators
    // have set one; until then each validator uses its registry's number. Only a quorum changes it.
    bytes32 public constant CONFIRMATIONS_TYPEHASH = keccak256("ConfirmationsChange(uint256 minConfirmations,uint256 nonce)");
    uint256 public constant MAX_CONFIRMATIONS = 1000;

    address public immutable exchange;
    bytes32 public immutable environment;
    uint256 public immutable changeDelay;

    uint64 public setNumber;
    mapping(uint64 => ValidatorSet) public sets;
    mapping(uint64 => address[]) private signersOf;
    mapping(uint64 => mapping(address => bool)) public memberOf;
    mapping(bytes32 => uint64) public setOfId;
    // Certificates of the set before the current one are accepted until this time.
    uint256 public previousValidUntil;
    mapping(bytes32 => bool) public consumed;

    address[] private pendingSigners;
    uint16 public pendingQuorum;
    uint64 public pendingGrace;
    uint256 public pendingAt;
    uint256 public changeNonce;
    uint256 public minConfirmations;
    bool public minConfirmationsSet;

    event ValidatorsProposed(uint64 indexed setNumber, address[] validators, uint16 quorum, uint64 grace, uint256 effectiveAt);
    event ValidatorsWithdrawn(uint64 indexed setNumber);
    event MinConfirmationsChanged(uint256 minConfirmations);
    event ValidatorsChanged(uint64 indexed setNumber, bytes32 validatorSetId, address[] validators, uint16 quorum, uint256 previousValidUntil);

    constructor(address target, bytes32 env, address[] memory validators, uint16 quorum, uint256 delay) EIP712("OLinxMessageVerifier", "3") {
        require(target != address(0) && env != bytes32(0) && delay <= MAX_CHANGE_DELAY, "CONFIG");
        exchange = target;
        environment = env;
        changeDelay = delay;
        _check(validators, quorum);
        _install(validators, quorum);
    }

    // ---------------------------------------------------------------- views

    function validatorSetId() external view returns (bytes32) { return sets[setNumber].id; }
    function threshold() external view returns (uint256) { return sets[setNumber].quorum; }
    function signers() external view returns (address[] memory) { return signersOf[setNumber]; }
    function signersOfSet(uint64 number) external view returns (address[] memory) { return signersOf[number]; }
    function pendingValidators() external view returns (address[] memory) { return pendingSigners; }

    function digest(OLinxExchangeTypes.Message calldata m) public view returns (bytes32) {
        return _hashTypedDataV4(keccak256(abi.encode(TYPEHASH, m)));
    }

    function changeDigest(address[] calldata validators, uint16 quorum, uint64 grace) public view returns (bytes32) {
        return _hashTypedDataV4(keccak256(abi.encode(CHANGE_TYPEHASH, setNumber + 1, keccak256(abi.encodePacked(validators)), quorum, grace, changeNonce)));
    }

    // ---------------------------------------------------------------- messages

    function verifyAndConsume(OLinxExchangeTypes.Message calldata m, bytes calldata proof) external returns (bytes32 id) {
        require(msg.sender == exchange, "ONLY_EXCHANGE");
        uint64 number = setOfId[m.validatorSetId];
        require(m.protocolVersion == OLinxExchangeTypes.VERSION && m.environment == environment && number != 0, "DOMAIN");
        require(number == setNumber || (number + 1 == setNumber && block.timestamp < previousValidUntil), "VALIDATOR_SET");
        require(m.targetChain == block.chainid && m.targetContract == exchange, "TARGET");
        require(m.originContract != address(0) && IOLinxExchangePeers(exchange).peer(m.originChain) == m.originContract, "ORIGIN");
        require(m.action >= OLinxExchangeTypes.FILL_REQUEST && m.action <= OLinxExchangeTypes.FILL_REJECTED, "ACTION");
        require(m.transactionHash != bytes32(0) && m.blockHash != bytes32(0) && m.takeId != bytes32(0), "PAYLOAD");
        id = digest(m);
        require(!consumed[id], "REPLAY");
        _quorum(number, id, abi.decode(proof, (bytes[])));
        consumed[id] = true;
    }

    function checkApproval(bytes32 structHash, bytes calldata proof) external view {
        _quorum(setNumber, _hashTypedDataV4(structHash), abi.decode(proof, (bytes[])));
    }

    // ---------------------------------------------------------------- changing the validators

    // Announces the next set, signed by a quorum of the current one. An empty list withdraws the
    // announced set instead. Anyone may submit the signatures.
    function proposeValidators(address[] calldata validators, uint16 quorum, uint64 grace, bytes calldata proof) external {
        _quorum(setNumber, changeDigest(validators, quorum, grace), abi.decode(proof, (bytes[])));
        ++changeNonce;
        if (validators.length == 0) {
            require(pendingAt != 0, "NO_CHANGE");
            _clearPending();
            emit ValidatorsWithdrawn(setNumber + 1);
            return;
        }
        _check(validators, quorum);
        require(grace <= MAX_GRACE, "GRACE");
        pendingSigners = validators;
        pendingQuorum = quorum;
        pendingGrace = grace;
        pendingAt = block.timestamp + changeDelay;
        emit ValidatorsProposed(setNumber + 1, validators, quorum, grace, pendingAt);
    }

    // The validators are the ones who wait, so their quorum alone says how long, and it holds at
    // once. Anyone may submit the signatures. The number is for the validators and the services to
    // read; no rule of this contract depends on it.
    function setMinConfirmations(uint256 value, bytes calldata proof) external {
        require(value > 0 && value <= MAX_CONFIRMATIONS, "CONFIRMATIONS");
        _quorum(setNumber, _hashTypedDataV4(keccak256(abi.encode(CONFIRMATIONS_TYPEHASH, value, changeNonce))), abi.decode(proof, (bytes[])));
        ++changeNonce;
        minConfirmations = value;
        minConfirmationsSet = true;
        emit MinConfirmationsChanged(value);
    }

    function activateValidators() external {
        require(pendingAt != 0 && block.timestamp >= pendingAt, "CHANGE_WAIT");
        require(block.timestamp <= pendingAt + APPLY_WINDOW, "CHANGE_EXPIRED");
        previousValidUntil = block.timestamp + pendingGrace;
        _install(pendingSigners, pendingQuorum);
        _clearPending();
    }

    // ---------------------------------------------------------------- internals

    function _check(address[] memory validators, uint16 quorum) private pure {
        uint256 size = validators.length;
        require(size >= MIN_VALIDATORS && size <= MAX_VALIDATORS, "SIGNER_COUNT");
        require(quorum <= size && uint256(quorum) * 3 > size * 2, "QUORUM_RULE");
        for (uint256 i; i < size; ++i) require(validators[i] != address(0) && (i == 0 || validators[i] > validators[i - 1]), "SIGNER_SET");
    }

    function _install(address[] memory validators, uint16 quorum) private {
        uint64 number = ++setNumber;
        bytes32 id = keccak256(abi.encode(number, validators, quorum));
        sets[number] = ValidatorSet(id, quorum, uint16(validators.length));
        signersOf[number] = validators;
        setOfId[id] = number;
        for (uint256 i; i < validators.length; ++i) memberOf[number][validators[i]] = true;
        emit ValidatorsChanged(number, id, validators, quorum, previousValidUntil);
    }

    function _clearPending() private {
        delete pendingSigners;
        pendingQuorum = 0;
        pendingGrace = 0;
        pendingAt = 0;
    }

    // Signatures in ascending signer order, each from a different member of set `number`.
    function _quorum(uint64 number, bytes32 hash, bytes[] memory signatures) private view {
        ValidatorSet storage set = sets[number];
        require(signatures.length >= set.quorum && signatures.length <= set.size, "QUORUM");
        address previous;
        for (uint256 i; i < signatures.length; ++i) {
            address signer = ECDSA.recover(hash, signatures[i]);
            require(memberOf[number][signer] && signer > previous, "SIGNER");
            previous = signer;
        }
    }
}

npm/@openzeppelin/[email protected]/utils/Strings.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/Strings.sol)

pragma solidity ^0.8.0;

/**
 * @dev String operations.
 */
library Strings {
    bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
    uint8 private constant _ADDRESS_LENGTH = 20;

    /**
     * @dev Converts a `uint256` to its ASCII `string` decimal representation.
     */
    function toString(uint256 value) internal pure returns (string memory) {
        // Inspired by OraclizeAPI's implementation - MIT licence
        // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol

        if (value == 0) {
            return "0";
        }
        uint256 temp = value;
        uint256 digits;
        while (temp != 0) {
            digits++;
            temp /= 10;
        }
        bytes memory buffer = new bytes(digits);
        while (value != 0) {
            digits -= 1;
            buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
            value /= 10;
        }
        return string(buffer);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
     */
    function toHexString(uint256 value) internal pure returns (string memory) {
        if (value == 0) {
            return "0x00";
        }
        uint256 temp = value;
        uint256 length = 0;
        while (temp != 0) {
            length++;
            temp >>= 8;
        }
        return toHexString(value, length);
    }

    /**
     * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
     */
    function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
        bytes memory buffer = new bytes(2 * length + 2);
        buffer[0] = "0";
        buffer[1] = "x";
        for (uint256 i = 2 * length + 1; i > 1; --i) {
            buffer[i] = _HEX_SYMBOLS[value & 0xf];
            value >>= 4;
        }
        require(value == 0, "Strings: hex length insufficient");
        return string(buffer);
    }

    /**
     * @dev Converts an `address` with fixed length of 20 bytes to its not checksummed ASCII `string` hexadecimal representation.
     */
    function toHexString(address addr) internal pure returns (string memory) {
        return toHexString(uint256(uint160(addr)), _ADDRESS_LENGTH);
    }
}

npm/@openzeppelin/[email protected]/utils/cryptography/ECDSA.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.3) (utils/cryptography/ECDSA.sol)

pragma solidity ^0.8.0;

import "../Strings.sol";

/**
 * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
 *
 * These functions can be used to verify that a message was signed by the holder
 * of the private keys of a given address.
 */
library ECDSA {
    enum RecoverError {
        NoError,
        InvalidSignature,
        InvalidSignatureLength,
        InvalidSignatureS,
        InvalidSignatureV
    }

    function _throwError(RecoverError error) private pure {
        if (error == RecoverError.NoError) {
            return; // no error: do nothing
        } else if (error == RecoverError.InvalidSignature) {
            revert("ECDSA: invalid signature");
        } else if (error == RecoverError.InvalidSignatureLength) {
            revert("ECDSA: invalid signature length");
        } else if (error == RecoverError.InvalidSignatureS) {
            revert("ECDSA: invalid signature 's' value");
        } else if (error == RecoverError.InvalidSignatureV) {
            revert("ECDSA: invalid signature 'v' value");
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature` or error string. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     *
     * Documentation for signature generation:
     * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
     * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
     *
     * _Available since v4.3._
     */
    function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
        if (signature.length == 65) {
            bytes32 r;
            bytes32 s;
            uint8 v;
            // ecrecover takes the signature parameters, and the only way to get them
            // currently is to use assembly.
            /// @solidity memory-safe-assembly
            assembly {
                r := mload(add(signature, 0x20))
                s := mload(add(signature, 0x40))
                v := byte(0, mload(add(signature, 0x60)))
            }
            return tryRecover(hash, v, r, s);
        } else {
            return (address(0), RecoverError.InvalidSignatureLength);
        }
    }

    /**
     * @dev Returns the address that signed a hashed message (`hash`) with
     * `signature`. This address can then be used for verification purposes.
     *
     * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
     * this function rejects them by requiring the `s` value to be in the lower
     * half order, and the `v` value to be either 27 or 28.
     *
     * IMPORTANT: `hash` _must_ be the result of a hash operation for the
     * verification to be secure: it is possible to craft signatures that
     * recover to arbitrary addresses for non-hashed data. A safe way to ensure
     * this is by receiving a hash of the original message (which may otherwise
     * be too long), and then calling {toEthSignedMessageHash} on it.
     */
    function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, signature);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
     *
     * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address, RecoverError) {
        bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
        uint8 v = uint8((uint256(vs) >> 255) + 27);
        return tryRecover(hash, v, r, s);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
     *
     * _Available since v4.2._
     */
    function recover(
        bytes32 hash,
        bytes32 r,
        bytes32 vs
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, r, vs);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Overload of {ECDSA-tryRecover} that receives the `v`,
     * `r` and `s` signature fields separately.
     *
     * _Available since v4.3._
     */
    function tryRecover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address, RecoverError) {
        // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
        // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
        // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
        // signatures from current libraries generate a unique signature with an s-value in the lower half order.
        //
        // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
        // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
        // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
        // these malleable signatures as well.
        if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
            return (address(0), RecoverError.InvalidSignatureS);
        }
        if (v != 27 && v != 28) {
            return (address(0), RecoverError.InvalidSignatureV);
        }

        // If the signature is valid (and not malleable), return the signer address
        address signer = ecrecover(hash, v, r, s);
        if (signer == address(0)) {
            return (address(0), RecoverError.InvalidSignature);
        }

        return (signer, RecoverError.NoError);
    }

    /**
     * @dev Overload of {ECDSA-recover} that receives the `v`,
     * `r` and `s` signature fields separately.
     */
    function recover(
        bytes32 hash,
        uint8 v,
        bytes32 r,
        bytes32 s
    ) internal pure returns (address) {
        (address recovered, RecoverError error) = tryRecover(hash, v, r, s);
        _throwError(error);
        return recovered;
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from a `hash`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
        // 32 is the length in bytes of hash,
        // enforced by the type signature above
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
    }

    /**
     * @dev Returns an Ethereum Signed Message, created from `s`. This
     * produces hash corresponding to the one signed with the
     * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
     * JSON-RPC method as part of EIP-191.
     *
     * See {recover}.
     */
    function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
    }

    /**
     * @dev Returns an Ethereum Signed Typed Data, created from a
     * `domainSeparator` and a `structHash`. This produces hash corresponding
     * to the one signed with the
     * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
     * JSON-RPC method as part of EIP-712.
     *
     * See {recover}.
     */
    function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
        return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
    }
}

npm/@openzeppelin/[email protected]/utils/cryptography/draft-EIP712.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol)

pragma solidity ^0.8.0;

import "./ECDSA.sol";

/**
 * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
 *
 * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
 * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
 * they need in their contracts using a combination of `abi.encode` and `keccak256`.
 *
 * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
 * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
 * ({_hashTypedDataV4}).
 *
 * The implementation of the domain separator was designed to be as efficient as possible while still properly updating
 * the chain id to protect against replay attacks on an eventual fork of the chain.
 *
 * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
 * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
 *
 * _Available since v3.4._
 */
abstract contract EIP712 {
    /* solhint-disable var-name-mixedcase */
    // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
    // invalidate the cached domain separator if the chain id changes.
    bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;
    address private immutable _CACHED_THIS;

    bytes32 private immutable _HASHED_NAME;
    bytes32 private immutable _HASHED_VERSION;
    bytes32 private immutable _TYPE_HASH;

    /* solhint-enable var-name-mixedcase */

    /**
     * @dev Initializes the domain separator and parameter caches.
     *
     * The meaning of `name` and `version` is specified in
     * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
     *
     * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
     * - `version`: the current major version of the signing domain.
     *
     * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
     * contract upgrade].
     */
    constructor(string memory name, string memory version) {
        bytes32 hashedName = keccak256(bytes(name));
        bytes32 hashedVersion = keccak256(bytes(version));
        bytes32 typeHash = keccak256(
            "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
        );
        _HASHED_NAME = hashedName;
        _HASHED_VERSION = hashedVersion;
        _CACHED_CHAIN_ID = block.chainid;
        _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
        _CACHED_THIS = address(this);
        _TYPE_HASH = typeHash;
    }

    /**
     * @dev Returns the domain separator for the current chain.
     */
    function _domainSeparatorV4() internal view returns (bytes32) {
        if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) {
            return _CACHED_DOMAIN_SEPARATOR;
        } else {
            return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
        }
    }

    function _buildDomainSeparator(
        bytes32 typeHash,
        bytes32 nameHash,
        bytes32 versionHash
    ) private view returns (bytes32) {
        return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this)));
    }

    /**
     * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
     * function returns the hash of the fully encoded EIP712 message for this domain.
     *
     * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
     *
     * ```solidity
     * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
     *     keccak256("Mail(address to,string contents)"),
     *     mailTo,
     *     keccak256(bytes(mailContents))
     * )));
     * address signer = ECDSA.recover(digest, signature);
     * ```
     */
    function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
        return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
    }
}

npm/@openzeppelin/[email protected]/utils/math/Math.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.7.0) (utils/math/Math.sol)

pragma solidity ^0.8.0;

/**
 * @dev Standard math utilities missing in the Solidity language.
 */
library Math {
    enum Rounding {
        Down, // Toward negative infinity
        Up, // Toward infinity
        Zero // Toward zero
    }

    /**
     * @dev Returns the largest of two numbers.
     */
    function max(uint256 a, uint256 b) internal pure returns (uint256) {
        return a >= b ? a : b;
    }

    /**
     * @dev Returns the smallest of two numbers.
     */
    function min(uint256 a, uint256 b) internal pure returns (uint256) {
        return a < b ? a : b;
    }

    /**
     * @dev Returns the average of two numbers. The result is rounded towards
     * zero.
     */
    function average(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b) / 2 can overflow.
        return (a & b) + (a ^ b) / 2;
    }

    /**
     * @dev Returns the ceiling of the division of two numbers.
     *
     * This differs from standard division with `/` in that it rounds up instead
     * of rounding down.
     */
    function ceilDiv(uint256 a, uint256 b) internal pure returns (uint256) {
        // (a + b - 1) / b can overflow on addition, so we distribute.
        return a == 0 ? 0 : (a - 1) / b + 1;
    }

    /**
     * @notice Calculates floor(x * y / denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
     * @dev Original credit to Remco Bloemen under MIT license (https://xn--2-umb.com/21/muldiv)
     * with further edits by Uniswap Labs also under MIT license.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator
    ) internal pure returns (uint256 result) {
        unchecked {
            // 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
            // use the Chinese Remainder Theorem to reconstruct the 512 bit result. The result is stored in two 256
            // variables such that product = prod1 * 2^256 + prod0.
            uint256 prod0; // Least significant 256 bits of the product
            uint256 prod1; // Most significant 256 bits of the product
            assembly {
                let mm := mulmod(x, y, not(0))
                prod0 := mul(x, y)
                prod1 := sub(sub(mm, prod0), lt(mm, prod0))
            }

            // Handle non-overflow cases, 256 by 256 division.
            if (prod1 == 0) {
                return prod0 / denominator;
            }

            // Make sure the result is less than 2^256. Also prevents denominator == 0.
            require(denominator > prod1);

            ///////////////////////////////////////////////
            // 512 by 256 division.
            ///////////////////////////////////////////////

            // Make division exact by subtracting the remainder from [prod1 prod0].
            uint256 remainder;
            assembly {
                // Compute remainder using mulmod.
                remainder := mulmod(x, y, denominator)

                // Subtract 256 bit number from 512 bit number.
                prod1 := sub(prod1, gt(remainder, prod0))
                prod0 := sub(prod0, remainder)
            }

            // Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
            // See https://cs.stackexchange.com/q/138556/92363.

            // Does not overflow because the denominator cannot be zero at this stage in the function.
            uint256 twos = denominator & (~denominator + 1);
            assembly {
                // Divide denominator by twos.
                denominator := div(denominator, twos)

                // Divide [prod1 prod0] by twos.
                prod0 := div(prod0, twos)

                // Flip twos such that it is 2^256 / twos. If twos is zero, then it becomes one.
                twos := add(div(sub(0, twos), twos), 1)
            }

            // Shift in bits from prod1 into prod0.
            prod0 |= prod1 * twos;

            // Invert denominator mod 2^256. Now that denominator is an odd number, it has an inverse modulo 2^256 such
            // that denominator * inv = 1 mod 2^256. Compute the inverse by starting with a seed that is correct for
            // four bits. That is, denominator * inv = 1 mod 2^4.
            uint256 inverse = (3 * denominator) ^ 2;

            // Use the Newton-Raphson iteration to improve the precision. Thanks to Hensel's lifting lemma, this also works
            // in modular arithmetic, doubling the correct bits in each step.
            inverse *= 2 - denominator * inverse; // inverse mod 2^8
            inverse *= 2 - denominator * inverse; // inverse mod 2^16
            inverse *= 2 - denominator * inverse; // inverse mod 2^32
            inverse *= 2 - denominator * inverse; // inverse mod 2^64
            inverse *= 2 - denominator * inverse; // inverse mod 2^128
            inverse *= 2 - denominator * inverse; // inverse mod 2^256

            // Because the division is now exact we can divide by multiplying with the modular inverse of denominator.
            // This will give us the correct result modulo 2^256. Since the preconditions guarantee that the outcome is
            // less than 2^256, this is the final result. We don't need to compute the high bits of the result and prod1
            // is no longer required.
            result = prod0 * inverse;
            return result;
        }
    }

    /**
     * @notice Calculates x * y / denominator with full precision, following the selected rounding direction.
     */
    function mulDiv(
        uint256 x,
        uint256 y,
        uint256 denominator,
        Rounding rounding
    ) internal pure returns (uint256) {
        uint256 result = mulDiv(x, y, denominator);
        if (rounding == Rounding.Up && mulmod(x, y, denominator) > 0) {
            result += 1;
        }
        return result;
    }

    /**
     * @dev Returns the square root of a number. It the number is not a perfect square, the value is rounded down.
     *
     * Inspired by Henry S. Warren, Jr.'s "Hacker's Delight" (Chapter 11).
     */
    function sqrt(uint256 a) internal pure returns (uint256) {
        if (a == 0) {
            return 0;
        }

        // For our first guess, we get the biggest power of 2 which is smaller than the square root of the target.
        // We know that the "msb" (most significant bit) of our target number `a` is a power of 2 such that we have
        // `msb(a) <= a < 2*msb(a)`.
        // We also know that `k`, the position of the most significant bit, is such that `msb(a) = 2**k`.
        // This gives `2**k < a <= 2**(k+1)` → `2**(k/2) <= sqrt(a) < 2 ** (k/2+1)`.
        // Using an algorithm similar to the msb conmputation, we are able to compute `result = 2**(k/2)` which is a
        // good first aproximation of `sqrt(a)` with at least 1 correct bit.
        uint256 result = 1;
        uint256 x = a;
        if (x >> 128 > 0) {
            x >>= 128;
            result <<= 64;
        }
        if (x >> 64 > 0) {
            x >>= 64;
            result <<= 32;
        }
        if (x >> 32 > 0) {
            x >>= 32;
            result <<= 16;
        }
        if (x >> 16 > 0) {
            x >>= 16;
            result <<= 8;
        }
        if (x >> 8 > 0) {
            x >>= 8;
            result <<= 4;
        }
        if (x >> 4 > 0) {
            x >>= 4;
            result <<= 2;
        }
        if (x >> 2 > 0) {
            result <<= 1;
        }

        // At this point `result` is an estimation with one bit of precision. We know the true value is a uint128,
        // since it is the square root of a uint256. Newton's method converges quadratically (precision doubles at
        // every iteration). We thus need at most 7 iteration to turn our partial result with one bit of precision
        // into the expected uint128 result.
        unchecked {
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            result = (result + a / result) >> 1;
            return min(result, a / result);
        }
    }

    /**
     * @notice Calculates sqrt(a), following the selected rounding direction.
     */
    function sqrt(uint256 a, Rounding rounding) internal pure returns (uint256) {
        uint256 result = sqrt(a);
        if (rounding == Rounding.Up && result * result < a) {
            result += 1;
        }
        return result;
    }
}

project/contracts/v9/IOLinxTransport.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.17;
import "./OLinxExchangeTypes.sol";

// Authenticates cross-chain facts for one OLinxExchange. The exchange depends only on this.
// v9: OLinxMessageVerifier (a validator set that its own quorum can replace). Later versions may add CCIP adapters.
interface IOLinxTransport {
    // Must revert unless `m` is authentic for the calling exchange; consumes it and returns its id.
    function verifyAndConsume(OLinxExchangeTypes.Message calldata m, bytes calldata proof) external returns (bytes32 messageId);

    // Must revert unless the transport's current authority approved `structHash` (an EIP-712 struct hash
    // in the transport's own domain). Used for the one decision the exchange leaves to the validators:
    // who its admin is.
    function checkApproval(bytes32 structHash, bytes calldata proof) external view;
}

interface IOLinxExchangeDelivery {
    function deliver(OLinxExchangeTypes.Message calldata m, bytes calldata proof) external;
}

// The partner networks are kept in one place, the exchange; the verifier reads them from it.
interface IOLinxExchangePeers {
    function peer(uint256 chain) external view returns (address);
}

// The order NFTs of this network (OLinxOrders): who holds each order and where its payments go.
interface IOLinxOrders {
    function mint(address to, uint256 id, address receiver) external;
    function burn(uint256 id) external;
    function ownerOf(uint256 id) external view returns (address);
    function receiverOf(uint256 id) external view returns (address);
    function isMinter(address account) external view returns (bool);
}

project/contracts/v9/OLinxExchangeTypes.sol

// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.8.17;
import "@openzeppelin/contracts/utils/math/Math.sol";

library OLinxExchangeTypes {
    bytes32 internal constant VERSION = keccak256("OLINX_EXCHANGE_V3");
    uint8 internal constant FILL_REQUEST = 1;
    uint8 internal constant FILL_CONFIRMED = 2;
    uint8 internal constant FILL_REJECTED = 3;
    uint8 internal constant REFUND = 1;
    uint8 internal constant CONVERT_TO_OFFER = 2;

    struct Offer {
        bytes32 version;
        address maker;
        uint256 nonce;
        uint256 offerChain;
        address offerContract;
        address offerToken;
        uint256 offerAmount;
        uint256 wantChain;
        address wantContract;
        address wantToken;
        uint256 wantAmount;
        address makerReceiver;
        uint256 minFill;
        uint16 feeBps;
    }
    struct Take {
        bytes32 version;
        address taker;
        uint256 nonce;
        bytes32 offerId;
        uint256 offerChain;
        address offerContract;
        uint256 paymentChain;
        address paymentContract;
        address payToken;
        uint256 fillAmount;
        uint256 payAmount;
        address recipient;
        bool allowPartial;
        uint8 onUnfilled;
        uint256 unfilledMinFill;
        uint16 feeBps;
    }
    struct Message {
        bytes32 protocolVersion;
        bytes32 environment;
        bytes32 validatorSetId;
        uint256 originChain;
        address originContract;
        uint256 targetChain;
        address targetContract;
        uint8 action;
        bytes32 takeId;
        bytes32 offerId;
        bytes32 transactionHash;
        uint256 logIndex;
        uint256 blockNumber;
        bytes32 blockHash;
        address token;
        uint256 fillAmount;
        uint256 filledAmount;
        uint256 payAmount;
        address beneficiary;
        bool allowPartial;
        // v9: who the payment goes to, recorded on the order's network when the take filled (FILL_CONFIRMED).
        address payee;
    }

    function offerId(Offer memory o) internal pure returns (bytes32) { return keccak256(abi.encode(o)); }
    function takeId(Take memory t) internal pure returns (bytes32) { return keccak256(abi.encode(t)); }

    // Payment for `amount` offered units at the offer's exact rate, rounded up in the maker's favor.
    function price(uint256 amount, uint256 wantAmount, uint256 offerAmount) internal pure returns (uint256) {
        return Math.mulDiv(amount, wantAmount, offerAmount, Math.Rounding.Up);
    }
}
Compiler settingsShow
{
  "viaIR": true,
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "london",
  "remappings": [
    "project/:@openzeppelin/contracts/=npm/@openzeppelin/[email protected]/"
  ]
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.