This tutorial aims to provide a solid foundation for getting started with Solidity, the main programming language for Ethereum Smart Contract development. By the end of this tutorial, you will understand the basic syntax of Solidity, key concepts, and how to write your first smart contract.
Solidity is statically typed, supports inheritance, and complex user-defined types which makes it possible to create complex contracts that are still easy to manage.
Here is a basic example of a Solidity contract:
pragma solidity ^0.4.0;
contract SimpleContract {
function doSomething() public {
}
}
In the example above, pragma solidity ^0.4.0;
specifies the compiler version. contract SimpleContract { }
is the contract declaration, and function doSomething() public { }
is a public function declaration.
Let's write a simple contract that stores a value and includes a function to change it.
pragma solidity ^0.4.0;
contract SimpleStorage {
uint storedData;
function set(uint x) public {
storedData = x;
}
function get() public view returns (uint) {
return storedData;
}
}
In this contract, we declare a state variable storedData
of type uint
. The set
function changes the value of the variable and the get
function returns the current value. The public
keyword makes the function callable from outside the contract.
Here's an example of a more complex contract, a basic voting contract:
pragma solidity ^0.4.0;
contract Voting {
// Model a Candidate
struct Candidate {
uint id;
string name;
uint voteCount;
}
// Store Candidates
// Fetch Candidate
mapping(uint => Candidate) public candidates;
// Store Candidates Count
uint public candidatesCount;
// Constructor
constructor () public {
addCandidate("Candidate 1");
addCandidate("Candidate 2");
}
function addCandidate (string _name) private {
candidatesCount ++;
candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);
}
}
In this contract, we have a struct
to model a candidate with an id
, name
, and voteCount
. We then have a mapping
that stores candidates. The constructor
function is called when the contract is deployed and adds two candidates to the contract.
In this tutorial, you've learned the basics of Solidity and how to write simple contracts. You're encouraged to experiment with the examples provided and try to extend them.
For further learning, you might want to explore topics such as contract inheritance, complex data types like arrays and enums, and how to interact with contracts using web3.js.
Remember, practicing is key to mastering Solidity. Happy coding!