15 关于合约调用合约的问题

这是A合约:

pragma solidity ^0.4.19;

contract Amoney{
    mapping (address => uint256) balances;

    function deposit() payable public{
        balances[msg.sender] += msg.value;
    }

    function withdraw(address add,uint amount) public{
        require(balances[add] >= amount);
        add.call.value(amount)();
        balances[add] -= amount;
    }
}

这是B合约,首先尝试用接口的方式调用A合约的方法:

pragma solidity ^0.4.19;

import "./Amoney.sol";

contract ABItest{
    Amoney public amoney;
    address target;

    constructor(address _target) public payable{
        amoney = Amoney(_target);
    }

    function deposit() public payable{
        amoney.deposit.value(msg.value);
    }

    function withdraw() public{
        amoney.withdraw(this,1 ether);
    }
}

问题一、这里出现了错误function deposit() public payable{ amoney.deposit.value(msg.value); }。 尝试存入1ether的时候,发现1 ether存到了B合约的地址,而不是调用A合约的deposit()从而存到A合约,这里应该怎么修改好呢?

这是C合约,尝试用call的方法调用A合约的方法:

pragma solidity ^0.4.25;

contract CallTest{
    address public target;
    address public owner;

    constructor () payable public{
        owner = msg.sender;
    }

    modifier ownerOnly{
        require (owner == msg.sender);
        _;
    }

    function setAdd(address add) ownerOnly public{
        target = add;
    }

    function deposit() public ownerOnly payable returns(bool){
       return target.call.value(msg.value)(bytes4(keccak256("deposit()")));
    }

    function withdraw() public ownerOnly payable returns(bool){
       return target.call(bytes4(keccak256("withdraw(address,uint256")),this,1 ether);
    }

问题二、这次是 function withdraw() public ownerOnly payable returns(bool){ return target.call(bytes4(keccak256("withdraw(address,uint256")),this,1 ether); } 这里出现了错误。实际操作的时候没动,明明deposit()成功了,并且B合约地址在A合约也确实有了足够余额,应该需要怎么修改呢?

问题三、本次测试使用的是0.4版本的solidity。 请问下0.6以后版本的call方法是否有做了什么更新或者改动?

请先 登录 后评论

最佳答案 2022-02-28 14:23

pragma solidity >=0.8.0;
contract contractA {
    function deposit() public payable {}
}

contract contractB {
    function invokeContractA() public payable { 
        contractA a = contractA(0x1234567891234567891234567891234567891234);
        uint ValueToSend = 1234;
        a.deposit{value: ValueToSend}();
      // 如果是低版本:a.deposit.value(ValueToSend);
    }  
}

问题二的错误在于,你没有实现receiver 或 fallback 函数,所以没法接收。

请先 登录 后评论

其它 0 个回答

  • 2 关注
  • 1 收藏,2366 浏览
  • bugfly 提出于 2022-02-28 12:04