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?