1

Below is the contract which imports another contract

pragma solidity ^0.8.7;

import "./SimpleStorage.sol"; 

contract StorageFactory {

   
   SimpleStorage[] public simpleStorageArray;    
   
   function createSimpleStorageContract() public {
       SimpleStorage simpleStorage = new SimpleStorage();
       simpleStorageArray.push(simpleStorage);
   }  
}

Now after using function createSimpleStorageContract() and trying to fetch elements of array , we are seeing

enter image description here

SimpleStorage is another contract which I wrote and then imported it. Now simpleStorageArray is an array of type SimpleStorage. However what I am not able to understand which I try to fetch any value by providing index number in remix , it returns me the address. In every element it should store a new instance of contract why is it storing addresses. Can anyone please explain if array is of SimpleStorage contract type then why it stores & returns address when given index number ?

2 Answers 2

1

That’s because when you call new = SimpleStorage() you are creating new smart contract SimpleStorage from StorageFactory and at the same time pushing it’s newly created smart contract address to the simpleStorageArray. After you can check those addresses by index number. Hope that helps.

3
  • How is address getting pushed in the array. simpleStorageArray.push(simpleStorage) it measn that I am pushing the newly created smart contract and not the address. Is there something which I am missing ?
    – Brijesh
    Nov 27, 2022 at 9:14
  • At the same time You are pushing newly created smart contract and it’s contract address. You can check it by copying that address and paste it into “ load contract from address “ in Remix.
    – kapitankot
    Nov 27, 2022 at 9:26
  • That's what I want to know that how address is being pushed into the array given that the type of array is SimpleStorage. Like which particular line is making the address go inside the array.
    – Brijesh
    Nov 27, 2022 at 11:29
0

When you store contract B inside A. It only stores a "reference" to B, that reference is its address. It the only thing it needs to store, the ABI will be used to generate the calls to the contract by the compiler so it won't be stored.

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;


contract B {
}

contract A {
    B public b;
    constructor() {
        b = new B();
    }
}

When storing an array of contract is exactly the same. Only the addresses are stored.

// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0 <0.9.0;


contract B {
}

contract A {
    B[] public bs;
    constructor() {
        bs.push(new B());
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.