Fufu0217
Fufu0217

學習Solidity之Hello world

最近開始使用Matters,把一些在我原本的blog文章給遷移過來。這篇是我之前在學習solidity的紀錄過程。

開發工具與環境設置

安裝所需要工具

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: 文章連結



CC BY-NC-ND 2.0 版权声明

喜欢我的文章吗?
别忘了给点支持与赞赏,让我知道创作的路上有你陪伴。

第一个支持了这篇作品
加载中…

发布评论