Truffle學習筆記
安裝truffle, 注意: 雖然目前truffle最新版是 5.0.0
, 但是經過我實踐之后, 返現和v4有很多不同(比如: web3.eth.accounts;
都獲取不到賬戶), 還是那句話:
“nodejs模塊的版本問題會搞死人的 !”
目前4.1.15之前的版本都不能用了, 只能安裝v4.1.15
npm install truffle@4.1.15
普通truffle項目
創建普通項目 truffle init
即可
react
創建react項目 truffle unbox react
, 可能會遇到錯誤npm WARN tar zlib error: unexpected end of file
, 這是在 安裝client依賴發生的錯誤.
切換到 client目錄執行 npm install --no-package-lock
安裝即可
錯誤: npm WARN tar zlib error: unexpected end of file
參考: https://github.com/npm/npm/issues/19353#issuecomment-367329967
啟動項目:
- 在項目目錄執行
truffle develop
- 打開metamask用custom RPC連接到
http://127.0.0.1:9545
- 然后執行
compile
, 如果報錯:編譯版本不符, 將智能合約中版本降為0.4.17
或其他低于或等于當前編譯器版本即可. - 打開另外一個終端, 進入client目錄, 執行
npm start
, 這時瀏覽器會訪問http://localhost:3000
, 因為Client/App.js中會調用合約的set方法, 需要花費gas, 所以提前將用戶導入metamask, 確保metamask的當前選擇的用戶有以太幣
項目效果
修改合約中變量
changeValue = async () =>{var value = Number( this.refs.dataInput.value ); //獲取輸入框的值console.log(value);await g_instance.methods.set(value).send({ from: g_accounts[0] }); //調用合約中的set方法// Get the value from the contract to prove it worked.const response = await g_instance.methods.get().call();// Update state with the result.this.setState({ storageValue: response });};-------------------------------
<div><input ref="dataInput" style={{width:200, height:30}}/><button onClick={this.changeValue} style={{width:100, height:30}}>確定</button>
</div>
IPFS搭建
參考: https://blog.csdn.net/u013022210/article/details/80363107
直接展示ipns部署博客效果
另外 可以通過nodejs和ipfs交互
npm install ipfs-http-client