Solidity

在不使用 Truffle 的情況下部署 Contract(由 Truffle 編譯)

  • November 13, 2017

TruffleSimpleStorage.sol使用truffle compile. 它的神器位於build/contracts/SimpleStorage.json

但是,只有當使用者點擊按鈕時,該合約才應部署到乙太坊網路。

在處理按鈕點擊時,一旦我得到對象,應該怎麼做來部署工件TruffleContract

部署後我們也可以獲取交易雜湊和合約地址嗎?

import SimpleStorageContract from '../../../build/contracts/SimpleStorage.json';

onDeployButtonClick() {
   const contract = require('truffle-contract');
   const simpleStorage = contract(SimpleStorageContract);
   simpleStorage.setProvider(this.props.web3.currentProvider);

   // How to deploy this contract to the Ethereum network?
   // then get the TX hash and contract address
}

試過這段程式碼testrpc

onDeployButtonClick() {
   const contract = require('truffle-contract');
   const simpleStorage = contract(SimpleStorageContract);
   simpleStorage.setProvider(this.props.web3.currentProvider);

   this.props.web3.eth.getAccounts((error, accounts) => {
       simpleStorage.new([], {from: accounts[0]})
   })
}

但是在 JS 控制台中,當onDeployButtonClick被觸發時,我得到一個錯誤

Uncaught (in promise) Error: VM Exception while processing transaction: out of gas
   at Object.InvalidResponse (errors.js:35)
   at requestmanager.js:86
   at XMLHttpRequest.r

使用 Truffle 合約,您可以使用從 ABI 建構的工廠輕鬆完成。

const Contract = require('truffle-contract');
const SimpleStorage = Contract(SimpleStorageContract);
SimpleStorage.setProvider(this.props.web3.currentProvider);

// deploy from accounts[0]
SimpleStorage.new({from: this.props.web3.eth.accounts[0], gas: 6000000}).then(instance => {
   console.log(instance.address);
});

相應地調整氣體。

實現這一目標的最佳方式是簽訂 2 份契約。您的 SimpleStorage 合約,以及使用工廠模式的 SimpleStorageFactory 合約。

您將部署 Factory 契約,該契約具有在您點擊按鈕時被呼叫的功能。這個函式基本上創建了一個 SimpleStorage 合約的新實例。像這樣的東西:

function createSStorage() {
   SimpleStorage s = new SimpleStorage(); // You can pass other constructor parameters.

   //Store the SStorages created in either an array or mapping so you can later list them, for example.

   //Array of SStorages
   SimpleStorageArray.push(address(s));

   // Mapping of SStorages with address key
   SimpleStorageMapping[address(s)] = s;

   SStorageCreated(address(s),msg.sender);
 }

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