學習Solidity之Hello world

2022/04/24閱讀時間約 3 分鐘
開發工具與環境設置
安裝所需要工具
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: 文章連結
Fufu
Fufu
樂愛學習,探索未知領域。目前在專研react、flutter和區塊鍊
留言0
查看全部
發表第一個留言支持創作者!