More Info
Private Name Tags
ContractCreator
TokenTracker
Latest 1 internal transaction
Advanced mode:
Parent Transaction Hash | Block |
From
|
To
|
|||
---|---|---|---|---|---|---|
19519631 | 303 days ago | Contract Creation | 0 ETH |
Loading...
Loading
Minimal Proxy Contract for 0xca310b1b942a30ff4b40a5e1b69ab4607ec79bc1
Contract Name:
HashflowPool
Compiler Version
v0.8.18+commit.87f61d96
Optimization Enabled:
Yes with 200 runs
Other Settings:
default evmVersion
Contract Source Code (Solidity Standard Json-Input format)
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity 0.8.18; import '@openzeppelin/contracts/proxy/utils/Initializable.sol'; import '@openzeppelin/contracts/token/ERC20/IERC20.sol'; import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol'; import '@openzeppelin/contracts/utils/cryptography/ECDSA.sol'; import '@openzeppelin/contracts/utils/Context.sol'; import '../interfaces/external/IWETH.sol'; import '../interfaces/IHashflowPool.sol'; import '../interfaces/IHashflowRouter.sol'; interface IERC20AllowanceExtension { function increaseAllowance(address spender, uint256 addedValue) external returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool); } contract HashflowPool is IHashflowPool, Initializable, Context { using Address for address payable; using SafeERC20 for IERC20; using ECDSA for bytes32; string public name; SignerConfiguration public signerConfiguration; address public operations; address public router; mapping(address => uint256) public nonces; mapping(bytes32 => uint256) public xChainNonces; mapping(address => bool) internal _withrawalAccountAuth; mapping(bytes32 => bool) internal _filledXChainTxids; address public immutable _WETH; constructor(address weth) { require( weth != address(0), 'HashflowPool::constructor WETH cannot be 0 address.' ); _WETH = weth; } /// @dev Fallback function to receive native token. receive() external payable {} /// @inheritdoc IHashflowPool function initialize( string memory _name, address _signer, address _operations, address _router ) public override initializer { require( _signer != address(0), 'HashflowPool::initialize Signer cannot be 0 address.' ); require( _operations != address(0), 'HashflowPool::initialize Operations cannot be 0 address.' ); require( _router != address(0), 'HashflowPool::initialize Router cannot be 0 address.' ); require( bytes(_name).length > 0, 'HashflowPool::initialize Name cannot be empty' ); name = _name; SignerConfiguration memory signerConfig; signerConfig.enabled = true; signerConfig.signer = _signer; emit UpdateSigner(_signer, address(0)); signerConfiguration = signerConfig; operations = _operations; router = _router; } modifier authorizedOperations() { require( _msgSender() == operations, 'HashflowPool:authorizedOperations Sender must be operator.' ); _; } modifier authorizedRouter() { require( _msgSender() == router, 'HashflowPool::authorizedRouter Sender must be Router.' ); _; } /// @inheritdoc IHashflowPool function tradeRFQT(RFQTQuote memory quote) external payable override authorizedRouter { /// Trust assumption: the Router has transferred baseToken. require( quote.baseToken != address(0) || quote.externalAccount != address(0) || msg.value == quote.effectiveBaseTokenAmount, 'HashflowPool::tradeRFQT msg.value must equal effectiveBaseTokenAmount' ); bytes32 quoteHash = _hashQuoteRFQT(quote); SignerConfiguration memory signerConfig = signerConfiguration; require(signerConfig.enabled, 'HashflowPool::tradeRFQT Disabled.'); require( quoteHash.recover(quote.signature) == signerConfig.signer, 'HashflowPool::tradeRFQT Invalid signer.' ); _updateNonce(quote.effectiveTrader, quote.nonce); uint256 quoteTokenAmount = quote.quoteTokenAmount; if (quote.effectiveBaseTokenAmount < quote.baseTokenAmount) { quoteTokenAmount = (quote.effectiveBaseTokenAmount * quote.quoteTokenAmount) / quote.baseTokenAmount; } emit Trade( quote.trader, quote.effectiveTrader, quote.txid, quote.baseToken, quote.quoteToken, quote.effectiveBaseTokenAmount, quoteTokenAmount ); if (quote.externalAccount == address(0)) { _transferFromPool(quote.quoteToken, quote.trader, quoteTokenAmount); } else { _transferFromExternalAccount( quote.externalAccount, quote.quoteToken, quote.trader, quoteTokenAmount ); } } /// @inheritdoc IHashflowPool function tradeRFQM(RFQMQuote memory quote) external override authorizedRouter { SignerConfiguration memory signerConfig = signerConfiguration; require(signerConfig.enabled, 'HashflowPool::tradeRFQM Disabled.'); bytes32 quoteHash = _hashQuoteRFQM(quote); require( quoteHash.recover(quote.makerSignature) == signerConfig.signer, 'HashflowPool::tradeRFQM Invalid signer.' ); emit Trade( quote.trader, quote.trader, quote.txid, quote.baseToken, quote.quoteToken, quote.baseTokenAmount, quote.quoteTokenAmount ); if (quote.externalAccount == address(0)) { _transferFromPool( quote.quoteToken, quote.trader, quote.quoteTokenAmount ); } else { _transferFromExternalAccount( quote.externalAccount, quote.quoteToken, quote.trader, quote.quoteTokenAmount ); } } /// @inheritdoc IHashflowPool function tradeXChainRFQT(XChainRFQTQuote memory quote, address trader) external payable override authorizedRouter { require( quote.srcExternalAccount != address(0) || quote.baseToken != address(0) || msg.value == quote.effectiveBaseTokenAmount, 'HashflowPool::tradeXChainRFQT msg.value must = amount' ); SignerConfiguration memory signerConfig = signerConfiguration; require( signerConfig.enabled, 'HashflowPool::tradeXChainRFQT Disabled.' ); _updateNonceXChain(quote.dstTrader, quote.nonce); bytes32 quoteHash = _hashXChainQuoteRFQT(quote); require( quoteHash.recover(quote.signature) == signerConfig.signer, 'HashflowPool::tradeXChainRFQT Invalid signer' ); uint256 effectiveQuoteTokenAmount = quote.quoteTokenAmount; if (quote.effectiveBaseTokenAmount < quote.baseTokenAmount) { effectiveQuoteTokenAmount = (quote.quoteTokenAmount * quote.effectiveBaseTokenAmount) / quote.baseTokenAmount; } emit XChainTrade( quote.dstChainId, quote.dstPool, trader, quote.dstTrader, quote.txid, quote.baseToken, quote.quoteToken, quote.effectiveBaseTokenAmount, effectiveQuoteTokenAmount ); } /// @inheritdoc IHashflowPool function fillXChain( address externalAccount, bytes32 txid, address trader, address quoteToken, uint256 quoteTokenAmount ) external override authorizedRouter { require( !_filledXChainTxids[txid], 'HashflowPool::fillXChain Quote has been executed previously.' ); _filledXChainTxids[txid] = true; emit XChainTradeFill(txid); if (externalAccount == address(0)) { _transferFromPool(quoteToken, trader, quoteTokenAmount); } else { _transferFromExternalAccount( externalAccount, quoteToken, trader, quoteTokenAmount ); } } /// @inheritdoc IHashflowPool function tradeXChainRFQM(XChainRFQMQuote memory quote) external override authorizedRouter { SignerConfiguration memory signerConfig = signerConfiguration; require( signerConfig.enabled, 'HashflowPool::tradeXChainRFQM Disabled.' ); bytes32 quoteHash = _hashXChainQuoteRFQM(quote); require( quoteHash.recover(quote.makerSignature) == signerConfig.signer, 'HashflowPool::tradeXChainRFQM Invalid signer' ); emit XChainTrade( quote.dstChainId, quote.dstPool, quote.trader, quote.dstTrader, quote.txid, quote.baseToken, quote.quoteToken, quote.baseTokenAmount, quote.quoteTokenAmount ); } /// @inheritdoc IHashflowPool function updateXChainPoolAuthorization( AuthorizedXChainPool[] calldata pools, bool status ) external override authorizedOperations { for (uint256 i = 0; i < pools.length; i++) { require(pools[i].pool != bytes32(0)); IHashflowRouter(router).updateXChainPoolAuthorization( pools[i].chainId, pools[i].pool, status ); } } /// @inheritdoc IHashflowPool function updateXChainMessengerAuthorization( address xChainMessenger, bool authorized ) external override authorizedOperations { require( xChainMessenger != address(0), 'HashflowPool::updateXChainMessengerAuthorization Invalid messenger address.' ); IHashflowRouter(router).updateXChainMessengerAuthorization( xChainMessenger, authorized ); } /// @dev ERC1271 implementation. function isValidSignature(bytes32 hash, bytes memory signature) external view override returns (bytes4 magicValue) { if (hash.recover(signature) == signerConfiguration.signer) { magicValue = 0x1626ba7e; } } /// @inheritdoc IHashflowPool function approveToken( address token, address spender, uint256 amount ) external override authorizedOperations { IERC20(token).forceApprove(spender, amount); } /// @inheritdoc IHashflowPool function increaseTokenAllowance( address token, address spender, uint256 amount ) external override authorizedOperations { IERC20(token).safeIncreaseAllowance(spender, amount); } /// @inheritdoc IHashflowPool function decreaseTokenAllowance( address token, address spender, uint256 amount ) external override authorizedOperations { IERC20(token).safeDecreaseAllowance(spender, amount); } /// @inheritdoc IHashflowPool function removeLiquidity( address token, address recipient, uint256 amount ) external override authorizedOperations { SignerConfiguration memory signerConfig = signerConfiguration; require( signerConfig.enabled, 'HashflowPool::removeLiquidity Disabled.' ); require(amount > 0, 'HashflowPool::removeLiquidity Invalid amount'); address _recipient; if (recipient != address(0)) { require( _withrawalAccountAuth[recipient], 'HashflowPool::removeLiquidity Recipient must be hedging account' ); _recipient = recipient; } else { _recipient = _msgSender(); } emit RemoveLiquidity(token, _recipient, amount); _transferFromPool(token, _recipient, amount); } /// @inheritdoc IHashflowPool function updateWithdrawalAccount( address[] memory withdrawalAccounts, bool authorized ) external override authorizedOperations { for (uint256 i = 0; i < withdrawalAccounts.length; i++) { require(withdrawalAccounts[i] != address(0)); _withrawalAccountAuth[withdrawalAccounts[i]] = authorized; emit UpdateWithdrawalAccount(withdrawalAccounts[i], authorized); } } /// @inheritdoc IHashflowPool function updateSigner(address newSigner) external override authorizedOperations { require(newSigner != address(0)); SignerConfiguration memory signerConfig = signerConfiguration; emit UpdateSigner(newSigner, signerConfig.signer); signerConfig.signer = newSigner; signerConfiguration = signerConfig; } /// @inheritdoc IHashflowPool function killswitchOperations(bool enabled) external override authorizedRouter { SignerConfiguration memory signerConfig = signerConfiguration; signerConfig.enabled = enabled; signerConfiguration = signerConfig; } function getReserves(address token) external view override returns (uint256) { return _getReserves(token); } /** * @dev Prevents against replay for RFQ-T. Checks that nonces are strictly increasing. */ function _updateNonce(address trader, uint256 nonce) internal { require( nonce > nonces[trader], 'HashflowPool::_updateNonce Invalid nonce.' ); nonces[trader] = nonce; } /** * @dev Prevents against replay for X-Chain RFQ-T. Checks that nonces are strictly increasing. */ function _updateNonceXChain(bytes32 trader, uint256 nonce) internal { require( nonce > xChainNonces[trader], 'HashflowPool::_updateNonceXChain Invalid nonce.' ); xChainNonces[trader] = nonce; } function _transferFromPool( address token, address recipient, uint256 value ) internal { if (token == address(0)) { payable(recipient).sendValue(value); } else { IERC20(token).safeTransfer(recipient, value); } } /// @dev Helper function to transfer quoteToken from external account. function _transferFromExternalAccount( address externalAccount, address token, address receiver, uint256 value ) private { if (token == address(0)) { IERC20(_WETH).safeTransferFrom( externalAccount, address(this), value ); IWETH(_WETH).withdraw(value); payable(receiver).sendValue(value); } else { IERC20(token).safeTransferFrom(externalAccount, receiver, value); } } function _getReserves(address token) internal view returns (uint256) { return token == address(0) ? address(this).balance : IERC20(token).balanceOf(address(this)); } /** * @dev Generates a quote hash for RFQ-t. */ function _hashQuoteRFQT(RFQTQuote memory quote) private view returns (bytes32) { return keccak256( abi.encodePacked( '\x19Ethereum Signed Message:\n32', keccak256( abi.encodePacked( address(this), quote.trader, quote.effectiveTrader, quote.externalAccount, quote.baseToken, quote.quoteToken, quote.baseTokenAmount, quote.quoteTokenAmount, quote.nonce, quote.quoteExpiry, quote.txid, block.chainid ) ) ) ); } function _hashQuoteRFQM(RFQMQuote memory quote) private view returns (bytes32) { return keccak256( abi.encodePacked( '\x19Ethereum Signed Message:\n32', keccak256( abi.encodePacked( quote.pool, quote.externalAccount, quote.trader, quote.baseToken, quote.quoteToken, quote.baseTokenAmount, quote.quoteTokenAmount, quote.quoteExpiry, quote.txid, block.chainid ) ) ) ); } function _hashXChainQuoteRFQT(XChainRFQTQuote memory quote) private pure returns (bytes32) { bytes32 digest = keccak256( abi.encodePacked( keccak256( abi.encodePacked( quote.srcChainId, quote.dstChainId, quote.srcPool, quote.dstPool, quote.srcExternalAccount, quote.dstExternalAccount ) ), quote.dstTrader, quote.baseToken, quote.quoteToken, quote.baseTokenAmount, quote.quoteTokenAmount, quote.quoteExpiry, quote.nonce, quote.txid, quote.xChainMessenger ) ); return keccak256( abi.encodePacked('\x19Ethereum Signed Message:\n32', digest) ); } function _hashXChainQuoteRFQM(XChainRFQMQuote memory quote) private pure returns (bytes32) { return keccak256( abi.encodePacked( '\x19Ethereum Signed Message:\n32', keccak256( abi.encodePacked( keccak256( abi.encodePacked( quote.srcChainId, quote.dstChainId, quote.srcPool, quote.dstPool, quote.srcExternalAccount, quote.dstExternalAccount ) ), quote.trader, quote.baseToken, quote.quoteToken, quote.baseTokenAmount, quote.quoteTokenAmount, quote.quoteExpiry, quote.txid, quote.xChainMessenger ) ) ) ); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.2; import "../../utils/Address.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] * ```solidity * 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. * * Similar to `reinitializer(1)`, except that functions marked with `initializer` can be nested in the context of a * constructor. * * Emits an {Initialized} event. */ modifier initializer() { bool isTopLevelCall = !_initializing; require( (isTopLevelCall && _initialized < 1) || (!Address.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. * * 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. * * When `version` is 1, this modifier is similar to `initializer`, except that functions marked with `reinitializer` * cannot be nested. If one is invoked in the context of another, execution will revert. * * 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. * * WARNING: setting the version to 255 will prevent any future reinitialization. * * Emits an {Initialized} event. */ 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. * * Emits an {Initialized} event the first time it is successfully executed. */ function _disableInitializers() internal virtual { require(!_initializing, "Initializable: contract is initializing"); if (_initialized != type(uint8).max) { _initialized = type(uint8).max; emit Initialized(type(uint8).max); } } /** * @dev Returns the highest version that has been initialized. See {reinitializer}. */ function _getInitializedVersion() internal view returns (uint8) { return _initialized; } /** * @dev Returns `true` if the contract is currently initializing. See {onlyInitializing}. */ function _isInitializing() internal view returns (bool) { return _initializing; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/extensions/IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address from, address to, uint256 amount) external returns (bool); }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../extensions/IERC20Permit.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; /** * @dev Transfer `value` amount of `token` from the calling contract to `to`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } /** * @dev Transfer `value` amount of `token` from `from` to `to`, spending the approval given by `from` to the * calling contract. If `token` returns no value, non-reverting calls are assumed to be successful. */ function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } /** * @dev Increase the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 oldAllowance = token.allowance(address(this), spender); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance + value)); } /** * @dev Decrease the calling contract's allowance toward `spender` by `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. */ function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, oldAllowance - value)); } } /** * @dev Set the calling contract's allowance toward `spender` to `value`. If `token` returns no value, * non-reverting calls are assumed to be successful. Compatible with tokens that require the approval to be set to * 0 before setting it to a non-zero value. */ function forceApprove(IERC20 token, address spender, uint256 value) internal { bytes memory approvalCall = abi.encodeWithSelector(token.approve.selector, spender, value); if (!_callOptionalReturnBool(token, approvalCall)) { _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, 0)); _callOptionalReturn(token, approvalCall); } } /** * @dev Use a ERC-2612 signature to set the `owner` approval toward `spender` on `token`. * Revert on invalid signature. */ function safePermit( IERC20Permit token, address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) internal { uint256 nonceBefore = token.nonces(owner); token.permit(owner, spender, value, deadline, v, r, s); uint256 nonceAfter = token.nonces(owner); require(nonceAfter == nonceBefore + 1, "SafeERC20: permit did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address-functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); require(returndata.length == 0 || abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). * * This is a variant of {_callOptionalReturn} that silents catches all reverts and returns a bool instead. */ function _callOptionalReturnBool(IERC20 token, bytes memory data) private returns (bool) { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We cannot use {Address-functionCall} here since this should return false // and not revert is the subcall reverts. (bool success, bytes memory returndata) = address(token).call(data); return success && (returndata.length == 0 || abi.decode(returndata, (bool))) && Address.isContract(address(token)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @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 * * Furthermore, `isContract` will also return true if the target contract within * the same transaction is already scheduled for destruction by `SELFDESTRUCT`, * which only has an effect at the end of a transaction. * ==== * * [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://consensys.net/diligence/blog/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.8.0/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 functionCallWithValue(target, data, 0, "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"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResultFromTarget(target, 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) { (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResultFromTarget(target, success, returndata, errorMessage); } /** * @dev Tool to verify that a low level call to smart-contract was successful, and revert (either by bubbling * the revert reason or using the provided one) in case of unsuccessful call or if target was not a contract. * * _Available since v4.8._ */ function verifyCallResultFromTarget( address target, bool success, bytes memory returndata, string memory errorMessage ) internal view returns (bytes memory) { if (success) { if (returndata.length == 0) { // only check isContract if the call was successful and the return data is empty // otherwise we already know that it was a contract require(isContract(target), "Address: call to non-contract"); } return returndata; } else { _revert(returndata, errorMessage); } } /** * @dev Tool to verify that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason or 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 { _revert(returndata, errorMessage); } } function _revert(bytes memory returndata, string memory errorMessage) private pure { // 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); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @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 Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (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 // Deprecated in v4.8 } 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"); } } /** * @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 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 message) { // 32 is the length in bytes of hash, // enforced by the type signature above /// @solidity memory-safe-assembly assembly { mstore(0x00, "\x19Ethereum Signed Message:\n32") mstore(0x1c, hash) message := keccak256(0x00, 0x3c) } } /** * @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 data) { /// @solidity memory-safe-assembly assembly { let ptr := mload(0x40) mstore(ptr, "\x19\x01") mstore(add(ptr, 0x02), domainSeparator) mstore(add(ptr, 0x22), structHash) data := keccak256(ptr, 0x42) } } /** * @dev Returns an Ethereum Signed Data with intended validator, created from a * `validator` and `data` according to the version 0 of EIP-191. * * See {recover}. */ function toDataWithIntendedValidatorHash(address validator, bytes memory data) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x00", validator, data)); } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.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) { // Solidity will revert if denominator == 0, unlike the div opcode on its own. // The surrounding unchecked block does not change this fact. // See https://docs.soliditylang.org/en/latest/control-structures.html#checked-or-unchecked-arithmetic. return prod0 / denominator; } // Make sure the result is less than 2^256. Also prevents denominator == 0. require(denominator > prod1, "Math: mulDiv overflow"); /////////////////////////////////////////////// // 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. If 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)`. This value can be written `msb(a)=2**k` with `k=log2(a)`. // // This can be rewritten `2**log2(a) <= a < 2**(log2(a) + 1)` // → `sqrt(2**k) <= sqrt(a) < sqrt(2**(k+1))` // → `2**(k/2) <= sqrt(a) < 2**((k+1)/2) <= 2**(k/2 + 1)` // // Consequently, `2**(log2(a) / 2)` is a good first approximation of `sqrt(a)` with at least 1 correct bit. uint256 result = 1 << (log2(a) >> 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) { unchecked { uint256 result = sqrt(a); return result + (rounding == Rounding.Up && result * result < a ? 1 : 0); } } /** * @dev Return the log in base 2, rounded down, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 128; } if (value >> 64 > 0) { value >>= 64; result += 64; } if (value >> 32 > 0) { value >>= 32; result += 32; } if (value >> 16 > 0) { value >>= 16; result += 16; } if (value >> 8 > 0) { value >>= 8; result += 8; } if (value >> 4 > 0) { value >>= 4; result += 4; } if (value >> 2 > 0) { value >>= 2; result += 2; } if (value >> 1 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 2, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log2(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log2(value); return result + (rounding == Rounding.Up && 1 << result < value ? 1 : 0); } } /** * @dev Return the log in base 10, rounded down, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >= 10 ** 64) { value /= 10 ** 64; result += 64; } if (value >= 10 ** 32) { value /= 10 ** 32; result += 32; } if (value >= 10 ** 16) { value /= 10 ** 16; result += 16; } if (value >= 10 ** 8) { value /= 10 ** 8; result += 8; } if (value >= 10 ** 4) { value /= 10 ** 4; result += 4; } if (value >= 10 ** 2) { value /= 10 ** 2; result += 2; } if (value >= 10 ** 1) { result += 1; } } return result; } /** * @dev Return the log in base 10, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log10(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log10(value); return result + (rounding == Rounding.Up && 10 ** result < value ? 1 : 0); } } /** * @dev Return the log in base 256, rounded down, of a positive value. * Returns 0 if given 0. * * Adding one to the result gives the number of pairs of hex symbols needed to represent `value` as a hex string. */ function log256(uint256 value) internal pure returns (uint256) { uint256 result = 0; unchecked { if (value >> 128 > 0) { value >>= 128; result += 16; } if (value >> 64 > 0) { value >>= 64; result += 8; } if (value >> 32 > 0) { value >>= 32; result += 4; } if (value >> 16 > 0) { value >>= 16; result += 2; } if (value >> 8 > 0) { result += 1; } } return result; } /** * @dev Return the log in base 256, following the selected rounding direction, of a positive value. * Returns 0 if given 0. */ function log256(uint256 value, Rounding rounding) internal pure returns (uint256) { unchecked { uint256 result = log256(value); return result + (rounding == Rounding.Up && 1 << (result << 3) < value ? 1 : 0); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.8.0) (utils/math/SignedMath.sol) pragma solidity ^0.8.0; /** * @dev Standard signed math utilities missing in the Solidity language. */ library SignedMath { /** * @dev Returns the largest of two signed numbers. */ function max(int256 a, int256 b) internal pure returns (int256) { return a > b ? a : b; } /** * @dev Returns the smallest of two signed numbers. */ function min(int256 a, int256 b) internal pure returns (int256) { return a < b ? a : b; } /** * @dev Returns the average of two signed numbers without overflow. * The result is rounded towards zero. */ function average(int256 a, int256 b) internal pure returns (int256) { // Formula from the book "Hacker's Delight" int256 x = (a & b) + ((a ^ b) >> 1); return x + (int256(uint256(x) >> 255) & (a ^ b)); } /** * @dev Returns the absolute unsigned value of a signed value. */ function abs(int256 n) internal pure returns (uint256) { unchecked { // must be unchecked in order to support `n = type(int256).min` return uint256(n >= 0 ? n : -n); } } }
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.9.0) (utils/Strings.sol) pragma solidity ^0.8.0; import "./math/Math.sol"; import "./math/SignedMath.sol"; /** * @dev String operations. */ library Strings { bytes16 private constant _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) { unchecked { uint256 length = Math.log10(value) + 1; string memory buffer = new string(length); uint256 ptr; /// @solidity memory-safe-assembly assembly { ptr := add(buffer, add(32, length)) } while (true) { ptr--; /// @solidity memory-safe-assembly assembly { mstore8(ptr, byte(mod(value, 10), _SYMBOLS)) } value /= 10; if (value == 0) break; } return buffer; } } /** * @dev Converts a `int256` to its ASCII `string` decimal representation. */ function toString(int256 value) internal pure returns (string memory) { return string(abi.encodePacked(value < 0 ? "-" : "", toString(SignedMath.abs(value)))); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, Math.log256(value) + 1); } } /** * @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] = _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); } /** * @dev Returns true if the two strings are equal. */ function equal(string memory a, string memory b) internal pure returns (bool) { return keccak256(bytes(a)) == keccak256(bytes(b)); } }
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity >=0.8.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; }
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity >=0.8.0; import '@openzeppelin/contracts/interfaces/IERC1271.sol'; import './IQuote.sol'; /// @title IHashflowPool /// @author Victor Ionescu /** * Pool contract used for trading. The Pool can either hold funds or * rely on external accounts. External accounts are used in order to preserve * Capital Efficiency on the Market Maker side. This way, a Market Maker can * make markets using funds that are also used on other venues. */ interface IHashflowPool is IQuote, IERC1271 { /// @notice Specifies a HashflowPool on a foreign chain. struct AuthorizedXChainPool { uint16 chainId; bytes32 pool; } /// @notice Contains a signer verification address, and whether trading is enabled. struct SignerConfiguration { address signer; bool enabled; } /// @notice Emitted when the authorization status of a withdrawal account changes. /// @param account The account for which the status changes. /// @param authorized The new authorization status. event UpdateWithdrawalAccount(address account, bool authorized); /// @notice Emitted when the signer key used for the pool has changed. /// @param signer The new signer key. /// @param prevSigner The old signer key. event UpdateSigner(address signer, address prevSigner); /// @notice Emitted when liquidity is withdrawn from the pool. /// @param token Token being withdrawn. /// @param recipient Address receiving the token. /// @param withdrawAmount Amount being withdrawn. event RemoveLiquidity( address token, address recipient, uint256 withdrawAmount ); /// @notice Emitted when an intra-chain trade happens. /// @param trader The trader. /// @param effectiveTrader The effective Trader. /// @param txid The txid of the quote. /// @param baseToken The token the trader sold. /// @param quoteToken The token the trader bought. /// @param baseTokenAmount The amount of baseToken sold. /// @param quoteTokenAmount The amount of quoteToken bought. event Trade( address trader, address effectiveTrader, bytes32 txid, address baseToken, address quoteToken, uint256 baseTokenAmount, uint256 quoteTokenAmount ); /// @notice Emitted when a cross-chain trade happens. /// @param dstChainId The Hashflow Chain ID for the destination chain. /// @param dstPool The pool address on the destination chain. /// @param trader The trader address. /// @param txid The txid of the quote. /// @param baseToken The token the trader sold. /// @param quoteToken The token the trader bought. /// @param baseTokenAmount The amount of baseToken sold. /// @param quoteTokenAmount The amount of quoteToken bought. event XChainTrade( uint16 dstChainId, bytes32 dstPool, address trader, bytes32 dstTrader, bytes32 txid, address baseToken, bytes32 quoteToken, uint256 baseTokenAmount, uint256 quoteTokenAmount ); /// @notice Emitted when a cross-chain trade is filled. /// @param txid The txid identified the quote that was filled. event XChainTradeFill(bytes32 txid); /// @notice Main initializer. /// @param name Name of the pool. /// @param signer Signer key used for quote / deposit verification. /// @param operations Operations key that governs the pool. /// @param router Address of the HashflowRouter contract. function initialize( string calldata name, address signer, address operations, address router ) external; /// @notice Returns the pool name. function name() external view returns (string memory); /// @notice Returns the signer address and whether the pool is enabled. function signerConfiguration() external view returns (address, bool); /// @notice Returns the Operations address of this pool. function operations() external view returns (address); /// @notice Returns the Router contract address. function router() external view returns (address); /// @notice Returns the current nonce for a trader. function nonces(address trader) external view returns (uint256); /// @notice Removes liquidity from the pool. /// @param token Token to withdraw. /// @param recipient Address to send token to. /// @param amount Amount to withdraw. function removeLiquidity( address token, address recipient, uint256 amount ) external; /// @notice Execute an RFQ-T trade. /// @param quote The quote to be executed. function tradeRFQT(RFQTQuote memory quote) external payable; /// @notice Execute an RFQ-M trade. /// @param quote The quote to be executed. function tradeRFQM(RFQMQuote memory quote) external; /// @notice Execute a cross-chain RFQ-T trade. /// @param quote The quote to be executed. /// @param trader The account that sends baseToken on this chain. function tradeXChainRFQT(XChainRFQTQuote memory quote, address trader) external payable; /// @notice Execute a cross-chain RFQ-M trade. /// @param quote The quote to be executed. function tradeXChainRFQM(XChainRFQMQuote memory quote) external; /// @notice Changes authorization for a set of pools to send X-Chain messages. /// @param pools The pools to change authorization status for. /// @param authorized The new authorization status. function updateXChainPoolAuthorization( AuthorizedXChainPool[] calldata pools, bool authorized ) external; /// @notice Changes authorization for an X-Chain Messenger app. /// @param xChainMessenger The address of the Messenger app. /// @param authorized The new authorization status. function updateXChainMessengerAuthorization( address xChainMessenger, bool authorized ) external; /// @notice Fills an x-chain order that completed on the source chain. /// @param externalAccount The external account to fill from, if any. /// @param txid The txid of the quote. /// @param trader The trader to receive the funds. /// @param quoteToken The token to be sent. /// @param quoteTokenAmount The amount of quoteToken to be sent. function fillXChain( address externalAccount, bytes32 txid, address trader, address quoteToken, uint256 quoteTokenAmount ) external; /// @notice Updates withdrawal account authorization. /// @param withdrawalAccounts the accounts for which to update authorization status. /// @param authorized The new authorization status. function updateWithdrawalAccount( address[] memory withdrawalAccounts, bool authorized ) external; /// @notice Updates the signer key. /// @param signer The new signer key. function updateSigner(address signer) external; /// @notice Used by the router to disable pool actions (Trade, Withdraw, Deposit) function killswitchOperations(bool enabled) external; /// @notice Returns the token reserves for this pool. /// @param token The token to check reserves for. function getReserves(address token) external view returns (uint256); /// @notice Approves a token for spend. Used for 1inch RFQ protocol. /// @param token The address of the ERC-20 token. /// @param spender The spender address (typically the 1inch RFQ order router) /// @param amount The approval amount. function approveToken( address token, address spender, uint256 amount ) external; /// @notice Increases allowance for a token. Used for 1inch RFQ protocol. /// @param token The address of the ERC-20 token. /// @param spender The spender address (typically the 1inch RFQ order router). /// @param amount The approval amount. function increaseTokenAllowance( address token, address spender, uint256 amount ) external; /// @notice Decreases allowance for a token. Used for 1inch RFQ protocol. /// @param token The address of the ERC-20 token. /// @param spender The spender address (typically the 1inch RFQ order router) /// @param amount The approval amount. function decreaseTokenAllowance( address token, address spender, uint256 amount ) external; }
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity >=0.8.0; import './IQuote.sol'; /// @title IHashflowRouter /// @author Victor Ionescu /** * @notice In terms of user-facing functionality, the Router is responsible for: * - orchestrating trades * - managing cross-chain permissions * * Every trade requires consent from two parties: the Trader and the Market Maker. * However, there are two models to establish consent: * - RFQ-T: in this model, the Market Maker provides an EIP-191 signature for the quote, * while the Trader signs the transaction and submits it on-chain * - RFQ-M: in this model, the Trader provides an EIP-712 signature for the quote, * the Market Maker provides an EIP-191 signature, and a 3rd party relays the trade. * The 3rd party can be the Market Maker itself. * * In terms of Hashflow internals, the Router maintains a set of authorized pool * contracts that are allowed to be used for trading. This allowlist creates * guarantees against malicious behavior, as documented in specific places. * * The Router contract is not upgradeable. In order to change functionality, a new * Router has to be deployed, and new HashflowPool contracts have to be deployed * by the Market Makers. */ /// @dev Trade / liquidity events are emitted at the HashflowPool level, rather than the router. interface IHashflowRouter is IQuote { /** * @notice X-Chain message received from an X-Chain Messenger. This is used by the * Router to communicate a fill to a HashflowPool. */ struct XChainFillMessage { /// @notice The Hashflow Chain ID of the source chain. uint16 srcHashflowChainId; /// @notice The address of the HashflowPool on the source chain. bytes32 srcPool; /// @notice The HashflowPool to disburse funds on the destination chain. address dstPool; /** * @notice The external account linked to the HashflowPool on the destination chain. * If the HashflowPool holds funds, this should be bytes32(0). */ address dstExternalAccount; /// @notice The recipient of the quoteToken on the destination chain. address dstTrader; /// @notice The token that the trader buys on the destination chain. address quoteToken; /// @notice The amount of quoteToken bought. uint256 quoteTokenAmount; /// @notice Unique identifier for the quote. /// @dev Generated off-chain via a distributed UUID generator. bytes32 txid; /// @notice The caller of the trade function on the source chain. bytes32 srcCaller; /// @notice The contract to call, if any. address dstContract; /// @notice The calldata for the contract. bytes dstContractCalldata; } /// @notice Emitted when the authorization status of a pool changes. /// @param pool The pool whose status changed. /// @param authorized The new auth status. event UpdatePoolAuthorizaton(address pool, bool authorized); /// @notice Emitted when a sender pool authorization changes. /// @param pool Pool address on this chain. /// @param otherHashflowChainId Hashflow Chain ID of the other chain. /// @param otherChainPool Pool address on the other chain. /// @param authorized Whether the pool is authorized. event UpdateXChainPoolAuthorization( address indexed pool, uint16 otherHashflowChainId, bytes32 otherChainPool, bool authorized ); /// @notice Emitted when the authorization of an x-caller changes. /// @param pool Pool address on this chain. /// @param otherHashflowChainId Hashflow Chain ID of the other chain. /// @param caller Caller address on the other chain. /// @param authorized Whether the caller is authorized. event UpdateXChainCallerAuthorization( address indexed pool, uint16 otherHashflowChainId, bytes32 caller, bool authorized ); /// @notice Emitted when the authorization status of an X-Chain Messenger changes for a pool. /// @param pool Pool address for which the Messenger authorization changes. /// @param xChainMessenger Address of the Messenger. /// @param authorized Whether the X-Chain Messenger is authorized. event UpdateXChainMessengerAuthorization( address indexed pool, address xChainMessenger, bool authorized ); /// @notice Emitted when the authorized status of an X-Chain Messenger changes for a callee. /// @param callee Address of the callee. /// @param xChainMessenger Address of the Messenger. /// @param authorized Whether the X-Chain Messenger is authorized. event UpdateXChainMessengerCallerAuthorization( address indexed callee, address xChainMessenger, bool authorized ); /// @notice Emitted when the Limit Order Guardian address is updated. /// @param guardian The new Guardian address. event UpdateLimitOrderGuardian(address guardian); /// @notice Initializes the Router. Called one time. /// @param factory The address of the HashflowFactory contract. function initialize(address factory) external; /// @notice Returns the address of the associated HashflowFactor contract. function factory() external view returns (address); function authorizedXChainPools( bytes32 dstPool, uint16 srcHChainId, bytes32 srcPool ) external view returns (bool); function authorizedXChainCallers( address dstContract, uint16 srcHashflowChainId, bytes32 caller ) external view returns (bool); function authorizedXChainMessengersByPool(address pool, address messenger) external view returns (bool); function authorizedXChainMessengersByCallee( address callee, address messenger ) external view returns (bool); /// @notice Executes an intra-chain RFQ-T trade. /// @param quote The quote data to be executed. function tradeRFQT(RFQTQuote memory quote) external payable; /// @notice Executes an intra-chain RFQ-T trade, leveraging an ERC-20 permit. /// @param quote The quote data to be executed. /// @dev Does not support native tokens for the baseToken. function tradeRFQTWithPermit( RFQTQuote memory quote, uint256 deadline, uint8 v, bytes32 r, bytes32 s, uint256 amountToApprove ) external; /// @notice Executes an intra-chain RFQ-T trade. /// @param quote The quote to be executed. function tradeRFQM(RFQMQuote memory quote) external; /// @notice Executes an intra-chain RFQ-T trade, leveraging an ERC-20 permit. /// @param quote The quote to be executed. /// @param deadline The deadline of the ERC-20 permit. /// @param v v-part of the signature. /// @param r r-part of the signature. /// @param s s-part of the signature. /// @param amountToApprove The amount being approved. function tradeRFQMWithPermit( RFQMQuote memory quote, uint256 deadline, uint8 v, bytes32 r, bytes32 s, uint256 amountToApprove ) external; /// @notice Executes an intra-chain RFQ-T trade. /// @param quote The quote to be executed. /// @param guardianSignature A signature issued by the Limit Order Guardian. function tradeRFQMLimitOrder( RFQMQuote memory quote, bytes memory guardianSignature ) external; /// @notice Executes an intra-chain RFQ-T trade, leveraging an ERC-20 permit. /// @param quote The quote to be executed. /// @param guardianSignature A signature issued by the Limit Order Guardian. /// @param deadline The deadline of the ERC-20 permit. /// @param v v-part of the signature. /// @param r r-part of the signature. /// @param s s-part of the signature. /// @param amountToApprove The amount being approved. function tradeRFQMLimitOrderWithPermit( RFQMQuote memory quote, bytes memory guardianSignature, uint256 deadline, uint8 v, bytes32 r, bytes32 s, uint256 amountToApprove ) external; /// @notice Executes an RFQ-T cross-chain trade. /// @param quote The quote to be executed. /// @param dstContract The address of the contract to be called on the destination chain. /// @param dstCalldata The calldata for the smart contract call. function tradeXChainRFQT( XChainRFQTQuote memory quote, bytes32 dstContract, bytes memory dstCalldata ) external payable; /// @notice Executes an RFQ-T cross-chain trade, leveraging an ERC-20 permit. /// @param quote The quote to be executed. /// @param dstContract The address of the contract to be called on the destination chain. /// @param dstCalldata The calldata for the smart contract call. /// @param deadline The deadline of the ERC-20 permit. /// @param v v-part of the signature. /// @param r r-part of the signature. /// @param s s-part of the signature. /// @param amountToApprove The amount being approved. function tradeXChainRFQTWithPermit( XChainRFQTQuote memory quote, bytes32 dstContract, bytes memory dstCalldata, uint256 deadline, uint8 v, bytes32 r, bytes32 s, uint256 amountToApprove ) external payable; /// @notice Executes an RFQ-M cross-chain trade. /// @param quote The quote to be executed. /// @param dstContract The address of the contract to be called on the destination chain. /// @param dstCalldata The calldata for the smart contract call. function tradeXChainRFQM( XChainRFQMQuote memory quote, bytes32 dstContract, bytes memory dstCalldata ) external payable; /// @notice Similar to tradeXChainRFQm, but includes a spend permit for the baseToken. /// @param quote The quote to be executed. /// @param dstContract The address of the contract to be called on the destination chain. /// @param dstCalldata The calldata for the smart contract call. /// @param deadline The deadline of the ERC-20 permit. /// @param v v-part of the signature. /// @param r r-part of the signature. /// @param s s-part of the signature. /// @param amountToApprove The amount to approve. function tradeXChainRFQMWithPermit( XChainRFQMQuote memory quote, bytes32 dstContract, bytes memory dstCalldata, uint256 deadline, uint8 v, bytes32 r, bytes32 s, uint256 amountToApprove ) external payable; /// @notice Completes the second leg of a cross-chain trade. /// @param fillMessage Payload containing information necessary to complete the trade. function fillXChain(XChainFillMessage memory fillMessage) external; /// @notice Returns whether the pool is authorized for trading. /// @param pool The address of the HashflowPool. function authorizedPools(address pool) external view returns (bool); /// @notice Allows the owner to unauthorize a potentially compromised pool. Cannot be reverted. /// @param pool The address of the HashflowPool. function forceUnauthorizePool(address pool) external; /// @notice Authorizes a HashflowPool for trading. /// @dev Can only be called by the HashflowFactory or the admin. function updatePoolAuthorization(address pool, bool authorized) external; /// @notice Updates the authorization status of an X-Chain pool pair. /// @param otherHashflowChainId The Hashflow Chain ID of the peer chain. /// @param otherPool The 32-byte representation of the Pool address on the peer chain. /// @param authorized Whether the pool is authorized to communicate with the sender pool. function updateXChainPoolAuthorization( uint16 otherHashflowChainId, bytes32 otherPool, bool authorized ) external; /// @notice Updates the authorization status of an X-Chain caller. /// @param otherHashflowChainId The Hashflow Chain ID of the peer chain. /// @param caller The caller address. /// @param authorized Whether the caller is authorized to send an x-call to the sender pool. function updateXChainCallerAuthorization( uint16 otherHashflowChainId, bytes32 caller, bool authorized ) external; /// @notice Updates the authorization status of an X-Chain Messenger app. /// @param xChainMessenger The address of the Messenger App. /// @param authorized The new authorization status. function updateXChainMessengerAuthorization( address xChainMessenger, bool authorized ) external; /// @notice Updates the authorization status of an X-Chain Messenger app. /// @param xChainMessenger The address of the Messenger App. /// @param authorized The new authorization status. function updateXChainMessengerCallerAuthorization( address xChainMessenger, bool authorized ) external; /// @notice Used to stop all operations on a pool, in case of an emergency. /// @param pool The address of the HashflowPool. /// @param enabled Whether the pool is enabled. function killswitchPool(address pool, bool enabled) external; /// @notice Used to update the Limit Order Guardian. /// @param guardian The address of the new Guardian. function updateLimitOrderGuardian(address guardian) external; /// @notice Allows the owner to withdraw excess funds from the Router. /// @dev Under normal operations, the Router should not have excess funds. function withdrawFunds(address token) external; }
/** * SPDX-License-Identifier: UNLICENSED */ pragma solidity >=0.8.0; /// @title IQuote /// @author Victor Ionescu /** * @notice Interface for quote structs used for trading. There are two major types of trades: * - intra-chain: atomic transactions within one chain * - cross-chain: multi-leg transactions between two chains, which utilize interoperability protocols * such as Wormhole. * * Separately, there are two trading modes: * - RFQ-T: the trader signs the transaction, the market maker signs the quote * - RFQ-M: both the trader and Market Maker sign the quote, any relayer can sign the transaction */ interface IQuote { /// @notice Used for intra-chain RFQ-T trades. struct RFQTQuote { /// @notice The address of the HashflowPool to trade against. address pool; /** * @notice The external account linked to the HashflowPool. * If the HashflowPool holds funds, this should be address(0). */ address externalAccount; /// @notice The recipient of the quoteToken at the end of the trade. address trader; /** * @notice The account "effectively" making the trade (ultimately receiving the funds). * This is commonly used by aggregators, where a proxy contract (the 'trader') * receives the quoteToken, and the effective trader is the user initiating the call. * * This field DOES NOT influence movement of funds. However, it is used to check against * quote replay. */ address effectiveTrader; /// @notice The token that the trader sells. address baseToken; /// @notice The token that the trader buys. address quoteToken; /** * @notice The amount of baseToken sold in this trade. The exchange rate * is going to be preserved as the quoteTokenAmount / baseTokenAmount ratio. * * Most commonly, effectiveBaseTokenAmount will == baseTokenAmount. */ uint256 effectiveBaseTokenAmount; /// @notice The max amount of baseToken sold. uint256 baseTokenAmount; /// @notice The amount of quoteToken bought when baseTokenAmount is sold. uint256 quoteTokenAmount; /// @notice The Unix timestamp (in seconds) when the quote expires. /// @dev This gets checked against block.timestamp. uint256 quoteExpiry; /// @notice The nonce used by this effectiveTrader. Nonces are used to protect against replay. uint256 nonce; /// @notice Unique identifier for the quote. /// @dev Generated off-chain via a distributed UUID generator. bytes32 txid; /// @notice Signature provided by the market maker (EIP-191). bytes signature; } /// @notice Used for intra-chain RFQ-M trades. struct RFQMQuote { /// @notice The address of the HashflowPool to trade against. address pool; /** * @notice The external account linked to the HashflowPool. * If the HashflowPool holds funds, this should be address(0). */ address externalAccount; /// @notice The account that will be debited baseToken / credited quoteToken. address trader; /// @notice The token that the trader sells. address baseToken; /// @notice The token that the trader buys. address quoteToken; /// @notice The amount of baseToken sold. uint256 baseTokenAmount; /// @notice The amount of quoteToken bought. uint256 quoteTokenAmount; /// @notice The Unix timestamp (in seconds) when the quote expires. /// @dev This gets checked against block.timestamp. uint256 quoteExpiry; /// @notice Unique identifier for the quote. /// @dev Generated off-chain via a distributed UUID generator. bytes32 txid; /// @notice Signature provided by the trader (EIP-712). bytes takerSignature; /// @notice Signature provided by the market maker (EIP-191). bytes makerSignature; } /// @notice Used for cross-chain RFQ-T trades. struct XChainRFQTQuote { /// @notice The Hashflow Chain ID of the source chain. uint16 srcChainId; /// @notice The Hashflow Chain ID of the destination chain. uint16 dstChainId; /// @notice The address of the HashflowPool to trade against on the source chain. address srcPool; /// @notice The HashflowPool to disburse funds on the destination chain. /// @dev This is bytes32 in order to anticipate non-EVM chains. bytes32 dstPool; /** * @notice The external account linked to the HashflowPool on the source chain. * If the HashflowPool holds funds, this should be address(0). */ address srcExternalAccount; /** * @notice The external account linked to the HashflowPool on the destination chain. * If the HashflowPool holds funds, this should be bytes32(0). */ bytes32 dstExternalAccount; /// @notice The recipient of the quoteToken on the destination chain. bytes32 dstTrader; /// @notice The token that the trader sells on the source chain. address baseToken; /// @notice The token that the trader buys on the destination chain. bytes32 quoteToken; /** * @notice The amount of baseToken sold in this trade. The exchange rate * is going to be preserved as the quoteTokenAmount / baseTokenAmount ratio. * * Most commonly, effectiveBaseTokenAmount will == baseTokenAmount. */ uint256 effectiveBaseTokenAmount; /// @notice The amount of baseToken sold. uint256 baseTokenAmount; /// @notice The amount of quoteToken bought. uint256 quoteTokenAmount; /** * @notice The Unix timestamp (in seconds) when the quote expire. Only enforced * on the source chain. */ /// @dev This gets checked against block.timestamp. uint256 quoteExpiry; /// @notice The nonce used by this trader. uint256 nonce; /// @notice Unique identifier for the quote. /// @dev Generated off-chain via a distributed UUID generator. bytes32 txid; /** * @notice The address of the IHashflowXChainMessenger contract used for * cross-chain communication. */ address xChainMessenger; /// @notice Signature provided by the market maker (EIP-191). bytes signature; } /// @notice Used for Cross-Chain RFQ-M trades. struct XChainRFQMQuote { /// @notice The Hashflow Chain ID of the source chain. uint16 srcChainId; /// @notice The Hashflow Chain ID of the destination chain. uint16 dstChainId; /// @notice The address of the HashflowPool to trade against on the source chain. address srcPool; /// @notice The HashflowPool to disburse funds on the destination chain. /// @dev This is bytes32 in order to anticipate non-EVM chains. bytes32 dstPool; /** * @notice The external account linked to the HashflowPool on the source chain. * If the HashflowPool holds funds, this should be address(0). */ address srcExternalAccount; /** * @notice The external account linked to the HashflowPool on the destination chain. * If the HashflowPool holds funds, this should be bytes32(0). */ bytes32 dstExternalAccount; /// @notice The account that will be debited baseToken on the source chain. address trader; /// @notice The recipient of the quoteToken on the destination chain. bytes32 dstTrader; /// @notice The token that the trader sells on the source chain. address baseToken; /// @notice The token that the trader buys on the destination chain. bytes32 quoteToken; /// @notice The amount of baseToken sold. uint256 baseTokenAmount; /// @notice The amount of quoteToken bought. uint256 quoteTokenAmount; /** * @notice The Unix timestamp (in seconds) when the quote expire. Only enforced * on the source chain. */ /// @dev This gets checked against block.timestamp. uint256 quoteExpiry; /// @notice Unique identifier for the quote. /// @dev Generated off-chain via a distributed UUID generator. bytes32 txid; /** * @notice The address of the IHashflowXChainMessenger contract used for * cross-chain communication. */ address xChainMessenger; /// @notice Signature provided by the trader (EIP-712). bytes takerSignature; /// @notice Signature provided by the market maker (EIP-191). bytes makerSignature; } }
{ "optimizer": { "enabled": true, "runs": 200 }, "outputSelection": { "*": { "*": [ "evm.bytecode", "evm.deployedBytecode", "devdoc", "userdoc", "metadata", "abi" ] } }, "libraries": {} }
[{"inputs":[{"internalType":"address","name":"weth","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint8","name":"version","type":"uint8"}],"name":"Initialized","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"token","type":"address"},{"indexed":false,"internalType":"address","name":"recipient","type":"address"},{"indexed":false,"internalType":"uint256","name":"withdrawAmount","type":"uint256"}],"name":"RemoveLiquidity","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"trader","type":"address"},{"indexed":false,"internalType":"address","name":"effectiveTrader","type":"address"},{"indexed":false,"internalType":"bytes32","name":"txid","type":"bytes32"},{"indexed":false,"internalType":"address","name":"baseToken","type":"address"},{"indexed":false,"internalType":"address","name":"quoteToken","type":"address"},{"indexed":false,"internalType":"uint256","name":"baseTokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"quoteTokenAmount","type":"uint256"}],"name":"Trade","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"signer","type":"address"},{"indexed":false,"internalType":"address","name":"prevSigner","type":"address"}],"name":"UpdateSigner","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"bool","name":"authorized","type":"bool"}],"name":"UpdateWithdrawalAccount","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"uint16","name":"dstChainId","type":"uint16"},{"indexed":false,"internalType":"bytes32","name":"dstPool","type":"bytes32"},{"indexed":false,"internalType":"address","name":"trader","type":"address"},{"indexed":false,"internalType":"bytes32","name":"dstTrader","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"txid","type":"bytes32"},{"indexed":false,"internalType":"address","name":"baseToken","type":"address"},{"indexed":false,"internalType":"bytes32","name":"quoteToken","type":"bytes32"},{"indexed":false,"internalType":"uint256","name":"baseTokenAmount","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"quoteTokenAmount","type":"uint256"}],"name":"XChainTrade","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"txid","type":"bytes32"}],"name":"XChainTradeFill","type":"event"},{"inputs":[],"name":"_WETH","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"approveToken","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"decreaseTokenAllowance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"externalAccount","type":"address"},{"internalType":"bytes32","name":"txid","type":"bytes32"},{"internalType":"address","name":"trader","type":"address"},{"internalType":"address","name":"quoteToken","type":"address"},{"internalType":"uint256","name":"quoteTokenAmount","type":"uint256"}],"name":"fillXChain","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"}],"name":"getReserves","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"spender","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"increaseTokenAllowance","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"string","name":"_name","type":"string"},{"internalType":"address","name":"_signer","type":"address"},{"internalType":"address","name":"_operations","type":"address"},{"internalType":"address","name":"_router","type":"address"}],"name":"initialize","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"hash","type":"bytes32"},{"internalType":"bytes","name":"signature","type":"bytes"}],"name":"isValidSignature","outputs":[{"internalType":"bytes4","name":"magicValue","type":"bytes4"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"bool","name":"enabled","type":"bool"}],"name":"killswitchOperations","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"name","outputs":[{"internalType":"string","name":"","type":"string"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"","type":"address"}],"name":"nonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"operations","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"address","name":"token","type":"address"},{"internalType":"address","name":"recipient","type":"address"},{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"removeLiquidity","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"router","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[],"name":"signerConfiguration","outputs":[{"internalType":"address","name":"signer","type":"address"},{"internalType":"bool","name":"enabled","type":"bool"}],"stateMutability":"view","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"address","name":"externalAccount","type":"address"},{"internalType":"address","name":"trader","type":"address"},{"internalType":"address","name":"baseToken","type":"address"},{"internalType":"address","name":"quoteToken","type":"address"},{"internalType":"uint256","name":"baseTokenAmount","type":"uint256"},{"internalType":"uint256","name":"quoteTokenAmount","type":"uint256"},{"internalType":"uint256","name":"quoteExpiry","type":"uint256"},{"internalType":"bytes32","name":"txid","type":"bytes32"},{"internalType":"bytes","name":"takerSignature","type":"bytes"},{"internalType":"bytes","name":"makerSignature","type":"bytes"}],"internalType":"struct IQuote.RFQMQuote","name":"quote","type":"tuple"}],"name":"tradeRFQM","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"address","name":"pool","type":"address"},{"internalType":"address","name":"externalAccount","type":"address"},{"internalType":"address","name":"trader","type":"address"},{"internalType":"address","name":"effectiveTrader","type":"address"},{"internalType":"address","name":"baseToken","type":"address"},{"internalType":"address","name":"quoteToken","type":"address"},{"internalType":"uint256","name":"effectiveBaseTokenAmount","type":"uint256"},{"internalType":"uint256","name":"baseTokenAmount","type":"uint256"},{"internalType":"uint256","name":"quoteTokenAmount","type":"uint256"},{"internalType":"uint256","name":"quoteExpiry","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"bytes32","name":"txid","type":"bytes32"},{"internalType":"bytes","name":"signature","type":"bytes"}],"internalType":"struct IQuote.RFQTQuote","name":"quote","type":"tuple"}],"name":"tradeRFQT","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"components":[{"internalType":"uint16","name":"srcChainId","type":"uint16"},{"internalType":"uint16","name":"dstChainId","type":"uint16"},{"internalType":"address","name":"srcPool","type":"address"},{"internalType":"bytes32","name":"dstPool","type":"bytes32"},{"internalType":"address","name":"srcExternalAccount","type":"address"},{"internalType":"bytes32","name":"dstExternalAccount","type":"bytes32"},{"internalType":"address","name":"trader","type":"address"},{"internalType":"bytes32","name":"dstTrader","type":"bytes32"},{"internalType":"address","name":"baseToken","type":"address"},{"internalType":"bytes32","name":"quoteToken","type":"bytes32"},{"internalType":"uint256","name":"baseTokenAmount","type":"uint256"},{"internalType":"uint256","name":"quoteTokenAmount","type":"uint256"},{"internalType":"uint256","name":"quoteExpiry","type":"uint256"},{"internalType":"bytes32","name":"txid","type":"bytes32"},{"internalType":"address","name":"xChainMessenger","type":"address"},{"internalType":"bytes","name":"takerSignature","type":"bytes"},{"internalType":"bytes","name":"makerSignature","type":"bytes"}],"internalType":"struct IQuote.XChainRFQMQuote","name":"quote","type":"tuple"}],"name":"tradeXChainRFQM","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint16","name":"srcChainId","type":"uint16"},{"internalType":"uint16","name":"dstChainId","type":"uint16"},{"internalType":"address","name":"srcPool","type":"address"},{"internalType":"bytes32","name":"dstPool","type":"bytes32"},{"internalType":"address","name":"srcExternalAccount","type":"address"},{"internalType":"bytes32","name":"dstExternalAccount","type":"bytes32"},{"internalType":"bytes32","name":"dstTrader","type":"bytes32"},{"internalType":"address","name":"baseToken","type":"address"},{"internalType":"bytes32","name":"quoteToken","type":"bytes32"},{"internalType":"uint256","name":"effectiveBaseTokenAmount","type":"uint256"},{"internalType":"uint256","name":"baseTokenAmount","type":"uint256"},{"internalType":"uint256","name":"quoteTokenAmount","type":"uint256"},{"internalType":"uint256","name":"quoteExpiry","type":"uint256"},{"internalType":"uint256","name":"nonce","type":"uint256"},{"internalType":"bytes32","name":"txid","type":"bytes32"},{"internalType":"address","name":"xChainMessenger","type":"address"},{"internalType":"bytes","name":"signature","type":"bytes"}],"internalType":"struct IQuote.XChainRFQTQuote","name":"quote","type":"tuple"},{"internalType":"address","name":"trader","type":"address"}],"name":"tradeXChainRFQT","outputs":[],"stateMutability":"payable","type":"function"},{"inputs":[{"internalType":"address","name":"newSigner","type":"address"}],"name":"updateSigner","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address[]","name":"withdrawalAccounts","type":"address[]"},{"internalType":"bool","name":"authorized","type":"bool"}],"name":"updateWithdrawalAccount","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"address","name":"xChainMessenger","type":"address"},{"internalType":"bool","name":"authorized","type":"bool"}],"name":"updateXChainMessengerAuthorization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"components":[{"internalType":"uint16","name":"chainId","type":"uint16"},{"internalType":"bytes32","name":"pool","type":"bytes32"}],"internalType":"struct IHashflowPool.AuthorizedXChainPool[]","name":"pools","type":"tuple[]"},{"internalType":"bool","name":"status","type":"bool"}],"name":"updateXChainPoolAuthorization","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[{"internalType":"bytes32","name":"","type":"bytes32"}],"name":"xChainNonces","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"stateMutability":"payable","type":"receive"}]
Loading...
Loading
Loading...
Loading
Multichain Portfolio | 30 Chains
Chain | Token | Portfolio % | Price | Amount | Value |
---|
Loading...
Loading
[ Download: CSV Export ]
[ Download: CSV Export ]
A contract address hosts a smart contract, which is a set of code stored on the blockchain that runs when predetermined conditions are met. Learn more about addresses in our Knowledge Base.