學習Solidity之Hello world
IPFS
開發工具與環境設置
安裝所需要工具
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: 文章連結
喜欢我的作品吗?别忘了给予支持与赞赏,让我知道在创作的路上有你陪伴,一起延续这份热忱!

