How to do it...

Follow these steps to write your "hello world" contract:

  1. Specify the target compiler version using version pragma. It is recommended to specify the target compiler version for each contract. This will avoid the contract getting compiled on future or older versions, which might have incompatible changes:
    pragma solidity ^0.4.21;

This source code will not compile with a compiler with a version lower than 0.4.21 or greater than 0.5.0.

  1. Create a contract with the contract keyword followed by the contract name:
 contract HelloWorld {
// Here goes your smart contract code
}
  1. Write a method that we can use for printing "hello world." The method declaration starts with the function keyword:
function printSomething() {
// things to do
}
  1. Return "hello world" from the method with the return keyword:
return "hello world";
  1. Specify the return type for each method using returns:
function printSomething() returns (string) { }
  1. This is how your contract will look now:
pragma solidity ^0.4.21;

contract HelloWorld {
function printSomething() returns (string) {
return "hello world";
}
}

Remix provides real-time errors and warnings as you write your contract. This option can be toggled using the Auto compile checkbox under the compile tab. A contract can be manually compiled with the Start to compile button.

  1. Let's try to do a little more with your first contract. Add a method that modifies the text to print based on user input. For storing the string value, add a state variable of type string:
string textToPrint = "hello world";
  1. Add a method that accepts user input and changes the default value of the text:
function changeText(string _text) {
textToPrint = _text;
}
  1. Finally, change the printSomething method to return the string state variable than print static text:
function printSomething() returns (string) {
return textToPrint;
}
  1. Make sure that you also tag this method as a read-only method using view. view restricts the method from modifying the state of the contract. These methods don't consume any gas and are free to use:

function printSomething() view returns (string) { }
  1. Methods have different levels of visibility and default to public. It is a good idea to specify this explicitly. We will discuss the other keywords used later in this chapter.
  2. This is how your contract should look after adding these parameters:

pragma solidity ^0.4.21;

contract HelloWorld {

string textToPrint = "hello world";

function changeText(string _text) public {
textToPrint = _text;
}

function printSomething() public view returns (string) {
return textToPrint;
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.251