Sagen wir, ich habe einen Vertrag, der eine Fabrik ist, und benutze Trüffel, um damit zu interagieren, ich gehe für:
ContractName.deployed().then(function(instance) {app = instance;})
Jetzt hat die Factory eine Funktion, die neue Verträge bereitstellt, die ich einfach aufrufe durch:
app.functionNameForCreatingNewContract({from: web3.accounts[1]})
und das obige erstellt einen neuen Vertrag.
Jetzt ist die „große Frage“, wie ich eine Instanz dieses neu erstellten Vertrags erstellen kann, damit ich damit interagieren kann.
Sie können CONTRACT_NAME.at()
in der Konsole die Adresse des neu erstellten Vertrags eingeben. Beispiel:
Vertragscode:
pragma solidity ^0.4.19;
contract ParentContract {
ChildContract _contract;
function createChildContract(address owner) public {
_contract = new ChildContract(owner);
}
function getContractAddress() public constant returns (address) {
return address(_contract);
}
}
contract ChildContract {
address _owner;
function ChildContract(address owner) public {
_owner = owner;
}
function getOwner() public constant returns (address) {
return _owner;
}
}
2_deploy_contracts.js:
var ParentContract = artifacts.require("ParentContract");
module.exports = function(deployer) {
deployer.deploy(ParentContract);
};
Bereitstellen mit truffle migrate
:
Running migration: 1_initial_migration.js
Replacing Migrations...
... 0x83fa4790e458809dab270f37b5445eaf163e9084a3223b7f6f58fc8237f4a67a
Migrations: 0x9962b2e8d276b8eacb07fd454ffe4267fb232e0b
Saving successful migration to network...
... 0x0cdc86c786c7825226948d93bcfef05f059a7e456a04516a2aedbd1fb7979d41
Saving artifacts...
Running migration: 2_deploy_contracts.js
Replacing ParentContract...
... 0x2f85718df4ee286394a78274afda5d8104bcec19c990d1d3f608a08b2b35fa34
ParentContract: 0x651cbb04e31699eb92740018e5a8e65f91164903
Saving successful migration to network...
... 0x04701683665a47720aa8f60efaca57f123ce85c2228775aec232c834124618ae
Saving artifacts...
In truffle console
(einige Ausgaben abgeschnitten):
$ truffle console
truffle(development)> var c = ParentContract.at('0x651cbb04e31699eb92740018e5a8e65f91164903');
undefined
truffle(development)> var a;
undefined
truffle(development)> web3.eth.getAccounts((e, r) => a = r[0]);
undefined
truffle(development)> c.createChildContract(a);
{ tx: '0x9f4967618355bb2bf6fe7a110a9be91b594c156f11b09176226966009c170f08',
receipt:
{ transactionHash: '0x9f4967618355bb2bf6fe7a110a9be91b594c156f11b09176226966009c170f08',
transactionIndex: 0,
blockHash: '0xba056ea5b6048dc13099ffd7f3049a2f7ff5378e0c9a5d914e059314ab385634',
blockNumber: 12,
gasUsed: 142754,
cumulativeGasUsed: 142754,
contractAddress: null,
logs: [] },
logs: [] }
truffle(development)> c.getContractAddress();
'0x64b999e71f5fab8b1c5dc718152d84b620cbbef9'
truffle(development)> var c2 = ChildContract.at(c.getContractAddress());
undefined
truffle(development)> c2.getOwner();
'0x9a6d82ef3912d5ab60473124bccd2f2a640769d7'
Brandstiftung