Reader small image

You're reading from  Hands-On Blockchain for Python Developers

Product typeBook
Published inFeb 2019
Reading LevelExpert
PublisherPackt
ISBN-139781788627856
Edition1st Edition
Languages
Concepts
Right arrow
Author (1)
Arjuna Sky Kok
Arjuna Sky Kok
author image
Arjuna Sky Kok

Arjuna Sky Kok has experience more than 10 years in expressing himself as a software engineer. He has developed web applications using Symfony, Laravel, Ruby on Rails, and Django. He also has built mobile applications on top of Android and iOS platforms. Currently, he is researching Ethereum technology. Other than that, he teaches Android and iOS programming to students. He graduated from Bina Nusantara University with majors in Computer Science and Applied Mathematics. He always strives to become a holistic person by enjoying leisure activities, such as dancing Salsa, learning French, and playing StarCraft 2. He lives quietly in the bustling city of Jakarta. In loving memory of my late brother, Hengdra Santoso (1979-2011).
Read more about Arjuna Sky Kok

Right arrow

Implementing Smart Contracts Using Vyper

Many programmers who are learning how to write a smart contract will learn about the Solidity programming language. There are abundant sources of online tutorials and books that can teach you about Solidity. When combined with the Truffle framework, Solidity forms a killer combo for developing a smart contract. Almost all smart contracts that live on the Ethereum blockchain are written in the Solidity programming language.

In this chapter, we will explore how to write a smart contract. However, we are not going to use the Solidity programming language for this. Instead, we will use the Vyper programming language.

The following topics will be covered in this chapter:

  • Motivations behind Vyper
  • Installing Vyper
  • Creating a smart contract using Vyper
  • Deploying a smart contract to Ganache
  • Going deeper into Vyper
  • Interacting with other smart...

Motivations behind Vyper

Writing a smart contract is different than developing a normal web application. When developing a normal web application, the motto is move fast and break things. The speed of developing a web application is paramount. If there is a bug in the application, you can always upgrade the application later. Alternatively, if the bug is catastrophic, you can patch it online or take the application offline before introducing a fix. There is a very popular word to describe the ideal mindset in developing a normal web application—agile. You need to be flexible in order to change the software as the requirements change.

However, writing a smart contract requires a different mindset. The application of smart contracts can range from writing a financial application to launching a rocket into space. Fixing an error once a smart contract is deployed is very difficult...

Installing Vyper

By default, Ubuntu Xenial has Python 3.5 installed. Vyper needs Python 3.6 software, and so you will need to install Python 3.6 first if you want to use Ubuntu Xenial. A newer version of Ubuntu, such as Bionic Beaver, will have Python 3.6 installed already.

So, if you don't have Python 3.6 software installed, you must install it first using the following commands:

$ sudo apt-get install build-essential
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$ sudo apt-get install python3.6 python3.6-dev

It’s not just Python 3.6 that is required by Vyper; you need to install the development files python3.6-dev as well. Then you can create a virtual environment for Python 3.6 by going through the following steps:

  1. First, you must install the virtualenv tool using the following code:
$ sudo apt-get install virtualenv
  1. Then, create a virtual...

Creating a smart contract with Vyper

Now let's create a smart contract with Vyper. First, we will create a file with the .vy extension and name it hello.vy, as follows:

name: public(bytes[24])

@public
def __init__():
self.name = "Satoshi Nakamoto"

@public
def change_name(new_name: bytes[24]):
self.name = new_name

@public
def say_hello() -> bytes[32]:
return concat("Hello, ", self.name)

If you come from a Solidity or Python background, you will notice a peculiarity: there is no class (as in the Python programming language) and there is no contract (as in the Solidity programming language) in a smart contract written with the Vyper programming language. However, there is an initializer function. The name of the initializer function is the same as it is in the Python programming language, which is __init__.

While using Python, you can create as many...

Deploying a smart contract to Ganache

So how do you deploy this smart contract to the Ethereum blockchain? There are few ways to do this, but let’s employ a familiar way using Truffle:

  1. Create a directory and initialize it with truffle init as follows:
$ mkdir hello_project
$ cd hello_project
$ truffle init
  1. Just as you did in the previous chapter, set truffle-config.js as the following:
module.exports = {
networks: {
"development": {
network_id: 5777,
host: "localhost",
port: 7545
},
}
};
  1. Create a build directory, as follows:
$ mkdir -p build/contracts
$ cd build/contracts
  1. Then create a Hello.json file there, as follows:
{
"abi":
"bytecode":
}
  1. Then fill the abi field with abi or json output from the compilation process, and fill the bytecode field with the bytecode output from the compilation process. You...

Going deeper into Vyper

Let’s take a look at our smart contract:

name: public(bytes[24])

@public
def __init__():
self.name = "Satoshi Nakamoto"

@public
def change_name(new_name: bytes[24]):
self.name = new_name

@public
def say_hello() -> bytes[32]:
return concat("Hello, ", self.name)

Take a look at the first line:

name: public(bytes[24])

The array of bytes is basically a string. The variable called name has a type of array of bytes or string. Its visibility is public. If you want to set it to private, then just omit the public keyword, as follows:

name: bytes[24]

Now, take a look at the next lines:

@public
def __init__():
self.name = “Satoshi Nakamoto”

If you are coming from a Python background, then you will recognize the Python decorator function. There are four of these in Vyper:

  • @public means you can execute this method as...

Interacting with other smart contracts

Did you know that your smart contract doesn't have to be lonely out there? Your smart contract can interact with other smart contracts on the blockchain.

The address data type is not only used for normal accounts, but it can also be used for smart contract accounts. So, a smart contract can donate ethers to our donatee via the donation smart contract!

Restart your Ganache; we will start our blockchain anew. Remember your hello.vy Vyper file? We want to deploy our Hello smart contract with a custom name.

Our migration file, migrations/2_deploy_hello.js, is still the same, as shown in the following code:

var Hello = artifacts.require("Hello");
module.exports = function(deployer) {
deployer.deploy(Hello);
};

Compile your hello.vy file again to get the interface and the bytecode. Open our contracts JSON file, the build/contracts...

Compiling code programmatically

You could create a script to compile Vyper code, instead of using a command-line utility. Make sure that you are in the same directory containing hello.vy and donation.vy. Create a script named compiler.vy, as follows:

import vyper
import os, json

filename = 'hello.vy'
contract_name = 'Hello'
contract_json_file = open('Hello.json', 'w')

with open(filename, 'r') as f:
content = f.read()

current_directory = os.curdir

smart_contract = {}
smart_contract[current_directory] = content

format = ['abi', 'bytecode']
compiled_code = vyper.compile_codes(smart_contract, format, 'dict')

smart_contract_json = {
'contractName': contract_name,
'abi': compiled_code[current_directory]['abi'],
'bytecode': compiled_code[current_directory]['bytecode...

Other tricks

Vyper is not as liberal as Python; there are some limitations that you must live with. To overcome these limitations, you need to make peace with them or you need to unlock your creativity. Here are some hints as to how to do this.

The first limitation is that the array must have a fixed size. In Python, you might be very accustomed to having a list that you can extend on your whim, as shown in the following code:

>>> flexible_list = []
>>> flexible_list.append('bitcoin')
>>> flexible_list.append('ethereum')
>>> flexible_list
['bitcoin', 'ethereum']

There is no such thing in Vyper. You have to declare how big your array is. Then you must use an integer variable to track how many items you have inserted into this fixed-size array. You used this strategy in the Donation smart contract.

If you are...

Summary

In this chapter, we learned how to write a smart contract using the Vyper programming language. First, we installed the Vyper compiler. Then we developed a smart contract. By doing this, we learned about most of the features of the Vyper programming language, including the function decorator, initialization function, and function permission modifier. There are also some data types such as address, integer, timestamp, map, array, and array of bytes (string). We learned how to compile a Vyper source to a smart contract and then deploy it to Ganache with the Truffle tool. We also interacted with that smart contract through the Truffle console.

In the next chapter, we are going to learn about web3.py. This is the first step towards building a decentralized application.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Hands-On Blockchain for Python Developers
Published in: Feb 2019Publisher: PacktISBN-13: 9781788627856
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Arjuna Sky Kok

Arjuna Sky Kok has experience more than 10 years in expressing himself as a software engineer. He has developed web applications using Symfony, Laravel, Ruby on Rails, and Django. He also has built mobile applications on top of Android and iOS platforms. Currently, he is researching Ethereum technology. Other than that, he teaches Android and iOS programming to students. He graduated from Bina Nusantara University with majors in Computer Science and Applied Mathematics. He always strives to become a holistic person by enjoying leisure activities, such as dancing Salsa, learning French, and playing StarCraft 2. He lives quietly in the bustling city of Jakarta. In loving memory of my late brother, Hengdra Santoso (1979-2011).
Read more about Arjuna Sky Kok