1

I want to make users pay with tokens instead of 'eth'. Smart contract:

contract Test {

    IERC20 token;

    constructor(address tokenAddress){
        token = IERC20(tokenAddress)
    }

    function payWithToken() external {
        require(token.balanceOf(msg.sender) > 5000, "insufficient token amount")
        token.transferFrom(msg.sender, address(this), 5000;
        ...
    }
}

Can users pay with tokens using this contract? And How can I do this in my frontend via web3.js?

In my frontend, I usually do

const address = 'xxxxxxxx'
const abi = 'xxxxxxxxx'
const url = 'xxxxxxxx'

const web3 = new Web3(url)
const contract = web3.eth.Contract(abi, address)

contract.methods.someFunctions().send({
    from: ethereum.selectedAddress,
    value: web3.utils.toWei('1', ether)
})

How can I call the 'payWithToken' method from the smart contract? Can I do something like this?

contract.methods.payWithToken().send({
    from: ethereum.selectedAddress,
    value: 'tokens here?'
})

I have no idea how can I use the payWithToken method in my frontend using web3.js.

MORĂˆ
  • 2,480
  • 3
  • 16
  • 23

1 Answers1

0

For token we need to first call the approval function from that token contract. Then call the contract function payWithToken without value field

contract.methods.payWithToken().send({
  from: ethereum.selectedAddress,
  # value: 'tokens here?' // no need of this
})
Sibiraj PR
  • 1,481
  • 1
  • 10
  • 25