A Simple Smart Contract
A basic example that sets the value of a variable and exposes it for other contracts to access
Storage Example
The first line tells you that the source code is written for Solidity version 0.8.17. This is to ensure that the contract is compatible with the current EVM version in Viction.
A contract in the sense of Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Viction blockchain. The line uint storedData;
declares a state variable called storedData
of type uint256
(unsigned integer of 256 bits). You can think of it as a single slot in a database that you can query and alter by calling functions of the code that manages the database. In this example, the contract defines the functions set
and get
that can be used to modify or retrieve the value of the variable.
To access a state variable, you do not need the prefix this
as is common in other languages.
This contract does not do much yet apart from allowing anyone to store a single number that is accessible by anyone in the world without a (feasible) way to prevent you from publishing this number. Anyone could call set
again with a different value and overwrite your number, but the number is still stored in the history of the blockchain. Later, you will see how you can impose access restrictions so that only you can alter the number.
Subcurrency Example
The following contract implements the simplest form of a cryptocurrency. The contract allows only its creator to create new coins (different issuance schemes are possible). Anyone can send coins to each other without a need for registering with a username and password, all you need is a Viction private key.
This contract introduces some new concepts, let us go through them one by one.
The keyword public
automatically generates a function that allows you to access the current value of the state variable from outside of the contract. Without this keyword, other contracts have no way to access the variable. The code of the function generated by the compiler is equivalent to the following (ignore external
and view
for now):
You could add a function like the above yourself, but you would have a function and state variable with the same name. You do not need to do this, the compiler figures it out for you.
You can use this function to query the balance of a single account.
The functions that make up the contract, and that users and contracts can call are mint
and send
.
The send
function can be used by anyone (who already has some of these coins) to send coins to anyone else. If the sender does not have enough coins to send, the require
call fails and provides the sender with an appropriate error message string.
Last updated