Search code examples
ethereumblockchainsoliditysmartcontractsremix

Solidity: Call Deposit function with value


I have a deposit smart contract (Bank) below. I can use remix entering the value and calling the Deposit function.

How can i write a smart contract to do the same (Sender) below. I tried adding the interface but I cant seem to add a value when i call the sendDeposit

enter image description here

//// Bank Smart Contract

pragma solidity ^0.8.0;

contract bank {
    uint256 public amountIn;
    function deposit() external payable returns(uint256) {
        amountIn = msg.value ;
        return amountIn;
    }
}

///// SENDER Contract

pragma solidity ^0.8.0;

interface Receiver {

    function deposit() external payable returns(uint256);
}

contract sender {
    Receiver private receiver = Receiver(0x0fC5022f7B5c4Df39A836);

    function sendDeposit(uint256 _amount) public payable {
        receiver.deposit{value: _amount}();
    }


    receive() external payable {
         require(msg.value > 0, "You cannot send 0 ether");
    }

 }

I tried writing it like this, but there is no value in the transaction send

function sendDeposit(uint256 _amount) public payable { receiver.deposit{value: _amount}(); }


Solution

  • //SPDX-License-Identifier: MIT
    pragma solidity ^0.8.7;
    
    contract Bank {
        uint256 public amountIn;
        function deposit() external payable returns(uint256) {
            amountIn = msg.value ;
            return amountIn;
        }
        // receive() external payable{}
        function getBalance() public view returns(uint){
            return address(this).balance;
        }
    }
    
    
    interface Receiver {
        function deposit() external payable returns(uint256);
    }
    
    contract Sender {
        Receiver private receiver ;
        constructor(address _receiver){
            receiver=Receiver(_receiver);
        }
    
        function sendDeposit(uint256 _amount) public payable {
            receiver.deposit{value: _amount}();
        }
    
        receive() external payable {
             require(msg.value > 0, "You cannot send 0 ether");
        }
    
     }
    

    1- Deploy the Bank contract first and copy the address

    2- Deploy the Sender contract, passing the copied Bank contract

    3- call sendDeposit from Sender contract, you need to pass same amout to function input and value input which is under the "Gas limit" input

    4- transaction will be succcessful. call the getBalance from Bank contract