- Contract name:
- FuturesAdapter
- Optimization enabled
- true
- Compiler version
- v0.8.9+commit.e5eed63a
- Optimization runs
- 200
- Verified at
- 2022-09-22T17:05:59.232265Z
contracts/protocol/FuturesAdapter.sol
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.8; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "../interfaces/CrosschainFunctionCallInterface.sol"; import "./common/CbcDecVer.sol"; import "../interfaces/NonAtomicHiddenAuthParameters.sol"; import "./common/ResponseProcessUtil.sol"; import "../interfaces/IFuturesGateway.sol"; contract FuturesAdapter is CrosschainFunctionCallInterface, CbcDecVer, NonAtomicHiddenAuthParameters, ResponseProcessUtil, ReentrancyGuardUpgradeable, PausableUpgradeable { // 0x77dab611 bytes32 internal constant CROSS_CALL_EVENT_SIGNATURE = keccak256("CrossCall(bytes32,uint256,address,uint256,address,bytes)"); IFuturesGateway public futuresGateway; // How old events can be before they are not accepted. // Also used as a time after which crosschain transaction ids can be purged from the // replayProvention map, thus reducing the cost of the crosschain transaction. // Measured in seconds. uint256 public timeHorizon; // Used to prevent replay attacks in transaction. // Mapping of txId to transaction expiry time. mapping(bytes32 => uint256) public replayPrevention; uint256 public myBlockchainId; // Use to determine different transactions but have same calldata, block timestamp uint256 txIndex; /** * Crosschain Transaction event. * * @param _txId Crosschain Transaction id. * @param _timestamp The time when the event was generated. * @param _caller Contract or EOA that submitted the crosschain call on the source blockchain. * @param _destBcId Destination blockchain Id. * @param _destContract Contract to be called on the destination blockchain. * @param _destFunctionCall The function selector and parameters in ABI packed format. */ event CrossCall( bytes32 _txId, uint256 _timestamp, address _caller, uint256 _destBcId, address _destContract, uint8 _destMethodID, bytes _destFunctionCall ); event CallFailure(string _revertReason); /** * @param _myBlockchainId Blockchain identifier of this blockchain. * @param _timeHorizon How old crosschain events can be before they are * deemed to be invalid. Measured in seconds. */ function initialize( uint256 _myBlockchainId, uint256 _timeHorizon ) public initializer { __ReentrancyGuard_init(); __Ownable_init(); __Pausable_init(); myBlockchainId = _myBlockchainId; timeHorizon = _timeHorizon; } function crossBlockchainCall( // NOTE: can keep using _destBcId and _destContract to determine which blockchain is calling uint256 _destBcId, address _destContract, uint8 _destMethodID, bytes calldata _destData ) external override { txIndex++; bytes32 txId = keccak256( abi.encodePacked( block.timestamp, myBlockchainId, _destBcId, _destContract, _destData, txIndex ) ); emit CrossCall( txId, block.timestamp, msg.sender, _destBcId, _destContract, _destMethodID, _destData ); } // For server function crossCallHandler( uint256 _sourceBcId, address _cbcAddress, bytes calldata _eventData, bytes calldata _signature ) public { address relayer = msg.sender; // decodeAndVerifyEvent( // _sourceBcId, // _cbcAddress, // CROSS_CALL_EVENT_SIGNATURE, // _eventData, // _signature, // relayer // ); // Decode _eventData // Recall that the cross call event is: // CrossCall(bytes32 _txId, uint256 _timestamp, address _caller, // uint256 _destBcId, address _destContract, bytes _destFunctionCall) bytes32 txId; uint256 timestamp; address caller; uint256 destBcId; address destContract; bytes memory functionCall; (txId, timestamp, caller, destBcId, destContract, functionCall) = abi .decode( _eventData, (bytes32, uint256, address, uint256, address, bytes) ); require(replayPrevention[txId] == 0, "Transaction already exists"); require( timestamp < block.timestamp, "Event timestamp is in the future" ); require(timestamp + timeHorizon > block.timestamp, "Event is too old"); replayPrevention[txId] = timestamp; require( destBcId == myBlockchainId, "Incorrect destination blockchain id" ); // Add authentication information to the function call. bytes memory functionCallWithAuth = encodeNonAtomicAuthParams( functionCall, _sourceBcId, caller ); bool isSuccess; bytes memory returnValueEncoded; (isSuccess, returnValueEncoded) = destContract.call( functionCallWithAuth ); require(isSuccess, getRevertMsg(returnValueEncoded)); } function updateFuturesGateway(address _address) external onlyOwner { futuresGateway = IFuturesGateway(_address); } function setMyChainID(uint256 _chainID) external onlyOwner { myBlockchainId = _chainID; } }
@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { _checkOwner(); _; } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if the sender is not the owner. */ function _checkOwner() internal view virtual { require(owner() == _msgSender(), "Ownable: caller is not the owner"); } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * The initialization functions use a version number. Once a version number is used, it is consumed and cannot be * reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in * case an upgrade adds a module that needs to be initialized. * * For example: * * [.hljs-theme-light.nopadding] * ``` * contract MyToken is ERC20Upgradeable { * function initialize() initializer public { * __ERC20_init("MyToken", "MTK"); * } * } * contract MyTokenV2 is MyToken, ERC20PermitUpgradeable { * function initializeV2() reinitializer(2) public { * __ERC20Permit_init("MyToken"); * } * } * ``` * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke * the {_disableInitializers} function in the constructor to automatically lock it when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() { * _disableInitializers(); * } * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. * @custom:oz-retyped-from bool */ uint8 private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Triggered when the contract has been initialized or reinitialized. */ event Initialized(uint8 version); /** * @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope, * `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!AddressUpgradeable.isContract(address(this)) && _initialized == 1), "Initializable: contract is already initialized" ); _initialized = 1; if (isTopLevelCall) { _initializing = true; } _; if (isTopLevelCall) { _initializing = false; emit Initialized(1); } } /** * @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the * contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be * used to initialize parent contracts. * * `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original * initialization step. This is essential to configure modules that are added through upgrades and that require * initialization. * * Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in * a contract, executing them in the right order is up to the developer or operator. */ modifier reinitializer(uint8 version) { require(!_initializing && _initialized < version, "Initializable: contract is already initialized"); _initialized = version; _initializing = true; _; _initializing = false; emit Initialized(version); } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} and {reinitializer} modifiers, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } /** * @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call. * Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized * to any version. It is recommended to use this to lock implementation contracts that are designed to be called * through proxies. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized < type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } }
@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { _requireNotPaused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { _requirePaused(); _; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Throws if the contract is paused. */ function _requireNotPaused() internal view virtual { require(!paused(), "Pausable: paused"); } /** * @dev Throws if the contract is not paused. */ function _requirePaused() internal view virtual { require(paused(), "Pausable: not paused"); } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; }
@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.7.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly /// @solidity memory-safe-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; }
@openzeppelin/contracts/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); } }
contracts/interfaces/CrosschainFunctionCallInterface.sol
/* * Copyright 2021 ConsenSys Software Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.8; /** * Crosschain Function Call Interface allows applications to call functions on other blockchains * and to get information about the currently executing function call. * */ interface CrosschainFunctionCallInterface { /** * Call a function on another blockchain. All function call implementations must implement * this function. * * @param _bcId Blockchain identifier of blockchain to be called. * @param _contract The address of the contract to be called. * @param _functionCallData The function selector and parameter data encoded using ABI encoding rules. */ function crossBlockchainCall( uint256 _bcId, address _contract, uint8 _destMethodID, bytes calldata _functionCallData ) external; }
contracts/interfaces/IFuturesGateway.sol
pragma solidity ^0.8.0; interface IFuturesGateway { function withdraw(address manager, address trader, uint256 amount) external; }
contracts/interfaces/ILightClient.sol
// SPDX-License-Identifier: BUSL-1.1 pragma solidity ^0.8.0; interface ILightClient { /** * Decode and verify event information. Use require to fail the transaction * if any of the information is invalid. * * @param _blockchainId The blockchain that emitted the event. This could be * used to determine which sets of signing keys are valid. * @param _eventSig The event function selector. This will be for a Start event, * a Segment event, or a Root event. Not all implementations will need to * use this value. Others may need this to allow then to find the event in a * transaction receipt. * @param _payload The abi.encodePacked of the blockchain id, the Crosschain * Control contract's address, the event function selector, and the event data. * @param _signature Signatures or proof information that an implementation can * use to check that _signedEventInfo is valid. */ function decodeAndVerifyEvent( uint256 _blockchainId, bytes32 _eventSig, bytes calldata _payload, bytes calldata _signature, address _relayer ) external view; }
contracts/interfaces/NonAtomicHiddenAuthParameters.sol
/* * Copyright 2021 ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.8; abstract contract NonAtomicHiddenAuthParameters { /** * Add authentication parameters to the end of an existing function call. * * @param _functionCall Function selector and an arbitrary list of parameters. * @param _sourceBlockchainId Blockchain identifier of the blockchain that is calling the function. * @param _sourceContract The address of the contract that is calling the function. */ function encodeNonAtomicAuthParams( bytes memory _functionCall, uint256 _sourceBlockchainId, address _sourceContract ) internal pure returns (bytes memory) { return bytes.concat( _functionCall, abi.encodePacked(_sourceBlockchainId, _sourceContract) ); } /** * Extract authentication values from the end of the call data. The parameters are expected to have been * added to the end of the function call using encodeNonAtomicAuthParams. * * @return _sourceBlockchainId Blockchain identifier of the blockchain that is calling the function. * @return _sourceContract The address of the contract that is calling the function. */ function decodeNonAtomicAuthParams() internal pure returns (uint256 _sourceBlockchainId, address _sourceContract) { bytes calldata allParams = msg.data; uint256 len = allParams.length; assembly { calldatacopy(0x0, sub(len, 52), 32) _sourceBlockchainId := mload(0) calldatacopy(12, sub(len, 20), 20) _sourceContract := mload(0) } } }
contracts/protocol/common/CbcDecVer.sol
/* * Copyright 2021 ConsenSys Software Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.8; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "../../interfaces/ILightClient.sol"; abstract contract CbcDecVer is OwnableUpgradeable{ // Address of verifier contract to be used for a certain blockchain id. mapping(uint256 => ILightClient) private verifiers; // Address of Crosschain Control Contract on another blockchain. mapping(uint256 => address) internal remoteFuturesAdapterContracts; function addVerifier(uint256 _blockchainId, address _verifier) external onlyOwner { require(_blockchainId != 0, "Invalid blockchain id"); require(_verifier != address(0), "Invalid verifier address"); verifiers[_blockchainId] = ILightClient(_verifier); } function addRemoteFuturesAdapter(uint256 _blockchainId, address _cbc) external onlyOwner { remoteFuturesAdapterContracts[_blockchainId] = _cbc; } /** * Decode signatures or proofs and use them to verify an event. * * @param _blockchainId The blockchain that the event was emitted on. * @param _cbcAddress The Crosschain Control Contract that emitted the event. * @param _eventFunctionSignature The function selector of the event that emitted the event. * @param _eventData The emitted event data. * @param _signature The signature of proof across the ABI encoded combination of: * _blockchainId, _cbcAddress, _eventFunctionSignature, and _signature. */ function decodeAndVerifyEvent( uint256 _blockchainId, address _cbcAddress, bytes32 _eventFunctionSignature, bytes calldata _eventData, bytes calldata _signature, address _relayer ) internal view { // This indirectly checks that _blockchainId is an authorised source blockchain // by checking that there is a verifier for the blockchain. // TODO implment when deploy production ILightClient verifier = verifiers[_blockchainId]; require( address(verifier) != address(0), "No registered verifier for blockchain" ); require( _cbcAddress == remoteFuturesAdapterContracts[_blockchainId], "Data not emitted by approved contract" ); bytes memory encodedEvent = abi.encodePacked( _blockchainId, _cbcAddress, _eventFunctionSignature, _eventData ); verifier.decodeAndVerifyEvent( _blockchainId, _eventFunctionSignature, encodedEvent, _signature, _relayer ); } }
contracts/protocol/common/ResponseProcessUtil.sol
/* * Copyright 2020 ConsenSys Software Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * SPDX-License-Identifier: Apache-2.0 */ pragma solidity >=0.7.1; import "@openzeppelin/contracts/utils/Strings.sol"; abstract contract ResponseProcessUtil { function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // A string will be 4 bytes for the function selector + 32 bytes for string length + // 32 bytes for first part of string. Hence, if the length is less than 68, then // this is a panic. // Another way of doing this would be to look for the function selectors for revert: // "0x08c379a0" = keccak256("Error(string)" // or panic: // "0x4e487b71" = keccak256("Panic(uint256)" if (_returnData.length < 36) { return string( abi.encodePacked( "Revert for unknown error. Error length: ", Strings.toString(_returnData.length) ) ); } bool isPanic = _returnData.length < 68; assembly { // Remove the function selector / sighash. _returnData := add(_returnData, 0x04) } if (isPanic) { uint256 errorCode = abi.decode(_returnData, (uint256)); return string( abi.encodePacked("Panic: ", Strings.toString(errorCode)) ); } return abi.decode(_returnData, (string)); // All that remains is the revert string } }
Contract ABI
[{"type":"event","name":"CallFailure","inputs":[{"type":"string","name":"_revertReason","internalType":"string","indexed":false}],"anonymous":false},{"type":"event","name":"CrossCall","inputs":[{"type":"bytes32","name":"_txId","internalType":"bytes32","indexed":false},{"type":"uint256","name":"_timestamp","internalType":"uint256","indexed":false},{"type":"address","name":"_caller","internalType":"address","indexed":false},{"type":"uint256","name":"_destBcId","internalType":"uint256","indexed":false},{"type":"address","name":"_destContract","internalType":"address","indexed":false},{"type":"uint8","name":"_destMethodID","internalType":"uint8","indexed":false},{"type":"bytes","name":"_destFunctionCall","internalType":"bytes","indexed":false}],"anonymous":false},{"type":"event","name":"Initialized","inputs":[{"type":"uint8","name":"version","internalType":"uint8","indexed":false}],"anonymous":false},{"type":"event","name":"OwnershipTransferred","inputs":[{"type":"address","name":"previousOwner","internalType":"address","indexed":true},{"type":"address","name":"newOwner","internalType":"address","indexed":true}],"anonymous":false},{"type":"event","name":"Paused","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false}],"anonymous":false},{"type":"event","name":"Unpaused","inputs":[{"type":"address","name":"account","internalType":"address","indexed":false}],"anonymous":false},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"addRemoteFuturesAdapter","inputs":[{"type":"uint256","name":"_blockchainId","internalType":"uint256"},{"type":"address","name":"_cbc","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"addVerifier","inputs":[{"type":"uint256","name":"_blockchainId","internalType":"uint256"},{"type":"address","name":"_verifier","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"crossBlockchainCall","inputs":[{"type":"uint256","name":"_destBcId","internalType":"uint256"},{"type":"address","name":"_destContract","internalType":"address"},{"type":"uint8","name":"_destMethodID","internalType":"uint8"},{"type":"bytes","name":"_destData","internalType":"bytes"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"crossCallHandler","inputs":[{"type":"uint256","name":"_sourceBcId","internalType":"uint256"},{"type":"address","name":"_cbcAddress","internalType":"address"},{"type":"bytes","name":"_eventData","internalType":"bytes"},{"type":"bytes","name":"_signature","internalType":"bytes"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"contract IFuturesGateway"}],"name":"futuresGateway","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"initialize","inputs":[{"type":"uint256","name":"_myBlockchainId","internalType":"uint256"},{"type":"uint256","name":"_timeHorizon","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"myBlockchainId","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"address","name":"","internalType":"address"}],"name":"owner","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"bool","name":"","internalType":"bool"}],"name":"paused","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"renounceOwnership","inputs":[]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"replayPrevention","inputs":[{"type":"bytes32","name":"","internalType":"bytes32"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"setMyChainID","inputs":[{"type":"uint256","name":"_chainID","internalType":"uint256"}]},{"type":"function","stateMutability":"view","outputs":[{"type":"uint256","name":"","internalType":"uint256"}],"name":"timeHorizon","inputs":[]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"transferOwnership","inputs":[{"type":"address","name":"newOwner","internalType":"address"}]},{"type":"function","stateMutability":"nonpayable","outputs":[],"name":"updateFuturesGateway","inputs":[{"type":"address","name":"_address","internalType":"address"}]}]
Deployed ByteCode
0x608060405234801561001057600080fd5b50600436106100f55760003560e01c806360bb02ef11610097578063b132353511610066578063b1323535146101e7578063b2832096146101fa578063e4a301161461020d578063f2fde38b1461022057600080fd5b806360bb02ef146101a8578063715018a6146101bb5780638da5cb5b146101c3578063a0cc0ae0146101d457600080fd5b8063196a5bc9116100d3578063196a5bc91461014b5780634088405214610176578063439160df146101895780635c975abb1461019257600080fd5b8063035a13d0146100fa5780630a3ef1f21461010f5780631101b8f014610142575b600080fd5b61010d610108366004610c4c565b610233565b005b61012f61011d366004610cc5565b60cd6020526000908152604090205481565b6040519081526020015b60405180910390f35b61012f60cc5481565b60cb5461015e906001600160a01b031681565b6040516001600160a01b039091168152602001610139565b61010d610184366004610cde565b6102cf565b61012f60ce5481565b60995460ff166040519015158152602001610139565b61010d6101b6366004610d6a565b61050e565b61010d610538565b6033546001600160a01b031661015e565b61010d6101e2366004610cc5565b61054c565b61010d6101f5366004610d87565b610559565b61010d610208366004610d87565b61058f565b61010d61021b366004610db7565b610660565b61010d61022e366004610d6a565b61078d565b60cf805490600061024383610def565b909155505060ce5460cf5460405160009261026a9242928a918a9189918991602001610e0a565b6040516020818303038152906040528051906020012090507f45de525d0b88f423106d8b064f59a759cea8314f4a35533f886aa54650f8831381423389898989896040516102bf989796959493929190610e4c565b60405180910390a1505050505050565b3360008080808060606102e48a8c018c610f28565b600086815260cd6020526040902054959b50939950919750955093509150156103545760405162461bcd60e51b815260206004820152601a60248201527f5472616e73616374696f6e20616c72656164792065786973747300000000000060448201526064015b60405180910390fd5b4285106103a35760405162461bcd60e51b815260206004820181905260248201527f4576656e742074696d657374616d7020697320696e2074686520667574757265604482015260640161034b565b4260cc54866103b29190610fe9565b116103f25760405162461bcd60e51b815260206004820152601060248201526f115d995b9d081a5cc81d1bdbc81bdb1960821b604482015260640161034b565b600086815260cd6020526040902085905560ce5483146104605760405162461bcd60e51b815260206004820152602360248201527f496e636f72726563742064657374696e6174696f6e20626c6f636b636861696e604482015262081a5960ea1b606482015260840161034b565b600061046d828f87610806565b905060006060846001600160a01b03168360405161048b9190611031565b6000604051808303816000865af19150503d80600081146104c8576040519150601f19603f3d011682016040523d82523d6000602084013e6104cd565b606091505b509092509050816104dd8261086d565b906104fb5760405162461bcd60e51b815260040161034b919061104d565b5050505050505050505050505050505050565b61051661091e565b60cb80546001600160a01b0319166001600160a01b0392909216919091179055565b61054061091e565b61054a6000610978565b565b61055461091e565b60ce55565b61056161091e565b60009182526066602052604090912080546001600160a01b0319166001600160a01b03909216919091179055565b61059761091e565b816105dc5760405162461bcd60e51b8152602060048201526015602482015274125b9d985b1a5908189b1bd8dad8da185a5b881a59605a1b604482015260640161034b565b6001600160a01b0381166106325760405162461bcd60e51b815260206004820152601860248201527f496e76616c696420766572696669657220616464726573730000000000000000604482015260640161034b565b60009182526065602052604090912080546001600160a01b0319166001600160a01b03909216919091179055565b600054610100900460ff16158080156106805750600054600160ff909116105b8061069a5750303b15801561069a575060005460ff166001145b6106fd5760405162461bcd60e51b815260206004820152602e60248201527f496e697469616c697a61626c653a20636f6e747261637420697320616c72656160448201526d191e481a5b9a5d1a585b1a5e995960921b606482015260840161034b565b6000805460ff191660011790558015610720576000805461ff0019166101001790555b6107286109ca565b6107306109f9565b610738610a28565b60ce83905560cc8290558015610788576000805461ff0019169055604051600181527f7f26b83ff96e1f2b6a682f133852f6798a09c465da95921460cefb38474024989060200160405180910390a15b505050565b61079561091e565b6001600160a01b0381166107fa5760405162461bcd60e51b815260206004820152602660248201527f4f776e61626c653a206e6577206f776e657220697320746865207a65726f206160448201526564647265737360d01b606482015260840161034b565b61080381610978565b50565b606083838360405160200161083792919091825260601b6bffffffffffffffffffffffff1916602082015260340190565b60408051601f19818403018152908290526108559291602001611080565b60405160208183030381529060405290509392505050565b60606024825110156108a9576108838251610a57565b60405160200161089391906110af565b6040516020818303038152906040529050919050565b81516004909201916044118015610903576000838060200190518101906108d09190611105565b90506108db81610a57565b6040516020016108eb919061111e565b60405160208183030381529060405292505050919050565b82806020019051810190610917919061114d565b9392505050565b6033546001600160a01b0316331461054a5760405162461bcd60e51b815260206004820181905260248201527f4f776e61626c653a2063616c6c6572206973206e6f7420746865206f776e6572604482015260640161034b565b603380546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e090600090a35050565b600054610100900460ff166109f15760405162461bcd60e51b815260040161034b906111c4565b61054a610b5d565b600054610100900460ff16610a205760405162461bcd60e51b815260040161034b906111c4565b61054a610b8b565b600054610100900460ff16610a4f5760405162461bcd60e51b815260040161034b906111c4565b61054a610bbb565b606081610a7b5750506040805180820190915260018152600360fc1b602082015290565b8160005b8115610aa55780610a8f81610def565b9150610a9e9050600a83611225565b9150610a7f565b60008167ffffffffffffffff811115610ac057610ac0610eb9565b6040519080825280601f01601f191660200182016040528015610aea576020820181803683370190505b5090505b8415610b5557610aff600183611239565b9150610b0c600a86611250565b610b17906030610fe9565b60f81b818381518110610b2c57610b2c611264565b60200101906001600160f81b031916908160001a905350610b4e600a86611225565b9450610aee565b949350505050565b600054610100900460ff16610b845760405162461bcd60e51b815260040161034b906111c4565b6001606755565b600054610100900460ff16610bb25760405162461bcd60e51b815260040161034b906111c4565b61054a33610978565b600054610100900460ff16610be25760405162461bcd60e51b815260040161034b906111c4565b6099805460ff19169055565b6001600160a01b038116811461080357600080fd5b60008083601f840112610c1557600080fd5b50813567ffffffffffffffff811115610c2d57600080fd5b602083019150836020828501011115610c4557600080fd5b9250929050565b600080600080600060808688031215610c6457600080fd5b853594506020860135610c7681610bee565b9350604086013560ff81168114610c8c57600080fd5b9250606086013567ffffffffffffffff811115610ca857600080fd5b610cb488828901610c03565b969995985093965092949392505050565b600060208284031215610cd757600080fd5b5035919050565b60008060008060008060808789031215610cf757600080fd5b863595506020870135610d0981610bee565b9450604087013567ffffffffffffffff80821115610d2657600080fd5b610d328a838b01610c03565b90965094506060890135915080821115610d4b57600080fd5b50610d5889828a01610c03565b979a9699509497509295939492505050565b600060208284031215610d7c57600080fd5b813561091781610bee565b60008060408385031215610d9a57600080fd5b823591506020830135610dac81610bee565b809150509250929050565b60008060408385031215610dca57600080fd5b50508035926020909101359150565b634e487b7160e01b600052601160045260246000fd5b6000600019821415610e0357610e03610dd9565b5060010190565b8781528660208201528560408201526bffffffffffffffffffffffff198560601b16606082015282846074830137607492019182015260940195945050505050565b888152602081018890526001600160a01b038781166040830152606082018790528516608082015260ff841660a082015260e060c08201819052810182905260006101008385828501376000838501820152601f909301601f191690910190910198975050505050505050565b634e487b7160e01b600052604160045260246000fd5b604051601f8201601f1916810167ffffffffffffffff81118282101715610ef857610ef8610eb9565b604052919050565b600067ffffffffffffffff821115610f1a57610f1a610eb9565b50601f01601f191660200190565b60008060008060008060c08789031215610f4157600080fd5b86359550602087013594506040870135610f5a81610bee565b9350606087013592506080870135610f7181610bee565b915060a087013567ffffffffffffffff811115610f8d57600080fd5b8701601f81018913610f9e57600080fd5b8035610fb1610fac82610f00565b610ecf565b8181528a6020838501011115610fc657600080fd5b816020840160208301376000602083830101528093505050509295509295509295565b60008219821115610ffc57610ffc610dd9565b500190565b60005b8381101561101c578181015183820152602001611004565b8381111561102b576000848401525b50505050565b60008251611043818460208701611001565b9190910192915050565b602081526000825180602084015261106c816040850160208701611001565b601f01601f19169190910160400192915050565b60008351611092818460208801611001565b8351908301906110a6818360208801611001565b01949350505050565b7f52657665727420666f7220756e6b6e6f776e206572726f722e204572726f722081526703632b733ba341d160c51b6020820152600082516110f8816028850160208701611001565b9190910160280192915050565b60006020828403121561111757600080fd5b5051919050565b6602830b734b19d160cd1b815260008251611140816007850160208701611001565b9190910160070192915050565b60006020828403121561115f57600080fd5b815167ffffffffffffffff81111561117657600080fd5b8201601f8101841361118757600080fd5b8051611195610fac82610f00565b8181528560208385010111156111aa57600080fd5b6111bb826020830160208601611001565b95945050505050565b6020808252602b908201527f496e697469616c697a61626c653a20636f6e7472616374206973206e6f74206960408201526a6e697469616c697a696e6760a81b606082015260800190565b634e487b7160e01b600052601260045260246000fd5b6000826112345761123461120f565b500490565b60008282101561124b5761124b610dd9565b500390565b60008261125f5761125f61120f565b500690565b634e487b7160e01b600052603260045260246000fdfea264697066735822122044be258e606679ef73b05991fd23d17eac6a2a36418bf6ff155403a02e0cd6e764736f6c63430008090033