Decentralized finance has exploded from a niche market to an over $1 billion industry earlier this year with new use-cases and verticals such as stablecoins, crypto-collateralized lending, trustless margin trading, and decentralized exchanges. However, without cross-chain liquidity and a secure oracle solution, the global liquidity of the DeFi is limited to Ethereum. A DeFi protocol is only as secure as its oracle design which we have seen being exploited in multiple cases with bZx, Synthetix, and MakerDAO recently.
Smart contracts inherently cannot access data outside of their own blockchain network without oracles, a middleware service that allows smart contracts to connect to external data and APIs to dictate and control the behavior of the application. Thus, solving the cross-chain and oracle problem will enable exponential growth for this new emerging industry.
On a mission to connect decentralized and distributed applications, Cosmos developed the Inter-Blockchain Protocol (IBC), which proposes a standard for data and token exchanges between blockchains. With IBC, developers and enterprises can unlock high-value data exchanges between native chains and bring interoperability to private or consortium decentralized applications.
⏱ IBC in 200 Words
Cosmos Inter-blockchain Communication Protocol (IBC) is a reliable and secure method for any Cosmos-SDK based blockchain to communicate. At a fundamental level, the IBC is responsible for relaying ‘packets’ from one blockchain to another while abstracting away from the complexity of maintaining the connection, data integrity and real-time communication from the application developer.
Recently, Cosmos has released the IBC spec, a relayer implementation and example code for building cross-chain applications.
While the IBC spec is full of technical concepts and jargon, you do not need to understand how the IBC is implemented on the protocol level — the Cosmos IBC implementation already abstracts away most of the complexity. In fact, application developers only need to understand two key components to work with IBC:
A particular data structure with sequence-related metadata (defined by the IBC specification) and an opaque value field referred to as the packet data (with semantics defined by the application layer, e.g. token amount and denomination)
- Relayer Process
A relayer process is an off-chain process responsible for relaying IBC packet data & metadata between two or more machines by scanning their states & submitting transactions.
💹 Building DeFi on Cosmos Ecosystem
This guide aims to provide developers with a step-by-step walkthrough of the most recent development and releases on BandChain & IBC, enabling them to build a cross-chain compatible DeFi application with secure price oracles provided by Band Protocol.
Band Protocol is a cross-chain data oracle platform built on the Cosmos-SDK that aggregates and connects real-world data and APIs to smart contracts. Blockchain smart contract is great for immutable storage and deterministic, verifiable computations — however, they still cannot access data and APIs available outside the blockchain networks. Band Protocol enables smart contract applications to be built on-chain with full flexibility for developers to specify their data type, data sources, and aggregation method without relying on the single point of failure or a centralized oracle.
Here are some examples of DeFi applications that you can build using IBC & Band Protocol:
- Lending platforms
- Derivative tokens (mirror price of other assets)
- Margin trading
- Decentralized Exchanges
- Prediction markets
🏅 Example App: Synthetic Gold
To explore how the IBC actually works, let’s dive into building a simplified synthetic gold application — we named it GoldChain — that satisfies to following requirements:
- The application supports the creation of a GOLD token, each representing 1 oz of gold.
- It allows a user to transfer ATOM from Gaia to the GoldChain and put it as a collateral to mint new GOLD token.
- When minting GOLD, the value of ATOM collateralized must be more than 125% of the GOLD minted.
For simplicity, we will not be implementing the CDP liquidation mechanism in this guide, but instead, focus primarily on demonstrating the IBC capability.
The ecosystem of GoldChain comprises of 4 different components:
- GoldChain — a Cosmos SDK based blockchain we are building.
- Gaia (Cosmos Hub) — a blockchain hosting ATOM token. It provides underlying value for the GOLD tokens being minted on GoldChain.
- BandChain — a blockchain for decentralized data oracle. It enables GoldChain to consume XAU (traded symbol for gold) and ATOM price feed from external sources.
- Relayers — third-party software that relay packets between multiple blockchains. They allow multiple blockchains to interoperate in a secure and trustless manner.
Each part plays an important role in working together to create a secure, synthetic gold application, as you will see in the following sections.
From the user’s perspective, here is how the creation of CDP works in GoldChain.
- A user transfers ATOM via IBC to the GoldChain.
- The user creates a buy transaction on the GoldChain to put ATOM as collateral.
- GoldChain requests spot price of ATOM and GOLD from BandChain, and mints the GOLD token for the user.
⛳ Building GoldChain: Step-by-Step Walkthrough
You can find the complete code in the GoldChain repository. This tutorial aims to provide a step-by-step guide on how you can start from a boilerplate repository and code your way up to the full GoldChain.
Step 1: Get the new GoldChain up and running
You can get started by cloning Cosmos Gaia, ibc-alpha branch as a starting point to develop your own blockchain with IBC support.
However, in this tutorial, we are going to use Band Protocol’s fork of Gaia that already has Band Protocol’s oracle module integrated as our boilerplate.
Let’s start by cloning the repository to our machine.
$ git clone https://github.com/bandprotocol/band-consumer
✅ Pro tip: you can also clone the https://github.com/bandprotocol/goldcdp and following this tutorial. This way you can run the full tutorial right away without having to write any Go code yourself.
Make sure you have Go 1.14+ installed and follow the installation guide.
Now, before we can get the blockchain up and running, we need to set a few parameters first. Let’s head into our freshly cloned repository and start it up.
To set up a new validator node, we begin by initializing a new genesis. Note this in this tutorial, we will use the name band-consumer and goldchain interchangeably as both refer to the chain that we are running locally.
$ bcd init validator --chain-id band-consumer
We will need 3 accounts in this tutorial.
- validator: the primary account that validates blocks.
- user: the account we will make user request to mint GOLD token.
- faucet: the account we will use to top up the relayer’s balance.
$ bccli keys add validator --keyring-backend test
$ bccli keys add user --keyring-backend test
$ bccli keys add faucet --keyring-backend test
Now that we have the accounts set up, we’ll be adding balances to these accounts at the genesis.
$ bcd add-genesis-account
validator 10000000000000stake --keyring-backend test
$ bcd add-genesis-account
user 10000000000000stake --keyring-backend test
$ bcd add-genesis-account
faucet 1000000000000000stake --keyring-backend test
We then need to do a quick setup to make our CLI client easier to work with.
$ bccli config chain-id band-consumer
$ bccli config output json
$ bccli config indent true
$ bccli config trust-node true
$ bccli config keyring-backend test
Finally, create a genesis transaction and create the genesis file.
$ bcd gentx --name validator --keyring-backend test
$ bcd collect-gentxs
Here comes the moment of truth. Let run our local node for the first time!
$ bcd start --rpc.laddr=tcp://0.0.0.0:26657 --pruning=nothing
When you see the blocks being produced, congratulations! You have a blockchain up and running — ready to continue to the next stage.
🟢 Keep it running: so blocks continue to be created.
Step 2: Set up a relayer and establish a connection between Gaia and GoldChain
Now let’s get to the fun part. We will be using a Gaia testnet running on gaia-ibc-hackathon.node.bandchain.org to transfer ATOM to the GoldChain we just set up.
This is going to be our first cross-chain transfer from Cosmos Gaia to the GoldChain.
We will start out by setting up a relayer. Let’s grab the relayer code and install it. Note that it’s important to make sure GOBIN and GOPATH are set correctly, or otherwise the installation will fail.
$ git clone https://github.com/bandprotocol/relayer
$ cd relayer
$ make install
✅ Once it’s done: you will have the rly command for Cosmos IBC relayer ready to use in GOBIN.
Next step, we will need to add a few config files, so the relayer knows how to communicate with the testnet Gaia and the GoldChain. The easiest way to get the config files is to download them from GoldChain repository.
Once you create or download the goldchain.json and gaia.json, we can start initializing the relayer and add the two chains from the aforementioned config files.
$ rly config init
$ rly chains add -f goldchain.json #chain-id: band-consumer
$ rly chains add -f gaia.json #chain-id: band-cosmoshub
Next, we need new accounts for the relayer, which we will be creating one for each chain. These accounts will be used to relay packets (send transactions) to their corresponding blockchains.
$ rly keys add band-consumer relayer-goldchain
$ rly keys add band-cosmoshub relayer-gaia
Now we’ll need to assign the accounts to the relayer.
$ rly ch edit band-consumer key relayer-goldchain
$ rly ch edit band-cosmoshub key relayer-gaia
⚠️ Important: we need to make sure that our relayer accounts have enough balances for sending transactions on both GoldChain and Gaia. Otherwise the relayer will not be able to send relay packets.
On the GoldChain we have already minted stake tokens at the genesis to our faucet account. Let’s go ahead and send it to our relayer-goldchain.
$ bccli tx send faucet $(rly keys show band-consumer)
On the testnet Gaia, we’ll use the relayer testnet faucet feature.
$ rly testnets request band-cosmoshub relayer-gaia
If we check balances on both chains, we should see some balances.
$ rly q bal band-consumer
$ rly q bal band-cosmoshub
Now we’re ready to initialize the lite clients.
$ rly lite init band-consumer -f
$ rly lite init band-cosmoshub -f
Next, we generate an identifier of a new path from GoldChain’s transfer and Gaia’s transfer and name it transfer path.
$ rly pth gen
We can create then clients, a connection, and a channel between the two chains configured for the transfer path.
$ rly tx link transfer
This will take a few seconds as the relayer register itself on both GoldChain and Gaia. Once it’s done, the last line should be showing a line like this. 👇
⚠️ Important: look out for the channel id, which in this case:
<goldchain_transfer_channel> = pwlpjyneba
<gaia_transfer_channel> = zijixuhhrf
Note this down as we’ll need it in the next step.
Lastly, we can start the relayer on the transfer path.
$ rly st transfer
🟢 Keep it running: otherwise, now IBC packets will be sent across chains.
Step 3: Transfer $ATOM from Gaia into GoldChain
Let’s test if our relayer works by sending some token over from the Gaia to GoldChain. We’ll start by creating a new account named user-gaia and top it up with the faucet.
$ bccli keys add user-gaia
# Faucet request to our new address
$ curl --location --request
"address": "'"$(bccli keys show -a user-gaia)"'",
# Check balance: you should see 10000000000uatom
$ bccli query bank balances $(bccli keys show -a user-gaia)
Now let’s create our first ATOM transfer from the Gaia to GoldChain. We will be sending 5000000000uatom (5,000 ATOM) to the account user with the <gaia_transfer_channel> established previously.
$ bccli tx transfer transfer
10000000 $(bccli keys show -a user)
Check the balance and you’ll find that we now have ATOM token on the GoldChain.
$ bccli query bank balances $(bccli keys show -a user)
# You should see something like this
# "denom": "stake",
# "amount": "10000000000000"
# "denom": "transfer/<goldchain_transfer_channel>/uatom",
# "amount": "5000000000"
Step 4: Add CDP and wire up Band Protocol oracle
Next, we will be adding support for collateralized debt position (CDP), similarly to how MarkerDAO allows users to collateralized Ether and mint new DAI tokens.
The primary condition that upholds the GOLD token’s value is the value of ATOM locked up for every GOLD token minted. Band Protocol enables the GoldChain to have access to a price feed of both XAU and ATOM against USD.
To make this happen, here’s what we need:
- Setting up the relayer that connects GoldChain with Band Protocol through the IBC.
- Creating a handler for storing default Gaia and BandChain channels. This helps with the UX of the application.
- Creating a handler for buying GOLD, which sends a request to BandChain over the IBC for ATOM and XAU price, and stores the buy transaction in the storage — effectively halting the transaction and waiting for the price to revert back from BandChain.
- Creating another handler for receiving the result back from the BandChain, calculate the GOLD to be minted based on the price, and mint the GOLD for the user.
As it would be too long to put all the code in this post. We have documented how we patch the current code with the changes outlined above to the Github link below 👇
Assuming that you’ve already added the code that implements CDP with Band Protocol (or you started out with the complete GoldChain code), let’s move forward to get the relayer up and running between the GoldChain and the BandChain so we can finally mint our first synthetic gold token.
This time around we will be going fast on initializing the relayer, as most of the steps will the same as the relayer between GoldChain <> Gaia we just setup.
First and foremost, let’s create a config file bandchain.json for the BandChain relayer.
Then get the relayer up and running for GoldChain <> BandChain.
$ rly chains add -f bandchain.json
$ rly keys add ibc-bandchain relayer-bandchain
$ rly ch edit ibc-bandchain key relayer-bandchain
# Get BAND from faucet
$ curl --location --request POST 'http://18.104.22.168/faucet/request'
--header 'Content-Type: application/json'
"address": "'"$(rly keys show ibc-bandchain)"'",
$ rly lite init ibc-bandchain -f
$ rly pth gen band-consumer goldcdp ibc-bandchain oracle oracle
$ rly tx link oracle
$ rly st oracle
⚠️ Important: note down the channels to use in the next step
🟢 Keep the relayer running: otherwiser the oracle would not work
With the relayer up, now we will be setting the default channel for CDP creation with GOLD and ATOM using BandChain oracle.
$ bccli tx goldcdp
set-channel bandchain goldcdp <goldchain_oracle_channel>
$ bccli tx goldcdp
set-channel band-cosmoshub transfer <goldchain_transfer_channel>
Step 5: Mint GOLD token using the transferred ATOMs as collateral
Now we’ve set up all the required ingredients to make the CDP creation works. Let’s try it out! Given the XAU price at around $1,700 the exchange rate at the time of writing is approximately 800 ATOM per XAU. As we require 125% collateral ratio, every 1,000 ATOM collateral would yield 1 GOLD token.
Let’s try to buy GOLD with 2000000000uatom (2,000 ATOM) collateral.
$ bccli tx
goldcdp buy 2000000000transfer/<goldchain_transfer_channel>/uatom
We can now check that the user account now will have approximately 2 GOLD tokens.
$ bccli query bank balances $(bccli keys show -a user)
The GOLD token can be transferred to any DEX on the Cosmos ecosystem that supports IBC token transfer and traded further with guaranteed value.
In this walkthrough, we’ve covered just enough features to demonstrate the power of IBC. For the GoldChain to become production-ready, there are many other tasks left to be done:
- Add selling GOLD and return the collateralized ATOM
- Add liquidation mechanism
- Tighten the security
There you have it! In this simple tutorial, we’ve explored how to send and receive tokens via IBC as well as using Band Protocol’s secure decentralized oracles to query the real-time prices of both a crypto-token and a commodity from the real-world market. This example can easily be extended to any other asset class such as stocks, bonds, and commodities to enable trustless global trading of such money instruments.
With this new-found knowledge on how to leverage IBC architecture with Band Protocol’s secure data points, you can now get started building your very first IBC applications!
The best way to do this is by participating in the upcoming Cross-Chain Hackathon alongside Agoric, Cosmos & the Band Protocol team who will be providing workshops, live streams, and technical support for all developers who will have the chance to win over $24K in total prizes!
Feel free to let us know if you have any questions regarding the Cosmos IBC or Band Protocol integration, and we’ll be happy to help. Join the discussion on our Discord channel.
The hackathon will be running from April 20 — May 11, we look forward to all the applications you’ll build.
Guide to Building DeFi using Band Protocol Oracle and Cosmos IBC was originally published in Cosmos Blog on Medium, where people are continuing the conversation by highlighting and responding to this story.