Develop your first python app integrated with decentralized Stellar network

In this post I am going to discuss how to create a decentralized blockchain app aka dApp for Stellar Network. I will build a very simple web app, world’s simplest Ecommerce app, called it RocketCommerce where people can buy a single item by paying Lumens(XLM), stellar’s currency. The interface of the app looks like below:

RocketCommerce - Stellar Blockchain App

Before we get into the development of the application itself, allow me to discuss some background of Blockchain, decentralized apps and Stellar Network itself.

What is Blockchain?

From Wikipedia:

blockchain, originally block chain is a continuously growing list of records, called blocks, which are linked and secured using cryptography.[1][6] Each block typically contains a cryptographic hash of the previous block,[6] a timestamp and transaction data.[7] By design, a blockchain is inherently resistant to modification of the data. It is “an open, distributed ledger that can record transactions between two parties efficiently and in a verifiable and permanent way

Don Tapscott says:

The blockchain is an incorruptible digital ledger of economic transactions that can be programmed to record not just financial transactions but virtually everything of value

What is a decentralized App or dApp?

In simple words dApps are the apps that run on P2P networks instead of running from a single server, entity or organization. P2P Apps are not new, remember Napster and torrents? they are early adaption of decentralized networks.

What is a Stellar Network?

In short Stellar network is a certain P2P network that is based on blockchain technology that performs operations very fast. Like many other coins it’s code is also open source and available on Github. You can learn further about it’s working here. Also there’s a separate section only for developers which you can access here. SDKs are available for different languages but since this post is about Python so we will focus on Python SDK only. I am going to make a simple web app in Python Flask that will interact with Stellar SDK for transactions and other operations.

The app is very simple and might not be taking care of a professional workflow but that’s OK; The app will be maintaining the wallets of all members thus the respective private keys. We first will be creating Wallet addresses and performed action on it. One of the address of the Business Wallet that will be receiving payments and other by the customer, which also be maintained by the site itself (nothing unique as sites like Earn.com maintains wallets of their users and dispatch money in it). It’s also assumed that the users are registered and their wallets generated at the time of signup. We will discuss how addresses are generated for Stellar network. We will be using TestNet instead of PubNet for this app. TestNets are similar to PubNet or Public Networks, just that they are using for testing and development purpose and issue fake tokens for transactions. We will be using Stellar Horizon Server having address:- http://horizon-testnet.stellar.org

OK enough talk, let’s get into the development!

What is Stellar Horizon Server?

From Stellar’s Official Site:

Horizon is an API server for the Stellar ecosystem. It acts as the interface between stellar-core and applications that want to access the Stellar network. It allows you to submit transactions to the network, check the status of accounts, subscribe to event streams, etc.

 

Basically, Horizon is kind of an API based front-end for the core Stellar System that let you interact with the main network by using APIs. I find it very helpful; unlike Ethereum where you have to learn a new language(Solidity) to write apps aka Smart Contracts, the learning curve is very small and you can consume APIs in your favorite language. We will not be interacting with Horizon  APIs directly as we are going to use Python SDK that are wrappers of the APIs itself and hide many unnecessary things that could become obstacles for beginners.

Python SDK Installation

We will be installing Python SDk via pip utility:

pip install stellar-base

It will install the main SDK along with all dependencies. I have been on Python3 for long time, not sure it will work for Py2 or not, give it a try. Most important give Python3 a try!

Setting up Wallets

The very first thing we need to do is to generate at least a couple of wallets here; one for the company receiving payments and other for the customer. This post is using Flask for writing app so It’s assumed you know Flask well, if not, you may find some good tutorial out there.

After importing Flask related stuff, I imported Stellar’s Keypair class. It will be responsible to generate a new wallet address and a private key aka seed that will be a private identification or password for the wallet itself. You keep this thing secure somewhere and provide a public key aka Wallet address to others for transaction purpose. Since we want to return both private and public keys aka Wallet Addresses, I will convert dict into a json and return.

Start the flask server by running python app.py from command line. It shows something like below:

Once it’s running you should access http://127.0.0.1:5000/gen_address to generate the address. If all goes well it will generate output like below:

Let’s run it one more time to generate another address and this time it produces:

In the __main__ of your Flask app assign these addresses to some variables, I do as below:

and for the customer:

Notice G in Stellar wallet’s address and S in seed values. This is standard by Stellar.

The Flask app’s __main__ will look like below:

So far so good. Addresses are generated but hold on! you still can’t use them. The reason is that these wallet are empty and yet not registered with the main TestNet. You need some money to buy, right? So who will pay, well, a FriendBot in need is a friend indeed. Stellar provides a friend bot. What this bot does that it hands you over 1000 coins for shopping (Wish they have a friend bot or a friend for main network too! Stellar team! please do something, pretty please??). So you gotta make a request to fetch some XLMs first. Let’s first access main Horizon Server. When you go to:- https://horizon-testnet.stellar.org/ it provides following output:

As you can see it provides different end points here. What I am going to access is: https://horizon-testnet.stellar.org/accounts/{account_id} by setting the address so it will then become https://horizon-testnet.stellar.org/accounts/GBYVSIXRDKJDHY5JGK6N37RFLZ2JDH3GDZPYOWXITQCWOCQ26VSRSXZF. If you check the JSON output it looks like below:

The address you generated does not exist in Stellar network. It’s time to call your friend ask for help. Go to the URL:- https://horizon-testnet.stellar.org/friendbot?addr=GBYVSIXRDKJDHY5JGK6N37RFLZ2JDH3GDZPYOWXITQCWOCQ26VSRSXZF and your friend will give you some bucks. When you access it provides following transaction output:

you can see transaction field with the URL. It’s standard by Stellar that gives you hint that is, All goes well. The transaction link you get something different. Most important part for us is:

Yay!! the friend rocks! he gave me 1000 XLM free!!

Alright enough excitement, it’s time to do shopping. But! before that we need to write the method that will be taking care of transaction.

I am calling a Builder class that will be building up the payment object. The Builder class take seed as a parameter. You need seed to make a transaction. Since RocketCommerce is maintaining customers wallets too so they are making payments on behalf of their customers.

So member seed is provided. The method append_payment_op() is used to assign the receiver’s address. In our case SITE_ADDR, the amount and the currency. In our case it’s XLM. Stellar can take care of other tokens and FIAT currency issuers as well and that’s the beauty of the Stellar that you could use both conventional and crypto coins on it. Next up you call add_text_memo with your transaction. It’s for friendly note. In my case I will be setting the customer name itself. You then sign your transaction and then submit it to the network. In our /pay route it looks like below:

I have kept it simple otherwise you can fetch the transaction from the returned JSON and make it more secure and sophisticated. If all goes well it redirects to to /thanks otherwise print Invalid Transaction. I am also printing the transaction url on console for debugging purpose. I am not gonna discuss how the screens were made since it’s out of the scope but screens will appear in order given below:

But wait.. it seems transaction failed as I got this object:

How do I check it out? Well Stellar has provided us a tool called XDR Viewer (Thanks @mikefair to come up with XDR debugging point and then  @sacarlson on Stellar Slack channel to help me out to find this issue with help of XDR Viewer) which you can read the content of envolope_xdr and figure out the reason. I input my XDR value and it produce the output. Do you see amount: 0 (raw: 0) there? it seems I am passing the 0 value to it that is I want to buy and paying nothing! Fix it up and it should work. I fixed it up and this time I got this encouraging JSON output

If you notice, transaction field is same as we had when our friend paid us. Let’s check the transaction URL. It returns a big JSON output, I am pasting relevant chunk below:

This output is enough for you to learn that transaction is successful as in successful one you get a transaction url, in this case it is https://horizon-testnet.stellar.org/transactions/0db911a502ddd67164a70c0c0627614d0619f3d9d1cac58d45ea3c7b23a0fedf but if you are still restless and want to know more about it then access the URL and another JSON will welcome you, the relevant chunk is below:

fee_paid tells the fee Stellar network charges, source_account is account sent money. memo tells the customer name you had set. If you notice you don’t find the amount field here. For that you gotta check envelope_xdr content in XDRViewer. Here you can see amount10 (raw: 100000000) mentioned that tells how much amount was sent. Check the member account again by accessing the account URL, check the balance now, it’s reduced now:

Conclusion

That’s it! in this post you learnt how easy it is to start writing blockchain apps for Stellar network and if you know Python it makes your learning curve further small. One might ask why did I pick Stellar, the answer is simple: I like this project and being both developer and an Stellar Lumens investor I found it very interesting and good project. The community is very helpful, documentation is very awesome and it did not take much time to write a simple app running on their network.

The code is available on Github

If you like this post or have some feedback then do comment below. Specially from Stellar experts so that in case if I did something wrong then I could correct it.

Oh and if you liked it so much and want to become a human version of a FriendBot for me then you can send XLM to me on the following address:

Address:- GB6YPGW5JFMMP2QB2USQ33EUWTXVL4ZT5ITUNCY3YKVWOJPP57CANOF3

Memo:- 8b54d016b8db47cda46

And since I am on Bittrex it provides some instructions as well

Stellar provides some instructions as well.

Or just plain BTC:- 12stJs8vZNuuVfjZSSzpLPA96quNissk1b 🙂

 

If you like this post then you should subscribe to my blog for future updates.

* indicates required




If you like my work then you can donate me in bitcoins

4 responses to “Develop your first python app integrated with decentralized Stellar network”

  1. Nerdman says:

    How is this decentralised? All this does is talk to the stellar blockchain from a python app. Webserver goes down app goes down with it.

Leave a Reply

Your email address will not be published. Required fields are marked *