1
//token_address is the adress of the contract : 0xc2132D05D31c914a87C6611C10748AEb04B58e8F
//because USDT on polygon is a Proxy contract, minABI is the abi of the contract where it redirect : https://polygonscan.com/address/0x7ffb3d637014488b63fb9858e279385685afc1e2#code

let contract = new web3.eth.Contract(minABI, token_address);

//Calculate the amount to transfer. In this example I want to transfer 5.44 usdt
let decimals_bn = await contract.methods.decimals().call();
const base = new BigNumber(10);
const amount_to_transfer = base.pow(decimals_bn).times(balance);//this gives 5440000 which seems correct

//Transaction count for nonce
let transaction_count = await web3.eth.getTransactionCount(account_from.address);

//Get gas price 
let gas_price = await web3.eth.getGasPrice();

//Estimate gas 
let estimated_gas = await web3.eth.estimateGas({from: account_from.address});

const createTransaction = await web3.eth.accounts.signTransaction(
{
    from: account_from.address,
    nonce: web3.toHex(transaction_count),
    gasPrice: web3.utils.toHex(gas_price),
    gas: web3.utils.toHex(estimated_gas),
    //gasLimit: web3.utils.toHex(estimated_gas),//I tried with gas , gasLimit or both         
    to: token_address,
    value: "0x0",
    data: contract.methods.transfer(adress_to, web3.toHex(amount_to_transfer)).encodeABI(),
    },
account_from.privateKey
);

//this is when the error trigger
await web3.eth.sendSignedTransaction(createTransaction.rawTransaction);

//Error : 'Error happened while trying to execute a function inside a smart contract'

48 hours on this matter and still no solution. I don't know if the problem is related to gas value or to something else.

Please advise, any help is appreciated.

2
  • How much was gas? Did you try setting a higher value? Usually for token transfer it is less than 100k, but for some tokens it could be higher. You can check other transactions for the same token on a block explorer.
    – Ismael
    Commented Mar 8 at 1:57
  • thank you for pointing out that gas can be higher for contracts call than a simple transaction
    – Francois
    Commented Mar 10 at 20:21

1 Answer 1

1

So it is working now, with a few changes :

Estimate the gas for the contract call, not for a simple transaction.

let estimated_gas_for_contract_call = await contract.methods.transfer(adress_to, amount_to_transfer).estimateGas({
    from: account_from.address
  });

In the method for transfer, toHex is not needed :

data: contract.methods.transfer(adress_to, amount_to_transfer).encodeABI()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.