自學以太坊智能合約,一知半解之下碰到很多問題,遂記錄下,方便以后查找,
第一個智能合約(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 {}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/297192.html
標籤:區塊鏈
