上一篇介紹的是以太坊下基於geth+remix-ide智能合約環境的搭建和部署運行,本篇介紹的是基於truffle+ganache。
ganache相當於是geth的圖形化操作界面,相對於純指令操作的geth較為簡單易上手,並且運行交易和生成區塊的過程一目了然。
【前期准備】
1.Node.js安裝(這一點在上一篇文章中提到過,所以此處不做展示)
2.指令輸入:
npm install -g solc(安裝智能合約) npm install -g ganache-cli (安裝ganache開發端) npm install -g truffle (安裝truffle框架)
3.vscode運行環境
【智能合約】
1.新建智能合約
①新建一個文件夾eg:helloworld,並進入該文件夾下進行指令操作:
cd helloworld
②創建一個truffle項目:
truffle init
③將新建的文件夾helloworldzheng整體搬進vscode中:
④在helloworld下的contracts文件夾中創建新合約,起名helloworld.sol,並輸入如下代碼:
pragma solidity ^0.5.2; contract helloworld{ function say() public pure returns(string memory){ return "hello world"; } }
⑤在helloworld下的migrations文件夾中點開1_initial_migrations.js文件,並將其中的"Migrations"參數一律改成helloworld:
const helloworld = artifacts.require("./helloworld.sol"); module.exports = function(deployer) { deployer.deploy(helloworld); };
⑥回到truffle操作環境里,對上述文件進行編譯:
注意,一定要進入到contracts文件夾下進行編譯操作,否則會報錯找不到對應合約。
編譯成功。
2.連接ganache
①運行ganache
②智能合約與ganache連接:
回到vscode,打開truffle-config.js文件:
在module-exports模塊中輸入如下內容:
之后我們回到ganache,打開設置,點擊server,看到如下操作面,其中上圖中的host,port,network_id參數都是根據ganache中對應的參數填寫的:
③准備好之后,可以部署合約:
回到truffle操作,指令輸入:
truffle migrate
如果按照上述操作一步步來,那么部署成功我們可以看到ganache下的區塊增加了:
④接下來可以開始嘗試調用合約:
回到truffle操作指令,輸入如下指令進入操作台:
truffle console
如果順利進入操作台即可以進行合約函數的調用:
輸入指令:
helloworld.deployed().then(instance=>contract=instance)
console中預載了truffle-contract函數庫,所以可以直接對合約的函數進行操作。
上述指令含義是獲取helloworld合約,存為instance,並將其存儲到contract變量中以便后期使用。
接下來可以調用helloworld合約中我們定義好的say()函數了:
輸入指令:
contract.say()
合約部署成功,調用成功。