Terra Luna – Python Guide

12 min read

Get 10-day Free Algo Trading Course

Loading

Last Updated on July 15, 2022

Terra Luna Python Guide

Table of contents:

  1. What is the Terra Blockchain?
  2. What is the Terra Blockchain used for?
  3. What is Luna?
  4. What programming languages does the Terra Blockchain support?
  5. Why should I use the Terra Blockchain?
  6. Why shouldn’t I use the Terra Blockchain?
  7. Does the Terra Blockchain have an API?
  8. What is the FCD and LCD on the Terra Blockchain?
  9. Is the Terra Blockchain API free?
  10. What are the alternatives to the Terra Blockchain?
  11. How to get started with Python on the Terra Blockchain?
  12. How to connect to the Terra Blockchain with Python?
  13. How to create a wallet on the Terra Blockchain with Python?
  14. How to send test tokens from the Terra Blockchain with Python?
  15. What are Terra Blockchain native tokens?
  16. What are Terra Blockchain CW-20 tokens?
  17. How to obtain data about the Terra Blockchain with Python?
  18. How to obtain price data from the Terra Blockchain with Python?
  19. How to perform a native swap on the Terra Blockchain with Python?
  20. How to check if the transaction was successful on the Terra Blockchain with Python?
  21. How to estimate fees on the Terra Blockchain with Python?
  22. How to send crypto from one wallet to another on the Terra Blockchain with Python?
  23. How to perform a non-native swap on the Terra Blockchain with Python?
  24. How to obtain the CW-20 token balance on the Terra Blockchain with Python?
  25. How to simulate a swap on the Terra Blockchain with Python?
  26. How to find adequate contract and token addresses for the Terra Blockchain?
  27. How to create your own smart contract on the Terra Blockchain with Python?
  28. Where can I learn more about the Terra Blockchain?
  29. Full code

What is the Terra Blockchain?

Terra Blockchain is one of the most known protocols that specializes in the deployment of stablecoins that allows cryptocurrency users mass access to DeFi. Terra Blockchain is built on the Cosmos SDK and Tendermint.

What is the Terra Blockchain used for?

The Terra Blockchain is mainly used for obtaining and utilizing various stablecoins and DeFi. The most known projects on the Terra Blockchain that allow for this are Anchor, Mirror, Astroport, Pylon, Valkyrie, and more.

What is Luna?

Luna is the native cryptocurrency to the Terra blockchain ecosystem.

What programming languages does the Terra Blockchain support?

Rust programming language is the main language used throughout the Terra Blockchain and the blockchain itself is built upon it. Terra also supports the use of Python and JavaScript with their respective SDKs.

Why should I use the Terra Blockchain?

  • You should use the Terra Blockchain to promote decentralization
  • Terra Blockchain allows you to be in charge of your money
  • To participate in DeFi
  • To obtain monetary rewards through delegating, staking, borrowing, lending, burning, bonding, providing liquidity, and more.
  • To support the Blockchain narrative
  • To avoid the use of a CEX
  • Has low fees
  • Allows for interoperability
  • Has fast transactions
  • Has decent development activity

Why shouldn’t I use the Terra Blockchain?

  • Terra Blockchain currently has limited nodes
  • Terra Blockchain, like the rest of the crypto space, will be addressed by regulators
  • The development documentation is currently scatterred
  • Needs more adoption outside of Asia

Does the Terra Blockchain have an API?

The Terra Blockchain features a swagger API that is used by its LCD and FCD client. It also offers the use of a Python SDK and JavaScript SDK. The Terra Blockchain also features an RPC and a GO implementation.

What is the FCD and LCD on the Terra Blockchain?

The Full Client Deamon (FCD) and the Light Client Deamon (LCD) are REST-based adapters to the Remote Procedure Call (RPC) endpoints and are used for decoding the Amino-encoded blockchain data into parseable JSON.

The LCD is a “light” client while the FCD isn’t as it pulls data from the LCD to its own database. When using the LCD or FCD, we are basically connecting to a Terra node so that we can broadcast our transaction or query.

You can think of this as analogous to using a basic API for an exchange but it is on a blockchain and decentralized.

Is the Terra Blockchain API free?

Yes, everything on Terra is open-sourced and free to use. You also have access to a testnet where you can play with the Terra Network. You can also run a test node locally.

What are the alternatives to the Terra Blockchain?

Main Terra alternatives are other Layer 1 protocols like:

  • Ethereum
  • Fantom
  • Tezos
  • Algorand
  • Solana
  • Avalanche
  • EOS and more

How to get started with Python on the Terra Blockchain?

To get started with Python on the Terra Blockchain, you will need to install the Python SDK. This can be done with the following command:

pip install terra_sdk

How to connect to the Terra Blockchain with Python?

To connect to the Terra Blockchain, you will want to load the terra LCD module and provide it with the blockchain address and client that you want to connect with. In our case, we will connect to the testnet with the Terra LCD.

from terra_sdk.client.lcd import LCDClient

terra = LCDClient(
    chain_id="bombay-12", 
    url="https://bombay-lcd.terra.dev"
    )
terra
<terra_sdk.client.lcd.lcdclient.LCDClient at 0x7f10f6ec0390>

How to create a wallet on the Terra Blockchain with Python?

A Terra Blockchain Wallet can be created with Python by issuing your own mnemonic key. This can be done by just calling the MnemonicKey module without any parameters. The result will be a randomly generated mnemonic.

from terra_sdk.key.mnemonic import MnemonicKey

mk = MnemonicKey()
mk.mnemonic
warm photo twenty series memory law range bonus shallow tent remove bone country chunk civil device harvest level lunar maid mom glad wood sight

Now, you can easily check your newly created wallet/account and also access the private key that is used for signing transactions.

print(mk.acc_address, '\n')
print(mk.private_key)
terra1sjvvhcvaqeg4x05dgn8avhwe56hr739ps8qnzp 

b'\x8e\x1d\r\x15\xda\x9c\xe6\xe4\xa4\xfc\x81x,\xbeM\xad\\\x87r\x18\x96_i\x96K$P\xf2j\xfe\xfe_'

I suggest using the newly generated mnemonic and passing it into the MnemonicKey as a parameter so that your test wallet is saved and that you don’t create a new one each time you want to do something.

If you want to use an existing Terra wallet (not advised when learning), you will pass the mnemonic into the MnemonicKey as a string parameter.

How to send test tokens from the Terra Blockchain with Python?

To send test tokens from the Terra Blockchain you will need to go over to the Terra Faucet and provide it your newly created account address and select the test tokens you wish to have. We will ask for LUNA and UST.

To confirm that we received the tokens, we will query our account balance.

terra.bank.balance(mk.acc_address)
Coins('1000000000uluna,5000000000uusd')

Our tokens have arrived! Take note that every number on the Terra Blockchain is multiplied by a 1000000 denominator, thus we have 5k UST and 1k LUNA to play with.

What are Terra Blockchain native tokens?

Terra Blockchain native tokens are the following: uluna, usdr, ukrw, uusd, umnt, ueur, ucny, ujpy, ugbp, uinr, ucad, uchf, uhkd, uaud, usgd, uthb, usek, unok, udkk, uidr, and uphp. Each currency has an “u” added in front of it.

What are Terra Blockchain CW-20 tokens?

Terra Blockchain CRW-20 tokens are fungible tokens based on CosmWasm. Their design is conceptually similar to the Ethereum ERC20 standard but they are quite manipulated and changed from them.

Some examples of these tokens are bLUNA, ANC, MINE, VKR, ASTRO, MIR, ORION, TWD, and more.

How to obtain data about the Terra Blockchain with Python?

To obtain Terra Blockchain data you can query many of the endpoints that are well explained in the Terra Python SDK documentation. These endpoints belong to their own groups like treasury, oracle, bank, and more.

For example, to get the tax rate we run the following command:

terra.treasury.tax_rate()

To get the oracle parameters we do this:

terra.oracle.parameters()

To get the last request high:

terra.last_request_height()

Take note that some of these calls might not give you a result due to the fact that we are using the testnet for the purpose of this article.

How to obtain price data from the Terra Blockchain with Python?

To obtain price data from the Terra Blockchain you can do things like previewing swap rates, parsing the block information, querying an external price API, or obtaining historical price data.

To preview the swap rate you will use the market swap rate endpoint and provide the amount of the offered coin and the crypto that is your ask. For example, let’s provide $100 and see how much Luna we can get:

terra.market.swap_rate('100000000uusd', 'uluna')
Coin(denom='uluna', amount=1259909)

We can obtain 1.25 LUNA for $100. Now, let us take in the historical prices by sending an API request to the FCD:

import requests

requests.get('https://fcd.terra.dev/v1/market/price?denom=uusd&interval=1h').json()

How to perform a native swap on the Terra Blockchain with Python?

To perform a native on the Terra Blockchain with Python, you will need to use the MsgSwap module with a specified transaction message and account address that you will use to sign the transaction.

The Python SDK allows shortening the amount of code you would need to write in order to perform a swap. The first thing that we want to do is to import the MsgSwap module and create the message that will swap 100 UST for Luna.

from terra_sdk.core.market import MsgSwap

# Swap 100 UST for Luna
msg = MsgSwap(mk.acc_address, "100000000uusd", "uluna")

Now we initialize our wallet that will do the signing and broadcasting of the transaction:

# Initialize the wallet
wallet = terra.wallet(mk)

The next step is to build the transaction message itself and sign it by passing it the message and addressing several optional parameters:

# Create and sign the transaction
tx = wallet.create_and_sign_tx(
    msgs=[msg],
    memo = "Algotrading101", # Optional
    gas_prices = "1uluna", # Optional
    gas_adjustment = "1.3", # Optional
    fee_denoms = ["uluna", "uusd"] # Optional
)

tx
StdTx(msg=[MsgSwap(trader='terra1sjvvhcvaqeg4x05dgn8avhwe56hr739ps8qnzp', offer_coin=Coin(denom='uusd', amount=100000000), ask_denom='uluna')], fee=StdFee(gas=134045, amount=Coins('134045uluna')), signatures=[StdSignature(signature='n+hJUQn0sT5zFS3JKQq7Tgqks5Fl6v+1RZ5439Ja/7hDeGoWXvBhh+fMwK17mq7HxVo46YabA4tpeMV6eBEqag==', pub_key=PublicKey(type='tendermint/PubKeySecp256k1', value='AlAdv8psEHZm56S9nzleTMhaEyEQmqR/UqACtRP8BnR9'))], memo='Algotrading101')

Now, let us go over some of these optional parameters:

  • memo – this is a simple message you might want to pass in order to mark your transaction or greet someone if you are sending him crypto
  • gas_prices – gas prices that are used for fee estimation
  • gas_adjustment – how much of a buffer you might want to have so that you don’t run out of gas
  • fee_denoms – what currency you want to use to pay for gas

Now that we have a simple transaction message ready, we will broadcast it on the testnet:

result = terra.tx.broadcast(tx)
result

On a side note, if you are ever unsure of all the available parameters for a specific module, you can write help(Module_Name) to see what you can use and what the model does exactly.

How to check if the transaction was successful on the Terra Blockchain with Python?

To check if the transaction was successful on the Terra Blockchain, you will either inspect its transaction hash manually on Terra Finder or use the tx_info module that will do that for you. Let us cover both approaches.

First, we print just the transaction hash from our previous example:

result.txhash
637AE50983E6F2AF45DD15013DF00B0F92DBA90DFF3E48A121B9E28CC594E2CD

Then, go over to Terra Finder, and in the upper right corner of your screen switch to the testnet and insert your transaction in the search bar. You will be navigated to your transaction and will be able to see its details.

We can observe all the transaction details and see that it was a successful one. Great, now we move on to our next example with Python:

terra.tx.tx_info(result.txhash)

How to estimate fees on the Terra Blockchain with Python?

To estimate fees on the Terra Blockchain you can either query the FCD to obtain the current gas prices or simulate the transaction you wish to make to obtain the precise amount of fees you might need. Let’s cover both ways.

Update: As of lately, there was a “silent” update to the SDK where the example below is outdated (v1.0.2). Now, the StdFee module doesn’t exist anymore and is replaced by the Fee module. Also, if you don’t pass the fee, it will be automatically estimated by the node for you. I advise letting the node do the job for you.

To obtain the fees by querying the FCD we do the following:

fees = requests.get(
        "https://fcd.terra.dev/v1/txs/gas_prices"
    ).json()
fees
{'uaud': '0.19',
 'ucad': '0.19',
 'uchf': '0.14',
 'ucny': '0.98',
 'udkk': '0.9',
 'ueur': '0.125',
 'ugbp': '0.11',
 'uhkd': '1.17',
 'uidr': '2180.0',
 'uinr': '10.88',
 'ujpy': '16.37',
 'ukrw': '169.77',
 'uluna': '0.01133',
 'umnt': '428.571',
 'unok': '1.25',
 'uphp': '7.6',
 'usdr': '0.104938',
 'usek': '1.25',
 'usgd': '0.2',
 'uthb': '4.62',
 'uusd': '0.15'}

The above values are the current mean fee estimations for the Terra Blockchain per 1 transaction. Now, let us imagine that we want to pay our fees in uusd.

We can simply insert the fee estimation into our transaction like this:

from terra_sdk.core.auth import StdFee

denominator = 1000000

fee = str(int(float(fees["uusd"]) * denominator)) + "uusd"

# Send tx
sendtx = wallet.create_and_sign_tx(
    msgs=[msg],
    fee=StdFee(denominator, fee),
    fee_denoms=['uusd']
)

fee
150000uusd

To estimate how much a transaction might take in terms of UST fees we do the following:

terra.tx.estimate_fee(
    sender=mk.acc_address, 
    msgs=[msg], 
    fee_denoms=['uusd']
    )
StdFee(gas=99535, amount=Coins())

How to send crypto from one wallet to another on the Terra Blockchain with Python?

To send crypto from one wallet to another on the Terra Blockchain, you will want to utilize the MsgSend module and provide it with your account address, the account address you want to send crypto to, and the crypto.

from terra_sdk.core.bank import MsgSend

# Send a third of coins to another account
send = MsgSend(
    mk.acc_address,
    'RECEIVER-ADDRESS-HERE',
    terra.bank.balance(mk.acc_address)/3
    )

The code above will send a third of the sender account balance to the receiver account. All you need to do for this to work is to broadcast the transaction like in the previous swap example.

For practice, try creating a new wallet and send funds to it. You can juggle multiple wallets at the same time easily.

How to perform a non-native swap on the Terra Blockchain with Python?

To perform a non-native swap on the Terra Blockchain with Python, you will need to create a bit different transaction message that can accommodate a non-native token.

Let us start with an example of swapping LUNA for bLUNA step-by-step. The first thing we need to import are several modules and specify the amount we wish to swap, the LUNA-bLUNA testnet address and bLUNA contract:

from terra_sdk.core.coins import Coins
from terra_sdk.core.coins import Coin
from terra_sdk.core.wasm import MsgExecuteContract

# Specify the amount of Luna to swap
amount = 10000000

# Populate the address and contact variables
luna_bluna_pair_address = "terra13e4jmcjnwrauvl2fnjdwex0exuzd8zrh5xk29v"
bluna_contract = "terra1u0t35drzyy0mujj8rkdyzhe264uls4ug3wdp3x"

Now we create a coins object that specifies how much LUNA are we offering to perform the swap. This object is required each time you offer a native asset:

# Specify how much LUNA you're sending 
coin = Coin("uluna", amount).to_data()
coins = Coins.from_data([coin])

The next thing that we want to do is to create the swap message. When swapping to a non-native asset you must point to the LUNA-bLUNA pair contract and specify the address it should go to:

# Create the message
send = (
    MsgExecuteContract(
        sender=mk.acc_address,
        contract=luna_bluna_pair_address,
        execute_msg={
            "swap": {
                "offer_asset": {
                    "max_spread":"0.005", # Optional
                    "info": {"native_token": {"denom": "uluna"}},
                    "amount": str(int(amount)),
                },
                "to": mk.acc_address,
            }
        },
        coins=coins,
    ),
)

Now, we simply obtain the fees and broadcast the transaction as shown in our previous examples. Be sure to inspect your transaction hash to see if you did everything correctly. Here is my transaction hash:

D3288A99A9861D57F91F050291C9E95251C7106C661DDF77CFF67C0C4455E244

If you want to swap back from a non-native asset to LUNA, you write the message like the following:

send = (
        MsgExecuteContract(
            sender=mk.acc_address,
            contract=bluna_contract,
            execute_msg={
                "send": {
                    "contract": luna_bluna_pair_address,
                    "amount": str(5000000),
                    "msg": "eyJzd2FwIjoge319",
                }
            },
            coins=Coins(),
        ),
  )
B229B2A24DF9E5F07B0292C36FCE207A3E74F9E039C8C397DE0F2DFDF7928474

How to obtain the CW-20 token balance on the Terra Blockchain with Python?

To obtain the CW-20 token balance on the Terra Blockchain with Python, you will need to issue a query to the store endpoint. For example, let us obtain the amount of bLUNA that we have in our test wallet:

query_msg = '{"balance":{"address":"' + mk.acc_address + '"}}'
response = requests.get(
    "https://bombay-lcd.terra.dev/wasm/contracts/" + bluna_contract + "/store",
    params={"query_msg": query_msg},
).json()

response
{'height': '7422940', 'result': {'balance': '5020394'}}

How to simulate a swap on the Terra Blockchain with Python?

To simulate a swap on the Terra Blockchain with Python, you will want to issue a query to the LCD that will do the simulation and show you the results of the swap as if it happened for real. Let’s simulate LUNA->bLUNA.

query_msg = (
    '{"simulation":{"offer_asset":{"amount":"'
    + str(50000000)
    + '","info":{"token":{"contract_addr":"terra1u0t35drzyy0mujj8rkdyzhe264uls4ug3wdp3x"}}}}}'
)


response = requests.get(
    "https://bombay-lcd.terra.dev/wasm/contracts/" + luna_bluna_pair_address + "/store",
    params={"query_msg": query_msg},
).json()

response
{'height': '7423219',
 'result': {'commission_amount': '149085',
  'return_amount': '49546156',
  'spread_amount': '53341'}}

If you wish to simulate the reverse of the above transaction, you do the following:

# Reverse
query_msg = (
    '{"reverse_simulation":{"ask_asset":{"amount":"'
    + str(50000000)
    + '","info":{"token":{"contract_addr":"terra1u0t35drzyy0mujj8rkdyzhe264uls4ug3wdp3x"}}}}}'
)


response = requests.get(
    "https://bombay-lcd.terra.dev/wasm/contracts/" + luna_bluna_pair_address + "/store",
    params={"query_msg": query_msg},
).json()

response
{'height': '7423233',
 'result': {'commission_amount': '150451',
  'offer_amount': '49952055',
  'spread_amount': '54049'}}

How to find adequate contract and token addresses for the Terra Blockchain?

Finding adequate contract and token addresses for the Terra Blockchain can be quite a task if you don’t know where to look for them. The best option is to go over to the Terra assets repo where you will find them.

Have in mind that each token and contract have a unique address for the mainnet and testnet. A good idea might be for you to scrape these addresses or download the JSON file from the repo so that you always have it in hand.

How to create your own smart contract on the Terra Blockchain with Python?

An example of how to create your own smart contract on the Terra Blockchain can be seen in the Python SDK docs. The issue here is that Python isn’t an environment where you want to do this.

The reason why is that it has limited support for what you might do in the native Rust language upon which the whole ecosystem was built. Thus, if you’re interested in going deep into development on Terra, I recommend Rust.

You can find interesting templates written in Rust in their GitHub repos that you can try out and mimic. This brings us to the following header.

Where can I learn more about the Terra Blockchain?

To learn more about the Terra Blockchain I advise checking out their main webpage, going through their GitHub repos, enrolling in the Terra Dev Academy, joining the Terra Discord, and above all – remaining curious.

If you’re new(er) to Rust like me, I advise joining this Discord that has a very good community ready to help and respond to your questions. Never be afraid to ask and help.

Full code

GitHub link

Igor Radovanovic