Hello World
Four simple Solidity hello world contracts are used as examples. Each takes a different approach, growing slightly more complex, in returning the Hello World! string.
Solidity smart contracts by themselves can not print a string.
There is a separate Python program for each
contract that uses simpleth
get and print the string.
The Python programs are found in <Python sys.prefix dir>/examples
. They
and the contracts are ready for you to try.
The Solidity source for the contracts is found in
<Python sys.prefix dir>/contracts
.
HelloWorld1 Contract
The simplest way to display Hello World! is to set that string as the initial value of a public state variable in the contract and use simpleth to get that variable and display the string.
pragma solidity ^0.8;
contract HelloWorld1 {
string public greeting = "Hello World!";
}
sender = Blockchain().address(0)
c = Contract('HelloWorld1')
c.deploy(sender)
greeting = c.get_var('greeting')
print(greeting)
$ python hello_world1.py
Hello World!
HelloWorld2 Contract
This contract has one function that returns the greeting string.
pragma solidity ^0.8;
contract HelloWorld2 {
function getGreeting() public pure returns (string memory) {
return 'Hello World!';
}
}
from simpleth import Blockchain, Contract
sender = Blockchain().address(0)
c = Contract('HelloWorld2')
c.deploy(sender)
greeting = c.call_fcn('getGreeting')
print(greeting)
$ python hello_world2.py
Hello World!
HelloWorld3 Contract
This contract has a transaction that lets us set the greeting and a function to return the greeting.
pragma solidity ^0.8;
contract HelloWorld3 {
string public greeting;
function setGreeting(string memory _greeting) public {
greeting = _greeting;
}
function getGreeting() public view returns (string memory) {
return greeting;
}
}
from simpleth import Blockchain, Contract
sender = Blockchain().address(0)
c = Contract('HelloWorld3')
c.deploy(sender)
c.run_trx(sender, 'setGreeting', 'Hello World!')
greeting = c.call_fcn('getGreeting')
print(greeting)
$ python hello_world3.py
Hello World!
HelloWorld4 Contract
This contract uses a constructor that takes the greeting as an arg and emits an event with the greeting.
1pragma solidity ^0.8;
2contract HelloWorld4 {
3 string public greeting;
4
5 event HelloWorld4Constructed(
6 uint timestamp,
7 address sender,
8 string initGreeting,
9 address HelloWorld4
10 );
11
12 constructor(string memory _initGreeting) {
13 greeting = _initGreeting;
14 emit HelloWorld4Constructed(
15 block.timestamp,
16 msg.sender,
17 greeting,
18 address(this)
19 );
20 }
21}
from simpleth import Blockchain, Contract, EventSearch
sender = Blockchain().address(0)
c = Contract('HelloWorld4')
c.deploy(sender, 'Hello World!')
e = EventSearch(c, 'HelloWorld4Constructed')
event = e.get_old()
print(event[0]['args']['initGreeting'])
$ python hello_world4.py
Hello World!