@YosephKS thanks for the pointers, I somewhat managed to get a clue but once again unsure what to do again.
I was able to find an example smart contract for the swap feature, my smart contract is similar except I don’t have “_token2” & “_owner2” as required parameters, I predefined them in the constructor(), as “_token2” will always be our custom token & “_owner2” will always be the wallet address where we store our custom token.
Anyway, moving along. To interact with the swap smart contract, this is the function that would run it when called after user has input the amount they want to swap:
(using “moralis”: “^0.0.134” & “react-moralis”: “^0.3.1” packages on React)
const swapToken = async () => {
const web3 = await Moralis.enableWeb3();
// This is the smart contract address
const swapConAdd = process.env.REACT_APP_TEST_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_TEST_USDT_ADD;
}
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"
}
];
const contract = new web3.eth.Contract(abi, swapConAdd);
const swap = await contract.methods.swap(
stableAdd,
buyerAdd,
Moralis.Units.Token(buyerAmt.toString(), stableDec.toString()),
Moralis.Units.Token(sellerAmt.toString(), "18")
).send({
from: buyerAdd,
value: Moralis.Units.Token(buyerAmt.toString(), stableDec.toString()),
gasPrice: web3.utils.toWei("5", "gwei"),
gas: web3.utils.toWei("0.0000000000005", "ether")
});
console.log(swap);
} catch(error) {
console.log("transfer error", error);
}
}
Once ran, the Metamask popup would appear to ask for confirmation of the transaction.
However, a few things were wrong:
- The smart contract address ended up being the recipient address.
- The swap value is correct but it’s not in USDT, instead it’s TBNB.
And when the transaction is confirmed, I got this error in the console:
I couldn’t see what’s the issue here & is clueless. Could it be the predefined variables in the smart contract? Or is it something to do with how the smart contract method was executed through React?
NOTE: All of this is on BSC Testnet, even the smart contract was compiled & deployed to BSC Testnet with Remix.