Obtain callData

Request endpoint to initiate the swap

Note

Before the swap, wallet address needs to confirm that FROM currency token approves the contract address. The contract address can be fetched by requesting the endpoint

Method 1: Endpoint usage

POST https://api.bridgers.xyz/api/sswap/swap

The fields with * are required, and the fields without * are optional

Request Body

{
 "resCode":"100",
 "resMsg":"Success",
 "data":{
  "txData":{
   "data":"0x...", //交易calldata
   "to": "0x6b4427caa371627e2a73521a2568fcf1212cd4d9", //合约地址Contract Address
   "value":"0x2dd47b4d9a4000"
  }
 }
}

Code example

// swap example
 import { ethers } from 'ethers'
 const provider = new ethers.providers.Web3Provider(window.ethereum, 'any')
 cosnt signer = provider.getSigner()
 const params = {
   fromTokenAddress: '0x55d398326f99059ff775485246999027b3197955',
   toTokenAddress: '0xa71edc38d189767582c38a3145b5873052c3e47a',
   fromAddress: '0x...',  //The wallet address used to send the tokens
   toAddress: '0x...',  //The wallet address used to accept tokens
   fromTokenChain: 'BSC',
   toTokenChain: 'HECO',
   fromTokenAmount: '8000000000000000000',
   amountOutMin:'7884000000000000000',
   fromCoinCode:'USDT(BSC)',
   toCoinCode:'USDT(HECO)',
   equipmentNo:'', // your equipment number
   sourceType:'H5',
   sourceFlag:'widget'
  }
  const res = await axios.post('https://api.bridgers.xyz/api/sswap/swap',params)
  console.log(res)
  if(res.resCode === '100'){
    const transactionParameters = {
        to: res.data.txData.to, // Required except during contract publications.
        from: state.wallet.address, // must match user's active address.
        data: res.data.txData.data,
        value: res.data.txData.value,
        //gasPrice: 5000000000, // 6 gwei
        //gas: new BigNumber(1000000), // 1000000
    }
    signer.sendTransaction(transactionParameters)
      .then((data) => {
        console.log(data.hash)
      })   
  }

Postman example

Method 2: Directly request the smart contract

To send a swap message, call the contract's swap() or swapEth() function.

Here is an explanation of the swap() and swapEth() interface:

// @param fromToken - fromToken token's address.
// @param toToken - The target token to be exchanged (obtained from the getToken interface's symbol. e.g. ETH(ARB))
// @param destination - The receiving address for the target token
// @param fromAmount - The amount of the original token
// @param minReturnAmount - The anticipated amount of the target token to be exchanged
function swap(
    address fromToken,
    string memory toToken,
    string memory destination,
    uint256 fromAmount,
    uint256 minReturnAmount
) external nonReentrant

// @param toToken - The target token to be exchanged (obtained from the getToken interface's symbol. e.g. ETH(ARB))
// @param destination - The receiving address for the target token
// @param minReturnAmount - The anticipated amount of the target token to be exchanged
function swapEth(
    string memory toToken,
    string memory destination,
    uint256 minReturnAmount
)

Mainnet currency swap calls the swapEth() method, and token swap calls the swap() method. EVM Contract call instance:

exports.swapCallData = async (nodeHost,fromTokenChain,fromTokenAddress,fromTokenAmount,toCoinCode,toAddress,amountOutMin) => {
    const web3 = new Web3(new Web3.providers.HttpProvider(nodeHost));
    const  ROUTER_ADDRESS =  ''; // contract address
    const ROUTE_ABI = require('./abis/BridgersAbi.json'); //ABI Stored inside the contract on chain
    const routerContract = new web3.eth.Contract(ROUTE_ABI, ROUTER_ADDRESS);
    let data;
    let value;
    if('0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee'==fromTokenAddress){
        data = routerContract.methods.swapEth(toCoinCode,toAddress,amountOutMin).encodeABI();
        value = '0x' + new BigNumber(fromTokenAmount).toString(16);
    }else{
        data = routerContract.methods.swap(fromTokenAddress,toCoinCode,toAddress,fromTokenAmount,amountOutMin).encodeABI();
        value = '0x0';
    }

    let res = {
        'data': data,
        'to': ROUTER_ADDRESS,
        'value': value
    };
    return res;
}

TON Contract call instance:

const TonWeb = require('tonweb');
const { Contract, ContractProvider, Sender, Address, Cell, contractAddress, beginCell, SendMode, toNano } = require("@ton/core");
const { TonClient, JettonMaster, WalletContractV4} = require("@ton/ton");
const { getHttpEndpoint } = require("@orbs-network/ton-access")

exports.swapCallData= async(fromAddress, fromTokenAddress, amount, toAddress, amountOutMin, toCoinCode) => {
    const swap = 1783769518;
    const swapETH = 1023744248;
    const transfer = 260734629;
    const gas = toNano("0.06").toString();
    const forwardAmount = toNano("0.01").toString();
    if (fromTokenAddress.toLowerCase() == '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee') {
        const forwardPayload = beginCell()
            .storeUint(swapETH, 32)
            .storeAddress(Address.parse(fromAddress))
            .storeCoins(forwardAmount)
            .storeRef(beginCell().storeUint(0, 32).storeStringTail(JSON.stringify({"fromToken": fromTokenAddress, "toToken":  toCoinCode, "sender": fromAddress, "destination" : toAddress, "minReturnAmount": amountOutMin})).endCell())
            .endCell();
        const body = beginCell()
            .storeUint(0x7362d09c, 32)
            .storeRef(forwardPayload)
            .endCell();
        return {address: sdkInfo.sswapContract.TON, amount: amount, payload: body.toBoc().toString("base64")};
    }
    const swap_forwardPayload = beginCell()
        .storeUint(swap, 32)
        .storeAddress(Address.parse(fromAddress))
        .storeCoins(forwardAmount)
        .storeRef(beginCell().storeUint(0, 32).storeStringTail(JSON.stringify({"fromToken": fromTokenAddress, "toToken":  toCoinCode, "sender": fromAddress, "destination" : toAddress, "minReturnAmount": amountOutMin})).endCell())
        .endCell();

    const swap_body = beginCell()
        .storeUint(transfer, 32)
        .storeUint(0, 64)
        .storeCoins(amount)
        .storeAddress(Address.parse(tonContractAddress))
        .storeAddress(Address.parse(fromAddress))
        .storeBit(0)
        .storeCoins(forwardAmount)
        .storeBit(1)
        .storeRef(swap_forwardPayload)
        .endCell();
    const client = new TonClient({
        endpoint: await getHttpEndpoint({ network: 'mainnet' }),
    })
    const jettonMasterAddress = Address.parse(fromTokenAddress);
    const userAddress = Address.parse(fromAddress);
    const jettonMaster = client.open(JettonMaster.create(jettonMasterAddress));
    const jettonWalletAddress = await jettonMaster.getWalletAddress(userAddress);
    return {address: jettonWalletAddress.toString(), amount: gas, payload: swap_body.toBoc().toString("base64")};
}

Last updated