工厂合同恢复

factory contract reverts

我正在尝试创建一个工厂合约,我称之为 DAG:

pragma solidity >=0.7.0 <0.9.0;
import "./Agent.sol";

    contract DAG {
    
        address[] agents;
    
        function createDAG() public returns (address) {
            // create root agent
            address[] memory parentsOfRoot;
            address rootAddress = createAgent(parentsOfRoot);
    
    
            // create child
            address[] memory parentsOfChild;
            parentsOfChild[0] = rootAddress;
            createAgent(parentsOfChild);
    
            return rootAddress;
            
        }
        function createAgent(address[] memory _parents) public returns(address) {
            Agent agent = new Agent(_parents);
            agents[agents.length - 1] = address(agent);
            return address(agent);        
        }
    }

它的目的是制作类似代理连接列表的东西。

pragma solidity >=0.7.0 <0.9.0;

contract Agent {

    address[] parents;

    constructor(
        address[] memory _parents
    ){
        parents = _parents;
    }

    function getParents() public view returns (address[] memory) {
        return parents;
    }
}

出于某种原因,当我在 RemixIDE 中调用 createDAG 时,出现以下错误:

transact to DAG.createDAG pending ... transact to DAG.createDAG errored: VM error: revert.

revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.

谁能帮我理解为什么我无法打电话给 createDAG

您的代码段正在尝试分配给数组的第 0 个索引,但此时该索引不存在。这会引发“越界”异常。

address[] memory parentsOfChild; // 0 items
parentsOfChild[0] = rootAddress; // trying to assign the first item (index 0)

目前 (v0.8) 无法调整 in-memory 数组的大小,因此您需要使用已经预定义的长度来初始化数组。

address[] memory parentsOfChild = new address[](1); // 1 empty item
parentsOfChild[0] = rootAddress;

那么你将运行陷入另一个逻辑错误。函数 createAgent() 也在尝试为“越界”索引赋值。

agents 数组为空时,此代码段试图分配到索引 -1。

agents[agents.length - 1] = address(agent);

如果要向agents数组添加新项,可以使用数组的.push()成员函数

// instead of `agents[agents.length - 1] = address(agent);`
agents.push(address(agent));