Contract approval

Network tokens need to grant permission to the contract first to be able to exchange on the contract

1. EVM Chain

This example uses the BSC chain USDT to apprive the contract 0x733dab9e78b67e1d4ccd1c2066f006d5eddf25be

abi File

Determine whether to approve and if gas is sufficient

// isApproved example
// USDT(BSC)  0x55d398326f99059ff775485246999027b3197955
 import { ethers } from "ethers";
 import abi from './abi'  // For details on the abi file, see the BridgersAbi.json file above
 import BigNumber from 'bignumber.js'

 const walletAddress = '0x6F14653a91AC36935bdB15db6ccC66dC57593653' // wallet address
 const contractAddress = '0x733dab9e78b67e1d4ccd1c2066f006d5eddf25be' //contract address
 const tokenContract = '0x55d398326f99059ff775485246999027b3197955' //token contract
 const provider = new ethers.providers.Web3Provider(window.ethereum, "any")
 const contract = new ethers.Contract(tokenContract, abi, provider)
 const fromNumber = 100 // 100 as a comparison quantity
 contract
  .allowance(walletAddress, contractAddress)
  .then((allowAmt) => {
    const num = new BigNumber(
     ethers.utils.formatUnits(allowAmt, 18),
    )
    const fromTokenNum = new BigNumber(fromNumber)
    console.log(num.toString())
    console.log(fromTokenNum.toString())
    if (num.gt(fromTokenNum)) {
        console.log('don`t need Approved')
    } else {
        console.log('need Approved')
    }
  })
  .catch( err => {
    //console.log(err)
  })

approval code example

// Approved example
// USDT(BSC)  0x55d398326f99059ff775485246999027b3197955
 import { ethers } from "ethers";
 import abi from './abi'
 import BigNumber from 'bignumber.js'
 
 const walletAddress = '0x6F14653a91AC36935bdB15db6ccC66dC57593653' // wallet address
 const contractAddress = '0x733dab9e78b67e1d4ccd1c2066f006d5eddf25be' //contract address
 const tokenContract = '0x55d398326f99059ff775485246999027b3197955' //token contract
 const provider = new ethers.providers.Web3Provider(window.ethereum, "any")
 const signer = provider.getSigner()
 const contract = new ethers.Contract(tokenContract, abi, provider)
 contract.estimateGas
   .approve(contractAddress, ethers.constants.MaxUint256, {
     from: walletAddress,
   }).then(res => {
     contract.connect(signer)
       .approve(contractAddress, ethers.constants.MaxUint256, {
         from: walletAddress,
       })
       .then((res) => {
          console.log('user Approved ')
        })
       .catch((error) => {
          console.log('user cancle Approved ')
       })
  })
 let filter = contract.filters.Approval(
   walletAddress,
   contractAddress,
   null,
 )
 contract.on(filter, (from, to, amount, event) => {
   console.log('Approve success')
 })

2、TRON Chain

This example uses the TRON chain USDT to apprive the contract TEorZTZ5MHx8SrvsYs1R3Ds5WvY1pVoMSA

Determine whether to approve and if gas is sufficient

// isApproved example
// USDT(TRON)  TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
 import { ethers } from "ethers";
 import BigNumber from 'bignumber.js'
 
const walletAddress = 'TV6MuMXfmLbBqPZvBHdwFsDnQeVfnmiuSi' // wallet address
const contractAddress = 'TEorZTZ5MHx8SrvsYs1R3Ds5WvY1pVoMSA' //contract address
const tokenContract = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t' //token contract
const fromNumber = 100 // 100 as a comparison quantity

let tronWeb = window.tronWeb
const contract = await tronWeb.contract().at(tokenContract );
const allowance = contract.allowance(walletAddress , contractAddress)
const allowAmt = await allowance.call()
const num = new BigNumber(
  ethers.utils.formatUnits(allowAmt, 6 ),
)
const fromTokenNum = new BigNumber(fromNumber)
console.log(num.toString())
console.log(fromTokenNum.toString())
if (num.gt(fromTokenNum)) {
   console.log('don`t need Approved')
} else {
  console.log('need Approved')
}

approval code example

// Approved example
// USDT(TRON)  TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t
 import { ethers } from "ethers";
 import BigNumber from 'bignumber.js'
 
 const walletAddress = 'TV6MuMXfmLbBqPZvBHdwFsDnQeVfnmiuSi' // wallet address
 const contractAddress = 'TEorZTZ5MHx8SrvsYs1R3Ds5WvY1pVoMSA' //contract address
 const tokenContract = 'TR7NHqjeKQxGTCi8q8ZY4pL8otSzgjLj6t' //token contract
const contract = await tronWeb.contract().at(tokenContract);
contract.approve(contractAddress , ethers.constants.MaxUint256).send().then( (hash)=> {
    console.log('user Approved',hash)
    tronWeb.trx.getTransaction(hash).then((result) => {
      console.log('Approve success',result)
    })
}).catch(err => {
  console.log('user cancle Approved')
 })

send coins code example

  const tronWeb = window.tronWeb
    const transaction = await tronWeb.transactionBuilder.triggerSmartContract(
      response.data.txData.tronRouterAddrees,  // From [Obtain callData] SWAP interface in the module to obtain the tronRouterAddrees field
      response.data.txData.functionName,  // From [Obtain callData] SWAP interface in the module to obtain the functionName field
      response.data.txData.options,// From [Obtain callData] SWAP interface in the module to obtain the options field
      response.data.txData.parameter,// From [Obtain callData] SWAP interface in the module to obtain the parameter field
      response.data.txData.fromAddress// From [Obtain callData] SWAP interface in the module to obtain the fromAddress field
    )
    let signedTx
    try{
      signedTx = await tronWeb.trx.sign(transaction.transaction)
    }catch{
      console.log("Signing failed")
    }
    tronWeb.trx.sendRawTransaction(signedTx)
    .then((broastTx) => {
      console.log(broastTx)
    }).catch( error => {
       console.log("Failed to send coins")
    })

Last updated