简体   繁体   English

如何将令牌发送到智能合约调用?

[英]How to send tokens to smart contract call?

I want to make users pay with tokens instead of 'eth'.我想让用户用代币而不是“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 ?我怎样才能通过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?如何从智能合约中调用“payWithToken”方法? 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.我不知道如何使用payWithToken在前端使用 payWithToken 方法。

For token we need to first call the approval function from that token contract.对于代币,我们需要先调用该代币合约的批准function。 Then call the contract function payWithToken without value field然后调用没有value字段的合约function payWithToken

contract.methods.payWithToken().send({
  from: ethereum.selectedAddress,
  # value: 'tokens here?' // no need of this
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM