4: Uploading your Smart Contract to the Blockchain

Jeff Scott
Lamden
Published in
11 min readNov 14, 2020

Wow, you made to Part 4!

Go Here to take a look at the previous tutorial parts.

To begin this tutorial you should have a project that mirrors this git repo.

Part 4 — Setup

At this point we have a smart contract and some interactions, but none of it is on the blockchain. A lot of the Dev Server and API work was to give you a ground level introduction to working with a blockchain and I hope you now have that understanding.

This next set of tutorials will have us uploading our smart contract to Lamden’s TestNet and applying what we have learned about interacting with the smart contract to change our frontend to work with the Lamden TestNet.

Lamden Wallet

Install

The first thing we need is Lamden’s Wallet. The wallet is a Chrome Extension that can be installed from the Chrome Web Store.

The wallet will allow us to do the following:

  • Make and safely store Lamden keypairs (wallets)
  • Upload our Smart Contract to the blockchain
  • Log users into our frontend by talking to the wallet
  • Have our frontend initiate transactions on behalf of the user

Once you have downloaded the wallet, open it and complete the first-time user setup.

When you get to the main screen you will need some test TAU (called dTAU). Head over to the Lamden Faucet to get some by copying your account address (vk)from the the Lamden Wallet and pasting it in the site.

dTau is free and has no value.

A quick note on keys. In cryptocurrency you have two keys referred to as a keypair. One of these keys you can share and one you keep secret. In this tutorial we will refer to the one you share as a vk or “verifying key” but you might have also heard it called a public key or account address. The wallet itself calls it an account address. Why are we calling it a vk and not an account address? Well we are developers now, and we need to use proper terminology!

The other key, the sk, is your “secret key” and is used to sign translations. Using cryptography the blockchain can read the digital signature of your transaction and match the vk to it. The Lamden Wallet takes care of safely storing your sk and automatically signing transactions. You should never need to manipulate your sk manually, and you can back it up using the Backup process on the left menu bar. (Which you should do now)

To copy your vk to the clipboard, click on your account in the list from the main Accoutns menu. Then click the Copy Address button.

**Make note of this vk as we will need to reference it later in the tutorial. This key is public information and is safe to share.

my_token.py

The first thing we need to do is make our seed method more dynamic. We hardcoded the value “me” to get 50 tokens but, we may not know the vk (public key) we will be using or the number of tokens we want as as supply, till later.

Open my_token.py and let’s give our seed method a “vk” argument and define it as string (str). We then will pass the vk argument down to the assignment statement where we assign 50 tokens. Now whatever vk we pass into this method will get minted the tokens.

Then we will give seed a second argument called amount, defined as an integer (int), which will be the token amount to mint at the time the contract is submitted. Replace the value 50 with our new variable amount.

#my_token.py

#Smart Contract State
S = Hash(default_value=0)

#This runs when our contract is created on the blockchain, and never again.
@construct
def seed(vk: str, amount: int):
S[vk] = amount

#This method will be exported so our users can call it
@export
def transfer(amount: int, receiver: str):

We can now set these values when the smart contract is submitted. Then a vk of our choosing will get the initial supply of whatever amount we decide.

Save my_token.py our changes are complete

tests/test_contract.py

Let’s update our tests to pass vk = “me” and amount = 50 when we submit our contract to contracting. See changes in bold.

#tests/test_contract.py
import unittest

from contracting.client import ContractingClient
client = ContractingClient()

with open('../my_token.py') as f:
code = f.read()
client.submit(code, name='my_token', constructor_args={'vk': 'me', 'amount': 50})

client.submit() calls our smart contract’s seed method when it submits the contract. It knows to do this because of the CONSTRUCT decorator we used above the seed function. The constructor_args property tells submit to pass along this object as arguments to the seed method.

When client.submit() runs our seed method it will now run it like this:

seed(vk=”me”, amount=50)

When the above method runs me will get assigned 50 tokens to start.

Run the test file.

cd tests
python3 test_contract.py

All 3 tests should pass

Ran 3 tests in 0.016sOK

server/contracting_server.py

Let’s make the same change in server/contracting_server.py.

See changes in bold.

# server/contracting_server.py

from sanic import Sanic, response
from sanic_cors import CORS, cross_origin
import ast
import json
from contracting.db.encoder import encode
from contracting.client import ContractingClient
client = ContractingClient()

with open('my_token.py') as f:
code = f.read()
client.submit(code, name='my_token', constructor_args={'vk': 'me', 'amount': 50})

app = Sanic("contracting server")
CORS(app)

Upload to the Blockchain

Uploading a contract to the Lamden Blockchain is done by calling the submission contract.

You can view the code for the submission contract on the blockchain here.

Let’s look at the submission contract code:

The submission contract is just 1 method called submit_contract and it take 4 arguments. Most of which should be familiar to you by now.

  • name: Contract name. Must be unique on the blockchain and must start with “con_”
  • code: Your contract code
  • constructor_args: Arguments for our seed method
  • owner: If an owner is specified then only that user (or contract) can transact with this contract. This is an advanced feature not needed for this tutorial series.

So, to upload our contract we need to make a Transaction with the same information we provided to server/contracting_server.py in Part 3b.

contractName: 'submission',
methodName: 'submit_contract',
kwargs: {
name: "con_my_token",
code: "contact code here",
constructor_args: {
"vk": "our public key",
"amount": 1000000
}
}

Luckily the Lamden Wallet will simplify this process for us.

  • Open up the wallet and click Smart Contracts on the left side menu. You should get taken to this screen.
Lamden Wallet — Smart Contract IDE
  • Click the blue + button next to the IDE tabs.
  • Click the Blank Contact button.
  • Paste the contents of my_token.py into the IDE.
my_token.py code in Lamden Wallet IDE
  • Clicking Check Contract should return the message Contract is Okay in the green box.

Before we go further make sure you have your wallet vk from earlier handy.

  • Click the Submit To Network button and you will get the following form to fill in.
  • From the Send Transaction From drop down select your wallet. This wallet will be the transaction sender (ctx.sender in our smart contract code).
  • Stamp Limit signifies how many stamps the system can use before the transaction aborts. On the current TestNet our submission transaction should cost about 200 stamps, which is about 10 dTau. There is no harm in leaving it higher, so we can set it at about 1000 to ensure the transaction doesn’t prematurely abort.
  • Contract Name is already filled in for us with submission
  • Function (another name for method) is already filled in and is the correct submit_contract method as we saw from the submission contract code above

These next 4 boxes are are the arguments we will supply to submit_contract

  • Name: We have been calling this contract my_token but there are two issues with using that name here. One is that all smart contracts need to be prefixed with con_ and con_my_token would work except for the second thing in which all smart contract names need to be unique. Multiple people will take this tutorial and that means everyone can’t use the same name. So here you get to be creative and replace my with whatever you want. I will use con_jeff_token, you use whatever you like.
  • Code: You can see the code string all packed in the box. Scroll down to marvel at your work.
  • Owner: Leave this blank as we want everyone to be able to transact with our contract.
  • Constructor Args: This is where we’re going to pass in the values to our seed method, just like we setup in or test_contracts.py and contracting_server.py. Copy and paste this JSON object into the box. Be sure to replace <your vk> with the one you copied down earlier. Be sure to not have any spaces in the string, including leading or trailing spaces.
{"vk":"<your vk>","amount":1000000}

This is my completed form. Yours should look similar.

** To continue further you need to have dTau in your wallet. If you don’t the submission transaction will fail with “bad seed size”.

  • Click the Confirm Transaction button
  • Say OK to this prompt and then you should get a successful result like below.
  • Click Close.

We can validate our contract is on the blockchain by finding it on the Masternode using the API. This is like how our Dev Server worked.

**Substitute your contract name for con_jeff_token in these Links.

Your contract’s code:

http://167.172.126.5:18080/contracts/con_jeff_token

Your contract’s exported methods and arguments:

http://167.172.126.5:18080/contracts/con_jeff_token/methods

Verify the initial minting of tokens to your vk:

http://167.172.126.5:18080/contracts/con_jeff_token/S?key=fc95219ed9e9bf31e36c2f70978a89a9e912b160c3daf28194f96d51298445b6

Quick functionality test

Looks like our smart contact is up on the network and we have our minted supply assigned to us. So, let’s do some quick testing.

Click the blue + button on the IDE

In the From Blockchain box type the name of your contract and then click the Open button.

You will now see your contract’s code that is stored on the blockchain. Notice your seed function has been renamed to ____ so it can never be run again.

All state variables have been appended with __ but you can ignore that when referencing them in code. For example, your State variable __S is will just be S when we use it.

Below the code box there is an easy way to query state. Put S in the Variable Name box, your vk in the keys box and hit RUN. Returned in the box below is the value of your vk in current state, which is the number of tokens we initially minted.

If you take a look back at the Masternode API URL this is the equivalent of doing:

http://167.172.126.5:18080/contracts/con_jeff_token/S?key=fc95219ed9e9bf31e36c2f70978a89a9e912b160c3daf28194f96d51298445b6

Below that we have a Contract Methods section and you can see our transfer method. This provides a simple way to run the methods in our contract.

There are two familiar argument boxes, amount and receiver. Previously we were testing just sending amount to “me” or “you”, and that will work here as well. The issue with that is that those are just string values and not keys so now one can controls the tokens after they are sent. That’s fine for testing but now how we want our app to work.

So, to test this properly we will need a second keypair, or “wallet” as the Lamden Wallet refers to them.

Let’s create one:

  • Click on the Holdings menu item on the left menu
  • Click the Add Wallet button in the bottom of the big purple rectangle.
  • Give this new wallet a nickname like Wallet 2
  • Then click the Save button

Now you have a new wallet, which in turn has its own keypair (vk & sk).

  • Click it the new wallet and then copy it’s vk to the clipboard by clicking the Receive Coin button and record it for use later.
  • Now go back to the IDE by clicking Smart Contracts on the left menu.
  • Make sure your contract is selected on the IDE tab and scroll back down the the bottom Contract Methods section.
  • Enter 100 into the amount box.
  • Paste the new vk we just created into the receiver box.
  • Click the RUN button beside the word transfer.
  • You will get another transfer form with the specifics already populated. We just need to select the sender for this transaction. In this case the sender should be the wallet that was minted all the coins. So, select that wallet from the Select Wallet to Send From drop down box.
  • Leave Stamp Limit the default.
  • click the Send Transaction button.

Assuming everything was done correctly you will get this confirmation box.

  • Click the Close button.
  • Head back to the Get Current State box and put S in the Variable Name box and our new vk in the key box.
  • click the RUN button to the right of the words Get Current State.

Our new wallet now has 100 JEFF TOKENS!

You can also put your original wallet in the keys box to validate that the 100 tokens were deducted from your supply.

DONE!

Things you should have a decent grasp of at this point having completed all 4 Parts to this tutorial:

  • Parts of a smart contract: state, methods, arguments, constructor method (seed method).
  • How to submit a contract to both the Python contracting client and the blockchain; using the IDE.
  • How to get the current state from a smart contract using both the Masternode API and the Wallet IDE.
  • The information needed to formulate a transaction: sender (ctx.caller), contractName, functionName, arguments (kwargs), stamp Limit.
  • How to send a transaction to a smart contract using the wallet IDE.

If you have got this far and are still struggling with these topics, then please leave a comment below.

I’m available to chat on twitter, telegram or linkedIn

--

--