天天看点

初学以太坊智能合约

自学以太坊智能合约,一知半解之下碰到很多问题,遂记录下,方便以后查找。

第一个智能合约(Faucet)

观看的B站尚硅谷的深入掌握以太坊核心技术-智能合约入门,仿着写个水龙头的智能合约

// Version of Solidity compiler this program was written for 
 pragma solidity ^0.4.19;

// Our first contract is a faucet! 
contract Faucet {
    // Give out ether to anyone who asks
    function withdraw(uint withdraw_amount) public {
        // Limit withdrawal amount 
        require(withdraw_amount <= 100000000000000000);
        // Send the amount to the address that requested it 
        msg.sender.transfer(withdraw_amount);
    }
    // Accept any incoming amount 
    function () public payable {}
}
           

编译通过:

初学以太坊智能合约

但是该学习视频已经是两年前的了,用的编译版本比较旧,remix上的例子里,版本都是

// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.7.0 <0.9.0
           

那就试着改一下版本,发现开始报错:

ParserError: Expected a state variable declaration. If you intended this as a fallback function or a function to handle plain ether transactions, use the "fallback" keyword or the "receive" keyword instead.
--> contracts/Faucet.sol:14:32:
|
14 | function () public payable {}
| ^
           
初学以太坊智能合约

这是因为在0.6.0的版本更新中

初学以太坊智能合约

所以我们需要对应下

初学以太坊智能合约

发现有回退,就要有接收,那就再增加一下receive方法

初学以太坊智能合约

编译后发现还剩下一个问题,仔细看一下,发现

0.5.0版本中

初学以太坊智能合约

0.6.0版本中

初学以太坊智能合约

0.8.0版本中

初学以太坊智能合约

由此可知,目前msg.sender已经不是address payable了,需要自己另外转一下

初学以太坊智能合约

编译通过,合约处可以选择Faucet合约了,语法修改完成。

最终改成如下代码:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.7.0 <0.9.0;

/**
 * @title Faucet
 * @dev Our first contract is a faucet!
 */
contract Faucet {
    
     
    // Give out ether to anyone who asks
    function withdraw(uint withdraw_amount) public {
        
        // Limit withdrawal amount 
        require(withdraw_amount <= 100000000000000000);
        
        // Send the amount to the address that requested it 
        payable(msg.sender).transfer(withdraw_amount);
    } 
    
    // Accept any incoming amount 
    fallback () payable external {}
    receive () payable external {}
}