###### tags : `blockchain` # Truffle使用介紹 ## 路徑資料夾 1. contract 撰寫合約 2. migration 部屬合約上鏈 3. test 測試合約 ## 使用流程 1. truffle init (自動產出基本的truffle結構) 2. truffle compile (編譯合約) 3. truffle migrate (將合約部屬上鏈) truffle-config.js的network改成 development: { host: "127.0.0.1", port: 7545, network_id: "*" } 會自動連上ganache 1_initial_migration只是範例 可以直接刪除 truffle migrate --reset 可重新佈署 4. truffle console (合約互動) 範例使用官方quickstart中的MetaCoin 已佈署合約MetaCoin truffle(development)> let instance = await MetaCoin.deployed() ganache該區塊的所有帳戶 truffle(development)> let accounts = await web3.eth.getAccounts() 合約MetaCoin的函式getBalance 返回的是餘額 truffle(development)> let balance = await instance.getBalance(accounts[0]) 查看其餘額 truffle(development)> balance.toNumber() 合約MetaCoin的函式sendCoin 發送500代幣到帳號[1] 發送者是msg.sender truffle(development)> instance.sendCoin(accounts[1], 500) # 合約互動技巧 該函式只有兩個參數 但truffle可以額外加一個{}使用 這段是確保來源來自accounts[0] instance.sendCoin(accounts[1], 10, {from: accounts[0]}) from to gas gasPrice value data nonce https://trufflesuite.com/docs/truffle/getting-started/interacting-with-your-contracts/ # 合約部屬與metamask交互 truffle使用@truffle/contract 是直接使用合約的json ( 部署地址和應用程序二進制接口 ABI ) 應該是方便truffle測試使用的 因為他含有truffle compile產生的json檔案 實際使用不知道要如何得到該json 結論 : 普通測試用內建的console就行 如果要真實模擬使用ether.js或web3.js https://github.com/trufflesuite/truffle/tree/master/packages/contract https://trufflesuite.com/docs/truffle/getting-started/truffle-with-metamask/ 合約範例 章節 : Creating a user interface to interact with the smart contract¶ 有關於 https://trufflesuite.com/guides/pet-shop/ # 連結metamask地址進行部屬 truffle Dashboard 要部屬時不用再VS黏貼私鑰 可以透過Dashboard連結metamask後部屬 https://trufflesuite.com/docs/truffle/getting-started/using-the-truffle-dashboard/ # 實際部屬上鏈的兩個網路 一個是開發者測試的區塊鏈 like Ganache or Truffle Develop 一個是最終部屬上鏈的區塊鏈 主網public Ethereum network private consortium 或是測試網路Rinkeby Ropsten之類的 部屬上ETH network_id:1 Rospten network_id:3 Rinkeby network_id:4 ganache chainId:1337 https://trufflesuite.com/guides/deploying-to-the-live-network/ 在測試中是用* 實際部屬網路要選擇目標主網 關於 network_id 是來自乙太坊的設定 https://besu.hyperledger.org/en/stable/Concepts/NetworkID-And-ChainID/ 相關討論 可使用以下code取得該網的網路和代幣ID const networkId = await web3.eth.net.getId(); const chainId = await web3.eth.getChainId(); https://trufflesuite.com/guides/deploying-to-the-live-network/ Networks and App Deployment https://trufflesuite.com/docs/truffle/advanced/networks-and-app-deployment/ # 參考資源 https://trufflesuite.com/docs/truffle/quickstart/#testing https://chunyu-hsiao93.medium.com/truffle-%E6%99%BA%E8%83%BD%E5%90%88%E7%B4%84%E6%B8%AC%E8%A9%A6%E6%B5%81%E7%A8%8B%E7%B0%A1%E6%98%93%E6%93%8D%E4%BD%9C%E6%95%99%E5%AD%B8-f7b0d5fc3880
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up