Solidity Functions
A function is a named block of code in a contract that runs when it is called. A function can take inputs, do work, and hand a value back to the caller.
The full shape of a function
This function is named double. It takes one number and hands back a number twice as big.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Doubler {
function double(uint256 number) public returns (uint256) {
return number * 2;
}
}
One function can call another
quadruple calls double twice. The inner result becomes the input for the outer call.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Quadrupler {
function double(uint256 number) public returns (uint256) {
return number * 2;
}
function quadruple(uint256 number) public returns (uint256) {
return double(double(number));
}
}
Two functions can share one helper
bonus is the shared helper here. afterWin and afterTwoWins both reuse it instead of repeating the same step.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract Levels {
function bonus(uint256 score) public returns (uint256) {
return score + 10;
}
function afterWin(uint256 score) public returns (uint256) {
return bonus(score);
}
function afterTwoWins(uint256 score) public returns (uint256) {
return bonus(bonus(score));
}
}
Example
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.30;
contract GameScore {
uint256 public score;
function winPoints() public returns (uint256) {
return 10;
}
function recordWin() public {
score = score + winPoints();
}
function recordTwoWins() public {
recordWin();
recordWin();
}
}
Key points
- Name: the word after the function keyword names the block.
- Inputs: the values in parentheses are the data a call sends in.
- Visibility: a word like public says who can call the function.
- Returns: the returns part names the type of value handed back.
- Call: write the function name with its inputs to run it.
- Reuse: one function can call another function in the same contract by name.
In this example, winPoints hands back 10 every time it is called. recordWin calls winPoints by name and adds the result to score. recordTwoWins reuses recordWin twice, so two calls add 20 points in total.
Note
a function does nothing until a call reaches it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Remix IDE
Exercise
What does the returns part of a function declare?