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

@cryptokid

I’ve modified the function slightly to run approve before running the swap but to no avail.

const swapToken = async () => {
    const web3 = await Moralis.enableWeb3();
    // This is the smart contract address
    const swapConAdd = process.env.REACT_APP_SWAP_SMART_CON;

    try {
      let stableAdd; // stablecoin's contract address
      const stableSym = fromToken; // stablecoin symbol
      const stableDec = fromDec; // stablecoin decimal
      const buyerAdd = props.wallAdd; // user wallet address
      const buyerAmt = stableVal; // stablecoin value/amount
      const sellerAmt = tysVal; // custom token value/amount

      if(stableSym.toLowerCase() === "usdt") {
        stableAdd = process.env.REACT_APP_USDT_ADD;
      }

      // 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 tys 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);

      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);
      swap.on("error", (error) => {
        console.log(error);
      })

    } catch(error) {
      console.log("transfer error", error);
    }
  }  

Approving both erc20 tokens was a success, it was showing the right value, with the right token during Metamask confirmation & I was able to get the blockHash data & etc. back.

But when it run the executeFunction for swap, I got “execution reverted” error.

What am I missing here? How do I make this work?

who is buyerAdd, you should approve the smart contract address

@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)?