2022-04-24|閱讀時間 ‧ 約 2 分鐘

學習Solidity之Hello world

開發工具與環境設置
安裝所需要工具
npm install -g truffle ganache-cli
啟動 ganache-cli來啟動乙太坊測試環境
ganache-cli
建立智能合約
mkdir hello
cd hello
truffle init
truffle create contract HelloWorld #建立合約
HelloWorld.sol:
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract HelloWorld {
  // constructor() public {
  // }

  function sayHello() public pure returns (string memory){
    return ("Hello World");
  }
}
編譯
truffle compile
編譯成功的話,在build/contracts/目錄下會多出HelloWorld.json這個檔案
部署
在migrate中新增2\_deploy\_contracts.js
(migration檔案會依照檔案的編號來執行。例如2\_就會在1\_之後執行。檔案後面的文字只為協助開發者理解之用)
2\_deploy\_contracts.js:
var HelloWorld = artifacts.require("HelloWorld");

module.exports = function(deployer) {
  deployer.deploy(HelloWorld);
};
區塊網路設定
在truffle-config檔案裡L
加入設定
開始部署:
truffle migrate
測試
使用truffle提供的命令行工具,執行:
truffle console
輸入
> let contract
> HelloWorld.deployed().then(instance => contract = instance)
> contract.sayHello.call()
## 我的名子合約
輸入名子,並藉由呼叫函數來顯示
MyName.sol:
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;

contract MyName {
 string public _name;

 constructor() {
   _name="Please Type Your Name";
 }

 function setName(string memory name) public{
   _name = name ;
 }

 function getName() public view returns (string memory){
   return _name;
 }
}
編譯並佈署後
我們開始測試
truffle console
let contract
MyName.deployed().then(instance => contract = instance)
call function:
contract.getName.call()
contract.setName("Test Name")
contract.getName.call()

歡迎大家來我的Blog看:
1.Blog: 文章連結
分享至
成為作者繼續創作的動力吧!
樂愛學習,探索未知領域。目前在專研react、flutter和區塊鍊
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言