WTF Solidity极简入门第二十讲:发送ETH transfer,send和call

This article is not available in the current language yet. Showing the original version.
Solidity 有三种方法向其他合约发送 ETH,他们是:transfer(),send() 和 call(),其中 call() 是被鼓励的用法。

原文:《Solidity 极简入门: 20. 发送 ETH transfer,send 和 call》

我最近在重新学 solidity,巩固一下细节,也写一个「Solidity 极简入门」,供小白们使用(编程大佬可以另找教程),每周更新 1-3 讲。

所有代码和教程开源在 github: github.com/AmazingAng/WTFSolidity

Solidity 有三种方法向其他合约发送 ETH,他们是:transfer(),send() 和 call(),其中 call() 是被鼓励的用法。

接收 ETH 合约

我们先部署一个接收 ETH 合约 ReceiveETH。ReceiveETH 合约里有一个事件 Log,记录收到的 ETH 数量和 gas 剩余。还有两个函数,一个是 receive(),收到 ETH 被触发,并发送 Log 事件;另一个是查询合约 ETH 余额的 getBalance().

WTF Solidity极简入门第二十讲:发送ETH transfer,send和call

部署好合约后,运行 getBalance() 函数,可以看到当前合约的 ETH 余额为 0.

发送 ETH 合约

我们将实现三种方法向 ReceiveETH 合约发送 ETH。首先,先在发送 ETH 合约 SendETH 中实现 payable 的构造函数和 receive(),让我们能够在部署时和部署后向合约转账。

WTF Solidity极简入门第二十讲:发送ETH transfer,send和call

transfer

- 用法是 transfer(发送 ETH 数额)。

- transfer() 的 gas 限制是 2300,足够用于转账,但对方合约的 fallback() 或 receive() 函数不能实现太复杂的逻辑。

- transfer() 如果转账失败,会自动 revert(回滚交易)。

代码样例,注意参数中的_to 填 ReceiveETH 合约的地址,amount 是 ETH 转账金额:

WTF Solidity极简入门第二十讲:发送ETH transfer,send和call

send

- 用法是 send(发送 ETH 数额)。

- send() 的 gas 限制是 2300,足够用于转账,但对方合约的 fallback() 或 receive() 函数不能实现太复杂的逻辑。

- send() 如果转账失败,不会 revert。

- send() 的返回值是 bool,代表着转账成功或失败,需要额外代码处理一下。

代码样例:

WTF Solidity极简入门第二十讲:发送ETH transfer,send和call

call

- 用法是 call{value: 发送 ETH 数额}("")。

- call() 没有 gas 限制,可以支持对方合约 fallback() 或 receive() 函数实现复杂逻辑。

- call() 如果转账失败,不会 revert。

- call() 的返回值是 (bool, data),其中 bool 代表着转账成功或失败,需要额外代码处理一下。

代码样例:

WTF Solidity极简入门第二十讲:发送ETH transfer,send和call

运行三种方法,可以看到,他们都可以成功的向 ReceiveETH 合约发送 ETH。

总结

这一讲,我们介绍 solidity 三种发送 ETH 的方法:transfer,send 和 call。

call 没有 gas 限制,最为灵活,是最提倡的方法;transfer 有 2300 gas 限制,但是发送失败会自动 revert 交易,是次优选择;send 有 2300 gas 限制,而且发送失败不会自动 revert 交易,几乎没有人用它。

推特:@0xAA_Science

社区:Discord微信群官网 wtf.academy

所有代码和教程开源在github: github.com/AmazingAng/WTFSolidity

Share to:

Author: 0xAA

Opinions belong to the column author and do not represent PANews.

This content is not investment advice.

Image source: 0xAA. If there is any infringement, please contact the author for removal.

Follow PANews official accounts, navigate bull and bear markets together
PANews APP
It is suspected that the Dragonfly address transferred 137 million SKY tokens to Coinbase, a decrease in value of more than half compared to when the tokens were withdrawn.
PANews Newsflash