Solidity Assignment 2

Published by Mario Oettler on

Now it is your turn.

Here, we want to test the functions send(), transfer() and call().

A working example

Create a smart contract called receiver. It should have an empty receive() function. It should also have a public function that returns the contract’s balance in the variable balance. In the function declaration, add the keyword “view”. This makes the output easier to see.

Compile the receiver contract and deploy it.

Next, code a contract with the name sender. It should have a payable constructor and the following public functions.

sendToReceiver(), transferToReceiver(), callToReceiver(). They should implement the respective payment method (send, transfer, and call). Use the receiver contract’s address as receiver address.

Add a public function getBalance() that returns the balance of the contract. In the function declaration, add the keyword “view”. This makes the output easier to see.

When deploying the sender contract, send an amount of maybe 5000 wei along.

You can use the following code:

Receiver

pragma solidity 0.8.20;


contract receiver{

    receive() external payable{

    }
    
    function getBalance() public view returns(uint256 balance){
        return address(this).balance;
    }
}

Sender

pragma solidity 0.8.20;

contract sender{
    address payable public receiver = payable (0x4a9C121080f6D9250Fc0143f41B595fD172E31bf); 

    constructor() payable{
        
    }
    
    function sendToReceiver() public{
        receiver.send(15);
    }
    
    function transferToReceiver() public {
        receiver.transfer(12);
    }
    
    function callToReceiver() public {
        receiver.call{value: 10}("");
    }
        
    
    function getMyBalance() public view returns(uint256 balance){
        return address(this).balance;
    }
}

Play a bit with those contracts and send e few wei to the receiver by using each method. Every time you have executed a method, check the balance in the sender and receiver contract. They should change every time.

Errors

Now, we want to take a closer look at the three functions send, transfer, and call.

In your receiver contract add a variable uint256 counter = 0; and add to the receive() function counter++;

This will increment the value of the variable by one.

Compile and deploy the sender contract again, copy the address to the receiver and deploy it too. Try the sendToReceiver function. You will see that nothing happens. The balance of the sender and receiver contract remains the same.

Now, try the transferToReceiver function. In the console, you will see that this transaction failed. The reason is, that the line we added to the receive() functions costs more than 2300 gas. This creates an out of gas exception. The transfer() reverts, the send() fails silently.

If you use call() instead, everything should go fine.

Categories:

if()