truffle是一個以太坊智能合約集成開發測試環境,他和一般的IDE不同,它並沒有代碼編輯環境,
但是它能夠方便的管理智能合約運行的環境,並且提供一套便捷開發智能合約(Smart Contract)的API,
能夠有效的提升開發效率。
truffle擁有以下特性:
內建的智能合約編譯、連接、發布和二進制文件管理工具。
快速開發自動化測試智能合約腳本。
腳本化、可拓展的發布、遷移框架。
管理任意公有以及私有的發布網絡(1或者其他數字,1是以太坊正式運行網絡,其他數字是本地開發網絡環境)。
使用 EthPM 和 NPM 進行包管理,使用ERC190標准規范。
擁有與智能合約能直接通信的交互式控制台。
可配置的構建管道,支持緊密集成。
外部腳本運行器,用於在Truffle環境中執行腳本。
1.運行環境
windows
$ node -v && npm -v
v14.17.0
6.14.13
2.代碼編輯器 vscode
下載后安裝solidity, nodejs 插件。
3.安裝 truffle
$ npm install -g truffle
$ truffle version
Truffle v5.3.10 (core: 5.3.10)
Solidity v0.5.16 (solc-js)
Node v14.17.0
Web3.js v1.3.6
3 快速入門
3.1 創建項目
創建項目文件夾
$ mkdir MetaCoin && cd MetaCoin
下載並解壓MetaCoin項目(unbox)
$ truffle unbox metacoin
完成以上步驟后,你將會看到工程目錄下有如下文件夾。
contracts/ 合約放在這個目錄下(Solidity contracts)
migrations 腳本化部署文件
test/ 測試你的智能合約和應用文件夾
truffle.js truffle配置文件
3.2. 瀏覽項目
打開 contracts/MetaCoin.sol ,
這是一個用solidity編寫的智能合約,它創建了一個MetaCoin token。
它使用了另外一個在該目錄下的合約文件ConvertLib.sol。
打開 contracts/Migrations.sol ,
這個是一個獨立的文件,沒有依賴其他合約,用來更新你發布的只能合約狀態。
這個是truffle生成的文件,一般我們不編輯它。
打開 migrations/1_initial_deployment.js ,
這個是用於遷移 Migrations.sol 的腳本文件。
打開 migrations/2_deploy_contracts.js ,
這個是用於遷移 MetaCoin.sol 的腳本。
(遷移的腳本會依次執行,以上兩個文件的開頭都是數字,執行順序將會按照數字順序執行。)
打開 test/TestMetaCoin.sol ,
這個是一個用solidity編寫的測試文件,他將確保你的智能合約按照你預期的結果運行。
打開 test/metacoin.js,
這個是一個用javascript腳本編寫的測試文件,他和上面的solidity編寫的測試文件功能基本相同。
打開 truffle.js ,
這個是 truffle 配置文件,用來設置網絡一起其他項目相關的設置。
這是一個空白文件,你可以不進行任何配置,truffle 的命令行中有一些內置的默認參數。
3.3. 測試
$ truffle test ./test/TestMetaCoin.sol
TestMetaCoin
√ testInitialBalanceUsingDeployedContract (120ms)
√ testInitialBalanceWithNewMetaCoin (119ms)
$ truffle test ./test/metacoin.js
Contract: MetaCoin
√ should put 10000 MetaCoin in the first account (115ms)
√ should call a function that depends on a linked library (93ms)
√ should send coin correctly (239ms)
3.4. 編譯
$ truffle compile
Compiling your contracts...
===========================
> Compiling .\contracts\ConvertLib.sol
> Compiling .\contracts\MetaCoin.sol
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\ConvertLib.sol
> Artifacts written to D:\Repo\truffle_test\MetaCoin\build\contracts
> Compiled successfully using:
- solc: 0.5.16+commit.9c3226ce.Emscripten.clang
3.5. 遷移到truffle開發環境
使用如下命令創建私有連並與其交互:
$ truffle develop
Truffle Develop started at http://127.0.0.1:9545/
Accounts:
(0) 0xdcdfaf7df3fbcd87dafc33edb6cf110e84ca0b8c
(1) 0xafe0ce1980ca48eaa4b8f8dbaeb6af92cc51a749
(2) 0x162a15bc43be3870383f17531a21c1c11314a5ef
...
這里顯示了10個賬戶和它們的私鑰,用於和區塊鏈交互。
truffle(develop)> 和 geth attach 是相同的交互式控制台。
在 truffle 交互控制台中,你可以省略 truffle 前綴,例如使用 truffle compile 你可以直接使用 compile 。
用於發布的命令行是 truffle migrate , 在交互命令行中使用 migrate 即可:
truffle(develop)> migrate
Summary
=======
> Total deployments: 3
> Final cost: 0.00109242 ETH
- Blocks: 0 Seconds: 0
- Saving migration to chain.
- Blocks: 0 Seconds: 0
- Blocks: 0 Seconds: 0
- Saving migration to chain.
這里顯示交易IDs,和智能合約的部署地址。
3.6. 使用 Ganache 遷移智能合約
安裝 Ganache 。
$ npm install -g ganache-cli
$ ganache-cli
Ganache CLI v6.12.2 (ganache-core: 2.13.2)
Available Accounts
==================
(0) 0x9D94916C27CCb9Ce84daeE18a4cD339f44736FC9 (100 ETH)
(1) 0xf6012D51dD8709c5FDda31279B43367eB7cc0881 (100 ETH)
(2) 0x42fceB310C0b4793BBB1cA7014fDDa01FFCdf8d2 (100 ETH)
...
...
Listening on 127.0.0.1:8545
打開 truffle.js 配置文件,替換 networks 配置:
module.exports = {
networks: {
development: {
host: "127.0.0.1",
port: 8545,
network_id: "*"
}
}
};
這個配置就是指定 truffle 連接到 Ganache 私有連。
保存並關閉文件。
在終端中輸入 migrate 命令,遷移智能合約到由 Ganache 創建的區塊鏈:(確認已經啟動 ganache-cli)
$ truffle migrate
Compiling your contracts...
===========================
> Everything is up to date, there is nothing to compile.
Starting migrations...
======================
> Network name: 'development'
> Network id: 1624084579260
> Block gas limit: 6721975 (0x6691b7)
...
...
Summary
=======
> Total deployments: 3
> Final cost: 0.0109242 ETH
為了與智能合約交互,你可使用 truffle 控制台。
truffle 控制台類似於 Truffle Develop ,
期望他連接到已經存在的區塊鏈(由 Ganache 保證創建區塊鏈)。
$ truffle console
truffle(development)>migrate
3.7.與智能合約交互
//創建新賬號
truffle(development)> web3.eth.personal.newAccount('!#superpassword')
'0x69D8e22Bbc9971782e50c3cfefeB5e60E0e0eE6c'
//獲取余額
truffle(development)> web3.eth.getBalance("0xD96e283D5213e81b33651178b59813e9da9713ee")
'0'
//創建獲取所有賬號
web3.eth.getAccounts()
truffle(development)> let accounts = await web3.eth.getAccounts()
undefined
truffle(development)> accounts
[
'0xc53e32f26F52101C04bB590A0EbcE89825323361',
'0x369CeFb91366d0a47c295895e7305b9a1855bD14',
'0x21fd2819ba51C1d4B36751b703A1733b65f6AB5d',
'0x79DEF71b768B332F99F96c9314757f9093C55934',
]
truffle(development)> accounts[0]
'0xc53e32f26F52101C04bB590A0EbcE89825323361'
truffle(development)> web3.eth.getBalance(accounts[0])
'99987682160000000000'
查詢 metacoin 發布后智能合約中的賬戶余額:
MetaCoin.deployed().then(function(instance){return instance.getBalance(web3.eth.accounts[0]);}).then(function(value){return value.toNumber()});
查詢賬戶余額值多少ETH
MetaCoin.deployed().then(function(instance){return instance.getBalanceInEth(web3.eth.accounts[0]);}).then(function(value){return value.toNumber()});
轉 metacoin 從一個賬戶轉賬到另外一個賬戶
MetaCoin.deployed().then(function(instance){return instance.sendCoin(web3.eth.accounts[1], 500);});
查詢接收 metacoin 的賬戶的余額:
MetaCoin.deployed().then(function(instance){return instance.getBalance(web3.eth.accounts[1]);}).then(function(value){return value.toNumber()});
查詢轉出 metacoin 賬戶的余額:
MetaCoin.deployed().then(function(instance){return instance.getBalance(web3.eth.accounts[0]);}).then(function(value){return value.toNumber()});
-----------------------------------------------------------------------------------------------------------------------------
pet-shop 記錄
1.TestAdoption.sol
將 // address expected = this;
修改為 address expected = address(this);
2. jquery高版本,load() 事件已經廢棄,替代即可解決:
將
// $(window).load(function() {
// App.init();
// });
修改為
$(window).on('load',function() {
App.init();
});
-----------------------------------------------------------------------------------------------------------------------------
defi 記錄
truffle init
https://github.com/JKinGH/DecentralizedFinance
npm install truffle-hdwallet-provider
在項目目錄執行truffle develop進入console 目錄,
此時truffle提供了一個模擬的區塊鏈環境RPC端口9545
truffle develop
執行compile命令編譯合約(如需重新編譯所有合約,可執行compile --all)
truffle(develop)> compile --all
執行migrate命令,Truffle會根據./migration/2_deploy_contracts.js 內容部署合約
如需重新部署所有合約,可執行migrate --reset
truffle(develop)> migrate --reset
truffle(develop)> let defi = await DeFi.deployed()
undefined
truffle(develop)>let accounts = await web3.eth.getAccounts()
undefined
truffle(develop)> accounts
truffle(develop)> defi //輸入抽象合約對象名稱即可
ruffle(develop)> web3.eth.getBalance(accounts[0])
truffle(develop)> defi.pledge.sendTransaction({ from: accounts[0], value: web3.utils.toWei("0.05", "ether"), gas: "220000"})
truffle(develop)> let contract = await defi.address
undefined
truffle(develop)> web3.eth.getBalance(contract)
'50000000000000000'
truffle(develop)> let result = await defi.pledge.sendTransaction({ from: accounts[0], value: web3.utils.toWei("0.006", "ether"), gas: "220000"})
undefined
truffle(develop)> result
truffle(develop)> result.logs //result.logs (array) - 解碼過的事件 (日志)
truffle(develop)> web3.eth.getBalance(contract)
-----------------------------------------------------------------------------------------------------------------------------
MetaCoin 記錄
truffle develop
truffle(develop)> compile
truffle(develop)> migrate
truffle(develop)>let accounts = await web3.eth.getAccounts()
truffle(develop)> accounts
ruffle(develop)> web3.eth.getBalance(accounts[0])
ruffle(develop)> web3.eth.getBalance(accounts[1])
truffle(develop)> let metaCoin = await MetaCoin.deployed()
truffle(develop)> metaCoin.address
truffle(develop)> let contract = await metaCoin.address
truffle(develop)> web3.eth.getBalance(contract)
