Solidity: Can a Parent contract see data updates from a Child contract?

妖精的绣舞 提交于 2019-12-11 01:44:45

问题


I have a premature implementation of an Ethereum game. I have divided my code in two contracts, separating "game" functions from functions called by the Admin.

Admin.sol inherits from Game.sol as seen below. A struct object is created in Admin, but Game cannot see it. (Getter function returns nothing)

import "./Game.sol";

contract Admin is Game

The same code, if not divided in two contracts, works perfectly.

Header of function in Admin.sol that creates the object:

function createJob(string memory _jname, uint _reward, uint _application_period, uint _job_duration) public {

Header of the getter function in Game.sol:

function getJob(uint _jID) public view returns (string memory, uint, uint, uint, uint)

What I get from the getter is:

Result { '0': '', '1': , '2': , '3': , '4': }

Which makes it clear it is just showing me an "empty" spot in the mapping.

Is it possible to have the data changes made in Admin.sol seen by Game.sol? If yes, how is it done?

Thanks for the help.


回答1:


Yes it is possible. Few things you have to understand first is that SmartContract can only access its own storage allocated in the EVM so one smartcontract can not access the variables of another SmartContract until they are inherit. In your case you may be deploying they seprately and while you are updating the values you are using different instances.

What you have to do is to deploy only one contract contract with inheritence (in below example its ContractB). Where as you can use the function of the parent contract too. Here is the sample

pragma solidity >=0.4.22 <0.6.0;

contract ContractA {

      int a;

      function setA(int _a)  public {
           a = _a;
      }
      function getA() view public returns(int){
           return a;
      }
}

Whereas Contract B is like this

pragma solidity >=0.4.22 <0.6.0;
import"./ContractA.sol";

contract ContractB is ContractA {
       function getContractAvalue() pure public returns(int){
           // For reference that you can also access the function of ContractA in ContractB
           return ContractA.a;
       }
}

So if you deploy the contract B only, you can access the function of Contract A so with one instance you can do the changes and it will be store in same space of storage in EVM, which can be access with correct values.

You can check it on remix too by just deploying the ContractB and you can see the functions of Contract A.



来源:https://stackoverflow.com/questions/55655626/solidity-can-a-parent-contract-see-data-updates-from-a-child-contract

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!