1

I have 2 contracts.

contract Contract1{
  struct Data {
      uint data1;
      string data2;
  }
  Data [] newData;
}

Let's assume that I have datas in newData

import "./Contract1.sol";
contract Contract2{
  Data storage newOne = newData[0];
}

I want to reach array of struct which is in Contract1 as above. How can I access to Contract1 from Contract2?

1 Answer 1

1

You can extend a contract with the is keyword.

Child contracts (in your case Contract2) can access all non-private parent (in your case Contract1) properties.

pragma solidity ^0.8;

import "./Contract1.sol";

contract Contract2 is Contract1 {
    function foo() external {
        Data storage newOne = newData[0];
        // newOne.data1 = 1;
        // newOne.data2 = 'hello';
    }
}

Edit: Mind that newData[0] is trying to access index 0 of the array, but when the contract is deployed, the array is empty (does not have index 0). You can create the first item (with index 0 and dummy data) by executing this function:

function add() external {
    newData.push(Data(1, 'a'));
}
Sign up to request clarification or add additional context in comments.

2 Comments

I got an type error. Contract "Contract2" should be marked as abstact.
@almi That's unrelated to your original question and to the solution. The "should be marked as abstract" error shows up when your contract has a function definition without implementation, e.g. function foo() external; (mind the semicolon at the end and no function body).

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.