Ethereum Solidity #2 ....Smart Contract Programming Tutorial Pt 2 - Create your first Smart Contract
Welcome Guys !!...
In this tutorial, we will write our first contract.
Assignment 1: Display your name
Solution:
Let me introduce to the basic syntaxes of solidity.
Line 1 :
pragma solidity ^0.4.0;
This defines the version i.e. 0.4.0. It's better to not use the latest version, as it may contain bugs.
The arrow indicates the code can be run with compiler version 0.4.0 or newer.
Line 2 :
contract Hello{
From here, the code starts executing.
Think contract as Classes in Java (if you are familiar with).
Note: Write the same contract's name as the file name.
Line 3 :
string name;
As we want to display our name, we are defining a variable name with type string.
Line 4 :
function Hello(){
If you know in Java, while making classes, we also have to define the constructor function. So, a function is used. This is the main function which will be executed first.
Line 4 :
name = "Abhijit Roy";
Using my name- Abhijit Roy as input to the variable name defined inside the contract.
Compile:
Now if you run the contract with these lines of code. It will display nothing. But, it will have the data Abhijit Roy saved in the variable name.
So, we have to add a function which can display the name when the contract is created.
Now we add the function displayName as follows:
Line 8-10 :
function displayName() constant returns(string){
return (name);
}
The whole code snippet is as follows:
pragma solidity ^0.4.0;
contract Hello{
string name;
function Hello(){
name = "Abhijit Roy";
}
function displayName() constant returns(string){
return (name);
}
}
Output:
Assignment 2: Display your name with a built-in editName function
Solution:
Basically, for editing the name we have to change the name in contract code and then create the contract.
This is not acceptable in real case scenario, because it is not possible to change the data everytime by modifying the code.
So, we have to add an additional function in order to modify & display after the contract is compiled and created.
There comes the function editName
Line 12-14 :
function editName(string s){
name = s;
}
The new Code snippet:
pragma solidity ^0.4.0;
contract Hello{
string name;
function Hello(){
name = "Abhijit Roy";
}
function displayName() constant returns(string){
return (name);
}
function editName(string s){
name = s;
}
}
Output:
That's it Guys !!....
The next tutorial is Coming soon....