Truffle

Truffle 沒有看到部署在 ganache 上的智能合約

  • April 18, 2021

etherjs (5.0) 用於部署智能合約Hello.sol。這是 js 程式碼(松露 5.1.52/ganache CLI 6.12.1):

 import { ContractFactory, ethers } from "ethers";

 let privateKey = "0xf43608a210da70d40115ad23526e50f2a502c018aeffd56477fcbe44119b53cc"; //<<==private key from ganache-cli
 let wallet = new ethers.Wallet(privateKey);  //address of the wallet
 console.log("wallet : ", wallet);
 //deploy
 const factory = new ContractFactory(abi, bytecode, signer); //<<==abi, bytecode, signer defined before
 const contract = await factory.deploy(wallet.address);
 console.log("contract deployed : ", contract);
 console.log("contract address : ", contract.address);
 // The transaction that the signer sent to deploy
 contract.deployTransaction;
 // Wait until the transaction is mined
 contract.deployTransaction.wait();

上面程式碼的執行會在以下位置生成輸出ganache-cli -b 3

 Transaction: 0xbbd7dfd7272cee291a2d1e62ac51e32dd99c98dacb44d04f1ae4bd50487f35b7
 Contract created: 0x03734542501c30e1ea22d6ddcb876e84eaa99381
 Gas usage: 92522
 Block Number: 2594
 Block Time: Thu Nov 12 2020 14:37:36 GMT-0800 (Pacific Standard Time)

合約部署在0x03734542501c30e1ea22d6ddcb876e84eaa99381.

truffle以 開頭truffle development。命令networks生成以下輸出:

truffle(development)> networks

Network: develop (id: 5777)
 No contracts deployed.

為什麼 truffle 找不到上面部署的合約?

Truffle 將部署資訊儲存在 build/ 目錄中的 JSON 文件中。

ethers.js 或 web3.js 部署的合約不會更新 JSON 文件,並且 truffle 不知道部署在遷移腳本之外的合約。

可以從 truffle 控制台使用這些合約。需要用 truffle 編譯程式碼。

然後MyContract從控制台使用地址0x1234123412341234,您可以執行

> myContract = await MyContract.at('0x1234123412341234');

makeBet從中呼叫函式。

> await myContract.makeBet(1, 1234, { from: '0x0001', value: '4444' })

引用自:https://ethereum.stackexchange.com/questions/90102