DEV Community

Cover image for Smart Contract Development - Functions
a_moah__
a_moah__

Posted on

Smart Contract Development - Functions

Introduction

The programming language Solidity, which underpins Ethereum smart contracts, enables programmers to design DApps (decentralised apps) that run smoothly on the blockchain. Functions, the fundamental units of smart contracts, are at the core of Solidity. We will explore the syntax, types, and real-world application of Solidity functions using the Remix IDE as we go on a quest to become experts in this blog.

Understanding Functions in Solidity

Functions are crucial elements in Solidity that include reusable code segments, enabling developers to effectively arrange and construct their smart contracts. Functions can be called by external accounts, by other functions, or even automatically when specific circumstances are met.

Basic Syntax

Let's dive into the basic syntax of a Solidity function:

// Function Declaration
function functionName(parameter1Type parameter1, parameter2Type parameter2) visibility returnType {
    // Function Body
    // Code logic goes here
    // ...

    // Return Statement (if applicable)
    return returnValue;
}
Enter fullscreen mode Exit fullscreen mode

Let us explain the above:

  • functionName: The name of the function.

  • parameter1Type, parameter2Type: The types of parameters the function accepts.

  • visibility: Specifies the visibility of the function (e.g., public, private, internal, external).

  • returnType: The type of the value the function returns (if any).

Remix IDE Examples

Example 1: Simple Function

Let's create a simple function that adds two numbers and returns the result. Click on the Create new file icon and name it as "SimpleMath.sol."

Start with the version of solidity you want to use. In our case, we will be using version "^0.8.0."

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
Enter fullscreen mode Exit fullscreen mode

Now, we will declare the smart contract. The name of our smart contract will be "SimpleMath."

contract SimpleMath {

}
Enter fullscreen mode Exit fullscreen mode

In our SimpleMath contract, we will add our addNumbers function. see below:

// Function to add two numbers
    function addNumbers(uint256 num1, uint256 num2) public pure returns (uint256) {
        uint256 sum = num1 + num2;
        return sum;
    }

Enter fullscreen mode Exit fullscreen mode

The entire code block will look like the below code:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.0;

contract SimpleMath {
    // Function to add two numbers
    function addNumbers(uint256 num1, uint256 num2) public pure returns (uint256) {
        uint256 sum = num1 + num2;
        return sum;
    }
}
Enter fullscreen mode Exit fullscreen mode

Compile the contract by pressing control or command and s or press the green play icon. Click on the icon that says "Deploy & run transactions.

Deploy and run image
Notice from the image above, there are Environment, Account, Gas Limit, Contract and others, we will not change anything. Click on the "Deploy button" beneath the contract to deploy it.
In the left panel, scroll down to the Deployed Contracts and expand the "SIMPLEMATH AT 0..." contract. You will have something like the below image:

Deployed contract image
In the input beside the "addNumbers button", provide two numbers say 17 and 24 and separate with a comma then click on the "addNumbers button" to interact with the addNumbers function. Observe the returned sum. You will have something like the image below:

Contract interaction

Example 2: Function Modifiers

Modifiers are used to enhance the functionality of functions. Let's create a modifier and apply it to a function. Click on the Create new file icon and name it as "FunctionModifier.sol."

Start with the version of solidity you want to use. In our case, we will be using version "^0.8.0."

// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
Enter fullscreen mode Exit fullscreen mode

Now, we will declare the smart contract. The name of our smart contract will be "FunctionModifier."

contract FunctionModifier {

}
Enter fullscreen mode Exit fullscreen mode

In our FunctionModifier contract, we will declare some variables. see below:

address public owner;
uint256 public value;

Enter fullscreen mode Exit fullscreen mode

In our FunctionModifier contract, we will declare our onlyOwner modifier. see below:

modifier onlyOwner() {
        require(msg.sender == owner, "Only the owner can call this function");
        _;
    }
Enter fullscreen mode Exit fullscreen mode

In our FunctionModifier contract, we will declare our setValue Function. see below:

// Function to set the value (accessible only to the owner)
    function setValue(uint256 newValue) public onlyOwner {
        value = newValue;
    }
Enter fullscreen mode Exit fullscreen mode

In our FunctionModifier contract, we will declare our Constructor. see below:

// Constructor to set the owner
    constructor() {
        owner = msg.sender;
    }
Enter fullscreen mode Exit fullscreen mode

The entire code block will look like this:

// SPDX-License-Identifier: GPL-3.0

pragma solidity ^0.8.0;

contract FunctionModifier {
    address public owner;
    uint256 public value;

    // Modifier to restrict access to the owner
    modifier onlyOwner() {
        require(msg.sender == owner, "Only the owner can call this function");
        _;
    }

    // Function to set the value (accessible only to the owner)
    function setValue(uint256 newValue) public onlyOwner {
        value = newValue;
    }

    // Constructor to set the owner
    constructor() {
        owner = msg.sender;
    }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the onlyOwner modifier ensures that only the owner of the contract can call the setValue function.

  • Contract Variables:
    address public owner;: This variable will store the Ethereum address of the owner of the contract.
    uint256 public value;: This variable will store an unsigned integer value, which can be set using the setValue function.

  • Modifier: onlyOwner():
    This is a custom modifier named onlyOwner. Modifiers are used to modify the behavior of functions in Solidity.
    The modifier checks if the sender of the transaction (msg.sender) is the owner of the contract (owner). If not, it raises an exception with the specified error message.
    The _; is a placeholder that represents the actual code of the function using the modifier. It acts as a wildcard where the function's code will be inserted.

  • Function: setValue(uint256 newValue) public onlyOwner { ... }:
    This function is intended to set the value of the value variable but is restricted to only be callable by the owner of the contract.
    The onlyOwner modifier is applied to this function, ensuring that only the owner can execute the code inside the function.
    If someone who is not the owner attempts to call this function, the transaction will fail due to the modifier's requirement.

  • Constructor: constructor() { ... }:
    The constructor is a special function that is executed only once when the contract is deployed. In this case, it sets the owner variable to the address of the account that deployed the contract (msg.sender).

Compile the contract by pressing control or command and s or press the green play icon. Click on the icon that says "Deploy & run transactions."
Click on the "Deploy button" beneath the contract to deploy it.

In the left panel, scroll down to the Deployed Contracts and expand the "FunctionModifier AT 0..." contract. You will have something like the below image:

Deployed Contract

In the input beside the "setValue button", provide any number you like and click on the "setValue button" to interact with the setValue function. Click on the "owner button" and you will get the owner address. Click on the "value button" and you will get the value you entered. You will have something like the image below:

Contract interaction

Conclusion

Becoming fluent in Solidity functions is a prerequisite for developing smart contracts. As the Remix IDE's examples show, functions offer an adaptable way to organise and manage the actions of your smart contracts. Gaining knowledge of the functions' syntax, visibility, and modifiers will prepare you to create reliable and effective decentralised apps on the Ethereum network. So start your Remix IDE, play about with functions, and let Solidity's full potential shine through in your blockchain development endeavours.

In our next blog of this series, we will talk about control structures.

Have fun with coding!

Top comments (0)