Building DeFi On Avalanche - The Hype Is Real

Louis Lapat
12 min readFeb 5, 2021

Two years ago, crypto winter forced me to shutter Coinflash, my homemade “Turn your spare change into cryptocurrency” app. I sent an email to my users, delivering the news that my beloved bootstrapped baby was being put out to pasture. After all funds were safely withdrawn I spun down the servers, ceased making API calls, and watched the sun set on my crypto startup days.

Goodnight, sweet prince.

Or so I thought.

A few days later, a Coinflash user named Brendan reached out to ask why I was closing shop. Short answer: it was losing money. Long answer: the US-based centralized exchange I used to execute the crypto buys changed their backend, breaking Coinflash’s buying function, and their customer support left me high and dry.

Brendan empathized, as he too had worked for a startup that failed to survive crypto winter. But he had an idea… what if we relaunched a Coinflash-like app on a new blockchain platform that could do everything Ethereum can do but faster, cheaper and designed specifically for building DeFi (Decentralized Finance) solutions?

I was skeptical to say the least. I was fed up with scammy wild-eyed crypto idealists preaching new protocols that fail to actually deliever the goods (at best) or rug pull ICO funds (at worst). Brendan assured me that this wasn’t the case with this mystery platform... then he introduced me to Avalanche — a protocol that claims to be the biggest crypto breakthrough since the Nakamoto Consensus.

Sure buddy. Heard it all before. Won’t believe it til’ I see it…

Avalanche was intriguing… in that it seemed far too good to be true. Brendan swore that the Avalanche team was the best in crypto, backed (ie vetted) by the best VCs in the world, and could be trusted. Plus, they recently launched a community grant program called “Ava-X” and he had soft-pitched a “Coinflash on Avalanche” idea to Avalanche’s COO on Twitter. The COO’s response was enthusiastic so... would I be down to try again?

There is a solid chance that if we hadn’t bonded over him being born and raised in same town I currently live in, my answer would have been a polite but firm no. Then again, Brendan is very persistent. After submitting our proposal, interviewing with Avalanche team members, and making it crystal clear that we intended to build a real business rather than “grant mine” we were awarded the grant.

Thus began my uncertain journey into the snowy wilds of Avalanche. This time I wouldn’t be wholly dependent on the whims of centralized exchanges. This time I would have a partner in the build rather than going it alone. And this time, our project would have a name that suggested the magical wizardry of crypto wealth-building. We would call it Prospero…

As long as Avalanche actually worked. Otherwise I’d call it a waste of time.

Time to grip it and rip it

Now that I was committed to build Prospero, I had to figure out exactly how Avalanche worked beneath the hood (aka why Brendan was so bullish on it). For Prospero’s purposes, I would be focusing on Avalanche’s C-Chain, their version of the Ethereum Virtual Machine —

In layman’s terms, Avalanche claims you can simply take an Ethereum project, deploy it on the Avalanche network with some minor tweaks, and it will work faster, with way lower fees, and increased security. For Prospero to work, we would need to build on top of a decentralized exchange like Uniswap so that it could never get shut down by centralized decision makers. Fortunately, the Avalanche community was already building Uniswap-style clones, and one in particular stood out as best in class — Pangolin.

Hmmm. Might just be the gamechagner we’re looking for…

Unfortunately, there just seemed to be too many moving pieces outside of our control that would determine Prospero’s fate. What if, like so many other Uniswap clones, Pangolin didn’t work all that well? What if the promised Avalanche-Ethereum bridge was janky? What if Avalanche itself suffered an exploit like so many “innovative” protocols that rolled their own crypto? Entering into DeFi was wholly uncharted territory for me. I had major doubts.

That’s why I want to walk you through how I went from being a skeptic to a believer. I started with knowing literally nothing about Avalanche to minting my own token, performing a Uniswap-like swap on Pangolin, and building the foundation layer for Prospero’s future. Everything you’ve heard about Avalanche? The hype is real.

The Nitty Gritty Details

The following sections are for builders. If you’re simply looking to learn more about Avalanche as an investment and economic ecosystem, check out the Ava Labs Medium page. But if you’re a coder looking to quickly get up to speed on Avalanche’s take on DeFi, come along and ride on a fantastic voyage.

Here was my “Dive Into DeFi on Avalanche” to-do list:

  • Deploy a local Avalanche Testnet node
  • Deploy a local Avalanche wallet
  • Fund the wallet with AVAX from a faucet
  • Move that AVAX to a Metamask wallet
  • Deploy my ERC-20 token
  • Deploy Pangolin
  • Add liquidity to Pangolin with my ERC-20 token and AVAX
  • Perform a swap between AVAX and my ERC-20 token

If anything on this list did not work, not only could our project not be built but everything Avalanche claimed it could do would be bogus. Frankly, I expected the worst.

Running A Local Avalanche Node

This is how I got this to work as of February, 2021 following the instructions on their git repo, first clone the AvalancheGo repo and build it.

go get -v -d github.com/ava-labs/avalanchego/...
cd $GOPATH/src/github.com/ava-labs/avalanchego
./scripts/build.sh

Before you run it, you’ll need to grab a grab the Ethereum Virtual Machine and patch here, now place what you unzipped from that download into your $GOPATH/src/github.com/ava-labs/avalanchego/build directory. If you try to run your node locally without doing that last step, the c-chain will not start up, now run it.

./build/avalanchego --network-id=local --staking-enabled=false --snow-sample-size=1 --snow-quorum-size=1

Now test that all your c chain is up and running

curl -X POST --data '{
"jsonrpc":"2.0",
"id" :1,
"method" :"info.isBootstrapped",
"params": {
"chain":"X"
}
}' -H 'content-type:application/json;' 127.0.0.1:9650/ext/info

The reply should look like

{“jsonrpc”:”2.0",”result”:{“isBootstrapped”:true},”id”:1}

Check that your C and P chains are running too by replacing the “X” with a “C” and “P”.

Taking a step back, Avalanche has 3 chains, the simple explanation is X is where your AVAX is stored, P is where your AVAX is staked and C is where Ethereum lives. C=Contract, like smart contracts, X is for Exchange, you can read more about that here.

Deploy a Local Avalanche Wallet and Faucet and Fund Metamask

The Avalanche wallet is where your AVAX will be held and the faucet allows you to fund the wallet with unlimited AVAX for testing. We need to pay for transaction costs, deploy smart contracts and make swaps on Pangolin. I wasn’t sure if I could fund my Metamask wallet directly with a faucet but I knew it worked when transferring from my Avalanche wallet, so the steps would look like this:

Local Avalanche Wallet->Fund wallet with local faucet->Move Tokens From X-chain to C-chain->Move tokens to Metamask address running on local node

First the Avalanche Wallet:

git clone https://github.com/ava-labs/avalanche-wallet.git
cd avalanche-wallet
yarn install
yarn serve

Now the Avalanche Faucet, you’ll need Node v12.14.1 and Google reCaptcha keys for reCaptcha v2 with “I’m not a robot” checkbox, ‘localhost’ listed in the domains.

git clone https://github.com/ava-labs/avalanche-faucet.git
cd avalanche-faucet
npm install

Create a .env file by copying .env.example and replace the captcha keys with the ones from Google and change your drop size to a really big number, that’s how much play AVAX you’ll get from the faucet, I used:

DROP_SIZE_X=90000000000000
DROP_SIZE_C=900000000000000000000

Then run it:

yarn serve

Now fund your wallet:

Add local Avalanche network to Metamask using these parameters:

Network Name: Avalanche Local
New RPC URL: http://localhost:9650/ext/bc/C/rpc
ChainID: 0xa868
Symbol: AVAX
Explorer: N/A

Make a cross chain transfer in your Avalanche wallet, X-chain to C-chain and then transfer to your Metamask wallet.

So far so good, everything has worked really well. The tutorials on Avalanche’s website were some of the best tutorials I’ve ever encountered, walking you through step by step with crystal clarity. Using their tutorial for creating an ERC-20 token on Avalanche, I progressed onto my next task, creating an ERC-20 token.

Creating an ERC-20 Token On Avalanche

We’ll be creating an ERC-20 token on Avalanche but instead of using Ethereum as gas, we’ll be spending AVAX as gas. Behind the scenes AVAX gets turned into WAVAX, an ERC-20 compatible wrapper contract around the AVAX token. First, load up remix using http because our node is local:

http://remix.ethereum.org/#optimize=true&runs=200&evmVersion=null&version=soljson-v0.6.6+commit.6c089d02.js

Create a new file in remix and paste this into it:

// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.2.0/contracts/presets/ERC20PresetMinterPauser.sol";

This will load an ERC-20 preset from OpenZepplin, think of OpenZepplin like templates for smart contracts. Compile the code on the left, wait for it to finish then go to the file explorer and click on the file ERC20PresetMinterPauser.sol, you can find it under the github folder.

Click on the ‘Deploy and Run Transactions’ tab, make sure the ‘contract’ you have selected is the ERC20PresetMinterPauser.sol contract and your environment is ‘Injected Web3’, then deploy it with the name of your token and your token symbol. Once it is deployed, it’ll show up under deployed contracts, now mint 100 tokens to your Metamask wallet, since functions in solidity require Ethereum be denominated in Wei not Eth, and every Eth is 1000000000000000000 Wei, you have to convert it. I just use a nifty ethereum-wei calculator to help me do this calc, 100 eth = 100000000000000000000 wei, now press mint.

Then add the token to your wallet in Metamask using the ‘add token’ command and the address you just deployed your token to:

You can find the address of the address you just deployed your contract to by clicking on the copy symbol under deployed contracts next to the contract name.

If it works, you should be 100 tokens richer. Here’s the video of the whole process, it’s about two minutes long.

Deploying Pangolin on Avalanche

Pangolin is a Uniswap clone. Uniswap is a decentralized cryptocurrency exchange that runs on Ethereum. It takes one cryptocurrency and converts it to another via liquidity pools and the mother of all basic price matching mechanisms. Right now as of February 2021, because Ethereum’s price is so high and the network so overburdened, fees for gas on Uniswap are very expensive, rendering Uniswap unusable for casual cryptocurrency buyers. With Avalanche’s low fees, Avalanche could solve this issue and fully unlock the theoretical potential of decentralized exchanges.

Lets get into Uniswap first, from Uniswap’s blog:

Like ETH is to WETH, AVAX is to WAVAX, more on that later. Now, first we are going to have to figure out how to deploy Uniswap on Ethereum. Once we know, we’ll do the same steps but with the Uniswap clone, Pangolin. If you wanted to deploy your own version of Uniswap, you would follow these same steps but with Ethereum’s net:

  1. Deploy factory contract.
  2. Deploy router contract.

Check out the Factory function in Uniswap, it takes an address as an input that is the feeToSetter which is the address for whoever is receiving the fee’s generated from Uniswap swaps, use your wallet address.

constructor(address _feeToSetter) public { feeToSetter = _feeToSetter; }

Now check out the Router contract:

constructor(address _factory, address _WETH) public { factory = _factory; WETH = _WETH; }

It will take the address for your Factory contract and your WETH address. Okay, so how would this work on Avalanche? Exactly the same except instead of WETH we’ll be talking about WAVAX. Quick side note about the WAVAX contract, you send it AVAX and it gives you back an ERC-20 version of AVAX called WAVAX 1 to 1, when you want your AVAX back, you send it WAVAX.

First, deploy WAVAX on your local test net using the WAVAX git repo in the same way we did above with our own ERC-20 token. Before we deploy the Pangolin factory, we have to do add one line of code to the factory contract at the top, we only need to do this if we run this code on a local net. If we were deploying the Uniswap factory, we’d have to add this line:

bytes32 public constant INIT_CODE_PAIR_HASH = keccak256(abi.encodePacked(type(UniswapV2Pair).creationCode));

But because it is Pangolin, replace UniswapV2Pair with PangolinPair. Make sure it is all compiled. Deploy it and press the button to get that INIT_CODE_PAIR_HASH.

Paste that code in your PairFor function in the PangolinLibrary contract, you would to do the same with Uniswap too.

Now compile and deploy the Pangolin Router. Just like in the original Uniswap, deploying the router takes two arguments.

constructor(address _factory, address _WAVAX) public {
factory = _factory;
WAVAX = _WAVAX;
}

Plug in your factory address and WAVAX address and deploy. Now check that all your constants are returning something in your factory and router calls. For example, your router should tell you the WAVAX and factory address you set it to:

Before you add liquidity, you have to ‘approve’ your ERC-20 token to allow the Router to interact with it. Once again, you would have to do the same thing with Uniswap.

Finally it is time to add liquidity, we’ll be using pangolins version of addLiquidityEth but instead of Eth we are using AVAX.

Check it worked by running allPairs in the factory, you should have 1.

Finally perform a swap, I’ll be using Pangolin’s version of Uniswaps swapExactEthForTokens, this is what it looks like in Uniswap:

function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts);

The anountOutMin is the minimum amount of output tokens that must be received for the transaction not to revert. Remember 1000000000000000000 wei =1 ETH= 1 AVAX, I’ll be sending in 100 AVAX or 100000000000000000000 Wei, now my parameters.

100,["0xEA3D75C5734fdB31a463DcF5bBf10354f6077890","0x3644315edf858AB39460921e395C2dbd2b41d31f"],0x34c3a99ACcf0267965BA2Da676ab9E80F9ebF3A4, 1640995200

In remix the function looks like this:

Before the swap I had 999966.025 now I have 999974.478.

Let’s Gooooooooooo!

There you have it. Avalanche works. Really really well. So what is Team Prospero going to build with it?

For starters, we’ve already mini-pivoted from the basic “turn your credit card change into crypto” play into social DeFi portfolio management. In order for DeFi to reach its full mainstream potential, we believe that engagement with crypto markets needs to be as intuitive as using Robin Hood. That’s why we’re building DeFi Portfolios for the People.

Prospero will allow users to construct new crypto portfolios, rebalance them with merely a few clicks of our sleek UX, and in time, automatically “tail” the trades of the best traders on the platform. But we’ll save that “secret sauce” for a later post.

For now, check out our website for more information about Prospero, sign up for our email list to gain early access, and follow us on twitter for updates.

--

--