繁体   English   中英

如何通过以太币向智能合约发送数据?

[英]How do I send data to Smart Contract via Ethers?

我可以通过如下的depositFunds function 将一定数量的以太币存入我的智能合约:

async function depositFunds() {
  console.log(`Depositing Funds...`);
  if (typeof window.ethereum !== "undefined") {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(contractAddress, abi, signer);
    const transactionResponse = await contract.depositFunds({
      value: ethers.utils.parseEther("1"),
    });
  }
}

我现在正试图提取部分资金(即不是全部),但我不知道如何将数据传递给我的合同的withdrawFunds function。

async function withdrawFunds() {
  console.log(`Withdrawing Funds...`);
  if (typeof window.ethereum !== "undefined") {
    const provider = new ethers.providers.Web3Provider(window.ethereum);
    const signer = provider.getSigner();
    const contract = new ethers.Contract(contractAddress, abi, signer);
    const transactionResponse = await contract.withdrawFunds({
      data: "0.5",
    });
  }
}

下面是我的withdrawFunds function的ABI:

{
    inputs: [
      {
        internalType: "uint256",
        name: "_weiToWithdraw",
        type: "uint256",
      },
    ],
    name: "withdrawFunds",
    outputs: [],
    stateMutability: "nonpayable",
    type: "function",
  }

关于如何解决这个问题的任何想法? 谢谢!

await contract.depositFunds({
  value: ethers.utils.parseEther("1"),
});

此代码段构建事务 object 的方式已包含 depositFunds depositFunds() function 选择器在data字段的开头,后跟 0 arguments。

包含value属性的 object 称为overrides参数。 它允许您覆盖交易的其他一些字段,例如它的value 它不允许您覆盖data字段,因为它已经从 function 名称和 arguments 构建。

parseEther() function 将一定数量的 ETH 转换为其对应的 wei 数量。 在你的情况下,这是1000000000000000000 wei。 因此,您通过交易发送的实际value是“1 和 18 个零”。


withdrawFunds(uint256) function 接受您要提取的 wei 数作为参数。 因此,您需要将“0.5 ether”转换为 wei 的数量,并将其作为 function 参数传递。

const transactionResponse = await contract.withdrawFunds(
  // the function argument
  // note that it's not wrapped in curly brackets
  ethers.utils.parseEther("0.5")
);

您还可以选择指定一些覆盖,但在这种情况下不需要。

const transactionResponse = await contract.withdrawFunds(
  ethers.utils.parseEther("0.5"),
  {
    // this is the `overrides` object after all function arguments
    gasPrice: "1000000000" // 1 billion wei == 1 Gwei
  }
);

暂无
暂无

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

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