【问题标题】:How to Use Web3 to Purchase ERC20 Token如何使用 Web3 购买 ERC20 代币
【发布时间】:2021-10-08 02:42:56
【问题描述】:

我正在尝试在 web3 中实现一个可靠的“购买”功能。最终,我希望有一个按钮,然后用户可以打开元掩码以向智能合约发送固定金额(简单示例为 1 以太币)以换取 ERC20 代币。我已经学会了如何在两个钱包之间转移代币,但现在我想更进一步,学习如何发送 Ether 以接收 ERC20。这是我一直在使用的solidity“购买”功能:

function purchase(uint amount, uint tokens) public payable{
        require (msg.value >= amount * 1 ether, "You must pay at least 1 ether per token");
        balances[address (this)] -= tokens;
        balances[msg.sender] += tokens; 

现在我一直在使用它和一个 Onclick 按钮结合 metamask 来传输 ERC20:

async function transfer() {
        contract.methods.transfer("Address", "Token quantity").send({
        from: "Address"});

对于如何在 JS 中实现这个 Ether to ERC20 函数,你有什么建议吗?谢谢!

【问题讨论】:

  • 好的,我已经成功使用购买功能向我的智能合约发送 1 个以太币并收到 ERC20 代币作为回报,尽管我只能使用我插入的地址进行此​​交易进入函数:``` async function purchase(){ contract.methods.purchase("1","1").send({ from: "Address", to: "Address", value: web3.utils.toWei ("1", "以太") }); ``` 任何发送者如何使用这个“购买”功能来与合约交互,而不仅仅是一个指定的地址?谢谢!

标签: javascript ethereum solidity web3 erc20


【解决方案1】:

问题中的信息不足。如果你问如何调用你写的solidity的购买,那么答案如下:

contract.methods.purchase("amount", "Token quantity").send({
    from: "Address", value: ("amount"*"Token quantity"(in wei)) });

【讨论】:

  • 感谢您的回复。是的,我正在尝试在 Solidity 中调用购买功能。我的目标是让用户向合约发送 1 个以太币以换取 1 个代币。我正在取得进展,但我在元掩码中遇到了失败的交易。我正在使用:``` async function purchase(){ contract.methods.purchase("Address","1").send({ from:"Address", to:"Address", value: web3.utils. toWei("1", "ether") }); ``` "未捕获(承诺中)错误:交易已被 EVM 还原:"
  • contract.methods.purchase("Address","1") => contract.methods.purchase(1, 1) 合约中的第一个参数是 uint 中的金额而不是地址,代币也应该是在单位。而且我认为合同写得不正确,它应该只有一个参数 tokenAmount
  • 如果你愿意,我也可以重写solidity代码!让我知道
  • 你在使用元掩码吗?还有你怎么调用购买功能是有按钮还是什么?
  • 是的 const Web3 = require("web3"); const ethEnabled = async () => { if (window.ethereum) { await window.ethereum.send('eth_requestAccounts'); window.web3 = new Web3(window.ethereum); return true; } return false; } if (!ethEnabled()) { alert("Please install MetaMask to use this dApp!"); } 这会给你访问权限...如果 metamask 没有连接到你的网站,这将提示它连接
猜你喜欢
  • 2020-01-31
  • 2022-01-24
  • 2021-07-20
  • 2018-04-10
  • 2020-10-15
  • 1970-01-01
  • 2023-04-10
  • 2018-09-12
  • 2018-08-01
相关资源
最近更新 更多