學習Solidity之Hello world
開發工具與環境設置
安裝所需要工具
npm install -g truffle ganache-cli
啟動 ganache-cli來啟動乙太坊測試環境
ganache-cli
![](https://assets.matters.news/embed/e7fa8670-bee7-4695-a48f-f11db338b90b.png)
![](https://assets.matters.news/embed/068be6ee-dfb4-476c-b6c3-43933df9ff87.png)
建立智能合約
mkdir hello cd hello truffle init truffle create contract HelloWorld #建立合約
![](https://assets.matters.news/embed/fbddc99f-f761-4638-ac31-032a295d8a67.png)
![](https://assets.matters.news/embed/a54c69ce-221e-4827-8504-24a935367237.png)
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這個檔案
![](https://assets.matters.news/embed/33f5c438-9668-4859-b787-6e62b4ba5d17.png)
部署
在migrate中新增2\_deploy\_contracts.js
(migration檔案會依照檔案的編號來執行。例如2\_就會在1\_之後執行。檔案後面的文字只為協助開發者理解之用)
![](https://assets.matters.news/embed/6e9bffaa-0b2c-41bc-9b95-4ad43d1e10d9.png)
2\_deploy\_contracts.js:
var HelloWorld = artifacts.require("HelloWorld"); module.exports = function(deployer) { deployer.deploy(HelloWorld); };
區塊網路設定
在truffle-config檔案裡L
![](https://assets.matters.news/embed/8ae6faa0-76e9-4dca-91ef-8a667912b3a7.png)
加入設定
![](https://assets.matters.news/embed/308b5bd4-62a7-45f7-bfa6-2bb8d6fbd6d2.png)
開始部署:
truffle migrate
![](https://assets.matters.news/embed/09336303-0cea-406c-b71a-06d64c7e0181.png)
測試
使用truffle提供的命令行工具,執行:
truffle console
輸入
> let contract > HelloWorld.deployed().then(instance => contract = instance) > contract.sayHello.call()
![](https://assets.matters.news/embed/f848a5cf-0bfa-4c6b-b28e-38f48e0dcc35.png)
![](https://assets.matters.news/embed/70194fee-7f67-4ce0-9ae8-dbe165a6a09c.png)
## 我的名子合約
> 輸入名子,並藉由呼叫函數來顯示
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)
![](https://assets.matters.news/embed/a3dca34f-8d60-4cd3-a6db-9eb455a3332c.png)
call function:
contract.getName.call() contract.setName("Test Name")
![](https://assets.matters.news/embed/163076d8-81d5-47a4-889a-18c1a71120d5.png)
contract.getName.call()
![](https://assets.matters.news/embed/a9ac558d-92bb-437c-9856-08ad526e24c3.png)
歡迎大家來我的Blog看:
1.Blog: 文章連結