0

dex.sol(contract A)

//SPDX-License-Identifier: MIT
pragma solidity 0.8.19;
import "./storage.sol";
contract dex1{
    storage_contract public contractaddress;
    constructor(address _storageContract){
        contractaddress = storage_contract(_storageContract);
    }
function addmoney(uint amount)public returns(uint){
    uint balance = contractaddress._addmoney(amount);
    return balance;

}
function getbalance(address _address)public view returns(uint) {
    uint balance = contractaddress._getbalance(_address);
    return balance;
}

}

storage.sol (contract B)

//SPDX-License-Identifier:MIT
pragma solidity 0.8.19;
contract storage_contract{
    mapping(address => uint) public balances;
function _addmoney(uint _money)public returns(uint) {
    return balances[msg.sender] += _money;
}
function _getbalance(address _address)public view returns(uint){
    return balances[_address];
}

}

Here when i tried to store a value from dex1 using addmoney() and try to retrieve the value by getbalance() but i'm not getting any.Here i want to access the values stored in the storage contract from the dex1 contract?

I have tried to many importing techiniques like using direct addressess and .call functions but they didnt workout but when i removed the parameters in getbalance() in dex1 and _getbalance() in storage_contract and changed the return balances[_address]; as return balances[msg.sender];we can able to retrevieving but i dont want this method of retreiving

kumar
  • 61
  • 4

1 Answers1

1

Your issue here probably lies in the fact that you're doing

    function _addmoney(uint _money)public returns(uint) {
        return balances[msg.sender] += _money;
    }

and calling that function only through your dex1 contract. That makes msg.sender in the context of storage_contract always be dex1 address would make any call to addmoney update dex1 balance in your storage contract, and not the user calling that function (which i assume is the intended behavior). There's 2 workarounds i can think of off the top of my head :

  • Use tx.origin (usually not recommended, as it's easy to exploit through phishing attacks)
contract storage_contract{
  // ...
  function _addmoney(uint _money) public returns(uint){
    return balances[tx.origin] += _money;
  }
}
  • have a param that represents the user address in _addmoney and pass it from your dex1 contract
 contract storage_contract{
   // ...
   function _addmoney(address user, uint _money)public returns(uint){
     return balances[user] += _money;
   }
 }
 contract dex1{
   // ...
   function addmoney(uint amount)public returns(uint){
       uint balance = contractaddress._addmoney(msg.sender, amount);
       return balance;

}

Foxxxey
  • 4,307
  • 1
  • 6
  • 22