How To Write Smart Contracts for Blockchain Using Python — Part Two

A step-by-step guide to getting started

Luiz Milfont
Jul 27 · 5 min read
Photo by Hitesh Choudhary on Unsplash

In this series of tutorial pieces, we are going to be using the SmartPy language from Smart Chain Arena. SmartPy offers a complete integrated development environment to write smart contracts online, test them, debug them, and deploy them in a blockchain.

Requirements

  • Computer programming experience
  • Basic Python programming knowledge
  • Blockchain technology acquaintance
  • A web browser

Welcome to SmartPy!

SmartPy is based on Python 3 language and requires Python code syntax. Python developers will feel at home when starting to code smart contracts with SmartPy.

However, note that although it is possible to import Python libraries through the import directive, some features will only work in the development environment. For example, when deployed to blockchain, there are specifics of that context.

For those who don’t know much of Python, it is important to remember that indentation is important. It affects the correctness of the code.

And for the newbies of smart contract programming, note that a smart contract will always have an entry point, by which it is going to be called from the outside world, through a transaction.

After being published, smart contracts reside in a blockchain, decentralized and distributed on a network of computer nodes. A copy of the smart contract is on each node.

Let’s begin by meeting the development environment. You will be granted access to the SmartPy IDE:

The SmartPy IDE at a glance

Couldn’t be simpler than that. The left side of the screen is the editor, where you will type your smart contract source code. The right side is the output panel; it will show the result output of your programming.


Hello World!

There is an ancient Greek saying that states that if your first program in a new language is not a “Hello World!” then you will have much trouble in your future with programming. So…

Click on the editor section of the screen and type:

alert("Hello World!")

Now, just click on Evaluate Script & Run Tests (the button over the output panel). Voilà! A box appears showing “Hello World!” on screen. That’s a fair beginning, just to break the ice.

OK, it was nice seeing that message alert on screen. But, let’s modify our code a little bit to change the way the message is displayed by adding a test to our smart contract script.

Just copy and paste the code below into the editor. Pay attention to the indentation, as it matters:

@addTest(name = "testHelloWorld")
def myTest():
setOutput("Hello World!")

Now, click again on the button Evaluate Script & Run Tests. You will see the result on the output panel, and you will also note that a new button called testHelloWorld appears over it:

Output result for the new script

The test is important because we need to simulate how the smart contract will behave before we publish it on the blockchain.

So far, so good. Still, there is not really much yet that is related to smart contracts.

So, lets get serious. We are now going to create our first smart contract. To begin, we will import the smartpy library. Clear the editor and paste the code below into it:

import smartpy as sp

Now that we have imported the library, we will be able to define a class based on an inherited contract. Add this to your code:

class MyClass(sp.Contract):
def __init__(self):
self.init(result = 0)

What we are doing here is defining a new class and declaring its constuctor method (init). That is how new instances (objects) of this class will be initialized.

A smart contract has at least one entry point. So, let’s declare the entry point for our contract. Add the text below to your code:

    @sp.entryPoint
def myEntryPoint(self, params):
self.data.result = params.op1 + params.op2

If you try to run the code by clicking on the Evaluate Scripts & Run Tests button now, nothing will happen. That’s because we need to add a test to our code.

So, let’s do it. Copy the text below and paste in your code:

@addTest(name = "myFirstSmartContractTest")
def mySmartContractTest():
html = ""
mySmartContract = MyClass()
html += mySmartContract.myEntryPoint(op1 = 1, op2 = 2).html()
setOutput(html)

Let’s break down our added test. What is being done here?

We are defining a string called html that we will use to render our output on screen. Then we create an object mySmartContract instance of the class MyClass, that is derived of sp.Contract type. This is how we enable the class to be effectively transformed in a Tezos smart contract. This derivation construct, and the constructor and initialization, are all pure standard Python syntax.

Also, the @ above method/functions declarations are Python decorators, used to guide the compiler for certain actions. They are what is called syntactic sugar, which offers a convenient way to add a little bit of magic to the function definition. You can think of it as a function which transforms the Python function you write into another Python function.

For example, the sp.entryPoint is a function that takes a Python function and transforms it into one that will become the actual Michelson entry point.

Now, try to run the code again and see what happens. You should get a result as follows:

If you got errors, first check if your code has been incorrectly indented. Usually, you have to indent the code with four spaces or TAB. Also, check the logical indentation, i.e. which definition belongs to each parent declaration.

This first example is a smart contract that sums two numbers passed by parameter to the method myEntryPoint of the class myClass and puts the result on the storage result of the contract.

To make it easier to understand and test, below is the full commented code:

This is a very brief first contact with the SmartPy environment to make you familiar with it. As we progress with future pieces, we will work on more real world use cases.

See you on Part Three! Don’t forget to read Part One!

Better Programming

Advice for programmers.

Luiz Milfont

Written by

IT Developer

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade