How to swap stablecoin with unlisted custom token without using Moralis plugins?

@cryptokid buyerAdd is the buyerā€™s wallet address, which is also the current userā€™s wallet address, sellerā€™s wallet address will always be the wallet where we hold our own custom token.

How do you approve a smart contract & which smart contract?
Do you mean calling the approve method for a transfer thatā€™s in an erc20 tokenā€™s smart contract?

If itā€™s the latter then thatā€™s already been called in ā€œstableOptā€, under ā€œcontractAddressā€ :

...

const stableOpt = {
    contractAddress: process.env.REACT_APP_USDT_ADD, // USDT SMART CONTRACT ADDRESS
    functionName: "approve",
    abi: stableAbi,
    params: {
      spender: buyerAdd,
      amount: Moralis.Units.Token(buyerAmt.toString(), stableDec.toString())
    },
};

...

I think that on approve, you have to put on spender the address that will transfer that ERC20 token, in your case it may be the smart contract that will do that transfer from one address to another address.

Ok, let me give that a try.

@cryptokid I think you were right, I should have approved the smart contract address instead of wallet addresses as stated in the Metamask confirmation popup.

However, still getting the same ā€œexecution revertedā€ error when trying to executeFunction for swap.
What is the usual cause of this error?

sometimes you can see a specific error message in bscscan after you submit the transaction, if it happen for the execution to stop in a require

Yea sorry but thereā€™s nothing on the testnet BscScan, no swap transactions recorded anywhere, I can only see the approve ones.

I mean the transaction that you are trying to make now, if you submit it, probably it will fail, but it could also show an error message

Yes, this is all that it is saying, same as before, which doesnā€™t really say much.

image

I mean, after you make that transaction with MetaMask, you can see the transaction that failed in bscscan and see there if there is additional info for the error.

There is literally NOTHING.

This is the latest transaction in Metamask

These are the latest transactions recorded on BscScan.

This is the last recorded bep-20 token transaction.

Like I said, I only see transactions for approve but not swap.

Then maybe you didnā€™t execute that swap, it should be there as a failed transaction.

Hereā€™s the smart contract for swap:

pragma solidity ^0.8.10;

import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.4/contracts/token/ERC20/IERC20.sol";

contract TokenSwap {
  IERC20 public buyerToken;
  address public buyer;
  uint public buyerAmt;
  IERC20 public sellerToken;
  address public seller;
  uint public sellerAmt;

  constructor(
    address _buyerToken,
    address _buyer,
    uint _buyerAmt,
    uint _sellerAmt
  ) {
    buyerToken = IERC20(_buyerToken);
    buyer = _buyer;
    buyerAmt = _buyerAmt;
    sellerToken = IERC20(<<custom token contract address>>);
    seller = <<wallet address that holds our custom token>>;
    sellerAmt = _sellerAmt;
  }

  function swap() public {
    require(msg.sender == buyer || msg.sender == seller, "Not authorized");
    require(
        buyerToken.allowance(buyer, address(this)) >= buyerAmt,
        "Token 1 allowance too low"
    );
    require(
        sellerToken.allowance(seller, address(this)) >= sellerAmt,
        "Token 2 allowance too low"
    );

    _safeTransferFrom(buyerToken, buyer, seller, buyerAmt);
      _safeTransferFrom(sellerToken, seller, buyer, sellerAmt);
  }

  function _safeTransferFrom(
    IERC20 token,
    address sender,
    address recipient,
    uint amount
  ) private {
    bool sent = token.transferFrom(sender, recipient, amount);
    require(sent, "Token transfer failed");
  }
}

This is how swap function was executed:

...

const abi = await getSwapAbi();
const swapOpt = {
    contractAddress: swapConAdd, // swap contract address
    functionName: "swap",
    abi: abi,
    params: {
      buyerToken: stableAdd, // stablecoin contract address
      buyer: buyerAdd, // buyer's wallet address
      buyerAmt: Moralis.Units.Token(buyerAmt.toString(), stableDec.toString()), // value of how much buyer has to transfer
      sellerAmt: Moralis.Units.Token(sellerAmt.toString(), "18") // value of how much seller has to transfer
    }
};

const swap = await Moralis.executeFunction(swapOpt);
swap.on("error", (error) => {
    console.log(error);
})

...

This is the ABI for swap:

const abi = [
    {
      constant: true,
      inputs: [
        {
          internalType: "address",
          name: "buyerToken",
          type: "address"
        },
        {
          internalType: "address",
          name: "buyer",
          type: "address"
        },
        {
          internalType: "uint256",
          name: "buyerAmt",
          type: "uint256"
        },
        {
          internalType: "uint256",
          name: "sellerAmt",
          type: "uint256"
        }
      ],
      name: "swap",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256"
        }
      ],
      payable: true,
      stateMutability: "view",
      type: "function"
    }
];

Now, just looking at these, can you see anything & tell me how swap was not executed correctly?

it looks like there are 2 transfers here, that means that it will require two approves

Yes, 2 transfers. I did approve both, even though it mightā€™ve been the wrong approach.

...

// Approve user wallet for transaction
      const stableAbi = await getStableCoinAbi(stableSym.toLowerCase());
      const stableOpt = {
        contractAddress: process.env.REACT_APP_USDT_ADD,
        functionName: "approve",
        abi: stableAbi,
        params: {
          spender: buyerAdd,
          amount: Moralis.Units.Token(buyerAmt.toString(), stableDec.toString())
        },
      };
      
      const approveStable = await Moralis.executeFunction(stableOpt);

      // Approve custom token wallet for transaction
      const tysAbi = await getStableCoinAbi("xrp"); // testing with xrp
      const tysOpt = {
        contractAddress: process.env.REACT_APP_TYS_ADD,
        functionName: "approve",
        abi: tysAbi,
        params: {
          spender: process.env.REACT_APP_TYS_WALLET,
          amount: Moralis.Units.Token(sellerAmt.toString(), "18")
        },
      };
      
      const approveTys = await Moralis.executeFunction(tysOpt);

...

Can I transfer out from our custom token wallet without having to approve? Since our goal is to make the swap automatic every time a user is trying to buy our custom token.

Ok so, weā€™re making some progress here, all I did was changing a line in the ABI.

From this :

stateMutability: "view"

To this :

stateMutability: "payable"

And now I got this little warning during the Metamask confirmation popup :

When it fails, I can finally see a transaction recorded on BscScan.

Let me try to see if I can find anything from the BscScan transaction.

No luck, even debug trace is not very helpful or descriptive about the error.

{
  "type": "CALL",
  "from": "0x04f...c19", // user wallet address
  "to": "0xa65...ac78", // smart contract address
  "value": "0x0",
  "gas": "0x1b28968",
  "gasUsed": "0xcb",
  "input": "0xfe029156000000000000000000000000337610d27c682e347c9cd60bd4b3b107c9d34ddd00000000000000000000000004fc654d2e22ef7243eb3cbc53d8aaf3fd25bc1900000000000000000000000000000000000000000000000012bc29d8eec7000000000000000000000000000000000000000000000000000029a2241af62c0000",
  "error": "execution reverted",
  "time": "0s"
}

Hereā€™s the transaction.

now it could be related to those approves
strange that you had to change that abi, didnā€™t you copy the abi from the contract compilation?

now it could be related to those approves

I thought so too. Probably because I was approving both transfers with the same Metamask wallet, when I shouldā€™ve approved the wallet that stores our custom token somewhere else.

Did some digging & found out about web3ā€™s signTransaction(), which can be used to automatically sign a transaction with apikey without the need to approve a transfer manually through Metamask.
So I created an api request that does that on the server side with nodejs.

...
const Web3 = require('web3');
const Accounts = require('web3-eth-accounts');
const Moralis = require('moralis/node');
...

require('dotenv').config();

const swapSmartCon = process.env.SWAP_SMART_CONTRACT;
const privateKey = process.env.TYS_PRIVATE_KEY;

router.post("/approve_tys_transfer", async (req, res) => {
  if(parseInt(req.body.buyerAmt) <= 0) {
    return false;
  }

  try {
    const accounts = new Accounts(process.env.BSC_SPEEDY_NODE); // TESTNET
    const buyerAmtStr = req.body.buyerAmt;
    const buyerAmt = Web3.utils.toWei(buyerAmtStr.toString(), 'ether');

    const params = {
      to: swapSmartCon, // swap smart contract address
      value: buyerAmt, // token value
      gas: 2000000,
      nonce: 0,
      chainId: parseInt(process.env.BSC_CHAIN_ID) // bsc testnet chain id
    };

    const signed = await accounts.signTransaction(params, privateKey);

    if(signed.hasOwnProperty("transactionHash")) {
      const json = {
        data: [signed.transactionHash],
        success: true,
        message: "Transaction approved."
      }

      res.json(json);
      res.status(200);
      return
    }

    console.log(signed);
  } catch (error) {
    console.log(error)
  }
})

With the above API method I was able to get the data back, with rawTransaction, transactionHash, etcā€¦

So what I did was:

  1. Have user to approve the transfer through the Metamask interface.
  2. Approve our wallet with the custom token by calling the API.
  3. Run the swap.

However, the transaction still failed but the error being thrown this time indicates that thereā€™s not enough funds in our wallet.

Hereā€™s the thing, thereā€™s enough custom token in the wallet. My guess is that signTransaction() is signing the wrong token maybe?

While I was looking through the transaction, I also noticed that the inputs were empty & the params should be passed through the constructor & not through swap(). I searched through Moralisā€™ documentation but couldnā€™t find anything that states how one could pass in smart contract constructor params with executeFunction().

const abi = await getSwapAbi();
const swapOpt = {
    contractAddress: swapConAdd,
    functionName: "swap",
    abi: abi,
    params: {
      buyerToken: stableAdd,
      buyer: buyerAdd,
      buyerAmt: Moralis.Units.Token(buyerAmt.toString(), stableDec.toString()),
      sellerAmt: Moralis.Units.Token(sellerAmt.toString(), "18")
    }
};

const swap = await Moralis.executeFunction(swapOpt);

How do I pass in params as constructor parameters with Moralis.executeFunction(option)?

usually you donā€™t call the constructor when you are making a transaction

you can also use directly web3 instead of Moralis.executeFunction of something doesnā€™t seem to work with executeFunction

Found out what was the problem, I was using the signTransaction method wrong, which was what made the approve fail in the backend.

Been searching high & low but not many examples out there, until I found one calling it this way.
Iā€™m supposed to pass the ABI to the approve transaction into the signTransaction method, then only run sendSignedTransaction.

Like so :

...

    const abi = await getTYSAbi(); // token ABI
    const tysContract = new web3.eth.Contract(abi, tysSmartCon); // token contract

    const buyerAmtStr = req.body.buyerAmt;
    const buyerAmt = await web3.utils.toWei(buyerAmtStr.toString(), 'ether');

    const tx = tysContract.methods.approve(swapSmartCon, buyerAmt);
    const estGas = await tx.estimateGas({ from: process.env.TYS_WALLET });
    const gasPrice = await web3.eth.getGasPrice();
    const data = tx.encodeABI();
    const nonce = await web3.eth.getTransactionCount(process.env.TYS_WALLET);

    const signedTx = await web3.eth.accounts.signTransaction(
      {
        to: tysContract.options.address, 
        data: data,
        gas: estGas,
        gasPrice: gasPrice,
        nonce: nonce, 
        chainId: process.env.BSC_CHAIN_ID
      },
      privateKey
    );

    const sendSignedTx = await web3.eth.sendSignedTransaction(signedTx.rawTransaction);

...

I checked the allowance after & indeed, it has been updated to the value instead of the usual 0 & the swap was successful.

Glad I can finally put a close to this, thank you @cryptokid for your time.

1 Like