Uniswap v3 – How to Resolve Token Swap Errors with Web3js and Hardhat

etherhardhattransactionsuniswapweb3js

I'm trying to execute a swap using web3 through following code snap:

const fromTokenAddress = `0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2`; // WETH9
const toTokenAddress = `0x6B175474E89094C44Da98b954EedeAC495271d0F`; // DAI
const routerContract = new web3.eth.Contract(routerABI, routerAddress);
const expiryDate = Math.floor(Date.now() / 1000) + 900;
const web3 = new Web3(`http://192.168.0.11:8545/`);
const privateKey = credentials.privateKey;
const activeAccount = web3.eth.accounts.privateKeyToAccount(privateKey);
const qty = web3.utils.toWei('0.01', 'ether');

const params = {
    tokenIn: fromTokenAddress,
    tokenOut: toTokenAddress,
    fee: 3000,
    recipient: activeAccount.address,
    deadline: expiryDate,
    amountIn: qty,
    amountOutMinimum: 0,
    sqrtPriceLimitX96: 0,
};

let encodedTx = routerContract.methods.exactInputSingle(params).encodeABI();
let transactionObject = {
    gas: 238989, // gas fee needs updating?
    data: encodedTx,
    from: activeAccount.address,
    to: routerAddress
};

web3.eth.accounts.signTransaction(transactionObject, privateKey, (error, signedTx) => {
    if (error) {
        console.log(error);
    } else {
        web3.eth.sendSignedTransaction(signedTx.rawTransaction).on('receipt', (receipt) => {
            console.log(receipt);
        });
    }
});

I'm using mainnet fork via hardhat and the transaction always fails with such error:

Returned error: Error: VM Exception while processing transaction: reverted with reason string 'STF'

Does anybody have a clue of what that error means? Or can somebody point me a working code that swaps tokens in Uniswap v3?

Best Answer

STF is safe transfer from - double check that you are approving your contract to spend your wallet's tokens, and any other approvals possible.

Related Topic