Skip to content
Verified contractExactNo

SwapFactory

Address0xa8c268c841c302e3d5f7a7d3e1cb0599fe7e1d8d
Balance

0 ETH

 

Transactions

50

 

Compiler

solc 0.6.12

 

Same code

1 more contract

 

Details

Compiler
solc 0.6.12+commit.27d51765
Language
solidity
Optimization
Yes, 200 runs
EVM version
istanbul
License
No
Match
Exactcreation code: yes, runtime code: yes
Verified on Sourcify
Created in block
11,379,855
Creation transaction
0xa1e95c1c2f…152331a038

localhost/contracts/BNBETH/SwapFactory.sol

// SPDX-License-Identifier: No License (None)
pragma solidity ^0.6.9;

//import "./SafeMath.sol";
//import "./Ownable.sol";
import "./SwapPair.sol";

interface IERC20 {
    function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
    function transfer(address recipient, uint256 amount) external returns (bool);
}

interface IValidator {
    // returns: user balance, native (foreign for us) encoded balance, foreign (native for us) encoded balance
    function checkBalances(address pair, address foreignSwapPair, address user) external returns(uint256);
    // returns: user balance
    function checkBalance(address pair, address foreignSwapPair, address user) external returns(uint256);
    // returns: oracle fee
    function getOracleFee(uint256 req) external returns(uint256);  //req: 1 - cancel, 2 - claim, returns: value
}

interface ISmart {
    function requestCompensation(address user, uint256 feeAmount) external returns(bool);
}

interface IAuction {
    function contributeFromSmartSwap(address payable _whom) external payable returns (bool);
}

contract SwapFactory is Ownable {
    using SafeMath for uint256;

    address constant NATIVE_COINS = 0x0000000000000000000000000000000000000009; // 1 - BNB, 2 - ETH, 3 - BTC
    uint256 constant INVESTMENT_FLAG = 2**224;

    mapping(address => mapping(address => address payable)) public getPair;
    mapping(address => address) public foreignPair;
    address[] public allPairs;
    address public foreignFactory;

    mapping(address => mapping(address => uint256)) public cancelAmount;    // pair => user => cancelAmount
    mapping(address => mapping(address => uint256)) public swapAmount;    // pair => user => swapAmount

    mapping(address => bool) public isExchange;         // is Exchange address
    mapping(address => bool) public isExcludedSender;   // address excluded from receiving SMART token as fee compensation

    
    uint256 public fee;
    address payable public validator;
    address public system;  // system address mey change fee amount
    address public auction; // auction address
    address public contractSmart;  // the contract address to request Smart token in exchange of fee
    address public feeReceiver; // address which receive the fee (by default is validator)
    

    address public newFactory;            // new factory address to upgrade
    event PairCreated(address indexed tokenA, address indexed tokenB, address pair, uint);
    event SwapRequest(address indexed tokenA, address indexed tokenB, address indexed user, uint256 amountA, bool isInvestment);
    event CancelRequest(address indexed tokenA, address indexed tokenB, address indexed user, uint256 amountA, bool isInvestment);
    event CancelApprove(address indexed tokenA, address indexed tokenB, address indexed user, uint256 amountA, bool isInvestment);
    event ClaimRequest(address indexed tokenA, address indexed tokenB, address indexed user, uint256 amountB, bool isInvestment);
    event ClaimApprove(address indexed tokenA, address indexed tokenB, address indexed user, uint256 amountB, uint256 amountA, bool isInvestment);
    event ExchangeInvestETH(address indexed exchange, address indexed whom, uint256 value);
    
    /**
    * @dev Throws if called by any account other than the system.
    */
    modifier onlySystem() {
        require(msg.sender == system || isOwner(), "Caller is not the system");
        _;
    }

    constructor (address _system) public {
        system = _system;
        newFactory = address(this);
    }
    
    //invest into auction
    function investAuction(address payable _whom) external payable returns (bool)
    {
        require(foreignPair[msg.sender] != address(0), "Investing allowed from pair only");
        IAuction(auction).contributeFromSmartSwap{value: msg.value}(_whom);
    }
    
    function setFee(uint256 _fee) external onlySystem returns(bool) {
        fee = _fee;
        return true;
    }

    function setSystem(address _system) external onlyOwner returns(bool) {
        system = _system;
        return true;
    }

    function setValidator(address payable _validator) external onlyOwner returns(bool) {
        validator = _validator;
        if(feeReceiver == address(0)) feeReceiver = _validator;
        return true;
    }

    function setForeignFactory(address _addr) external onlyOwner returns(bool) {
        foreignFactory = _addr;
        return true;
    }

    function setFeeReceiver(address _addr) external onlyOwner returns(bool) {
        feeReceiver = _addr;
        return true;
    }

    function setMSSContract(address _addr) external onlyOwner returns(bool) {
        contractSmart = _addr;
        return true;
    }

    function setNewFactory(address _addr) external onlyOwner returns(bool) {
        newFactory = _addr;
        return true;
    }

    function setAuction(address _addr) external onlyOwner returns(bool) {
        auction = _addr;
        return true;
    }
    
    // for ETH side only
    function changeExchangeAddress(address _which,bool _bool) external onlyOwner returns(bool){
        isExchange[_which] = _bool;
        return true;
    }
    
    function changeExcludedAddress(address _which,bool _bool) external onlyOwner returns(bool){
        isExcludedSender[_which] = _bool;
        return true;
    }
    
    function createPair(address tokenA, uint8 decimalsA, address tokenB, uint8 decimalsB) public onlyOwner returns (address payable pair) {
        require(getPair[tokenA][tokenB] == address(0), 'PAIR_EXISTS'); // single check is sufficient
        bytes memory bytecode = type(SwapPair).creationCode;
        bytes32 salt = keccak256(abi.encodePacked(tokenA, tokenB));
        assembly {
            pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
        }
        foreignPair[pair] = getForeignPair(tokenB, tokenA);
        SwapPair(pair).initialize(foreignPair[pair], tokenA, decimalsA, tokenB, decimalsB);
        getPair[tokenA][tokenB] = pair;

        allPairs.push(pair);
        emit PairCreated(tokenA, tokenB, pair, allPairs.length);
    }

    function getForeignPair(address tokenA, address tokenB) internal view returns(address pair) {
        pair = address(uint(keccak256(abi.encodePacked(
                hex'ff',
                foreignFactory,
                keccak256(abi.encodePacked(tokenA, tokenB)),
                hex'05a14d15386c927ac1a2b1e515003107665e36f549246b88b3d136d36426eded' // init code hash
            ))));
    }

    // set already existed pairs in case of contract upgrade
    function setPairs(address[] memory tokenA, address[] memory tokenB, address payable[] memory pair) external onlyOwner returns(bool) {
        uint256 len = tokenA.length;
        while (len > 0) {
            len--;
            getPair[tokenA[len]][tokenB[len]] = pair[len];
            foreignPair[pair[len]] = SwapPair(pair[len]).foreignSwapPair();
            allPairs.push(pair[len]);
            emit PairCreated(tokenA[len], tokenB[len], pair[len], allPairs.length);            
        }
        return true;
    }
    // calculates the CREATE2 address for a pair without making any external calls
    function pairAddressFor(address tokenA, address tokenB) external view returns (address pair, bytes32 bytecodeHash) {
        bytes memory bytecode = type(SwapPair).creationCode;
        bytecodeHash = keccak256(bytecode);
        pair = address(uint(keccak256(abi.encodePacked(
                hex'ff',
                address(this),
                keccak256(abi.encodePacked(tokenA, tokenB)),
                bytecodeHash    // hex'05a14d15386c927ac1a2b1e515003107665e36f549246b88b3d136d36426eded' // init code hash
            ))));
    }

    // ================== on Ethereum network only =========================================================================

    //user should approve tokens transfer before calling this function.
    function swapInvestment(address tokenA, uint256 amount) external payable returns (bool) {
        address tokenB = address(1);    // BNB (foreign coin)
        return _swap(tokenA, tokenB, msg.sender, amount, true);
    }

    function cancelInvestment(address tokenA, uint256 amount) external payable returns (bool) {
        address tokenB = address(1);    // BNB (foreign coin)
        return _cancel(tokenA, tokenB, msg.sender, amount, true);
    }


    // function for invest ETH from from exchange on user behalf
    function contributeWithEtherBehalf(address payable _whom) external payable returns (bool) {
        require(isExchange[msg.sender], "Not an Exchange address");
        address tokenA = address(2);    // ETH (native coin)
        address tokenB = address(1);    // BNB (foreign coin)
        uint256 amount = msg.value - fee;
        emit ExchangeInvestETH(msg.sender, _whom, msg.value);
        return _swap(tokenA, tokenB, _whom, amount, true);
    }
    // ================= end Ethereum part =================================================================================

    // ====================== on BSC side only =============================================================================

    // tokenB - foreign token address or address(1) for ETH
    // amountB - amount of foreign tokens or ETH
    function claimInvestmentBehalf(address tokenB, address user, uint256 amountB) external onlySystem returns (bool) {
        address tokenA = address(1);    // BNB (native coin)
        return _claimTokenBehalf(tokenA, tokenB, user, amountB, true);
    }
    // ====================== end BSC part =================================================================================

    
    //user should approve tokens transfer before calling this function.
    function swap(address tokenA, address tokenB, uint256 amount) external payable returns (bool) {
        return _swap(tokenA, tokenB, msg.sender, amount, false);
    }

    function cancel(address tokenA, address tokenB, uint256 amount) external payable returns (bool) {
        return _cancel(tokenA, tokenB, msg.sender, amount, false);
    }
    function claimTokenBehalf(address tokenA, address tokenB, address user, uint256 amountB) external onlySystem returns (bool) {
        return _claimTokenBehalf(tokenA, tokenB, user, amountB, false);
    }

    // transfer fee to receiver and request MASS token as compensation.
    function transferFee(uint256 feeAmount, address user) internal {
        TransferHelper.safeTransferETH(feeReceiver, feeAmount);
        if(contractSmart != address(0) && !isExcludedSender[msg.sender]) {
            ISmart(contractSmart).requestCompensation(user, feeAmount);
        }
    }

    //user should approve tokens transfer before calling this function.
    function _swap(address tokenA, address tokenB, address user, uint256 amount, bool isInvestment) internal returns (bool) {
        uint256 feeAmount = msg.value;
        if (tokenA < NATIVE_COINS) feeAmount = feeAmount.sub(amount,"Insuficiant value");   // if native coin, then feeAmount = msg.value - swap amount
        require(feeAmount >= fee,"Insufficient fee");
        require(amount != 0, "Zero amount");
        address payable pair = getPair[tokenA][tokenB];
        require(pair != address(0), 'PAIR_NOT_EXISTS');
        
        // transfer fee to validator. May be changed to request tokens for compensation
        transferFee(feeAmount, user);

        if (tokenA < NATIVE_COINS)
            TransferHelper.safeTransferETH(pair, amount);
        else 
            TransferHelper.safeTransferFrom(tokenA, user, pair, amount);
        SwapPair(pair).deposit(user, amount, isInvestment);
        emit SwapRequest(tokenA, tokenB, user, amount, isInvestment);
        return true;
    }

    function _cancel(address tokenA, address tokenB, address user, uint256 amount, bool isInvestment) internal returns (bool) {
        require(msg.value >= IValidator(validator).getOracleFee(1), "Insufficient fee");    // check oracle fee for Cancel request
        require(amount != 0, "Zero amount");
        address payable pair = getPair[tokenA][tokenB];
        require(pair != address(0), 'PAIR_NOT_EXISTS');
        if (cancelAmount[pair][user] == 0) {  // new cancel request
            cancelAmount[pair][user] = amount;
            SwapPair(pair).cancel(user, amount, isInvestment);
        }
        else { // repeat cancel request in case oracle issues.
            amount = cancelAmount[pair][user];
        }

        // transfer fee to validator. May be changed to request tokens for compensation
        transferFee(msg.value, user);

        if (isInvestment)
            IValidator(validator).checkBalance(pair, foreignPair[pair], _investAddress(user));    // on Ethereum network only
        else
            IValidator(validator).checkBalance(pair, foreignPair[pair], _swapAddress(user));
        emit CancelRequest(tokenA, tokenB, user, amount, isInvestment);
        return true;
    }


    // amountB - amount of foreign token to swap
    function _claimTokenBehalf(address tokenA, address tokenB, address user, uint256 amountB, bool isInvestment) internal returns (bool) {
        address payable pair = getPair[tokenA][tokenB];
        require(pair != address(0), 'PAIR_NOT_EXISTS');
        require(amountB != 0, "Zero amount");
        if (swapAmount[pair][user] == 0) {  // new claim request
            swapAmount[pair][user] = amountB;
            SwapPair(pair).claim(user, amountB, isInvestment);
        }
        else { // repeat claim request in case oracle issues.
            amountB = swapAmount[pair][user];
        }
        if (isInvestment)
            IValidator(validator).checkBalances(pair, foreignPair[pair], _investAddress(user));    // on BSC network only
        else
            IValidator(validator).checkBalances(pair, foreignPair[pair], user);
        emit ClaimRequest(tokenA, tokenB, user, amountB, isInvestment);
        return true;
    }

    // On both side (BEP and ERC) we accumulate user's deposits (balance).
    // If balance on one side it greater then on other, the difference means user deposit.
    function balanceCallback(address payable pair, address user, uint256 balanceForeign) external returns(bool) {
        require (validator == msg.sender, "Not validator");
        (uint256 balance, bool isInvestment) = _getBalance(SwapPair(pair).balanceOf(user));
        if (isInvestment) user = _swapAddress(user);    // real user address = investAddress + 1
        uint256 amount = cancelAmount[pair][user];
        require (amount != 0, "No active cancel request");
        cancelAmount[pair][user] = 0;
        address tokenA;
        address tokenB;
        bool isApproved = (balanceForeign <= balance);
        (tokenA, tokenB) = SwapPair(pair).cancelApprove(user, amount, isApproved, isInvestment);
        if(!isApproved) amount = 0;

        emit CancelApprove(tokenA, tokenB, user, amount, isInvestment);
        return true;
    }

    function balancesCallback(
            address payable pair,
            address user,
            uint256 balanceForeign,
            uint256 nativeEncoded,
            uint256 foreignSpent,
            uint256 rate    // rate = foreignPrice.mul(NOMINATOR) / nativePrice;   // current rate
        ) external returns(bool) {
        require (validator == msg.sender, "Not validator");
        (uint256 balance, bool isInvestment) = _getBalance(balanceForeign);
        address userSwap;
        if (isInvestment) {
            userSwap = user;    // investAddress
            user = _swapAddress(user);    // real user address = investAddress + 1
        }
        else {
            userSwap = _swapAddress(user);
        }

        uint256 amountB = swapAmount[pair][user];
        require (amountB != 0, "No active swap request");
        swapAmount[pair][user] = 0;
        address tokenA;
        address tokenB;
        uint256 nativeAmount;
        uint256 rest;
        if (balance >= SwapPair(pair).balanceOf(userSwap)) { // is approve claim
            (tokenA, tokenB, nativeAmount, rest) = SwapPair(pair).claimApprove(user, amountB, nativeEncoded, foreignSpent, rate, true, isInvestment);
            amountB = amountB.sub(rest);
        }
        else {
            (tokenA, tokenB, nativeAmount, rest) = SwapPair(pair).claimApprove(user, amountB, nativeEncoded, foreignSpent, rate, false, isInvestment);
            amountB = 0;
        }

        emit ClaimApprove(tokenA, tokenB, user, amountB, nativeAmount, isInvestment);
        return true;
    }

    // swapAddress = user address + 1.
    // balanceOf contain two types of balance:
    // 1. balanceOf[user] - balance of tokens on native chain
    // 2. balanceOf[user+1] - swapped balance of foreign tokens. I.e. on BSC chain it contain amount of ETH that was swapped.
    function _swapAddress(address user) internal pure returns(address swapAddress) {
        swapAddress = address(uint160(user)+1);
    }
    // 3. balanceOf[user-1] - investment to auction total balance.
    function _investAddress(address user) internal pure returns(address investAddress) {
        investAddress = address(uint160(user)-1);
    }
    // return balance and investment flag
    function _getBalance(uint256 balanceWithFlag) internal pure returns(uint256 balance, bool isInvestment) {
        if(INVESTMENT_FLAG & balanceWithFlag != 0) {
            balance = uint192(balanceWithFlag);
            isInvestment = true;
        }
        else {
            balance = balanceWithFlag;
            isInvestment = false;
        }
    }
}

localhost/contracts/BNBETH/Ownable.sol

// SPDX-License-Identifier: No License (None)
pragma solidity ^0.6.9;

/**
 * @title Ownable
 * @dev The Ownable contract has an owner address, and provides basic authorization control
 * functions, this simplifies the implementation of "user permissions".
 *
 * Source https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-solidity/v2.1.3/contracts/ownership/Ownable.sol
 * This contract is copied here and renamed from the original to avoid clashes in the compiled artifacts
 * when the user imports a zos-lib contract (that transitively causes this contract to be compiled and added to the
 * build/artifacts folder) as well as the vanilla Ownable implementation from an openzeppelin version.
 */
contract Ownable {
    address private _owner;

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

    /**
     * @dev The Ownable constructor sets the original `owner` of the contract to the sender
     * account.
     */
    constructor () internal {
        _owner = msg.sender;
        emit OwnershipTransferred(address(0), _owner);
    }

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

    /**
     * @dev Throws if called by any account other than the owner.
     */
    modifier onlyOwner() {
        require(isOwner(),"Not Owner");
        _;
    }

    /**
     * @return true if `msg.sender` is the owner of the contract.
     */
    function isOwner() public view returns (bool) {
        return msg.sender == _owner;
    }

    /**
     * @dev Allows the current owner to relinquish control of the contract.
     * @notice Renouncing to ownership will leave the contract without an owner.
     * It will not be possible to call the functions with the `onlyOwner`
     * modifier anymore.
     */
    function renounceOwnership() public onlyOwner {
        emit OwnershipTransferred(_owner, address(0));
        _owner = address(0);
    }

    /**
     * @dev Allows the current owner to transfer control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     */
    function transferOwnership(address newOwner) public onlyOwner {
        _transferOwnership(newOwner);
    }

    /**
     * @dev Transfers control of the contract to a newOwner.
     * @param newOwner The address to transfer ownership to.
     */
    function _transferOwnership(address newOwner) internal {
        require(newOwner != address(0),"Zero address not allowed");
        emit OwnershipTransferred(_owner, newOwner);
        _owner = newOwner;
    }
}

localhost/contracts/BNBETH/SafeMath.sol

// SPDX-License-Identifier: No License (None)
pragma solidity ^0.6.9;

/**
 * @dev Wrappers over Solidity's arithmetic operations with added overflow
 * checks.
 *
 * Arithmetic operations in Solidity wrap on overflow. This can easily result
 * in bugs, because programmers usually assume that an overflow raises an
 * error, which is the standard behavior in high level programming languages.
 * `SafeMath` restores this intuition by reverting the transaction when an
 * operation overflows.
 *
 * Using this library instead of the unchecked operations eliminates an entire
 * class of bugs, so it's recommended to use it always.
 */
library SafeMath {
  /**
   * @dev Returns the addition of two unsigned integers, reverting on
   * overflow.
   *
   * Counterpart to Solidity's `+` operator.
   *
   * Requirements:
   * - Addition cannot overflow.
   */
  function add(uint256 a, uint256 b) internal pure returns (uint256) {
    uint256 c = a + b;
    require(c >= a, "SafeMath: addition overflow");

    return c;
  }

  /**
   * @dev Returns the subtraction of two unsigned integers, reverting on
   * overflow (when the result is negative).
   *
   * Counterpart to Solidity's `-` operator.
   *
   * Requirements:
   * - Subtraction cannot overflow.
   */
  function sub(uint256 a, uint256 b) internal pure returns (uint256) {
    return sub(a, b, "SafeMath: subtraction overflow");
  }

  /**
   * @dev Returns the subtraction of two unsigned integers, reverting with custom message on
   * overflow (when the result is negative).
   *
   * Counterpart to Solidity's `-` operator.
   *
   * Requirements:
   * - Subtraction cannot overflow.
   */
  function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
    require(b <= a, errorMessage);
    uint256 c = a - b;

    return c;
  }

  /**
   * @dev Returns the multiplication of two unsigned integers, reverting on
   * overflow.
   *
   * Counterpart to Solidity's `*` operator.
   *
   * Requirements:
   * - Multiplication cannot overflow.
   */
  function mul(uint256 a, uint256 b) internal pure returns (uint256) {
    // Gas optimization: this is cheaper than requiring 'a' not being zero, but the
    // benefit is lost if 'b' is also tested.
    // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
    if (a == 0) {
      return 0;
    }

    uint256 c = a * b;
    require(c / a == b, "SafeMath: multiplication overflow");

    return c;
  }

  /**
   * @dev Returns the integer division of two unsigned integers. Reverts on
   * division by zero. The result is rounded towards zero.
   *
   * Counterpart to Solidity's `/` operator. Note: this function uses a
   * `revert` opcode (which leaves remaining gas untouched) while Solidity
   * uses an invalid opcode to revert (consuming all remaining gas).
   *
   * Requirements:
   * - The divisor cannot be zero.
   */
  function div(uint256 a, uint256 b) internal pure returns (uint256) {
    return div(a, b, "SafeMath: division by zero");
  }

  /**
   * @dev Returns the integer division of two unsigned integers. Reverts with custom message on
   * division by zero. The result is rounded towards zero.
   *
   * Counterpart to Solidity's `/` operator. Note: this function uses a
   * `revert` opcode (which leaves remaining gas untouched) while Solidity
   * uses an invalid opcode to revert (consuming all remaining gas).
   *
   * Requirements:
   * - The divisor cannot be zero.
   */
  function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
    // Solidity only automatically asserts when dividing by 0
    require(b > 0, errorMessage);
    uint256 c = a / b;
    // assert(a == b * c + a % b); // There is no case in which this doesn't hold

    return c;
  }

  /**
   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
   * Reverts when dividing by zero.
   *
   * Counterpart to Solidity's `%` operator. This function uses a `revert`
   * opcode (which leaves remaining gas untouched) while Solidity uses an
   * invalid opcode to revert (consuming all remaining gas).
   *
   * Requirements:
   * - The divisor cannot be zero.
   */
  function mod(uint256 a, uint256 b) internal pure returns (uint256) {
    return mod(a, b, "SafeMath: modulo by zero");
  }

  /**
   * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
   * Reverts with custom message when dividing by zero.
   *
   * Counterpart to Solidity's `%` operator. This function uses a `revert`
   * opcode (which leaves remaining gas untouched) while Solidity uses an
   * invalid opcode to revert (consuming all remaining gas).
   *
   * Requirements:
   * - The divisor cannot be zero.
   */
  function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
    require(b != 0, errorMessage);
    return a % b;
  }
}

localhost/contracts/BNBETH/SwapPair.sol

// SPDX-License-Identifier: No License (None)
pragma solidity ^0.6.9;

import "./SafeMath.sol";
import "./Ownable.sol";
import "./TransferHelper.sol";

// TODO: balance + 1, to avoid Zero balance

interface ISwapFactory {
    function newFactory() external view returns(address);
    function auction() external view returns(address);
    function validator() external view returns(address);
    function investAuction(address payable _whom) external payable returns (bool);
}

contract SwapPair {
    using SafeMath for uint256;

    //uint256 constant chain = 97;  // ETH mainnet = 1, Ropsten = 2, BSC_TESTNET = 97, BSC_MAINNET = 56
    uint256 constant MAX_AMOUNT = 2**192;
    uint256 constant INVESTMENT_FLAG = 2**224;
    uint256 constant NOMINATOR = 10**18;
    uint256 constant PRICE_NOMINATOR = 10**9;     // rate nominator
    address constant NATIVE = address(-1);  // address which holds native token ballance that was spent
    address constant FOREIGN = address(-2); // address which holds foreign token encoded ballance that was spent
    address constant NATIVE_COINS = 0x0000000000000000000000000000000000000009; // 0 - BNB, 1 - ETH, 2 - BTC

    address public token;               // token address
    address public tokenForeign;        // Foreign token address
    address public foreignSwapPair;     // foreign SwapPair contract address (on other blockchain)
    address public factory;             // factory address
    uint256 public decimalsNative;
    uint256 public decimalsForeign;
    uint256 public totalSupply;

    // balanceOf contain two types of balance:
    // 1. balanceOf[user] - balance of tokens on native chain
    // 2. balanceOf[user+1] - swapped balance of foreign tokens. I.e. on BSC chain it contain amount of ETH that was swapped.
    // 3. balanceOf[user-1] - swapped balance of foreign tokens for investment. I.e. on BSC chain it contain amount of ETH that was swapped.
    mapping (address => uint256) public balanceOf;
    //mapping (address => uint256) public cancelAmount;
    //mapping (address => uint256) public swapAmount;

    event CancelRequest(address indexed user, address token, uint256 amount);
    event CancelApprove(address indexed user, address token, uint256 amount);
    event ClaimRequest(address indexed user, address foreignToken, uint256 foreignAmount);
    event ClaimApprove(address indexed user, address foreignToken, uint256 foreignAmount, address token, uint256 amount);

    modifier onlyFactory() {
        require(msg.sender == factory, "Caller is not the factory");
        _;
    }

    constructor() public {
        factory = msg.sender;
    }

    function initialize(address _foreignPair, address tokenA, uint8 decimalsA, address tokenB, uint8 decimalsB) public onlyFactory {
        foreignSwapPair = _foreignPair;
        token = tokenA;
        tokenForeign = tokenB;
        decimalsNative = 10**uint256(decimalsA);
        decimalsForeign = 10**uint256(decimalsB);
    }

    function update() public returns(bool) {
        factory = ISwapFactory(factory).newFactory();
        return true;
    }

    function getTokens() external view returns(address tokenA, address tokenB) {
        tokenA = token;
        tokenB = tokenForeign;
    }
    
    // encode 64 bits of rate (decimal = 9). and 192 bits of amount 
    // into uint256 where high 64 bits is rate and low 192 bit is amount
    // rate = foreign token price / native token price
    function _encode(uint256 rate, uint256 amount) internal pure returns(uint256 encodedBalance) {
        require(amount < MAX_AMOUNT, "Amount overflow");
        require(rate < 2**64, "Rate overflow");
        encodedBalance = rate * MAX_AMOUNT + amount;
    }

    // decode from uint256 where high 64 bits is rate and low 192 bit is amount
    // rate = foreign token price / native token price
    function _decode(uint256 encodedBalance) internal pure returns(uint256 rate, uint256 amount) {
        rate = encodedBalance / MAX_AMOUNT;
        amount = uint192(encodedBalance);
    }

    // swapAddress = user address + 1.
    // balanceOf contain two types of balance:
    // 1. balanceOf[user] - balance of tokens on native chain
    // 2. balanceOf[user+1] - swapped balance of foreign tokens. I.e. on BSC chain it contain amount of ETH that was swapped.
    function _swapAddress(address user) internal pure returns(address swapAddress) {
        swapAddress = address(uint160(user)+1);
    }
    // 3. balanceOf[user-1] - investment to auction total balance.
    function _investAddress(address user) internal pure returns(address investAddress) {
        investAddress = address(uint160(user)-1);
    }

    // call appropriate transfer function
    function _transfer(address to, uint value) internal {
        if (token < NATIVE_COINS) 
            TransferHelper.safeTransferETH(to, value);
        else
            TransferHelper.safeTransfer(token, to, value);
    }

    // user's deposit to the pool, waiting for swap
    function deposit(address user, uint256 amount, bool isInvestment) external onlyFactory returns(bool) {
        if (isInvestment) {
            address investAddress = _investAddress(user);   // on Ethereum side only
            balanceOf[investAddress] = (balanceOf[investAddress].add(amount)) | INVESTMENT_FLAG;
        }
        else {
            balanceOf[user] = balanceOf[user].add(amount);
        }
        totalSupply = totalSupply.add(amount);
        return true;
    }

    // cancel swap order request
    function cancel(address user, uint256 amount, bool isInvestment) external onlyFactory returns(bool) {
        if (isInvestment) {
            address investAddress = _investAddress(user);   // on Ethereum side only
            uint256 balance = uint192(balanceOf[investAddress]);
            balance = balance.sub(amount,"Not enough tokens on the balance");
            balanceOf[investAddress] = balance | INVESTMENT_FLAG;
        }
        else {
            balanceOf[user] = balanceOf[user].sub(amount,"Not enough tokens on the balance");
        }
        totalSupply = totalSupply.sub(amount,"Not enough Total Supply");
        return true;
    }
    // approve cancel swap order and withdraw token from pool or discard cancel request
    // if isInvestment then user = investAddress (user - 1)
    function cancelApprove(address user, uint256 amount, bool approve, bool isInvestment) external onlyFactory returns(address, address) {
        if (approve) {    //approve cancel
            _transfer(user, amount);
        }
        else {  // discard cancel request.
            if (isInvestment)
                user = _investAddress(user);   // on Ethereum side only
            balanceOf[user] = balanceOf[user].add(amount);
            totalSupply = totalSupply.add(amount);
        }
        return (token, tokenForeign);
    }

    // request to claim token after swap
    function claim(address user, uint256 amount, bool isInvestment) external onlyFactory returns(bool) {
        address userBalance;
        if (isInvestment)
            userBalance = _investAddress(user); // on BSC side only
        else
            userBalance = _swapAddress(user);
        balanceOf[userBalance] = balanceOf[userBalance].add(amount);
        return true;
    }

    // approve / discard claim request
    function claimApprove(
            address user,
            uint256 amount, // foreign token amount to swap
            uint256 nativeEncoded,
            uint256 foreignSpent,
            uint256 rate,
            bool approve,
            bool isInvestment
        ) external onlyFactory returns(address, address, uint256 nativeAmount, uint256 rest) {
        address userSwap;
        if (isInvestment) {   //claim investment only on BSC side
            userSwap = _investAddress(user);    // invest address (real user address - 1)
        }
        else {
            userSwap = _swapAddress(user);  // swap address = real user address + 1
        }

        if(approve) { // approve claim
            (nativeAmount, rest) = calculateAmount(amount,nativeEncoded,foreignSpent,rate);
            if (rest != 0) {
                balanceOf[userSwap] = balanceOf[userSwap].sub(rest);    // not all amount swapped
            }
            totalSupply = totalSupply.sub(nativeAmount,"Not enough Total Supply");
            if (isInvestment)
                ISwapFactory(factory).investAuction{value: nativeAmount}(payable(user));
            else
                _transfer(user, nativeAmount);
        }
        else {  // discard claim
            balanceOf[userSwap] = balanceOf[userSwap].sub(amount);
        }
        return (token, tokenForeign, nativeAmount, rest);
    }

    function calculateAmount(
        uint256 foreignAmount,
        uint256 nativeEncoded,
        uint256 foreignSpent,
        uint256 rate    // Foreign token price / Native token price = (Native amount / Foreign amount)
    ) internal returns(uint256 nativeAmount, uint256 rest) {
        uint256 nativeDecimals = decimalsNative;
        uint256 foreignDecimals = decimalsForeign;
        
        // step 1. Check is it enough unspent native tokens
        {
            (uint256 rate1, uint256 amount1) = _decode(nativeEncoded);  // rate1 = Native token price / Foreign token price
            rate1 = rate1*NOMINATOR*foreignDecimals/nativeDecimals;
            amount1 = amount1.sub(balanceOf[NATIVE], "NativeSpent balance higher then remote");
            // rate1, amount1 - rate and amount ready to spend native tokens
            if (amount1 != 0) {
                uint256 requireAmount = foreignAmount.mul(PRICE_NOMINATOR*NOMINATOR).div(rate1);
                if (requireAmount <= amount1) {
                    nativeAmount = requireAmount;
                    foreignAmount = 0;
                }
                else {
                    nativeAmount = amount1;
                    foreignAmount = (requireAmount - amount1).mul(rate1) / (PRICE_NOMINATOR*NOMINATOR);
                }
                balanceOf[NATIVE] = balanceOf[NATIVE].add(nativeAmount);
            }
        }
        require(totalSupply >= nativeAmount,"ERR: Not enough Total Supply");
        // step 2. recalculate rate for swapped tokens
        if (foreignAmount != 0) {
            uint256 rate2 = rate.mul(NOMINATOR).mul(nativeDecimals).div(foreignDecimals);
            uint256 requireAmount = foreignAmount.mul(rate2) / (PRICE_NOMINATOR*NOMINATOR);
            if (totalSupply < nativeAmount.add(requireAmount)) {
                requireAmount = totalSupply.sub(nativeAmount);
                rest = foreignAmount.sub(requireAmount.mul(PRICE_NOMINATOR*NOMINATOR).div(rate2));
                foreignAmount = foreignAmount.sub(rest);
            }
            nativeAmount = nativeAmount.add(requireAmount);
            uint256 amount;
            (rate2, amount) = _decode(balanceOf[FOREIGN]);
            rate2 = rate2.mul(NOMINATOR).mul(nativeDecimals).div(foreignDecimals);
            uint256 amount2 = amount.sub(foreignSpent, "ForeignSpent balance higher then local");
            // rate2, amount2 - rate and amount swapped foreign tokens

            if (amount2 != 0) { // recalculate avarage rate (native amount / foreign amount)
                rate =  ((amount2.mul(rate2)/(PRICE_NOMINATOR*NOMINATOR)).add(requireAmount)).mul(PRICE_NOMINATOR*foreignDecimals).div((amount2.add(foreignAmount)).mul(nativeDecimals));
            }
            balanceOf[FOREIGN] = _encode(rate, amount.add(foreignAmount));
        }
    }

    receive() external payable {
        require(msg.sender == factory, "Not a factory");
    }
}

localhost/contracts/BNBETH/TransferHelper.sol

// SPDX-License-Identifier: GPL-3.0-or-later

pragma solidity >=0.6.0;

// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
    function safeApprove(address token, address to, uint value) internal {
        // bytes4(keccak256(bytes('approve(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
    }

    function safeTransfer(address token, address to, uint value) internal {
        // bytes4(keccak256(bytes('transfer(address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
    }

    function safeTransferFrom(address token, address from, address to, uint value) internal {
        // bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
        (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
        require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
    }

    function safeTransferETH(address to, uint value) internal {
        (bool success,) = to.call{value:value}(new bytes(0));
        require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
    }
}
Compiler settingsShow
{
  "metadata": {
    "bytecodeHash": "ipfs"
  },
  "libraries": {},
  "optimizer": {
    "runs": 200,
    "enabled": true
  },
  "evmVersion": "istanbul",
  "remappings": []
}

Source code and metadata: Sourcify.

The source code belongs to the authors of the contract.