获取另一份合同部署的合同地址 [英] Getting the address of a contract deployed by another contract

查看:104
本文介绍了获取另一份合同部署的合同地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从另一个工厂合同部署合同,然后返回新创建的合同的地址。但它返回的地址是事务哈希而不是契约地址。我相信这是因为当地址被退回时合同尚未开采。当我使用web3部署合同时,似乎要等到合同部署才输出地址。

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 not the contract address. I believe this is because the contract is not yet mined when the address is returned. When I deploy a contract using the web3 deploy it seems to wait until the contract is deployed before outputting the address.

工厂合同:

contract Factory {
mapping(uint256 => Contract) deployedContracts;
uint256 numContracts;
function Factory(){
    numContracts = 0;
}

function createContract (uint32 name) returns (address){
    deployedContracts[numContracts] = new Contract(name);
    numContracts++;
    return deployedContracts[numContracts];
}}

这就是我调用createContract函数的方式。

This is how I am calling the createContract function.

factory.createContract(2,function(err, res){
        if (err){
            console.log(err)
        }else{
        console.log(res)
        }
    });


推荐答案

请考虑以下示例。您可以通过多种方式获取合同地址:

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存储地址并将其退回:



将合同中的地址存储为属性,并使用普通的getter方法检索它。


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 致电在您进行交易之前



您可以进行致电在您进行交易之前:


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计算未来地址



否则,您可以计算未来合约的地址,如下所示:


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)));

这篇关于获取另一份合同部署的合同地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆