Getting the address of a contract deployed by another contract

前端 未结 2 1738
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-06 03:06

I am trying to deploy a contract from another factory contract and then return the address of the newly created contract. The address it returns however is the transaction hash

2条回答
  •  故里飘歌
    2021-02-06 03:36

    Consider the below example. There are a number of ways you can get the address of the contract:

    contract Object {
    
        string name;
        function Object(String _name) {
            name = _name
        }
    }
    
    contract ObjectFactory {
        function createObject(string name) returns (address objectAddress) {
            return address(new Object(name));
        }
    }
    

    1 Store the Address and Return it:

    Store the address in the contract as an attribute and retrieve it using a normal getter method.

    contract ObjectFactory {
        Object public theObj;
    
        function createObject(string name) returns (address objectAddress) {
            theObj = address(new Object(name));
            return theObj;
        }
    }
    

    2 Call Before You Make A Transaction

    You can make a call before you make a transaction:

    var address = web3.eth.contract(objectFactoryAbi)
        .at(contractFactoryAddress)
        .createObject.call("object");
    

    Once you have the address perform the transaction:

    var txHash = web3.eth.contract(objectFactoryAbi)
        .at(contractFactoryAddress)
        .createObject("object", { gas: price, from: accountAddress });
    

    3 Calculate the Future Address

    Otherwise, you can calculate the address of the future contract like so:

    var ethJsUtil = require('ethereumjs-util');
    var futureAddress = ethJsUtil.bufferToHex(ethJsUtil.generateAddress(
          contractFactoryAddress,
          await web3.eth.getTransactionCount(contractFactoryAddress)));
    

提交回复
热议问题