Ethers Pass方法名称带有参数而不是Hexdata

发布于 2025-01-26 20:44:39 字数 460 浏览 5 评论 0原文

我正在使用ethers与以太坊上的合同进行交互。 这就是我的方法的样子:

const tx = await signer
      .sendTransaction({
        to: contractAddress,
        value: ethers.utils.parseEther(price),
        data: hex,
        gasPrice: ethers.utils.parseUnits(gas, 9),
      })

它可以正常工作。但是,每当我必须查看etherscan以查找事务十六进制并将其传递到data参数。是否可以将方法名称从合同和参数传递给它,而不是传递此HEX值?

也许ethers中有任何方法可以用参数编码该方法中的十六进制值?

I am using ethers to interact with contracts on Ethereum.
This is how my method looks like:

const tx = await signer
      .sendTransaction({
        to: contractAddress,
        value: ethers.utils.parseEther(price),
        data: hex,
        gasPrice: ethers.utils.parseUnits(gas, 9),
      })

And it works fine. But every time I have to look on Etherscan to find transaction hex and pass it to the data parameter. Is it possible to just pass method name from contract and parameters to it instead of passing this hex value?

Maybe there is any method in ethers to encode that method with parameters into hex value?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

婴鹅 2025-02-02 20:44:39

您需要的是合同ABI。通常,它以JSON对象的形式写成您可以在JS脚本中导入的对象,也可以像这样写入(人类可读性):

const contractABI = [
  "function foo(uint256 bar) external",
  // other functions or events ...
]

ABI包含合同的所有(或某些)方法以及如何对其进行编码/解码。

使用ABI,您可以创建这样的合同对象:

const contract = new ethers.Contract(contractAddress, contractABI, provider);

可以用来发送这样的交易:

const my_bar = 123  // example
const tx = await contract.connect(signer).foo(my_bar, {
  value: ethers.utils.parseEther(price),
  gasPrice: ethers.utils.parseUnits(gas, 9),
})

What you need is the contract ABI. Generally it's written as a json object you can import in your js script, or it can be written like this (human-readable-ABI):

const contractABI = [
  "function foo(uint256 bar) external",
  // other functions or events ...
]

The ABI contains all (or some) methods of a contract and how to encode/decode them.

With the ABI you can create a contract object like this:

const contract = new ethers.Contract(contractAddress, contractABI, provider);

which can be used to send transactions like this:

const my_bar = 123  // example
const tx = await contract.connect(signer).foo(my_bar, {
  value: ethers.utils.parseEther(price),
  gasPrice: ethers.utils.parseUnits(gas, 9),
})
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文