I am desperately trying to manage an array of contracts from a parent contract. Going back to basics, I have implemented the code coming from Pushing a contract to an array in another contract witch roughly does what I want.
//SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.14;
contract Dog {
string public name;
constructor(string memory _name){
name = _name;
}
}
contract Human {
Dog[] public dogs;
uint public currDogs;
function addDog() public {
dogs.push(new Dog("test"));
currDogs++;
}
}
Compilation using solc: solc Human.sol --bin --abi -o . --overwrite
Deployment using a JS script similar to the one described in the doc: https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#deploy
Going to the JavaScript console, I do the following:
> var abi = [{"inputs":[],"name":"addDog","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"currDogs","outputs":[{"internalType":"uint256","name":"","type":"uint256"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"","type":"uint256"}],"name":"dogs","outputs":[{"internalType":"contract Dog","name":"","type":"address"}],"stateMutability":"view","type":"function"}]
undefined
> var cnt = web3.eth.contract(abi);
undefined
>
> var cntinst = cnt.at('0x43d0A1BAC182803587ae9bFF6a4EbF27f3600900');
undefined
> cntinst.addDog({from: eth.accounts[0], gas:3000000});
"0xf9426240a47cb6d0f6f58b47f8b54206bcd665079a6a421f088d41c40b22b5f4"
> cntinst.dogs.length.valueOf()
0
> cntinst.dogs.length
0
> cntinst.dogs[0].name
TypeError: Cannot read property 'name' of undefined
at <eval>:1:1(4)
The question is: Why is my array "dogs" always empty?
cntinst.dogs(index)
. For web3 version 1.xx and abovecntinst.dogs
doesn't exists, it was replaced bycntinst.methods.dogs(index)
.