0

I can call functions of other smart contracts that don't require payment, I can send money to another smart contract, but how do make a smart contract call a function and pay another smart contract at the same time?

Here's a sample code to demonstrate what I'm talking about:

Smart contract 1 whose function I want to call:

function buyTicket() public payable {
        require(msg.value == 2 ether, "not enough ether");
        require(lotteryFunds >= 2 ether, "casino closed for lack of funding");
        tickets++;
    }

Smart contract 2 who is trying to call that function:

   function getTicket() private {
        require(address(this).balance >= 2 ether, "not enough in the contract");
        (bool success,) = payable(casino).call{value: 2 ether}("");
        require(success, "Fail at stage one");
        t.buyTicket();
    }

getTicket() (which is called by another function) returns "not enough ether". I think this is because the function is first sending ether, then calling the function with 0 ether, which would return "not enough ether". How do I call the function with the payment?

Ilan Katz
  • 29
  • 7

2 Answers2

1

In order to call a specific function of another smart contract you can use the function selector:

(bool success,) = payable(casino).call{value: 2 ether}(abi.encodeWithSignature("buyTicket()"));
Javier Marchetti
  • 1,217
  • 3
  • 12
1

You need to call the function buyTicket of the second contract while sending 2 eth

Here is an example:

contract Receiver {
uint public tickets;

function buyTicket() public payable {
        require(msg.value == 2 ether, "not enough ether");
        // require(lotteryFunds >= 2 ether, "casino closed for lack of funding");
        tickets++;
    }

}

contract Sender {

Receiver public receiver;

constructor(address payable _receiverAddress) payable {
    receiver = Receiver(_receiverAddress);
}

function getTicket() external payable {
    require(msg.value >= 2 ether, "Not sending enought");
    receiver.buyTicket{value: 2 ether}();
}

}

Hope this helps

P.s. I commanded out the lotteryFund require since I had no idea what it was.

Olivier Demeaux
  • 1,957
  • 2
  • 8
  • 16