Урок 3

Writing a Basic Smart Contract

Variables, functions, and modifiers are essential components in Solidity smart contracts. Solidity has two types of variables: state variables and local variables.

In this section, we will discuss the process of writing a basic smart contract using Solidity. We will cover essential components such as variables, functions, and modifiers. Then, we will walk through an example of implementing a simple token contract.

Variables, functions, and modifiers

  • Variables: In Solidity, there are two types of variables – state variables and local variables. State variables are permanently stored on the blockchain, whereas local variables are temporary and exist only within the scope of a function.
  • Functions: Functions are the building blocks of smart contracts. They are used to performing specific tasks, like creating transactions and executing custom logic. Functions can have input parameters and return values, allowing for greater customization and flexibility.
  • Modifiers: Modifiers are unique to Solidity and are used to modify the behavior of a function. They can improve the readability and manageability of the code and can be used to authenticate incoming values or conditionally execute a called function.

Example1: Implementing a simple token contract

Let’s create a simple token contract using Solidity. This contract will allow users to transfer tokens between accounts and check the token balance of any account.

TypeScript
pragma solidity ^0.8.0;

contract SimpleToken {
    // Declare state variables
    address public owner;
    mapping(address => uint256) public balances;

    // Initialize the token contract
    constructor(uint256 initialSupply) {
        owner = msg.sender;
        balances[owner] = initialSupply;
    }

    // Function to transfer tokens
    function transfer(address to, uint256 amount) public {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }

    // Function to check the token balance of an account
    function balanceOf(address account) public view returns (uint256) {
        return balances[account];
    }
}

In this contract, we have:

  • State variables owner and balances to store the contract owner’s address and token balances of all addresses, respectively.
  • A constructor function that sets the initial supply of tokens and assigns them to the contract owner.
  • A transfer function that allows users to transfer tokens to other accounts. It uses the require statement to ensure the sender has enough tokens to transfer.
  • A balanceOf function that returns the token balance of a specified account.
  • This basic token contract demonstrates how to use variables, functions, and modifiers in Solidity to create a simple, functional smart contract.

Example2: Implementing a simple voting system

TypeScript
pragma solidity ^0.8.0;

contract VotingSystem {
    mapping (bytes32 => uint256) public votesReceived;
    bytes32[] public candidateList;

    constructor(bytes32[] memory candidateNames) {
        candidateList = candidateNames;
    }

    function voteForCandidate(bytes32 candidate) public {
        require(validCandidate(candidate), "Invalid candidate.");
        votesReceived[candidate] += 1;
    }

    function totalVotesFor(bytes32 candidate) public view returns (uint256) {
        require(validCandidate(candidate), "Invalid candidate.");
        return votesReceived[candidate];
    }

    function validCandidate(bytes32 candidate) public view returns (bool) {
        for (uint256 i = 0; i < candidateList.length; i++) {
            if (candidateList[i] == candidate) {
                return true;
            }
        }
        return false;
    }
}

In this example, the VotingSystem contract allows users to vote for one of several candidates by calling the voteForCandidate function. The contract keeps track of the number of votes received for each candidate using a votesReceived mapping, where the key is the name of the candidate and the value is the number of votes. The candidateList variable stores the list of valid candidates. The totalVotesFor function can be called to check the number of votes a specific candidate has received, and the validCandidate function checks whether a candidate is valid. This is a simple example of how Solidity can be used to build decentralized applications with complex logic.

Highlights
Variables, functions, and modifiers are essential components in Solidity smart contracts.
Solidity has two types of variables: state variables and local variables.
Functions are used to perform tasks and can have input parameters and return values.
Modifiers are used to modify the behavior of a function and improve code readability and manageability.
The SimpleToken contract allows users to transfer tokens and check token balances.
The SimpleToken contract demonstrates the use of state variables, a constructor function, and functions like transfer and balanceOf.
The VotingSystem contract enables users to vote for candidates and tracks vote counts.
The VotingSystem contract showcases the use of mappings, arrays, and functions like voteForCandidate, totalVotesFor, and validCandidate.

Отказ от ответственности
* Криптоинвестирование сопряжено со значительными рисками. Будьте осторожны. Курс не является инвестиционным советом.
* Курс создан автором, который присоединился к Gate Learn. Мнение автора может не совпадать с мнением Gate Learn.
Каталог
Урок 3

Writing a Basic Smart Contract

Variables, functions, and modifiers are essential components in Solidity smart contracts. Solidity has two types of variables: state variables and local variables.

In this section, we will discuss the process of writing a basic smart contract using Solidity. We will cover essential components such as variables, functions, and modifiers. Then, we will walk through an example of implementing a simple token contract.

Variables, functions, and modifiers

  • Variables: In Solidity, there are two types of variables – state variables and local variables. State variables are permanently stored on the blockchain, whereas local variables are temporary and exist only within the scope of a function.
  • Functions: Functions are the building blocks of smart contracts. They are used to performing specific tasks, like creating transactions and executing custom logic. Functions can have input parameters and return values, allowing for greater customization and flexibility.
  • Modifiers: Modifiers are unique to Solidity and are used to modify the behavior of a function. They can improve the readability and manageability of the code and can be used to authenticate incoming values or conditionally execute a called function.

Example1: Implementing a simple token contract

Let’s create a simple token contract using Solidity. This contract will allow users to transfer tokens between accounts and check the token balance of any account.

TypeScript
pragma solidity ^0.8.0;

contract SimpleToken {
    // Declare state variables
    address public owner;
    mapping(address => uint256) public balances;

    // Initialize the token contract
    constructor(uint256 initialSupply) {
        owner = msg.sender;
        balances[owner] = initialSupply;
    }

    // Function to transfer tokens
    function transfer(address to, uint256 amount) public {
        require(balances[msg.sender] >= amount, "Insufficient balance");
        balances[msg.sender] -= amount;
        balances[to] += amount;
    }

    // Function to check the token balance of an account
    function balanceOf(address account) public view returns (uint256) {
        return balances[account];
    }
}

In this contract, we have:

  • State variables owner and balances to store the contract owner’s address and token balances of all addresses, respectively.
  • A constructor function that sets the initial supply of tokens and assigns them to the contract owner.
  • A transfer function that allows users to transfer tokens to other accounts. It uses the require statement to ensure the sender has enough tokens to transfer.
  • A balanceOf function that returns the token balance of a specified account.
  • This basic token contract demonstrates how to use variables, functions, and modifiers in Solidity to create a simple, functional smart contract.

Example2: Implementing a simple voting system

TypeScript
pragma solidity ^0.8.0;

contract VotingSystem {
    mapping (bytes32 => uint256) public votesReceived;
    bytes32[] public candidateList;

    constructor(bytes32[] memory candidateNames) {
        candidateList = candidateNames;
    }

    function voteForCandidate(bytes32 candidate) public {
        require(validCandidate(candidate), "Invalid candidate.");
        votesReceived[candidate] += 1;
    }

    function totalVotesFor(bytes32 candidate) public view returns (uint256) {
        require(validCandidate(candidate), "Invalid candidate.");
        return votesReceived[candidate];
    }

    function validCandidate(bytes32 candidate) public view returns (bool) {
        for (uint256 i = 0; i < candidateList.length; i++) {
            if (candidateList[i] == candidate) {
                return true;
            }
        }
        return false;
    }
}

In this example, the VotingSystem contract allows users to vote for one of several candidates by calling the voteForCandidate function. The contract keeps track of the number of votes received for each candidate using a votesReceived mapping, where the key is the name of the candidate and the value is the number of votes. The candidateList variable stores the list of valid candidates. The totalVotesFor function can be called to check the number of votes a specific candidate has received, and the validCandidate function checks whether a candidate is valid. This is a simple example of how Solidity can be used to build decentralized applications with complex logic.

Highlights
Variables, functions, and modifiers are essential components in Solidity smart contracts.
Solidity has two types of variables: state variables and local variables.
Functions are used to perform tasks and can have input parameters and return values.
Modifiers are used to modify the behavior of a function and improve code readability and manageability.
The SimpleToken contract allows users to transfer tokens and check token balances.
The SimpleToken contract demonstrates the use of state variables, a constructor function, and functions like transfer and balanceOf.
The VotingSystem contract enables users to vote for candidates and tracks vote counts.
The VotingSystem contract showcases the use of mappings, arrays, and functions like voteForCandidate, totalVotesFor, and validCandidate.

Отказ от ответственности
* Криптоинвестирование сопряжено со значительными рисками. Будьте осторожны. Курс не является инвестиционным советом.
* Курс создан автором, который присоединился к Gate Learn. Мнение автора может не совпадать с мнением Gate Learn.