Skip to content
Verified contractExactMIT

EthereumFeeProxy

Address0xfcfbcfc4f5a421089e3df45455f7f4985fe2d6a8
Balance

0 ETH

 

Transactions

265

 

Compiler

solc 0.8.9

 

Same code

Only this contract

 

Details

Compiler
solc 0.8.9+commit.e5eed63a
Language
solidity
Optimization
No
EVM version
london
License
MIT
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
14,392,218
Creation transaction
0x943694df5a…cd915d0d55

39 files

src/contracts/EthereumFeeProxy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import '@openzeppelin/contracts/security/ReentrancyGuard.sol';

/**
 * @title EthereumFeeProxy
 * @notice This contract performs an Ethereum transfer with a Fee sent to a third address and stores a reference
 */
contract EthereumFeeProxy is ReentrancyGuard {
    // Event to declare a transfer with a reference
    event TransferWithReferenceAndFee(
        address to,
        uint256 amount,
        bytes indexed paymentReference,
        uint256 feeAmount,
        address feeAddress
    );

    // Fallback function returns funds to the sender
    receive() external payable {
        revert('not payable receive');
    }

    /**
     * @notice Performs an Ethereum transfer with a reference
     * @param _to Transfer recipient
     * @param _paymentReference Reference of the payment related
     * @param _feeAmount The amount of the payment fee (part of the msg.value)
     * @param _feeAddress The fee recipient
     */
    function transferWithReferenceAndFee(
        address payable _to,
        bytes calldata _paymentReference,
        uint256 _feeAmount,
        address payable _feeAddress
    ) external payable {
        transferExactEthWithReferenceAndFee(
            _to,
            msg.value - _feeAmount,
            _paymentReference,
            _feeAmount,
            _feeAddress
        );
    }

    /**
     * @notice Performs an Ethereum transfer with a reference with an exact amount of eth
     * @param _to Transfer recipient
     * @param _amount Amount to transfer
     * @param _paymentReference Reference of the payment related
     * @param _feeAmount The amount of the payment fee (part of the msg.value)
     * @param _feeAddress The fee recipient
     */
    function transferExactEthWithReferenceAndFee(
        address payable _to,
        uint256 _amount,
        bytes calldata _paymentReference,
        uint256 _feeAmount,
        address payable _feeAddress
    ) public payable nonReentrant {
        (bool sendSuccess, ) = _to.call{value: _amount}('');
        require(sendSuccess, 'Could not pay the recipient');

        _feeAddress.transfer(_feeAmount);

        // transfer the remaining ethers to the sender
        (bool sendBackSuccess, ) = payable(msg.sender).call{
            value: msg.value - _amount - _feeAmount
        }('');
        require(sendBackSuccess, 'Could not send remaining funds to the payer');

        emit TransferWithReferenceAndFee(_to, _amount, _paymentReference, _feeAmount, _feeAddress);
    }
}

@openzeppelin/contracts/access/Ownable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which provides a basic access control mechanism, where
 * there is an account (an owner) that can be granted exclusive access to
 * specific functions.
 *
 * By default, the owner account will be the one that deploys the contract. This
 * can later be changed with {transferOwnership}.
 *
 * This module is used through inheritance. It will make available the modifier
 * `onlyOwner`, which can be applied to your functions to restrict their use to
 * the owner.
 */
abstract contract Ownable is Context {
    address private _owner;

    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);

    /**
     * @dev Initializes the contract setting the deployer as the initial owner.
     */
    constructor() {
        _transferOwnership(_msgSender());
    }

    /**
     * @dev Returns the address of the current owner.
     */
    function owner() public view virtual returns (address) {
        return _owner;
    }

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(owner() == _msgSender(), "Ownable: caller is not the owner");
        _;
    }

    /**
     * @dev Leaves the contract without owner. It will not be possible to call
     * `onlyOwner` functions anymore. Can only be called by the current owner.
     *
     * NOTE: Renouncing ownership will leave the contract without an owner,
     * thereby removing any functionality that is only available to the owner.
     */
    function renounceOwnership() public virtual onlyOwner {
        _transferOwnership(address(0));
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Can only be called by the current owner.
     */
    function transferOwnership(address newOwner) public virtual onlyOwner {
        require(newOwner != address(0), "Ownable: new owner is the zero address");
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers ownership of the contract to a new account (`newOwner`).
     * Internal function without access restriction.
     */
    function _transferOwnership(address newOwner) internal virtual {
        address oldOwner = _owner;
        _owner = newOwner;
        emit OwnershipTransferred(oldOwner, newOwner);
    }
}

@openzeppelin/contracts/security/Pausable.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)

pragma solidity ^0.8.0;

import "../utils/Context.sol";

/**
 * @dev Contract module which allows children to implement an emergency stop
 * mechanism that can be triggered by an authorized account.
 *
 * This module is used through inheritance. It will make available the
 * modifiers `whenNotPaused` and `whenPaused`, which can be applied to
 * the functions of your contract. Note that they will not be pausable by
 * simply including this module, only once the modifiers are put in place.
 */
abstract contract Pausable is Context {
    /**
     * @dev Emitted when the pause is triggered by `account`.
     */
    event Paused(address account);

    /**
     * @dev Emitted when the pause is lifted by `account`.
     */
    event Unpaused(address account);

    bool private _paused;

    /**
     * @dev Initializes the contract in unpaused state.
     */
    constructor() {
        _paused = false;
    }

    /**
     * @dev Returns true if the contract is paused, and false otherwise.
     */
    function paused() public view virtual returns (bool) {
        return _paused;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    modifier whenNotPaused() {
        require(!paused(), "Pausable: paused");
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    modifier whenPaused() {
        require(paused(), "Pausable: not paused");
        _;
    }

    /**
     * @dev Triggers stopped state.
     *
     * Requirements:
     *
     * - The contract must not be paused.
     */
    function _pause() internal virtual whenNotPaused {
        _paused = true;
        emit Paused(_msgSender());
    }

    /**
     * @dev Returns to normal state.
     *
     * Requirements:
     *
     * - The contract must be paused.
     */
    function _unpause() internal virtual whenPaused {
        _paused = false;
        emit Unpaused(_msgSender());
    }
}

@openzeppelin/contracts/security/ReentrancyGuard.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)

pragma solidity ^0.8.0;

/**
 * @dev Contract module that helps prevent reentrant calls to a function.
 *
 * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
 * available, which can be applied to functions to make sure there are no nested
 * (reentrant) calls to them.
 *
 * Note that because there is a single `nonReentrant` guard, functions marked as
 * `nonReentrant` may not call one another. This can be worked around by making
 * those functions `private`, and then adding `external` `nonReentrant` entry
 * points to them.
 *
 * TIP: If you would like to learn more about reentrancy and alternative ways
 * to protect against it, check out our blog post
 * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
 */
abstract contract ReentrancyGuard {
    // Booleans are more expensive than uint256 or any type that takes up a full
    // word because each write operation emits an extra SLOAD to first read the
    // slot's contents, replace the bits taken up by the boolean, and then write
    // back. This is the compiler's defense against contract upgrades and
    // pointer aliasing, and it cannot be disabled.

    // The values being non-zero value makes deployment a bit more expensive,
    // but in exchange the refund on every call to nonReentrant will be lower in
    // amount. Since refunds are capped to a percentage of the total
    // transaction's gas, it is best to keep them low in cases like this one, to
    // increase the likelihood of the full refund coming into effect.
    uint256 private constant _NOT_ENTERED = 1;
    uint256 private constant _ENTERED = 2;

    uint256 private _status;

    constructor() {
        _status = _NOT_ENTERED;
    }

    /**
     * @dev Prevents a contract from calling itself, directly or indirectly.
     * Calling a `nonReentrant` function from another `nonReentrant`
     * function is not supported. It is possible to prevent this from happening
     * by making the `nonReentrant` function external, and making it call a
     * `private` function that does the actual work.
     */
    modifier nonReentrant() {
        // On the first call to nonReentrant, _notEntered will be true
        require(_status != _ENTERED, "ReentrancyGuard: reentrant call");

        // Any calls to nonReentrant after this point will fail
        _status = _ENTERED;

        _;

        // By storing the original value once again, a refund is triggered (see
        // https://eips.ethereum.org/EIPS/eip-2200)
        _status = _NOT_ENTERED;
    }
}

@openzeppelin/contracts/token/ERC20/ERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)

pragma solidity ^0.8.0;

import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";

/**
 * @dev Implementation of the {IERC20} interface.
 *
 * This implementation is agnostic to the way tokens are created. This means
 * that a supply mechanism has to be added in a derived contract using {_mint}.
 * For a generic mechanism see {ERC20PresetMinterPauser}.
 *
 * TIP: For a detailed writeup see our guide
 * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
 * to implement supply mechanisms].
 *
 * We have followed general OpenZeppelin Contracts guidelines: functions revert
 * instead returning `false` on failure. This behavior is nonetheless
 * conventional and does not conflict with the expectations of ERC20
 * applications.
 *
 * Additionally, an {Approval} event is emitted on calls to {transferFrom}.
 * This allows applications to reconstruct the allowance for all accounts just
 * by listening to said events. Other implementations of the EIP may not emit
 * these events, as it isn't required by the specification.
 *
 * Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
 * functions have been added to mitigate the well-known issues around setting
 * allowances. See {IERC20-approve}.
 */
contract ERC20 is Context, IERC20, IERC20Metadata {
    mapping(address => uint256) private _balances;

    mapping(address => mapping(address => uint256)) private _allowances;

    uint256 private _totalSupply;

    string private _name;
    string private _symbol;

    /**
     * @dev Sets the values for {name} and {symbol}.
     *
     * The default value of {decimals} is 18. To select a different value for
     * {decimals} you should overload it.
     *
     * All two of these values are immutable: they can only be set once during
     * construction.
     */
    constructor(string memory name_, string memory symbol_) {
        _name = name_;
        _symbol = symbol_;
    }

    /**
     * @dev Returns the name of the token.
     */
    function name() public view virtual override returns (string memory) {
        return _name;
    }

    /**
     * @dev Returns the symbol of the token, usually a shorter version of the
     * name.
     */
    function symbol() public view virtual override returns (string memory) {
        return _symbol;
    }

    /**
     * @dev Returns the number of decimals used to get its user representation.
     * For example, if `decimals` equals `2`, a balance of `505` tokens should
     * be displayed to a user as `5.05` (`505 / 10 ** 2`).
     *
     * Tokens usually opt for a value of 18, imitating the relationship between
     * Ether and Wei. This is the value {ERC20} uses, unless this function is
     * overridden;
     *
     * NOTE: This information is only used for _display_ purposes: it in
     * no way affects any of the arithmetic of the contract, including
     * {IERC20-balanceOf} and {IERC20-transfer}.
     */
    function decimals() public view virtual override returns (uint8) {
        return 18;
    }

    /**
     * @dev See {IERC20-totalSupply}.
     */
    function totalSupply() public view virtual override returns (uint256) {
        return _totalSupply;
    }

    /**
     * @dev See {IERC20-balanceOf}.
     */
    function balanceOf(address account) public view virtual override returns (uint256) {
        return _balances[account];
    }

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `recipient` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
        _transfer(_msgSender(), recipient, amount);
        return true;
    }

    /**
     * @dev See {IERC20-allowance}.
     */
    function allowance(address owner, address spender) public view virtual override returns (uint256) {
        return _allowances[owner][spender];
    }

    /**
     * @dev See {IERC20-approve}.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function approve(address spender, uint256 amount) public virtual override returns (bool) {
        _approve(_msgSender(), spender, amount);
        return true;
    }

    /**
     * @dev See {IERC20-transferFrom}.
     *
     * Emits an {Approval} event indicating the updated allowance. This is not
     * required by the EIP. See the note at the beginning of {ERC20}.
     *
     * Requirements:
     *
     * - `sender` and `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     * - the caller must have allowance for ``sender``'s tokens of at least
     * `amount`.
     */
    function transferFrom(
        address sender,
        address recipient,
        uint256 amount
    ) public virtual override returns (bool) {
        _transfer(sender, recipient, amount);

        uint256 currentAllowance = _allowances[sender][_msgSender()];
        require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
        unchecked {
            _approve(sender, _msgSender(), currentAllowance - amount);
        }

        return true;
    }

    /**
     * @dev Atomically increases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     */
    function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
        _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
        return true;
    }

    /**
     * @dev Atomically decreases the allowance granted to `spender` by the caller.
     *
     * This is an alternative to {approve} that can be used as a mitigation for
     * problems described in {IERC20-approve}.
     *
     * Emits an {Approval} event indicating the updated allowance.
     *
     * Requirements:
     *
     * - `spender` cannot be the zero address.
     * - `spender` must have allowance for the caller of at least
     * `subtractedValue`.
     */
    function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
        uint256 currentAllowance = _allowances[_msgSender()][spender];
        require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
        unchecked {
            _approve(_msgSender(), spender, currentAllowance - subtractedValue);
        }

        return true;
    }

    /**
     * @dev Moves `amount` of tokens from `sender` to `recipient`.
     *
     * This internal function is equivalent to {transfer}, and can be used to
     * e.g. implement automatic token fees, slashing mechanisms, etc.
     *
     * Emits a {Transfer} event.
     *
     * Requirements:
     *
     * - `sender` cannot be the zero address.
     * - `recipient` cannot be the zero address.
     * - `sender` must have a balance of at least `amount`.
     */
    function _transfer(
        address sender,
        address recipient,
        uint256 amount
    ) internal virtual {
        require(sender != address(0), "ERC20: transfer from the zero address");
        require(recipient != address(0), "ERC20: transfer to the zero address");

        _beforeTokenTransfer(sender, recipient, amount);

        uint256 senderBalance = _balances[sender];
        require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
        unchecked {
            _balances[sender] = senderBalance - amount;
        }
        _balances[recipient] += amount;

        emit Transfer(sender, recipient, amount);

        _afterTokenTransfer(sender, recipient, amount);
    }

    /** @dev Creates `amount` tokens and assigns them to `account`, increasing
     * the total supply.
     *
     * Emits a {Transfer} event with `from` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     */
    function _mint(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: mint to the zero address");

        _beforeTokenTransfer(address(0), account, amount);

        _totalSupply += amount;
        _balances[account] += amount;
        emit Transfer(address(0), account, amount);

        _afterTokenTransfer(address(0), account, amount);
    }

    /**
     * @dev Destroys `amount` tokens from `account`, reducing the
     * total supply.
     *
     * Emits a {Transfer} event with `to` set to the zero address.
     *
     * Requirements:
     *
     * - `account` cannot be the zero address.
     * - `account` must have at least `amount` tokens.
     */
    function _burn(address account, uint256 amount) internal virtual {
        require(account != address(0), "ERC20: burn from the zero address");

        _beforeTokenTransfer(account, address(0), amount);

        uint256 accountBalance = _balances[account];
        require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
        unchecked {
            _balances[account] = accountBalance - amount;
        }
        _totalSupply -= amount;

        emit Transfer(account, address(0), amount);

        _afterTokenTransfer(account, address(0), amount);
    }

    /**
     * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
     *
     * This internal function is equivalent to `approve`, and can be used to
     * e.g. set automatic allowances for certain subsystems, etc.
     *
     * Emits an {Approval} event.
     *
     * Requirements:
     *
     * - `owner` cannot be the zero address.
     * - `spender` cannot be the zero address.
     */
    function _approve(
        address owner,
        address spender,
        uint256 amount
    ) internal virtual {
        require(owner != address(0), "ERC20: approve from the zero address");
        require(spender != address(0), "ERC20: approve to the zero address");

        _allowances[owner][spender] = amount;
        emit Approval(owner, spender, amount);
    }

    /**
     * @dev Hook that is called before any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * will be transferred to `to`.
     * - when `from` is zero, `amount` tokens will be minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens will be burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _beforeTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}

    /**
     * @dev Hook that is called after any transfer of tokens. This includes
     * minting and burning.
     *
     * Calling conditions:
     *
     * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
     * has been transferred to `to`.
     * - when `from` is zero, `amount` tokens have been minted for `to`.
     * - when `to` is zero, `amount` of ``from``'s tokens have been burned.
     * - `from` and `to` are never both zero.
     *
     * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
     */
    function _afterTokenTransfer(
        address from,
        address to,
        uint256 amount
    ) internal virtual {}
}

@openzeppelin/contracts/token/ERC20/IERC20.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface of the ERC20 standard as defined in the EIP.
 */
interface IERC20 {
    /**
     * @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 `recipient`.
     *
     * Returns a boolean value indicating whether the operation succeeded.
     *
     * Emits a {Transfer} event.
     */
    function transfer(address recipient, 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 `sender` to `recipient` 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 sender,
        address recipient,
        uint256 amount
    ) external returns (bool);

    /**
     * @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);
}

@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)

pragma solidity ^0.8.0;

import "../IERC20.sol";

/**
 * @dev Interface for the optional metadata functions from the ERC20 standard.
 *
 * _Available since v4.1._
 */
interface IERC20Metadata is IERC20 {
    /**
     * @dev Returns the name of the token.
     */
    function name() external view returns (string memory);

    /**
     * @dev Returns the symbol of the token.
     */
    function symbol() external view returns (string memory);

    /**
     * @dev Returns the decimals places of the token.
     */
    function decimals() external view returns (uint8);
}

@openzeppelin/contracts/utils/Context.sol

// 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;
    }
}

@openzeppelin/contracts/utils/Create2.sol

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

pragma solidity ^0.8.0;

/**
 * @dev Helper to make usage of the `CREATE2` EVM opcode easier and safer.
 * `CREATE2` can be used to compute in advance the address where a smart
 * contract will be deployed, which allows for interesting new mechanisms known
 * as 'counterfactual interactions'.
 *
 * See the https://eips.ethereum.org/EIPS/eip-1014#motivation[EIP] for more
 * information.
 */
library Create2 {
    /**
     * @dev Deploys a contract using `CREATE2`. The address where the contract
     * will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     *
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `amount`.
     * - if `amount` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(
        uint256 amount,
        bytes32 salt,
        bytes memory bytecode
    ) internal returns (address) {
        address addr;
        require(address(this).balance >= amount, "Create2: insufficient balance");
        require(bytecode.length != 0, "Create2: bytecode length is zero");
        assembly {
            addr := create2(amount, add(bytecode, 0x20), mload(bytecode), salt)
        }
        require(addr != address(0), "Create2: Failed on deploy");
        return addr;
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}. Any change in the
     * `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 bytecodeHash) internal view returns (address) {
        return computeAddress(salt, bytecodeHash, address(this));
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a contract located at
     * `deployer`. If `deployer` is this contract's address, returns the same value as {computeAddress}.
     */
    function computeAddress(
        bytes32 salt,
        bytes32 bytecodeHash,
        address deployer
    ) internal pure returns (address) {
        bytes32 _data = keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, bytecodeHash));
        return address(uint160(uint256(_data)));
    }
}

@openzeppelin/contracts/utils/introspection/ERC1820Implementer.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC1820Implementer.sol)

pragma solidity ^0.8.0;

import "./IERC1820Implementer.sol";

/**
 * @dev Implementation of the {IERC1820Implementer} interface.
 *
 * Contracts may inherit from this and call {_registerInterfaceForAddress} to
 * declare their willingness to be implementers.
 * {IERC1820Registry-setInterfaceImplementer} should then be called for the
 * registration to be complete.
 */
contract ERC1820Implementer is IERC1820Implementer {
    bytes32 private constant _ERC1820_ACCEPT_MAGIC = keccak256("ERC1820_ACCEPT_MAGIC");

    mapping(bytes32 => mapping(address => bool)) private _supportedInterfaces;

    /**
     * @dev See {IERC1820Implementer-canImplementInterfaceForAddress}.
     */
    function canImplementInterfaceForAddress(bytes32 interfaceHash, address account)
        public
        view
        virtual
        override
        returns (bytes32)
    {
        return _supportedInterfaces[interfaceHash][account] ? _ERC1820_ACCEPT_MAGIC : bytes32(0x00);
    }

    /**
     * @dev Declares the contract as willing to be an implementer of
     * `interfaceHash` for `account`.
     *
     * See {IERC1820Registry-setInterfaceImplementer} and
     * {IERC1820Registry-interfaceHash}.
     */
    function _registerInterfaceForAddress(bytes32 interfaceHash, address account) internal virtual {
        _supportedInterfaces[interfaceHash][account] = true;
    }
}

@openzeppelin/contracts/utils/introspection/IERC1820Implementer.sol

// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Implementer.sol)

pragma solidity ^0.8.0;

/**
 * @dev Interface for an ERC1820 implementer, as defined in the
 * https://eips.ethereum.org/EIPS/eip-1820#interface-implementation-erc1820implementerinterface[EIP].
 * Used by contracts that will be registered as implementers in the
 * {IERC1820Registry}.
 */
interface IERC1820Implementer {
    /**
     * @dev Returns a special value (`ERC1820_ACCEPT_MAGIC`) if this contract
     * implements `interfaceHash` for `account`.
     *
     * See {IERC1820Registry-setInterfaceImplementer}.
     */
    function canImplementInterfaceForAddress(bytes32 interfaceHash, address account) external view returns (bytes32);
}

src/contracts/BadERC20.sol

// SPDX-License-Identifier: MIT
/**
 * Bad ERC20 token with no return values from transfer and transferFrom
 */
pragma solidity ^0.8.0;

import '@openzeppelin/contracts/access/Ownable.sol';

/**
 * @title ERC20Basic
 * @dev Simpler version of ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
abstract contract ERC20Basic {
    uint256 public _totalSupply;

    function totalSupply() public view virtual returns (uint256);

    function balanceOf(address who) public view virtual returns (uint256);

    function transfer(address to, uint256 value) public virtual;

    event Transfer(address indexed from, address indexed to, uint256 value);
}

/**
 * @title ERC20 interface
 * @dev see https://github.com/ethereum/EIPs/issues/20
 */
abstract contract ERC20 is ERC20Basic {
    function allowance(address owner, address spender) public view virtual returns (uint256);

    function transferFrom(
        address from,
        address to,
        uint256 value
    ) public virtual;

    function approve(address spender, uint256 value) public virtual;

    event Approval(address indexed owner, address indexed spender, uint256 value);
}

/**
 * @title Basic token
 * @dev Basic version of StandardToken, with no allowances.
 */
abstract contract BasicToken is Ownable, ERC20Basic {
    mapping(address => uint256) public balances;

    // additional variables for use if transaction fees ever became necessary
    uint256 public basisPointsRate = 0;
    uint256 public maximumFee = 0;

    /**
     * @dev Fix for the ERC20 short address attack.
     */
    modifier onlyPayloadSize(uint256 size) {
        require(!(msg.data.length < size + 4), '');
        _;
    }

    /**
     * @dev transfer token for a specified address
     * @param _to The address to transfer to.
     * @param _value The amount to be transferred.
     */
    function transfer(address _to, uint256 _value) public virtual override onlyPayloadSize(2 * 32) {
        uint256 fee = (_value * basisPointsRate) / 10000;
        if (fee > maximumFee) {
            fee = maximumFee;
        }
        uint256 sendAmount = _value - fee;
        balances[msg.sender] = balances[msg.sender] - _value;
        balances[_to] = balances[_to] + sendAmount;
        if (fee > 0) {
            balances[owner()] = balances[owner()] + fee;
            emit Transfer(msg.sender, owner(), fee);
        }
        emit Transfer(msg.sender, _to, sendAmount);
    }

    /**
     * @dev Gets the balance of the specified address.
     * @param _owner The address to query the the balance of.
     * @return balance An uint representing the amount owned by the passed address.
     */
    function balanceOf(address _owner) public view virtual override returns (uint256 balance) {
        return balances[_owner];
    }
}

/**
 * @title Standard ERC20 token
 *
 * @dev Implementation of the basic standard token.
 * @dev https://github.com/ethereum/EIPs/issues/20
 * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
 */
abstract contract StandardToken is BasicToken, ERC20 {
    mapping(address => mapping(address => uint256)) public allowed;

    uint256 public constant MAX_UINT = 2**256 - 1;

    /**
     * @dev Transfer tokens from one address to another
     * @param _from address The address which you want to send tokens from
     * @param _to address The address which you want to transfer to
     * @param _value uint the amount of tokens to be transferred
     */
    function transferFrom(
        address _from,
        address _to,
        uint256 _value
    ) public virtual override onlyPayloadSize(3 * 32) {
        uint256 _allowance = allowed[_from][msg.sender];

        // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
        // if (_value > _allowance) throw;

        uint256 fee = (_value * basisPointsRate) / 10000;
        if (fee > maximumFee) {
            fee = maximumFee;
        }
        if (_allowance < MAX_UINT) {
            allowed[_from][msg.sender] = _allowance - _value;
        }
        uint256 sendAmount = _value - fee;
        balances[_from] = balances[_from] - _value;
        balances[_to] = balances[_to] + sendAmount;
        if (fee > 0) {
            balances[owner()] = balances[owner()] + fee;
            emit Transfer(_from, owner(), fee);
        }
        emit Transfer(_from, _to, sendAmount);
    }

    /**
     * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
     * @param _spender The address which will spend the funds.
     * @param _value The amount of tokens to be spent.
     */
    function approve(address _spender, uint256 _value)
        public
        virtual
        override
        onlyPayloadSize(2 * 32)
    {
        // To change the approve amount you first have to reduce the addresses`
        //  allowance to zero by calling `approve(_spender, 0)` if it is not
        //  already 0 to mitigate the race condition described here:
        //  https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
        require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)), '');

        allowed[msg.sender][_spender] = _value;
        emit Approval(msg.sender, _spender, _value);
    }

    /**
     * @dev Function to check the amount of tokens than an owner allowed to a spender.
     * @param _owner address The address which owns the funds.
     * @param _spender address The address which will spend the funds.
     * @return remaining A uint specifying the amount of tokens still available for the spender.
     */
    function allowance(address _owner, address _spender)
        public
        view
        virtual
        override
        returns (uint256 remaining)
    {
        return allowed[_owner][_spender];
    }
}

/**
 * @title Pausable
 * @dev Base contract which allows children to implement an emergency stop mechanism.
 */
contract Pausable is Ownable {
    event Pause();
    event Unpause();

    bool public paused = false;

    /**
     * @dev Modifier to make a function callable only when the contract is not paused.
     */
    modifier whenNotPaused() {
        require(!paused, '');
        _;
    }

    /**
     * @dev Modifier to make a function callable only when the contract is paused.
     */
    modifier whenPaused() {
        require(paused, '');
        _;
    }

    /**
     * @dev called by the owner to pause, triggers stopped state
     */
    function pause() public onlyOwner whenNotPaused {
        paused = true;
        emit Pause();
    }

    /**
     * @dev called by the owner to unpause, returns to normal state
     */
    function unpause() public onlyOwner whenPaused {
        paused = false;
        emit Unpause();
    }
}

abstract contract BlackList is Ownable, BasicToken {
    /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded) ///////
    function getBlackListStatus(address _maker) external view returns (bool) {
        return isBlackListed[_maker];
    }

    function getOwner() external view returns (address) {
        return owner();
    }

    mapping(address => bool) public isBlackListed;

    function addBlackList(address _evilUser) public onlyOwner {
        isBlackListed[_evilUser] = true;
        emit AddedBlackList(_evilUser);
    }

    function removeBlackList(address _clearedUser) public onlyOwner {
        isBlackListed[_clearedUser] = false;
        emit RemovedBlackList(_clearedUser);
    }

    function destroyBlackFunds(address _blackListedUser) public onlyOwner {
        require(isBlackListed[_blackListedUser], '');
        uint256 dirtyFunds = balanceOf(_blackListedUser);
        balances[_blackListedUser] = 0;
        _totalSupply -= dirtyFunds;
        emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
    }

    event DestroyedBlackFunds(address _blackListedUser, uint256 _balance);

    event AddedBlackList(address _user);

    event RemovedBlackList(address _user);
}

abstract contract UpgradedStandardToken is StandardToken {
    // those methods are called by the legacy contract
    // and they must ensure msg.sender to be the contract address
    function transferByLegacy(
        address from,
        address to,
        uint256 value
    ) public virtual;

    function transferFromByLegacy(
        address sender,
        address from,
        address spender,
        uint256 value
    ) public virtual;

    function approveByLegacy(
        address from,
        address spender,
        uint256 value
    ) public virtual;
}

contract BadERC20 is Pausable, StandardToken, BlackList {
    string public name;
    string public symbol;
    uint256 public decimals;
    address public upgradedAddress;
    bool public deprecated;

    //  The contract can be initialized with a number of tokens
    //  All the tokens are deposited to the owner address
    //
    // @param _balance Initial supply of the contract
    // @param _name Token Name
    // @param _symbol Token symbol
    // @param _decimals Token decimals
    constructor(
        uint256 _initialSupply,
        string memory _name,
        string memory _symbol,
        uint256 _decimals
    ) {
        _totalSupply = _initialSupply;
        name = _name;
        symbol = _symbol;
        decimals = _decimals;
        balances[owner()] = _initialSupply;
        deprecated = false;
    }

    // Forward ERC20 methods to upgraded contract if this one is deprecated
    function transfer(address _to, uint256 _value) public override whenNotPaused {
        require(!isBlackListed[msg.sender], '');
        if (deprecated) {
            return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
        } else {
            return super.transfer(_to, _value);
        }
    }

    // Forward ERC20 methods to upgraded contract if this one is deprecated
    function transferFrom(
        address _from,
        address _to,
        uint256 _value
    ) public override whenNotPaused {
        require(!isBlackListed[_from], '');
        if (deprecated) {
            return
                UpgradedStandardToken(upgradedAddress).transferFromByLegacy(
                    msg.sender,
                    _from,
                    _to,
                    _value
                );
        } else {
            return super.transferFrom(_from, _to, _value);
        }
    }

    // Forward ERC20 methods to upgraded contract if this one is deprecated
    function balanceOf(address who) public view override returns (uint256) {
        if (deprecated) {
            return UpgradedStandardToken(upgradedAddress).balanceOf(who);
        } else {
            return super.balanceOf(who);
        }
    }

    // Forward ERC20 methods to upgraded contract if this one is deprecated
    function approve(address _spender, uint256 _value) public override onlyPayloadSize(2 * 32) {
        if (deprecated) {
            return
                UpgradedStandardToken(upgradedAddress).approveByLegacy(
                    msg.sender,
                    _spender,
                    _value
                );
        } else {
            return super.approve(_spender, _value);
        }
    }

    // Forward ERC20 methods to upgraded contract if this one is deprecated
    function allowance(address _owner, address _spender)
        public
        view
        override
        returns (uint256 remaining)
    {
        if (deprecated) {
            return StandardToken(upgradedAddress).allowance(_owner, _spender);
        } else {
            return super.allowance(_owner, _spender);
        }
    }

    // deprecate current contract in favour of a new one
    function deprecate(address _upgradedAddress) public onlyOwner {
        deprecated = true;
        upgradedAddress = _upgradedAddress;
        emit Deprecate(_upgradedAddress);
    }

    // deprecate current contract if favour of a new one
    function totalSupply() public view override returns (uint256) {
        if (deprecated) {
            return StandardToken(upgradedAddress).totalSupply();
        } else {
            return _totalSupply;
        }
    }

    // Issue a new amount of tokens
    // these tokens are deposited into the owner address
    //
    // @param _amount Number of tokens to be issued
    function issue(uint256 amount) public onlyOwner {
        require(_totalSupply + amount > _totalSupply, '');
        require(balances[owner()] + amount > balances[owner()], '');

        balances[owner()] += amount;
        _totalSupply += amount;
        emit Issue(amount);
    }

    // Redeem tokens.
    // These tokens are withdrawn from the owner address
    // if the balance must be enough to cover the redeem
    // or the call will fail.
    // @param _amount Number of tokens to be issued
    function redeem(uint256 amount) public onlyOwner {
        require(_totalSupply >= amount, '');
        require(balances[owner()] >= amount, '');

        _totalSupply -= amount;
        balances[owner()] -= amount;
        emit Redeem(amount);
    }

    function setParams(uint256 newBasisPoints, uint256 newMaxFee) public onlyOwner {
        // Ensure transparency by hardcoding limit beyond which fees can never be added
        require(newBasisPoints < 20, '');
        require(newMaxFee < 50, '');

        basisPointsRate = newBasisPoints;
        maximumFee = newMaxFee * (10**decimals);

        emit Params(basisPointsRate, maximumFee);
    }

    // Called when new token are issued
    event Issue(uint256 amount);

    // Called when tokens are redeemed
    event Redeem(uint256 amount);

    // Called when contract is deprecated
    event Deprecate(address newAddress);

    // Called if contract ever adds fees
    event Params(uint256 feeBasisPoints, uint256 maxFee);
}

src/contracts/Bytes.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/**
 * @title Bytes util library.
 * @notice Collection of utility functions to manipulate bytes for Request.
 */
library Bytes {
  /**
    * @notice Extract a bytes32 from a bytes.
    * @param data bytes from where the bytes32 will be extract
    * @param offset position of the first byte of the bytes32
    * @return result the 32 bytes extracted
    */
  function extractBytes32(bytes memory data, uint offset)
    internal
    pure
    returns (bytes32 result)
  {
    require(offset >= 0 && offset + 32 <= data.length, "offset value should be in the correct range");

    // solium-disable-next-line security/no-inline-assembly
    assembly {
        result := mload(add(data, add(32, offset)))
    }
  }
}

src/contracts/ChainlinkConversionPath.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import './legacy_openzeppelin/contracts/access/roles/WhitelistAdminRole.sol';

interface ERC20fraction {
    function decimals() external view returns (uint8);
}

interface AggregatorFraction {
    function decimals() external view returns (uint8);

    function latestAnswer() external view returns (int256);

    function latestTimestamp() external view returns (uint256);
}

/**
 * @title ChainlinkConversionPath
 *
 * @notice ChainlinkConversionPath is a contract computing currency conversion rates based on Chainlink aggretators
 */
contract ChainlinkConversionPath is WhitelistAdminRole {
    uint256 constant PRECISION = 1e18;
    uint256 constant NATIVE_TOKEN_DECIMALS = 18;
    uint256 constant FIAT_DECIMALS = 8;
    address public nativeTokenHash;

    /**
     * @param _nativeTokenHash hash of the native token
     */
    constructor(address _nativeTokenHash) {
        nativeTokenHash = _nativeTokenHash;
    }

    // Mapping of Chainlink aggregators (input currency => output currency => contract address)
    // input & output currencies are the addresses of the ERC20 contracts OR the sha3("currency code")
    mapping(address => mapping(address => address)) public allAggregators;

    // declare a new aggregator
    event AggregatorUpdated(address _input, address _output, address _aggregator);

    /**
     * @notice Update an aggregator
     * @param _input address representing the input currency
     * @param _output address representing the output currency
     * @param _aggregator address of the aggregator contract
     */
    function updateAggregator(
        address _input,
        address _output,
        address _aggregator
    ) external onlyWhitelistAdmin {
        allAggregators[_input][_output] = _aggregator;
        emit AggregatorUpdated(_input, _output, _aggregator);
    }

    /**
     * @notice Update a list of aggregators
     * @param _inputs list of addresses representing the input currencies
     * @param _outputs list of addresses representing the output currencies
     * @param _aggregators list of addresses of the aggregator contracts
     */
    function updateAggregatorsList(
        address[] calldata _inputs,
        address[] calldata _outputs,
        address[] calldata _aggregators
    ) external onlyWhitelistAdmin {
        require(_inputs.length == _outputs.length, 'arrays must have the same length');
        require(_inputs.length == _aggregators.length, 'arrays must have the same length');

        // For every conversions of the path
        for (uint256 i; i < _inputs.length; i++) {
            allAggregators[_inputs[i]][_outputs[i]] = _aggregators[i];
            emit AggregatorUpdated(_inputs[i], _outputs[i], _aggregators[i]);
        }
    }

    /**
     * @notice Computes the conversion of an amount through a list of intermediate conversions
     * @param _amountIn Amount to convert
     * @param _path List of addresses representing the currencies for the intermediate conversions
     * @return result The result after all the conversions
     * @return oldestRateTimestamp The oldest timestamp of the path
     */
    function getConversion(uint256 _amountIn, address[] calldata _path)
        external
        view
        returns (uint256 result, uint256 oldestRateTimestamp)
    {
        (uint256 rate, uint256 timestamp, uint256 decimals) = getRate(_path);

        // initialize the result
        result = (_amountIn * rate) / decimals;

        oldestRateTimestamp = timestamp;
    }

    /**
     * @notice Computes the conversion rate from a list of currencies
     * @param _path List of addresses representing the currencies for the conversions
     * @return rate The rate
     * @return oldestRateTimestamp The oldest timestamp of the path
     * @return decimals of the conversion rate
     */
    function getRate(address[] memory _path)
        public
        view
        returns (
            uint256 rate,
            uint256 oldestRateTimestamp,
            uint256 decimals
        )
    {
        // initialize the result with 18 decimals (for more precision)
        rate = PRECISION;
        decimals = PRECISION;
        oldestRateTimestamp = block.timestamp;

        // For every conversion of the path
        for (uint256 i; i < _path.length - 1; i++) {
            (
                AggregatorFraction aggregator,
                bool reverseAggregator,
                uint256 decimalsInput,
                uint256 decimalsOutput
            ) = getAggregatorAndDecimals(_path[i], _path[i + 1]);

            // store the latest timestamp of the path
            uint256 currentTimestamp = aggregator.latestTimestamp();
            if (currentTimestamp < oldestRateTimestamp) {
                oldestRateTimestamp = currentTimestamp;
            }

            // get the rate of the current step
            uint256 currentRate = uint256(aggregator.latestAnswer());
            // get the number of decimals of the current rate
            uint256 decimalsAggregator = uint256(aggregator.decimals());

            // mul with the difference of decimals before the current rate computation (for more precision)
            if (decimalsAggregator > decimalsInput) {
                rate = rate * (10**(decimalsAggregator - decimalsInput));
            }
            if (decimalsAggregator < decimalsOutput) {
                rate = rate * (10**(decimalsOutput - decimalsAggregator));
            }

            // Apply the current rate (if path uses an aggregator in the reverse way, div instead of mul)
            if (reverseAggregator) {
                rate = (rate * (10**decimalsAggregator)) / currentRate;
            } else {
                rate = (rate * currentRate) / (10**decimalsAggregator);
            }

            // div with the difference of decimals AFTER the current rate computation (for more precision)
            if (decimalsAggregator < decimalsInput) {
                rate = rate / (10**(decimalsInput - decimalsAggregator));
            }
            if (decimalsAggregator > decimalsOutput) {
                rate = rate / (10**(decimalsAggregator - decimalsOutput));
            }
        }
    }

    /**
     * @notice Gets aggregators and decimals of two currencies
     * @param _input input Address
     * @param _output output Address
     * @return aggregator to get the rate between the two currencies
     * @return reverseAggregator true if the aggregator returned give the rate from _output to _input
     * @return decimalsInput decimals of _input
     * @return decimalsOutput decimals of _output
     */
    function getAggregatorAndDecimals(address _input, address _output)
        private
        view
        returns (
            AggregatorFraction aggregator,
            bool reverseAggregator,
            uint256 decimalsInput,
            uint256 decimalsOutput
        )
    {
        // Try to get the right aggregator for the conversion
        aggregator = AggregatorFraction(allAggregators[_input][_output]);
        reverseAggregator = false;

        // if no aggregator found we try to find an aggregator in the reverse way
        if (address(aggregator) == address(0x00)) {
            aggregator = AggregatorFraction(allAggregators[_output][_input]);
            reverseAggregator = true;
        }

        require(address(aggregator) != address(0x00), 'No aggregator found');

        // get the decimals for the two currencies
        decimalsInput = getDecimals(_input);
        decimalsOutput = getDecimals(_output);
    }

    /**
     * @notice Gets decimals from an address currency
     * @param _addr address to check
     * @return decimals number of decimals
     */
    function getDecimals(address _addr) private view returns (uint256 decimals) {
        // by default we assume it is fiat
        decimals = FIAT_DECIMALS;
        // if address is the hash of the ETH currency
        if (_addr == nativeTokenHash) {
            decimals = NATIVE_TOKEN_DECIMALS;
        } else if (isContract(_addr)) {
            // otherwise, we get the decimals from the erc20 directly
            decimals = ERC20fraction(_addr).decimals();
        }
    }

    /**
     * @notice Checks if an address is a contract
     * @param _addr Address to check
     * @return true if the address hosts a contract, false otherwise
     */
    function isContract(address _addr) private view returns (bool) {
        uint32 size;
        // solium-disable security/no-inline-assembly
        assembly {
            size := extcodesize(_addr)
        }
        return (size > 0);
    }
}

src/contracts/ERC20EscrowToPay.sol

/// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./lib/SafeERC20.sol";
import "./interfaces/ERC20FeeProxy.sol";

/**
 * @title   ERC20EscrowToPay
 * @notice  Request Invoice with Escrow.
 */
contract ERC20EscrowToPay {
    using SafeERC20 for IERC20;

    IERC20FeeProxy public paymentProxy;

    struct Request {
        address tokenAddress;
        address payee;
        address payer;
        uint256 amount;
        uint256 unlockDate;
        uint256 emergencyClaimDate;
        bool emergencyState;
        bool isFrozen;
    }

    /**
    * @notice Mapping is used to store the Requests in escrow. 
    */
    mapping(bytes => Request) public requestMapping;

    /**
    * @notice Modifier checks if msg.sender is the requestpayment payer.
    * @param _paymentRef Reference of the requestpayment related.
    * @dev It requires msg.sender to be equal to requestMapping[_paymentRef].payer. 
    */
    modifier OnlyPayer(bytes memory _paymentRef) {
        require(msg.sender == requestMapping[_paymentRef].payer, "Not Authorized.");
        _;
    }
    
    /**
    * @notice Modifier checks if msg.sender is the requestpayment payee.
    * @param _paymentRef Reference of the requestpayment related.
    * @dev It requires msg.sender to be equal to requestMapping[_paymentRef].payee. 
    */
    modifier OnlyPayee(bytes memory _paymentRef) {
        require(msg.sender == requestMapping[_paymentRef].payee, "Not Authorized."); 
        _;
    }

    /**
    * @notice Modifier checks that the request is not already is in escrow.
    * @param _paymentRef Reference of the payment related.
    * @dev It requires the requestMapping[_paymentRef].amount to be zero.
    */
    modifier IsNotInEscrow(bytes memory _paymentRef) {
        require(requestMapping[_paymentRef].amount == 0, "Already in Escrow.");
        _;
    }

    /**
    * @notice Modifier checks if the request already is in escrow.
    * @param _paymentRef Reference of the payment related.
    * @dev It requires the requestMapping[_paymentRef].amount to have a value above zero.
    */
    modifier IsInEscrow(bytes memory _paymentRef) {
        require(requestMapping[_paymentRef].amount > 0, "Not in escrow.");
        _;
    }

    /**
    * @notice Modifier checks if the request already is in emergencyState.
    * @param _paymentRef Reference of the payment related.
    * @dev It requires the requestMapping[_paymentRef].emergencyState to be false.
    */
    modifier IsNotInEmergencyState(bytes memory _paymentRef) {
        require(!requestMapping[_paymentRef].emergencyState, "In emergencyState");
        _;
    }

    /**
    * @notice Modifier checks that the request is not frozen.
    * @param _paymentRef Reference of the payment related.
    * @dev It requires the requestMapping[_paymentRef].isFrozen to be false.
    */
    modifier IsNotFrozen(bytes memory _paymentRef) {
        require(!requestMapping[_paymentRef].isFrozen, "Request Frozen!");
        _;
    }

    /**
     * @notice Emitted when a request has been frozen.
     * @param paymentReference Reference of the payment related.
     */
    event RequestFrozen(bytes indexed paymentReference);
 
    /**
     * @notice Emitted when an emergency claim is initiated by payee.
     * @param paymentReference Reference of the payment related.
     */
    event InitiatedEmergencyClaim(bytes indexed paymentReference);

    /**
     * @notice Emitted when an emergency claim has been reverted by payer.
     * @param paymentReference Reference of the payment related.
     */
    event RevertedEmergencyClaim(bytes indexed paymentReference);

    /**
     * @notice Emitted when transaction to and from the escrow has been executed.
     * @param tokenAddress Address of the ERC20 token smart contract.
     * @param to Address to the payment issuer, alias payee.
     * @param amount Amount transfered.
     * @param paymentReference Reference of the payment related.
     * @param feeAmount Set to zero when emited by _withdraw function.
     * @param feeAddress Set to address(0) when emited by _withdraw function. 
     */
    event TransferWithReferenceAndFee(
        address tokenAddress,
        address to,
        uint256 amount,
        bytes indexed paymentReference,
        uint256 feeAmount,
        address feeAddress
    );

    constructor(address _paymentProxyAddress) {
        paymentProxy = IERC20FeeProxy(_paymentProxyAddress);
    }

    /**
     * @notice receive function reverts and returns the funds to the sender.
     */ 
    receive() external payable {
        revert("not payable receive");
    }

    /** 
    * @notice Stores the invoice details, and transfers funds to this Escrow contract.
    * @param _tokenAddress Address of the ERC20 token smart contract.
    * @param _to Address to the payment issuer, alias payee.
    * @param _amount Amount to transfer.
    * @param _paymentRef Reference of the payment related.
    * @param _feeAmount Amount of fee to be paid.
    * @param _feeAddress Address to where the fees will be paid.
    * @dev Uses modifier IsNotInEscrow.
    * @dev Uses transferFromWithReferenceAndFee() to transfer funds from the msg.sender, 
    * into the escrowcontract and pays the _fees to the _feeAdress.
    * @dev Emits RequestInEscrow(_paymentRef) when the funds are in escrow.
    */
    function payEscrow(
        address _tokenAddress,
        address _to,
        uint256 _amount,
        bytes memory _paymentRef,
        uint256 _feeAmount,
        address _feeAddress
    )   
        external 
        IsNotInEscrow(_paymentRef)
    {   
        if (_amount == 0 || _feeAmount == 0) revert("Zero Value");

        requestMapping[_paymentRef] = Request(
            _tokenAddress,
            _to,
            msg.sender,
            _amount,
            0,
            0,
            false,
            false
        );
        
        (bool status, ) = address(paymentProxy).delegatecall(
        abi.encodeWithSignature(
        "transferFromWithReferenceAndFee(address,address,uint256,bytes,uint256,address)",
            _tokenAddress,
            address(this),
            _amount,
            _paymentRef,
            _feeAmount,
            _feeAddress
            )
        );
        require(status, "transferFromWithReferenceAndFee failed");
    }
    
    /**
     * @notice Locks the request funds for the payer to recover them
     *         after 12 months and cancel any emergency claim.
     * @param _paymentRef Reference of the Invoice related.
     * @dev Uses modifiers OnlyPayer, IsInEscrow and IsNotFrozen.
     * @dev unlockDate is set with block.timestamp + twelve months..
     */
    function freezeRequest(bytes memory _paymentRef) 
        external
        OnlyPayer(_paymentRef)
        IsInEscrow(_paymentRef)
        IsNotFrozen(_paymentRef)
    {
        if (requestMapping[_paymentRef].emergencyState) 
        {
            requestMapping[_paymentRef].emergencyState = false;
            requestMapping[_paymentRef].emergencyClaimDate = 0;
            emit RevertedEmergencyClaim(_paymentRef);
        }

        requestMapping[_paymentRef].isFrozen = true; 
        requestMapping[_paymentRef].unlockDate = block.timestamp + 52 weeks;

        emit RequestFrozen(_paymentRef);
    }

    /**
     * @notice Closes an open escrow and pays the request to payee.
     * @param _paymentRef Reference of the related Invoice.
     * @dev Uses OnlyPayer, IsInEscrow, IsNotInEmergencyState and IsNotFrozen.
     */
    function payRequestFromEscrow(bytes memory _paymentRef) 
        external 
        OnlyPayer(_paymentRef) 
        IsInEscrow(_paymentRef)
        IsNotInEmergencyState(_paymentRef)
        IsNotFrozen(_paymentRef) 
    {
        require(_withdraw(_paymentRef, requestMapping[_paymentRef].payee), "Withdraw Failed!");
    }

    /**
     * @notice Allows the payee to initiate an emergency claim after a six months lockperiod .
     * @param _paymentRef Reference of the related Invoice.
     * @dev Uses modifiers OnlyPayee, IsInEscrow, IsNotInEmergencyState and IsNotFrozen.
     */
    function initiateEmergencyClaim(bytes memory _paymentRef) 
        external
        OnlyPayee(_paymentRef)
        IsInEscrow(_paymentRef)
        IsNotInEmergencyState(_paymentRef)
        IsNotFrozen(_paymentRef)
    {
        requestMapping[_paymentRef].emergencyClaimDate = block.timestamp + 24 weeks;
        requestMapping[_paymentRef].emergencyState = true;

        emit InitiatedEmergencyClaim(_paymentRef);
    }

    /**
     * @notice Allows the payee claim funds after a six months emergency lockperiod .
     * @param _paymentRef Reference of the related Invoice.
     * @dev Uses modifiers OnlyPayee, IsInEscrow and IsNotFrozen.
     */
    function completeEmergencyClaim(bytes memory _paymentRef) 
        external
        OnlyPayee(_paymentRef)
        IsInEscrow(_paymentRef)
        IsNotFrozen(_paymentRef)
    {
        require(requestMapping[_paymentRef].emergencyState && 
            requestMapping[_paymentRef].emergencyClaimDate <= block.timestamp, 
            "Not yet!"
        );

        requestMapping[_paymentRef].emergencyState = false;
        requestMapping[_paymentRef].emergencyClaimDate = 0;

        require(_withdraw(_paymentRef, requestMapping[_paymentRef].payee), "Withdraw failed!");
    }

    /**
     * @notice Reverts the emergencyState to false and cancels emergencyClaim.
     * @param _paymentRef Reference of the Invoice related.
     * @dev Uses modifiers OnlyPayer, IsInEscrow and IsNotFrozen.
     * @dev Resets emergencyState to false and emergencyClaimDate to zero.
     */
    function revertEmergencyClaim(bytes memory _paymentRef) 
        external
        OnlyPayer(_paymentRef)
        IsInEscrow(_paymentRef)
        IsNotFrozen(_paymentRef)
    {
        require(requestMapping[_paymentRef].emergencyState, "EmergencyClaim NOT initiated"); 
        requestMapping[_paymentRef].emergencyState = false;
        requestMapping[_paymentRef].emergencyClaimDate = 0;
        
        emit RevertedEmergencyClaim(_paymentRef);
    }

    /**
     * @notice Refunds to payer after twelve months and delete the escrow.
     * @param  _paymentRef Reference of the Invoice related.
     * @dev requires that the request .isFrozen = true and .unlockDate to
     *      be lower or equal to block.timestamp.
     */
    function refundFrozenFunds(bytes memory _paymentRef) 
        external 
        IsInEscrow(_paymentRef)
        IsNotInEmergencyState(_paymentRef)
    {
        require(requestMapping[_paymentRef].isFrozen, "Not frozen!");
        require(requestMapping[_paymentRef].unlockDate <= block.timestamp, "Not Yet!");

        requestMapping[_paymentRef].isFrozen = false;
        
        require(_withdraw(_paymentRef, requestMapping[_paymentRef].payer), "Withdraw Failed!");
    }
    
    /**
     * @notice Withdraw the funds from the escrow.  
     * @param _paymentRef Reference of the related Invoice.
     * @param _receiver Receiving address.
     * @dev Internal function to withdraw funds from escrow, to a given reciever.
     * @dev Emits TransferWithReferenceAndFee() when payee is the _receiver.
     * @dev Asserts .amount, .isFrozen and .emergencyState are reset before deleted.   
     */
    function _withdraw(bytes memory _paymentRef, address _receiver)
        internal
        IsInEscrow(_paymentRef)
        IsNotInEmergencyState(_paymentRef)
        IsNotFrozen(_paymentRef)
        returns (bool result) 
    {
        require(_receiver != address(0), "ZERO adddress");
        require(requestMapping[_paymentRef].amount > 0, "ZERO Amount");
        
        IERC20 requestedToken = IERC20(requestMapping[_paymentRef].tokenAddress);

        uint256 _amount = requestMapping[_paymentRef].amount;
        requestMapping[_paymentRef].amount = 0;

        // Checks if the requestedToken is allowed to spend.
        if (requestedToken.allowance(address(this),address(paymentProxy)) < _amount) {
            approvePaymentProxyToSpend(address(requestedToken));
        }

        paymentProxy.transferFromWithReferenceAndFee(
            address(requestedToken),
            _receiver,
            _amount,
            _paymentRef,
            0,
            address(0)
        );
        
        assert(requestMapping[_paymentRef].amount == 0);
        assert(!requestMapping[_paymentRef].isFrozen);
        assert(!requestMapping[_paymentRef].emergencyState);

        delete requestMapping[_paymentRef];

        return true;
    }

    /**
    * @notice Authorizes the proxy to spend a new request currency (ERC20).
    * @param _erc20Address Address of an ERC20 used as the request currency.
    */
    function approvePaymentProxyToSpend(address _erc20Address) public {
        IERC20 erc20 = IERC20(_erc20Address);
        uint256 max = 2**256 - 1;
        erc20.safeApprove(address(paymentProxy), max);
    }

}

src/contracts/ERC20FeeProxy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/**
 * @title ERC20FeeProxy
 * @notice This contract performs an ERC20 token transfer, with a Fee sent to a third address and stores a reference
 */
contract ERC20FeeProxy {
  // Event to declare a transfer with a reference
  event TransferWithReferenceAndFee(
    address tokenAddress,
    address to,
    uint256 amount,
    bytes indexed paymentReference,
    uint256 feeAmount,
    address feeAddress
  );

  // Fallback function returns funds to the sender
  receive() external payable {
    revert("not payable receive");
  }

  /**
    * @notice Performs a ERC20 token transfer with a reference
              and a transfer to a second address for the payment of a fee
    * @param _tokenAddress Address of the ERC20 token smart contract
    * @param _to Transfer recipient
    * @param _amount Amount to transfer
    * @param _paymentReference Reference of the payment related
    * @param _feeAmount The amount of the payment fee
    * @param _feeAddress The fee recipient
    */
  function transferFromWithReferenceAndFee(
    address _tokenAddress,
    address _to,
    uint256 _amount,
    bytes calldata _paymentReference,
    uint256 _feeAmount,
    address _feeAddress
    ) external
    {
    require(safeTransferFrom(_tokenAddress, _to, _amount), "payment transferFrom() failed");
    if (_feeAmount > 0 && _feeAddress != address(0)) {
      require(safeTransferFrom(_tokenAddress, _feeAddress, _feeAmount), "fee transferFrom() failed");
    }
    emit TransferWithReferenceAndFee(
      _tokenAddress,
      _to,
      _amount,
      _paymentReference,
      _feeAmount,
      _feeAddress
    );
  }

  /**
   * @notice Call transferFrom ERC20 function and validates the return data of a ERC20 contract call.
   * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value.
   * @return result The return value of the ERC20 call, returning true for non-standard tokens
   */
  function safeTransferFrom(address _tokenAddress, address _to, uint256 _amount) internal returns (bool result) {
    /* solium-disable security/no-inline-assembly */
    // check if the address is a contract
    assembly {
      if iszero(extcodesize(_tokenAddress)) { revert(0, 0) }
    }
    
    // solium-disable-next-line security/no-low-level-calls
    (bool success, ) = _tokenAddress.call(abi.encodeWithSignature(
      "transferFrom(address,address,uint256)",
      msg.sender,
      _to,
      _amount
    ));

    assembly {
        switch returndatasize()
        case 0 { // not a standard erc20
            result := 1
        }
        case 32 { // standard erc20
            returndatacopy(0, 0, 32)
            result := mload(0)
        }
        default { // anything else, should revert for safety
            revert(0, 0)
        }
    }

    require(success, "transferFrom() has been reverted");

    /* solium-enable security/no-inline-assembly */
    return result;
  }
}

src/contracts/ERC20Proxy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";


/**
 * @title ERC20Proxy
 * @notice This contract performs an ERC20 token transfer and stores a reference
  */
contract ERC20Proxy {
  // Event to declare a transfer with a reference
  event TransferWithReference(
    address tokenAddress,
    address to,
    uint256 amount,
    bytes indexed paymentReference
  );

  // Fallback function returns funds to the sender
  receive() external payable {
    revert("not payable receive");
  }
  /**
  * @notice Performs a ERC20 token transfer with a reference
  * @param _tokenAddress Address of the ERC20 token smart contract
  * @param _to Transfer recipient
  * @param _amount Amount to transfer
  * @param _paymentReference Reference of the payment related
  */
  function transferFromWithReference(
    address _tokenAddress,
    address _to,
    uint256 _amount,
    bytes calldata _paymentReference
  )
    external 
  {
    ERC20 erc20 = ERC20(_tokenAddress);
    require(erc20.transferFrom(msg.sender, _to, _amount), "transferFrom() failed");
    emit TransferWithReference(
      _tokenAddress,
      _to,
      _amount,
      _paymentReference
    );
  }
}

src/contracts/ERC20SwapToConversion.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./lib/SafeERC20.sol";
import "./Erc20ConversionProxy.sol";
import "./ChainlinkConversionPath.sol";


interface IUniswapV2Router02 {
  function swapTokensForExactTokens(
    uint amountOut,
    uint amountInMax,
    address[] calldata path,
    address to,
    uint deadline
  ) external returns (uint[] memory amounts);
}


/**
 * @title ERC20SwapToConversion
 * @notice This contract swaps ERC20 tokens before paying a request thanks to a payment proxy
  */
contract ERC20SwapToConversion is Ownable {
  using SafeERC20 for IERC20;

  IUniswapV2Router02 public swapRouter;
  Erc20ConversionProxy public paymentProxy;
  ChainlinkConversionPath public chainlinkConversionPath;

  constructor(address _swapRouterAddress, address _paymentProxyAddress, address _chainlinkConversionPath) {
    swapRouter = IUniswapV2Router02(_swapRouterAddress);
    paymentProxy = Erc20ConversionProxy(_paymentProxyAddress);
    chainlinkConversionPath = ChainlinkConversionPath(_chainlinkConversionPath);
  }

  /**
  * @notice Performs a request payment, denominated in a token or currency A,
  *         where the issuer expects a token B, and the payer uses a token C.
  *         The conversion rate from A to B is done using Chainlink.
  *         The token swap is done using Uniswap.
  * @param _to Transfer recipient = request issuer
  * @param _requestAmount Amount to transfer in request currency
  * @param _amountInMax Maximum amount allowed to spend for currency swap, in payment network currency.
            This amount should take into account the fees.
    @param _uniswapPath, path of ERC20 tokens to swap from paymentNetworkToken to spentToken. The first
            address of the path should be the spent currency. The last element should be the
            payment network currency.
    @param _chainlinkPath, path of currencies to convert from request currency to paymentNetworkToken. The first
            address of the path should be the request currency. The last element should be the
            payment network currency.
  * @param _paymentReference Reference of the payment related
  * @param _requestFeeAmount Amount of the fee in request currency
  * @param _feeAddress Where to pay the fee
  * @param _uniswapDeadline Deadline for the swap to be valid
  * @param _chainlinkMaxRateTimespan Max time span with the oldestrate, ignored if zero
  */
  function swapTransferWithReference(
    address _to,
    uint256 _requestAmount, // requestCurrency
    uint256 _amountInMax, // SpentToken
    address[] memory _uniswapPath, // from paymentNetworkToken to spentToken on uniswap
    address[] memory _chainlinkPath, // from requestCurrency to spentToken on chainlink
    bytes calldata _paymentReference,
    uint256 _requestFeeAmount, // requestCurrency
    address _feeAddress,
    uint256 _uniswapDeadline,
    uint256 _chainlinkMaxRateTimespan
  )
    external
  {
    require(
      _uniswapPath[_uniswapPath.length-1] == _chainlinkPath[_chainlinkPath.length-1],
      "the requested token on uniswap must be the payment currency");

    // Get the amount to pay in paymentNetworkToken
    uint256 paymentNetworkTotalAmount = getConversion(_chainlinkPath, _requestAmount, _requestFeeAmount);

    require(
      IERC20(_uniswapPath[0]).safeTransferFrom(msg.sender, address(this), _amountInMax),
      "Could not transfer payment token from swapper-payer");

    swapRouter.swapTokensForExactTokens(
      paymentNetworkTotalAmount,
      _amountInMax,
      _uniswapPath,
      address(this),
      _uniswapDeadline
    );

    // Pay the request and fees
    paymentProxy.transferFromWithReferenceAndFee(
      _to,
      _requestAmount,
      _chainlinkPath,
      _paymentReference,
      _requestFeeAmount,
      _feeAddress,
      paymentNetworkTotalAmount, // _maxToSpend
      _chainlinkMaxRateTimespan
    );

    // Give the change back to the payer, in both currencies (only spent token should remain)
    if (IERC20(_uniswapPath[0]).balanceOf(address(this)) > 0) {
      IERC20(_uniswapPath[0]).safeTransfer(msg.sender, IERC20(_uniswapPath[0]).balanceOf(address(this)));
    }
    if (IERC20(_uniswapPath[_uniswapPath.length-1]).balanceOf(address(this)) > 0) {
      IERC20(_uniswapPath[0]).safeTransfer(msg.sender, IERC20(_uniswapPath[0]).balanceOf(address(this)));
    }
  }

 /**
  * @notice Authorizes the proxy to spend a new request currency (ERC20).
  * @param _erc20Address Address of an ERC20 used as a request currency
  */
  function approvePaymentProxyToSpend(address _erc20Address) public {
    IERC20 erc20 = IERC20(_erc20Address);
    uint256 max = 2**256 - 1;
    erc20.safeApprove(address(paymentProxy), max);
  }

 /**
  * @notice Authorizes the swap router to spend a new payment currency (ERC20).
  * @param _erc20Address Address of an ERC20 used for payment
  */
  function approveRouterToSpend(address _erc20Address) public {
    IERC20 erc20 = IERC20(_erc20Address);
    uint256 max = 2**256 - 1;
    erc20.safeApprove(address(swapRouter), max);
  }

  /*
  * Admin functions to edit the admin, router address or proxy address
  */
  function setPaymentProxy(address _paymentProxyAddress) public onlyOwner {
    paymentProxy = Erc20ConversionProxy(_paymentProxyAddress);
    chainlinkConversionPath = ChainlinkConversionPath(paymentProxy.chainlinkConversionPath());
  }

  function setRouter(address _newSwapRouterAddress) public onlyOwner {
    swapRouter = IUniswapV2Router02(_newSwapRouterAddress);
  }

  /*
  * Internal functions to reduce the stack in swapTransferWithReference()
  */
  function getConversion(
    address[] memory _path,
    uint256 _requestAmount,
    uint256 _requestFeeAmount
  )
    internal
    view
    returns (uint256 conversion)
  {
    (conversion, ) = chainlinkConversionPath.getConversion(_requestAmount + _requestFeeAmount, _path);
  }
}

src/contracts/ERC20SwapToPay.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./lib/SafeERC20.sol";
import "./interfaces/ERC20FeeProxy.sol";

interface IUniswapV2Router02 {
  function swapTokensForExactTokens(
    uint amountOut,
    uint amountInMax,
    address[] calldata path,
    address to,
    uint deadline
  ) external returns (uint[] memory amounts);
}


/**
 * @title ERC20SwapToPay
 * @notice This contract swaps ERC20 tokens before paying a request thanks to a payment proxy
  */
contract ERC20SwapToPay is Ownable {
  using SafeERC20 for IERC20;

  IUniswapV2Router02 public swapRouter;
  IERC20FeeProxy public paymentProxy;

  constructor(address _swapRouterAddress, address _paymentProxyAddress) {
    swapRouter = IUniswapV2Router02(_swapRouterAddress);
    paymentProxy = IERC20FeeProxy(_paymentProxyAddress);
  }

 /**
  * @notice Authorizes the proxy to spend a new request currency (ERC20).
  * @param _erc20Address Address of an ERC20 used as a request currency
  */
  function approvePaymentProxyToSpend(address _erc20Address) public {
    IERC20 erc20 = IERC20(_erc20Address);
    uint256 max = 2**256 - 1;
    erc20.safeApprove(address(paymentProxy), max);
  }

 /**
  * @notice Authorizes the swap router to spend a new payment currency (ERC20).
  * @param _erc20Address Address of an ERC20 used for payment
  */
  function approveRouterToSpend(address _erc20Address) public {
    IERC20 erc20 = IERC20(_erc20Address);
    uint256 max = 2**256 - 1;
    erc20.safeApprove(address(swapRouter), max);
  }

  /**
  * @notice Performs a token swap between a payment currency and a request currency, and then
  *         calls a payment proxy to pay the request, including fees.
  * @param _to Transfer recipient = request issuer
  * @param _amount Amount to transfer in request currency
  * @param _amountInMax Maximum amount allowed to spend for currency swap, in payment currency.
            This amount should take into account the fees.
    @param _path, path of ERC20 tokens to swap from requestedToken to spentToken. The first
            address of the path should be the payment currency. The last element should be the
            request currency.
  * @param _paymentReference Reference of the payment related
  * @param _feeAmount Amount of the fee in request currency
  * @param _feeAddress Where to pay the fee
  * @param _deadline Deadline for the swap to be valid
  */
  function swapTransferWithReference(
    address _to,
    uint256 _amount,      // requestedToken
    uint256 _amountInMax, // spentToken
    address[] calldata _path, // from requestedToken to spentToken
    bytes calldata _paymentReference,
    uint256 _feeAmount,   // requestedToken
    address _feeAddress,
    uint256 _deadline
  )
    external
  {
    IERC20 spentToken = IERC20(_path[0]);
    IERC20 requestedToken = IERC20(_path[_path.length-1]);

    uint256 requestedTotalAmount = _amount + _feeAmount;

    require(spentToken.allowance(msg.sender, address(this)) > _amountInMax,
                                 "Not sufficient allowance for swap to pay.");
    require(spentToken.safeTransferFrom(msg.sender, address(this), _amountInMax), 
                                        "Could not transfer payment token from swapper-payer");

    // Allow the router to spend all this contract's spentToken
    if (spentToken.allowance(address(this),address(swapRouter)) < _amountInMax) {
      approveRouterToSpend(address(spentToken));
    }

    swapRouter.swapTokensForExactTokens(
      requestedTotalAmount,
      _amountInMax,
      _path,
      address(this),
      _deadline
    );

    // Allow the payment network to spend all this contract's requestedToken
    if (requestedToken.allowance(address(this),address(paymentProxy)) < requestedTotalAmount) {
      approvePaymentProxyToSpend(address(requestedToken));
    }

    // Pay the request and fees
    paymentProxy.transferFromWithReferenceAndFee(
      address(requestedToken),
      _to,
      _amount,
      _paymentReference,
      _feeAmount,
      _feeAddress
    );

    // Give the change back to the payer, in both currencies (only spent token should remain)

    if (spentToken.balanceOf(address(this)) > 0) {
      spentToken.safeTransfer(msg.sender, spentToken.balanceOf(address(this)));
    }
    if (requestedToken.balanceOf(address(this)) > 0) {
      requestedToken.safeTransfer(msg.sender, requestedToken.balanceOf(address(this)));
    }
  }

  /*
  * Admin functions to edit the admin, router address or proxy address
  */

  function setPaymentProxy(address _paymentProxyAddress) public onlyOwner {
    paymentProxy = IERC20FeeProxy(_paymentProxyAddress);
  }

  function setRouter(address _newSwapRouterAddress) public onlyOwner {
    swapRouter = IUniswapV2Router02(_newSwapRouterAddress);
  }
}

src/contracts/Erc20ConversionProxy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import './ChainlinkConversionPath.sol';
import './interfaces/ERC20FeeProxy.sol';
import '@openzeppelin/contracts/access/Ownable.sol';

/**
 * @title Erc20ConversionProxy
 * @notice This contract convert from chainlink then swaps ERC20 tokens
 *         before paying a request thanks to a conversion payment proxy
 */
contract Erc20ConversionProxy is Ownable {
    address public paymentProxy;
    ChainlinkConversionPath public chainlinkConversionPath;

    constructor(address _paymentProxyAddress, address _chainlinkConversionPathAddress) {
        paymentProxy = _paymentProxyAddress;
        chainlinkConversionPath = ChainlinkConversionPath(_chainlinkConversionPathAddress);
    }

    // Event to declare a conversion with a reference
    event TransferWithConversionAndReference(
        uint256 amount,
        address currency,
        bytes indexed paymentReference,
        uint256 feeAmount,
        uint256 maxRateTimespan
    );

    // Event to declare a transfer with a reference
    event TransferWithReferenceAndFee(
        address tokenAddress,
        address to,
        uint256 amount,
        bytes indexed paymentReference,
        uint256 feeAmount,
        address feeAddress
    );

    /**
     * @notice Transfers ERC20 tokens with a reference with amount based on the request amount in fiat
     * @param _to Transfer recipient of the payement
     * @param _requestAmount Request amount
     * @param _path Conversion path
     * @param _paymentReference Reference of the payment related
     * @param _feeAmount The amount of the payment fee
     * @param _feeAddress The fee recipient
     * @param _maxToSpend Amount max that we can spend on the behalf of the user
     * @param _maxRateTimespan Max time span with the oldestrate, ignored if zero
     */
    function transferFromWithReferenceAndFee(
        address _to,
        uint256 _requestAmount,
        address[] calldata _path,
        bytes calldata _paymentReference,
        uint256 _feeAmount,
        address _feeAddress,
        uint256 _maxToSpend,
        uint256 _maxRateTimespan
    ) external {
        (uint256 amountToPay, uint256 amountToPayInFees) = getConversions(
            _path,
            _requestAmount,
            _feeAmount,
            _maxRateTimespan
        );

        require(
            amountToPay + amountToPayInFees <= _maxToSpend,
            'Amount to pay is over the user limit'
        );

        // Pay the request and fees
        (bool status, ) = paymentProxy.delegatecall(
            abi.encodeWithSignature(
                'transferFromWithReferenceAndFee(address,address,uint256,bytes,uint256,address)',
                // payment currency
                _path[_path.length - 1],
                _to,
                amountToPay,
                _paymentReference,
                amountToPayInFees,
                _feeAddress
            )
        );
        require(status, 'transferFromWithReferenceAndFee failed');

        // Event to declare a transfer with a reference
        emit TransferWithConversionAndReference(
            _requestAmount,
            // request currency
            _path[0],
            _paymentReference,
            _feeAmount,
            _maxRateTimespan
        );
    }

    function getConversions(
        address[] memory _path,
        uint256 _requestAmount,
        uint256 _feeAmount,
        uint256 _maxRateTimespan
    ) internal view returns (uint256 amountToPay, uint256 amountToPayInFees) {
        (uint256 rate, uint256 oldestTimestampRate, uint256 decimals) = chainlinkConversionPath
            .getRate(_path);

        // Check rate timespan
        require(
            _maxRateTimespan == 0 || block.timestamp - oldestTimestampRate <= _maxRateTimespan,
            'aggregator rate is outdated'
        );

        // Get the amount to pay in the crypto currency chosen
        amountToPay = (_requestAmount * rate) / decimals;
        amountToPayInFees = (_feeAmount * rate) / decimals;
    }

    /**
     * @notice Update the conversion path contract used to fetch conversions
     * @param _chainlinkConversionPathAddress address of the conversion path contract
     */
    function updateConversionPathAddress(address _chainlinkConversionPathAddress)
        external
        onlyOwner
    {
        chainlinkConversionPath = ChainlinkConversionPath(_chainlinkConversionPathAddress);
    }

    /**
     * @notice Update the conversion proxy used to process the payment
     * @param _paymentProxyAddress address of the ETH conversion proxy
     */
    function updateConversionProxyAddress(address _paymentProxyAddress) external onlyOwner {
        paymentProxy = _paymentProxyAddress;
    }
}

src/contracts/EthConversionProxy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import './ChainlinkConversionPath.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import './legacy_openzeppelin/contracts/access/roles/WhitelistAdminRole.sol';

/**
 * @title EthConversionProxy
 * @notice This contract converts from chainlink then swaps ETH (or native token)
 *         before paying a request thanks to a conversion payment proxy.
 *         The inheritance from ReentrancyGuard is required to perform
 *         "transferExactEthWithReferenceAndFee" on the eth-fee-proxy contract
 */
contract EthConversionProxy is ReentrancyGuard, WhitelistAdminRole {
    address public paymentProxy;
    ChainlinkConversionPath public chainlinkConversionPath;
    address public nativeTokenHash;

    constructor(
        address _paymentProxyAddress,
        address _chainlinkConversionPathAddress,
        address _nativeTokenHash
    ) {
        paymentProxy = _paymentProxyAddress;
        chainlinkConversionPath = ChainlinkConversionPath(_chainlinkConversionPathAddress);
        nativeTokenHash = _nativeTokenHash;
    }

    // Event to declare a conversion with a reference
    event TransferWithConversionAndReference(
        uint256 amount,
        address currency,
        bytes indexed paymentReference,
        uint256 feeAmount,
        uint256 maxRateTimespan
    );

    // Event to declare a transfer with a reference
    // This event is emitted by this contract from a delegate call of the payment-proxy
    event TransferWithReferenceAndFee(
        address to,
        uint256 amount,
        bytes indexed paymentReference,
        uint256 feeAmount,
        address feeAddress
    );

    /**
     * @notice Performs an ETH transfer with a reference computing the payment amount based on the request amount
     * @param _to Transfer recipient of the payement
     * @param _requestAmount Request amount
     * @param _path Conversion path
     * @param _paymentReference Reference of the payment related
     * @param _feeAmount The amount of the payment fee
     * @param _feeAddress The fee recipient
     * @param _maxRateTimespan Max time span with the oldestrate, ignored if zero
     */
    function transferWithReferenceAndFee(
        address _to,
        uint256 _requestAmount,
        address[] calldata _path,
        bytes calldata _paymentReference,
        uint256 _feeAmount,
        address _feeAddress,
        uint256 _maxRateTimespan
    ) external payable {
        require(
            _path[_path.length - 1] == nativeTokenHash,
            'payment currency must be the native token'
        );

        (uint256 amountToPay, uint256 amountToPayInFees) = getConversions(
            _path,
            _requestAmount,
            _feeAmount,
            _maxRateTimespan
        );

        // Pay the request and fees
        (bool status, ) = paymentProxy.delegatecall(
            abi.encodeWithSignature(
                'transferExactEthWithReferenceAndFee(address,uint256,bytes,uint256,address)',
                _to,
                amountToPay,
                _paymentReference,
                amountToPayInFees,
                _feeAddress
            )
        );

        require(status, 'paymentProxy transferExactEthWithReferenceAndFee failed');

        // Event to declare a transfer with a reference
        emit TransferWithConversionAndReference(
            _requestAmount,
            // request currency
            _path[0],
            _paymentReference,
            _feeAmount,
            _maxRateTimespan
        );
    }

    function getConversions(
        address[] memory _path,
        uint256 _requestAmount,
        uint256 _feeAmount,
        uint256 _maxRateTimespan
    ) internal view returns (uint256 amountToPay, uint256 amountToPayInFees) {
        (uint256 rate, uint256 oldestTimestampRate, uint256 decimals) = chainlinkConversionPath
            .getRate(_path);

        // Check rate timespan
        require(
            _maxRateTimespan == 0 || block.timestamp - oldestTimestampRate <= _maxRateTimespan,
            'aggregator rate is outdated'
        );

        // Get the amount to pay in the native token
        amountToPay = (_requestAmount * rate) / decimals;
        amountToPayInFees = (_feeAmount * rate) / decimals;
    }

    /**
     * @notice Update the conversion path contract used to fetch conversions
     * @param _chainlinkConversionPathAddress address of the conversion path contract
     */
    function updateConversionPathAddress(address _chainlinkConversionPathAddress)
        external
        onlyWhitelistAdmin
    {
        chainlinkConversionPath = ChainlinkConversionPath(_chainlinkConversionPathAddress);
    }

    /**
     * @notice Update the conversion proxy used to process the payment
     * @param _paymentProxyAddress address of the ETH conversion proxy
     */
    function updateConversionProxyAddress(address _paymentProxyAddress)
        external
        onlyWhitelistAdmin
    {
        paymentProxy = _paymentProxyAddress;
    }
}

src/contracts/EthereumProxy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/**
 * @title EthereumProxy
 * @notice This contract performs an Ethereum transfer and stores a reference
 */
contract EthereumProxy {
    // Event to declare a transfer with a reference
    event TransferWithReference(address to, uint256 amount, bytes indexed paymentReference);

    // Fallback function returns funds to the sender
    receive() external payable {
        revert('not payable receive');
    }

    /**
     * @notice Performs an Ethereum transfer with a reference
     * @param _to Transfer recipient
     * @param _paymentReference Reference of the payment related
     */
    function transferWithReference(address payable _to, bytes calldata _paymentReference)
        external
        payable
    {
        (bool success, ) = _to.call{value: msg.value}('');
        require(success, 'Could not pay the recipient');
        emit TransferWithReference(_to, msg.value, _paymentReference);
    }
}

src/contracts/FakeSwapRouter.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./lib/SafeERC20.sol";

/**
 * @title TestSwapRouter
 *
 * @notice TestSwapRouter is a contract to test swap to pay
 * cf. https://github.com/Uniswap/uniswap-v2-periphery/blob/master/contracts/UniswapV2Router02.sol
*/
contract FakeSwapRouter {
  using SafeERC20 for ERC20;

  modifier ensure(uint deadline) {
    require(deadline >= block.timestamp, "UniswapV2Router: EXPIRED");
    _;
  }

  // Will fail if amountInMax < 2 * amountOut
  function swapTokensForExactTokens(
    uint amountOut,
    uint amountInMax,
    address[] calldata path,
    address to,
    uint deadline
  ) external ensure(deadline) returns (uint[] memory amounts) 
  {
    amounts = new uint[](2);
    amounts[0] = amountOut;
    amounts[1] = amountOut * 2;
    require(amounts[1] <= amountInMax, "UniswapV2Router: EXCESSIVE_INPUT_AMOUNT");
    ERC20 paid = ERC20(path[0]);
    ERC20 swapped = ERC20(path[1]);
    require(swapped.balanceOf(address(this)) > amounts[0], "Test cannot proceed, lack of tokens in fake swap contract");
    paid.safeTransferFrom(msg.sender, address(this), amounts[1]);
    swapped.transfer(to, amounts[0]);
  }
}

src/contracts/Migrations.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


contract Migrations {
  address public owner;
  uint public lastCompletedMigration;

  constructor() {
    owner = msg.sender;
  }

  modifier restricted() {
    if (msg.sender == owner)
      _;
  }

  function setCompleted(uint completed) public restricted {
    lastCompletedMigration = completed;
  }

  function upgrade(address newAddress) public restricted {
    Migrations upgraded = Migrations(newAddress);
    upgraded.setCompleted(lastCompletedMigration);
  }
}

src/contracts/RequestDeployer.sol

// SPDX-License-Identifier: MIT
// Further information: https://eips.ethereum.org/EIPS/eip-1014

pragma solidity ^0.8.9;

import '@openzeppelin/contracts/utils/Create2.sol';
import '@openzeppelin/contracts/utils/introspection/ERC1820Implementer.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/security/Pausable.sol';

/**
 * @title CREATE2 Deployer Smart Contract
 * @author Pascal Marco Caversaccio, [email protected]
 * @dev Helper smart contract to make easier and safer usage of the
 * `CREATE2` EVM opcode. `CREATE2` can be used to compute in advance
 * the address where a smart contract will be deployed, which allows
 * for interesting new mechanisms known as 'counterfactual interactions'.
 */

contract RequestDeployer is Ownable, Pausable {
    /**
     * @dev Deploys a contract using `CREATE2`. The address where the
     * contract will be deployed can be known in advance via {computeAddress}.
     *
     * The bytecode for a contract can be obtained from Solidity with
     * `type(contractName).creationCode`.
     *
     * Requirements:
     * - `bytecode` must not be empty.
     * - `salt` must have not been used for `bytecode` already.
     * - the factory must have a balance of at least `value`.
     * - if `value` is non-zero, `bytecode` must have a `payable` constructor.
     */
    function deploy(
        uint256 value,
        bytes32 salt,
        bytes memory code
    ) public whenNotPaused {
        Create2.deploy(value, salt, code);
    }

    /**
     * @dev Deployment of the {ERC1820Implementer}.
     * Further information: https://eips.ethereum.org/EIPS/eip-1820
     */
    function deployERC1820Implementer(uint256 value, bytes32 salt) public whenNotPaused {
        Create2.deploy(value, salt, type(ERC1820Implementer).creationCode);
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy}.
     * Any change in the `bytecodeHash` or `salt` will result in a new destination address.
     */
    function computeAddress(bytes32 salt, bytes32 codeHash) public view returns (address) {
        return Create2.computeAddress(salt, codeHash);
    }

    /**
     * @dev Returns the address where a contract will be stored if deployed via {deploy} from a
     * contract located at `deployer`. If `deployer` is this contract's address, returns the
     * same value as {computeAddress}.
     */
    function computeAddressWithDeployer(
        bytes32 salt,
        bytes32 codeHash,
        address deployer
    ) public pure returns (address) {
        return Create2.computeAddress(salt, codeHash, deployer);
    }

    /**
     * @dev Contract can receive ether. However, the only way to transfer this ether is
     * to call the function `killCreate2Deployer`.
     */
    receive() external payable {}

    /**
     * @dev Triggers stopped state.
     * Requirements: The contract must not be paused.
     */
    function pause() public onlyOwner {
        _pause();
    }

    /**
     * @dev Returns to normal state.
     * Requirements: The contract must be paused.
     */
    function unpause() public onlyOwner {
        _unpause();
    }

    /**
     * @dev Destroys the Create2Deployer contract and transfers all ether to a pre-defined payout address.
     * @notice Using the `CREATE2` EVM opcode always allows to redeploy a new smart contract to a
     * previously seldestructed contract address. However, if a contract creation is attempted,
     * due to either a creation transaction or the `CREATE`/`CREATE2` EVM opcode, and the destination
     * address already has either nonzero nonce, or non-empty code, then the creation throws immediately,
     * with exactly the same behavior as would arise if the first byte in the init code were an invalid opcode.
     * This applies retroactively starting from genesis.
     */
    function killCreate2Deployer(address payable payoutAddress) public onlyOwner {
        payoutAddress.transfer(address(this).balance);
        selfdestruct(payoutAddress);
    }
}

src/contracts/RequestHashStorage.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./legacy_openzeppelin/contracts/access/roles/WhitelistedRole.sol";


/**
 * @title RequestHashStorage
 * @notice This contract is the entry point to retrieve all the hashes of the request network system.
  */
contract RequestHashStorage is WhitelistedRole {

  // Event to declare a new hash
  event NewHash(string hash, address hashSubmitter, bytes feesParameters);

  /**
   * @notice Declare a new hash
   * @param _hash hash to store
   * @param _feesParameters Parameters use to compute the fees. 
                            This is a bytes to stay generic,
                            the structure is on the charge of the hashSubmitter contracts.
   */
  function declareNewHash(string calldata _hash, bytes calldata _feesParameters)
    external
    onlyWhitelisted
  {
    // Emit event for log
    emit NewHash(_hash, msg.sender, _feesParameters);
  }
}

src/contracts/RequestOpenHashSubmitter.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./StorageFeeCollector.sol";
import "./RequestHashStorage.sol";
import "./Bytes.sol";


/**
 * @title RequestOpenHashSubmitter
 * @notice Contract declares data hashes and collects the fees.
 * @notice The hash is declared to the whole request network system through the RequestHashStorage contract.
 * @notice Anyone can submit hashes.
 */
contract RequestOpenHashSubmitter is StorageFeeCollector {

  RequestHashStorage public requestHashStorage;
  
  /**
   * @param _addressRequestHashStorage contract address which manages the hashes declarations
   * @param _addressBurner Burner address
   */
  constructor(address _addressRequestHashStorage, address payable _addressBurner)
    StorageFeeCollector(_addressBurner)
  {
    requestHashStorage = RequestHashStorage(_addressRequestHashStorage);
  }

  // Fallback function returns funds to the sender
  receive() external payable {
    revert("not payable receive");
  }

  /**
   * @notice Submit a new hash to the blockchain.
   *
   * @param _hash Hash of the request to be stored
   * @param _feesParameters fees parameters used to compute the fees. Here, it is the content size in an uint256
   */
  function submitHash(string calldata _hash, bytes calldata _feesParameters)
    external
    payable
  {
    // extract the contentSize from the _feesParameters
    uint256 contentSize = uint256(Bytes.extractBytes32(_feesParameters, 0));

    // Check fees are paid
    require(getFeesAmount(contentSize) == msg.value, "msg.value does not match the fees");

    // Send fees to burner, throws on failure
    collectForREQBurning(msg.value);

    // declare the hash to the whole system through to RequestHashStorage
    requestHashStorage.declareNewHash(_hash, _feesParameters);
  }
}

src/contracts/StorageFeeCollector.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "./legacy_openzeppelin/contracts/access/roles/WhitelistAdminRole.sol";


/**
 * @title StorageFeeCollector
 *
 * @notice StorageFeeCollector is a contract managing the fees
 */
contract StorageFeeCollector is WhitelistAdminRole {
  /**
   * Fee computation for storage are based on four parameters:
   * minimumFee (wei) fee that will be applied for any size of storage
   * rateFeesNumerator (wei) and rateFeesDenominator (byte) define the variable fee,
   * for each <rateFeesDenominator> bytes above threshold, <rateFeesNumerator> wei will be charged
   *
   * Example:
   * If the size to store is 50 bytes, the threshold is 100 bytes and the minimum fee is 300 wei,
   * then 300 will be charged
   *
   * If rateFeesNumerator is 2 and rateFeesDenominator is 1 then 2 wei will be charged for every bytes above threshold,
   * if the size to store is 150 bytes then the fee will be 300 + (150-100)*2 = 400 wei
   */
  uint256 public minimumFee;
  uint256 public rateFeesNumerator;
  uint256 public rateFeesDenominator;

  // address of the contract that will burn req token
  address payable public requestBurnerContract;

  event UpdatedFeeParameters(uint256 minimumFee, uint256 rateFeesNumerator, uint256 rateFeesDenominator);
  event UpdatedMinimumFeeThreshold(uint256 threshold);
  event UpdatedBurnerContract(address burnerAddress);

  /**
   * @param _requestBurnerContract Address of the contract where to send the ether.
   * This burner contract will have a function that can be called by anyone
   * and will exchange ether to req via Kyber and burn the REQ
   */
  constructor(address payable _requestBurnerContract) {
    requestBurnerContract = _requestBurnerContract;
  }

  /**
    * @notice Sets the fees rate and minimum fee.
    * @dev if the _rateFeesDenominator is 0, it will be treated as 1.
            (in other words, the computation of the fees will not use it)
    * @param _minimumFee minimum fixed fee
    * @param _rateFeesNumerator numerator rate
    * @param _rateFeesDenominator denominator rate
    */
  function setFeeParameters(uint256 _minimumFee, uint256 _rateFeesNumerator, uint256 _rateFeesDenominator)
    external
    onlyWhitelistAdmin
  {
    minimumFee = _minimumFee;
    rateFeesNumerator = _rateFeesNumerator;
    rateFeesDenominator = _rateFeesDenominator;
    emit UpdatedFeeParameters(minimumFee, rateFeesNumerator, rateFeesDenominator);
  }

  /**
    * @notice Set the request burner address.
    * @param _requestBurnerContract address of the contract that will burn req token (probably through Kyber)
    */
  function setRequestBurnerContract(address payable _requestBurnerContract)
    external
    onlyWhitelistAdmin
  {
    requestBurnerContract = _requestBurnerContract;
    emit UpdatedBurnerContract(requestBurnerContract);
  }

  /**
    * @notice Computes the fees.
    * @param _contentSize Size of the content of the block to be stored
    * @return the expected amount of fees in wei
    */
  function getFeesAmount(uint256 _contentSize)
    public
    view
    returns(uint256)
  {
    // Transactions fee
    uint256 computedAllFee = _contentSize * rateFeesNumerator;

    if (rateFeesDenominator != 0) {
      computedAllFee = computedAllFee / rateFeesDenominator;
    }

    if (computedAllFee <= minimumFee) {
      return minimumFee;
    } else {
      return computedAllFee;
    }
  }

  /**
    * @notice Sends fees to the request burning address.
    * @param _amount amount to send to the burning address
    */
  function collectForREQBurning(uint256 _amount)
    internal
  {
    // .transfer throws on failure
    requestBurnerContract.transfer(_amount);
  }
}

src/contracts/TestERC20.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

/**
 * @title TestERC20
 *
 * @notice TestERC20 is a contract to test ERC20 detection
*/
contract TestERC20 is ERC20 {
  constructor(uint256 initialSupply) ERC20("ERC 20", "ERC20") {
    _mint(msg.sender, initialSupply);
    transfer(0xf17f52151EbEF6C7334FAD080c5704D77216b732, 10);
  }
}


contract ERC20True {
  function transferFrom(address, address, uint) pure public returns (bool) {
    return true;
  }
}


contract ERC20False {
  function transferFrom(address, address, uint) pure public returns (bool) {
    return false;
  }
}


contract ERC20NoReturn {
  function transferFrom(address _from, address _to, uint _value) pure public {}
}


contract ERC20Revert {
  function transferFrom(address, address, uint) pure public {
    revert("bad thing happened");
  }
}

contract ERC20Alpha is ERC20 {
  constructor(uint256 initialSupply) ERC20("Alpha ERC 20", "ALPHA") {
    _mint(msg.sender, initialSupply);
  }
}

src/contracts/interfaces/ERC20FeeProxy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

interface IERC20FeeProxy {
  event TransferWithReferenceAndFee(
    address tokenAddress,
    address to,
    uint256 amount,
    bytes indexed paymentReference,
    uint256 feeAmount,
    address feeAddress
  );

  function transferFromWithReferenceAndFee(
    address _tokenAddress,
    address _to,
    uint256 _amount,
    bytes calldata _paymentReference,
    uint256 _feeAmount,
    address _feeAddress
    ) external;
}

src/contracts/legacy_openzeppelin/contracts/access/Roles.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

/**
 * @title Roles
 * @dev Library for managing addresses assigned to a Role.
 */
library Roles {
    struct Role {
        mapping (address => bool) bearer;
    }

    /**
     * @dev Give an account access to this role.
     */
    function add(Role storage role, address account) internal {
        require(!has(role, account), "Roles: account already has role");
        role.bearer[account] = true;
    }

    /**
     * @dev Remove an account's access to this role.
     */
    function remove(Role storage role, address account) internal {
        require(has(role, account), "Roles: account does not have role");
        role.bearer[account] = false;
    }

    /**
     * @dev Check if an account has this role.
     * @return bool
     */
    function has(Role storage role, address account) internal view returns (bool) {
        require(account != address(0), "Roles: account is the zero address");
        return role.bearer[account];
    }
}

src/contracts/legacy_openzeppelin/contracts/access/roles/WhitelistAdminRole.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import '@openzeppelin/contracts/utils/Context.sol';
import "../Roles.sol";

/**
 * @title WhitelistAdminRole
 * @dev WhitelistAdmins are responsible for assigning and removing Whitelisted accounts.
 */
abstract contract WhitelistAdminRole is Context {
    using Roles for Roles.Role;

    event WhitelistAdminAdded(address indexed account);
    event WhitelistAdminRemoved(address indexed account);

    Roles.Role private _whitelistAdmins;

    constructor () {
        _addWhitelistAdmin(_msgSender());
    }

    modifier onlyWhitelistAdmin() {
        require(isWhitelistAdmin(_msgSender()), "WhitelistAdminRole: caller does not have the WhitelistAdmin role");
        _;
    }

    function isWhitelistAdmin(address account) public view returns (bool) {
        return _whitelistAdmins.has(account);
    }

    function addWhitelistAdmin(address account) public onlyWhitelistAdmin {
        _addWhitelistAdmin(account);
    }

    function renounceWhitelistAdmin() public {
        _removeWhitelistAdmin(_msgSender());
    }

    function _addWhitelistAdmin(address account) internal {
        _whitelistAdmins.add(account);
        emit WhitelistAdminAdded(account);
    }

    function _removeWhitelistAdmin(address account) internal {
        _whitelistAdmins.remove(account);
        emit WhitelistAdminRemoved(account);
    }
}

src/contracts/legacy_openzeppelin/contracts/access/roles/WhitelistedRole.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import '@openzeppelin/contracts/utils/Context.sol';
import "../Roles.sol";
import "./WhitelistAdminRole.sol";

/**
 * @title WhitelistedRole
 * @dev Whitelisted accounts have been approved by a WhitelistAdmin to perform certain actions (e.g. participate in a
 * crowdsale). This role is special in that the only accounts that can add it are WhitelistAdmins (who can also remove
 * it), and not Whitelisteds themselves.
 */
abstract contract WhitelistedRole is Context, WhitelistAdminRole {
    using Roles for Roles.Role;

    event WhitelistedAdded(address indexed account);
    event WhitelistedRemoved(address indexed account);

    Roles.Role private _whitelisteds;

    modifier onlyWhitelisted() {
        require(isWhitelisted(_msgSender()), "WhitelistedRole: caller does not have the Whitelisted role");
        _;
    }

    function isWhitelisted(address account) public view returns (bool) {
        return _whitelisteds.has(account);
    }

    function addWhitelisted(address account) public onlyWhitelistAdmin {
        _addWhitelisted(account);
    }

    function removeWhitelisted(address account) public onlyWhitelistAdmin {
        _removeWhitelisted(account);
    }

    function renounceWhitelisted() public {
        _removeWhitelisted(_msgSender());
    }

    function _addWhitelisted(address account) internal {
        _whitelisteds.add(account);
        emit WhitelistedAdded(account);
    }

    function _removeWhitelisted(address account) internal {
        _whitelisteds.remove(account);
        emit WhitelistedRemoved(account);
    }
}

src/contracts/lib/SafeERC20.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "@openzeppelin/contracts/token/ERC20/ERC20.sol";

/**
 * @title SafeERC20
 * @notice Works around implementations of ERC20 with transferFrom not returning success status.
 */
library SafeERC20 {

  /**
   * @notice Call transferFrom ERC20 function and validates the return data of a ERC20 contract call.
   * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value.
   * @return result The return value of the ERC20 call, returning true for non-standard tokens
   */
  function safeTransferFrom(
    IERC20  _token,
    address _from,
    address _to,
    uint256 _amount
  ) internal returns (bool result)
  {
    // solium-disable-next-line security/no-low-level-calls
    (bool success, bytes memory data) = address(_token).call(abi.encodeWithSignature(
      "transferFrom(address,address,uint256)",
      _from,
      _to,
      _amount
    ));

    return success && (data.length == 0 || abi.decode(data, (bool)));
  }

  /**
   * @notice Call approve ERC20 function and validates the return data of a ERC20 contract call.
   * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value.
   * @return result The return value of the ERC20 call, returning true for non-standard tokens
   */
  function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool result) {
    // solium-disable-next-line security/no-low-level-calls
    (bool success, bytes memory data) = address(_token).call(abi.encodeWithSignature(
      "approve(address,uint256)",
      _spender,
      _amount
    ));

    return success && (data.length == 0 || abi.decode(data, (bool)));
  }

  /**
   * @notice Call transfer ERC20 function and validates the return data of a ERC20 contract call.
   * @dev This is necessary because of non-standard ERC20 tokens that don't have a return value.
   * @return result The return value of the ERC20 call, returning true for non-standard tokens
   */
  function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal  returns (bool result) {
    // solium-disable-next-line security/no-low-level-calls
    (bool success, bytes memory data) = address(_token).call(abi.encodeWithSignature(
      "transfer(address,uint256)",
      _to,
      _amount
    ));

    return success && (data.length == 0 || abi.decode(data, (bool)));
  }
}

src/contracts/test/AggregatorMock.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


contract AggregatorMock {
  uint8 private _decimals;
  int256 private _rate;
  uint8 private _rateAge;

  constructor(int256 _r, uint8 _d, uint8 _ra) {
      _rate = _r;
      _decimals = _d;
      _rateAge = _ra;
  }

  function decimals() external view returns (uint8) {
    return _decimals;
  }

  function latestAnswer() external view returns (int256) {
    return _rate;
  }

  function latestTimestamp() external view returns (uint256) {
    // one minute old
    return block.timestamp - _rateAge;
  }
}

src/contracts/test/BytesUtilsMock.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

import "../Bytes.sol";


contract BytesUtilsMock {
  bytes32 public extractBytes32Result;
  function extractBytes32(bytes memory data, uint offset) public {
    extractBytes32Result = Bytes.extractBytes32(data, offset);
  }
}

src/contracts/test/EtherFallbackPayment.sol

// SPDX-License-Identifier: LGPL-3.0-only
pragma solidity >=0.7.0 <0.9.0;

/// @title EtherPaymentFallback - A contract that has a fallback to accept ether payments
/// @author Richard Meissner - <[email protected]>
contract EtherPaymentFallback {
    event SafeReceived(address indexed sender, uint256 value);

    /// @dev Fallback function accepts Ether transactions.
    receive() external payable {
        emit SafeReceived(msg.sender, msg.value);
    }

    constructor() {}
}

src/contracts/test/GnosisProxy.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract GnosisSafeProxy {
    address internal singleton;

    /// @dev Constructor function sets address of singleton contract.
    /// @param _singleton Singleton address.
    constructor(address _singleton) {
        require(_singleton != address(0), 'Invalid singleton address provided');
        singleton = _singleton;
    }

    /// @dev Fallback function forwards all transactions and returns all received return data.
    fallback() external payable {
        // solhint-disable-next-line no-inline-assembly
        assembly {
            let _singleton := and(sload(0), 0xffffffffffffffffffffffffffffffffffffffff)
            // 0xa619486e == keccak("masterCopy()"). The value is right padded to 32-bytes with 0s
            if eq(
                calldataload(0),
                0xa619486e00000000000000000000000000000000000000000000000000000000
            ) {
                mstore(0, _singleton)
                return(0, 0x20)
            }
            calldatacopy(0, 0, calldatasize())
            let success := delegatecall(gas(), _singleton, 0, calldatasize(), 0, 0)
            returndatacopy(0, 0, returndatasize())
            if eq(success, 0) {
                revert(0, returndatasize())
            }
            return(0, returndatasize())
        }
    }
}

src/contracts/test/UsdtFake.sol

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


contract UsdtFake {
  function decimals() external pure returns (uint8) {
    return 6;
  }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": false
  },
  "evmVersion": "london",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.