调用合约方法创建子合约后获取子合约地址

在通过调用合约的方法创建合约后,不能直接得到子合约地址。不便于单元测试。如下方法可解决:

合约:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.13;

contract A {                    // 子合约
    string public name;
}

contract B {                    // 父合约
    event NEWA(address addr);   //定义事件
    address private aa;         // 用来验证

    function createA() public returns (A){  // 创建A合约
        A a = new A();
        aa = address(a);
        emit NEWA(address(a));  // 发送事件
        return a;
    }

    function getaa() public view returns (address){
        return aa;
    }
}

单元测试:

const { expect } = require('chai');
const { ethers } = require('hardhat');

describe('Test', () => {
	let owner, user1, users, contract;

	it('Should return address of sub-contract.', async () => {
		[ owner, user1, ...users ] = await ethers.getSigners();

		const Contract = await ethers.getContractFactory('B');
		contract = await Contract.deploy();     // 部署父合约B          

		const exec = await contract.createA();        // 通过B合约创建子合约A
		const event = await exec.wait();
		const Baddr = ethers.utils.getAddress(          // 标准化为地址格式
            ethers.utils.hexStripZeros(                 // 去0
                event.events[0].data                    // 读取事件的值
                )
            );
		expect(await contract.getaa()).to.equal(Baddr);
	});
});

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
方式有两种:一种是通过 web3j 框架调用;另一种是通过 ethereumj 框架调用。 1. web3j 框架调用合约方法 web3j 是一个基于 Java 的以太坊客户端库,提供了访问以太坊网络的 API。可以使用 web3j 框架调用合约方法,具体步骤如下: 1)创建 web3j 客户端对象 Web3j web3j = Web3j.build(new HttpService("http://localhost:8545")); 2)加载合约 ABI 文件 String contractAddress = "0x123456..."; String contractABI = "合约ABI文件内容"; Contract contract = Contract.load(contractAddress, web3j, credentials, gasPrice, gasLimit); 3)调用合约方法 TransactionReceipt receipt = contract.someMethod().send(); 其中 someMethod() 是合约的一个方法,可以根据合约的具体情况调用不同的方法。 2. ethereumj 框架调用合约方法 ethereumj 是一个 Java 实现的以太坊客户端,可以使用 ethereumj 框架调用合约方法,具体步骤如下: 1)创建 ethereumj 客户端对象 ECKey key = ECKey.fromPrivate(privateKey); InMemoryStorageProvider storageProvider = new InMemoryStorageProvider(); Repository repository = new Repository(storageProvider); BlockchainImpl blockchain = new BlockchainImpl(repository); EthereumImpl ethereum = new EthereumImpl(blockchain); ethereum.addListener(new EthereumListenerAdapter()); ethereum.connect(); 2)加载合约 ABI 文件 String contractAddress = "0x123456..."; String contractABI = "合约ABI文件内容"; Contract contract = new Contract(new Address(contractAddress), ethereum, key, contractABI.getBytes()); 3)调用合约方法 TransactionReceipt receipt = contract.callFunction("someMethod", args); 其中 someMethod 是合约的一个方法名,args 是方法的参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值