0

I am currently developing a dAPP and I am splitting it in 2 distinct contracts. I will be calling functions from contract A to contract B. In contract B I have an array of struct which I can manipulate. However I need some functions called from A to B and B must return the struct array or a copy of it to contract A. How can I do this? If I use a mapping instead of struct arrays, can I still do it?

Thanks

1 Answer 1

2
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

contract A {
  B private b;

  constructor (B _b) public {
    b = _b;
  }

  function bar () public {
    B.S [] memory structs = b.foo ();
  }
}

contract B {
  struct S {
    uint x;
    uint y;
  }

  S [] private structs;

  function foo () public view returns (S [] memory) {
    return structs;        
  }
}

With mappings situation is a bit more complicated because:

  1. ABI encoding does not support mappings
  2. Mappings do not store the keys, but only the values

However you may return mapping like this:

pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;

contract A {
  B private b;

  constructor (B _b) public {
    b = _b;
  }

  function bar () public {
    address [] memory keys;
    B.S [] memory values;

    (keys, values) = b.foo ();
  }
}

contract B {
  struct S {
    uint x;
    uint y;
  }

  mapping (address => S) private structs;
  address [] private keys;

  function foo () public view returns (address [] memory _keys, S [] memory _values) {
    _keys = keys;
    _values = new S [] (_keys.length);
    for (uint i = 0; i < _keys.length; i++)
      _values [i] = structs [_keys [i]];
  }
}
3
  • Dear Mikhail, thank you you have saved my day :)
    – Zunga 2019
    Commented Dec 19, 2019 at 14:37
  • 1
    You are welcome. BTW, people usually say "thank you" here by accepting the answer. Commented Dec 19, 2019 at 14:40
  • Upvoted. I wonder if this deserves warnings about scalability or the practice of using experimental code in production for anyone else who comes across this. Commented Dec 19, 2019 at 15:51

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.