The Payable Modifier
In this lab Iām going to show you the payable modifier.
In the previous code example we had a simple smart contract that stores a string. Weāre going to expand this functionality now and charge for every string change 1 Eth š¤.
Sample Smart Contract
This is the Smart Contract weāre getting started with:
//SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
contract SampleContract {
string public myString = "Hello World";
function updateString(string memory _newString) public {
myString = _newString;
}
}
In order for it to receive Eth, you need to add two things here:
- you need to add the payable modifier. That is the keyword āpayableā right next to the visibility specifier āpublicā
- you need to understand the global msg-objects property called value.
msg.value
.
But before that, try to send 1 eth to the smart contracts āupdateStringā function. You will see it ends in an error.
The first thing we need to change is the āpayableā modifier.
What is the payable modifier
The payable modifier tells solidity that the function is expecting eth to receive. Thatās it! Letās expand our smart contract so it can receive eth:
//SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
contract SampleContract {
string public myString = "Hello World";
function updateString(string memory _newString) public payable {
myString = _newString;
}
}
What is msg.value
Youāre probably wondering what exactly is the msg-object. The msg-object contains information about the current message with the smart contract. Itās a global variable that can be accessed in every function.
Letās extend the smart contract to charge 1 eth for each string update:
//SPDX-License-Identifier: MIT
pragma solidity 0.8.15;
contract SampleContract {
string public myString = "Hello World";
function updateString(string memory _newString) public payable {
if(msg.value == 1 ether) {
myString = _newString;
} else {
payable(msg.sender).transfer(msg.value);
}
}
}
Run it again, and youāll see that every time you send 1 eth, you can update the string. But if you send less or more, you just get refunded.
In the next lab Iāll show how you can send ether to a smart contract without actually sending it to a specific function!