Create and deploy a DeFi App to Ethereum
Tags: decentralizedfinance, ethereum, blockchain, cryptocurrency
Published: 2021-01-06 17:19:06

---
title: Create and deploy a DeFi App to Ethereum
published: true
date: 2020-12-31 17:47:20 UTC
tags: decentralizedfinance,ethereum,blockchain,cryptocurrency
canonical_url: https://medium.com/coinmonks/create-and-deploy-a-defi-app-to-ethereum-a02bb680aa78
---

#### Decentralized Finance

#### Deposit ERC20 tokens to the smart contract and mint Farm Tokens

![](https://cdn-images-1.medium.com/max/1024/1*ULGtG5gGAUYjBtxTO9D5Ew.jpeg)<figcaption><a href="https://pixabay.com/photos/ethereum-cryptocurrency-3818347/">Ethereum Cryptocurrency The Value — Free photo on Pixabay</a></figcaption>

Decentralized Finance was very popular on 2020 and it will keep growing on the next few years. It consists of decentralized financial services such as decentralized exchanges (e.g. Uniswap, Curve, Balancer) and decentralized lending and borrowing (e.g. Aave). They are open-source and they are built mostly on Ethereum.

In this article we will build a DeFi Application with Solidity where users can deposit an ERC20 token to the smart contract and it will mint and transfer Farm Tokens to them. The users can later withdraw their ERC20 tokens by burning their Farm Token on smart contract and the ERC20 tokens will be transferred back to them.

### Install Truffle and Ganache

If this is the first time you are writing a smart contract, you will need to set up your environment. We are going to use two tools: [Truffle](https://www.trufflesuite.com/) and [Ganache](https://www.trufflesuite.com/ganache).

Truffle is a development environment and testing framework for developing smart contracts for Ethereum. With Truffle it is easy to build and deploy smart contracts to the blockchain. Ganache allow us to create a local Ethereum blockchain in order to test smart contracts. It simulates the features of the real network and the first 10 accounts are funded with 100 test Ether, thus making the smart contract deployment and testing free and easy. Ganache is available as a desktop application and a command-line tool. For this article we will be using the UI desktop application.

![](https://cdn-images-1.medium.com/max/1024/1*V1iQ5onbLbT5Ib2QaiOSyg.png)<figcaption>Ganache UI desktop application</figcaption>

To create the project, run the following commands

mkdir YourProjectName  
cd YourProjectName  
truffle init

This will create a blank project for the development and deployment of our smart contracts. The created project structure is the following:

- contracts: Folder for the solidity smart contracts
- migrations: Folder for the deployment scripts
- test: Folder for testing our smart contracts
- truffle-config.js: Truffle configuration file

### Create the ERC20 Token

First we need to create our ERC20 token that we will use to stake on the smart contract. To create our fungible token, we will first need to install the OpenZeppelin library. This library contains the implementations of standards such as the ERC20 and the ERC721. To install it, run the command:

npm install @openzeppelin/contracts

Using the openzeppelin library we can create our ERC20 token called MyToken with the following solidity code:

{% gist https://gist.github.com/strykerin/aebf1fbcccd9c4dab76e16a2ddfa8c25 %}

In the code above on:

- Line 3: We import the contract ERC20.sol from openzeppelin that contains the implementation for this token standard.
- Line 5: We inherit from the ERC20.sol contract.
- Line 6: We are calling the ERC20.sol constructor and passing for the name and symbol parameters as "MyToken" and "MTKN" respectively.
- Line 7: We are minting and transferring 1 million tokens for the account that is deploying the smart contract (we are using the default 18 decimals for the ERC20 token, that means that if we want to mint 1 token, you will represent it as 1000000000000000000, 1 with 18 zeros).

We can see below the ERC20.sol constructor implementation where the \_decimals field is set to 18:

{% gist https://gist.github.com/strykerin/e773ffc8c7da8a55128e684436b5d2d3 %}

### Deploy ERC20 Token

On the migrations folder, create a file called 2\_deploy\_Tokens.js. This file is where we will deploy both our ERC20 Token and our FarmToken smart contract. The code below is used to deploy our MyToken.sol contract:

{% gist https://gist.github.com/strykerin/a94835cfe3f4343d9ea4fff5d8fa9b1c %}

To compile our smart contract, we must first check our solidity compiler version. You can check that by running the command:

truffle version

The default version is the Solidity v0.5.16. Since our token is written using the solidity version 0.6.2, if we run the command to compile our contracts we will get a compiler error. In order to specify which solidity compiler version to use, go to the file truffle-config.js and set to the desired compiler version as seen below:

{% gist https://gist.github.com/strykerin/5c29020ab3319bbde774d03dfddb5737 %}

Now we can compile our smart contract by running the following command:

truffle compile

After compiling, we can now deploy our token. For this open Ganache and select the option “Quickstart” to start a local Ethereum blockchain. To deploy our contract, run:

truffle migrate

The address used to deploy our contracts is the first one from the list of addresses that Ganache shows us. To verify that, we can open the Ganache desktop application and we can verify that the balance of Ether for the first account has been reduced due to the cost of Ether to deploy our smart contracts:

![](https://cdn-images-1.medium.com/max/1024/1*1iJ9VRlyLuza58HL3DLfpg.png)<figcaption>Ganache desktop application</figcaption>

To verify that 1 million MyToken tokens have been sent to the deployer address, we can use the Truffle Console to interact with our deployed smart contract.

> [Truffle Console is a a basic interactive console connecting to any Ethereum client.](https://www.trufflesuite.com/docs/truffle/getting-started/using-truffle-develop-and-the-console)

In order to interact with our smart contract, run the following command:

truffle console

Now we can write the following commands in the terminal:

- Get the smart contract: myToken = await MyToken.deployed()
- Get the array of accounts from Ganache: accounts = await web3.eth.getAccounts()
- Get the balance for the first account: balance = await myToken.balanceOf(accounts[0])
- Format the balance from 18 decimals: web3.utils.fromWei(balance.toString())

By running the commands above, we will see that the first address has in fact 1 million MyTokens:

![](https://cdn-images-1.medium.com/max/517/1*AQlj9A7dw-qtY4QAD3Bpxw.png)<figcaption>First address has 1000000 MyTokens</figcaption>

### Create FarmToken Smart Contract

The FarmToken smart contract will have 3 functions:

- balance(): Get the MyToken balance on the FarmToken smart contract.
- deposit(uint256 \_amount): Transfer MyToken on behalf of the user to the FarmToken smart contract then mint and transfer FarmToken to the user.
- withdraw(uint256 \_amount): Burn user’s FarmTokens and transfer MyTokens to the user’s address.

Let’s look at the FarmToken constructor:

{% gist https://gist.github.com/strykerin/f42c268f60ee5b40c3c9b6be0e062d4d %}

- Lines 3–6: We are importing the following contracts from openzeppelin: IERC20.sol, Address.sol, SafeERC20.sol and ERC20.sol.
- Line 8: The FarmToken will inherit from the ERC20 contract.
- Lines 14–19: The FarmToken constructor will receive as parameter the address of MyToken contract and we will assign its contract to our public variable called token.

Let’s implement the balance() function. It will receive no parameters and it will return the balance of MyToken on this smart contract. It is implemented as shown below:

{% gist https://gist.github.com/strykerin/3ddb8ab9874708be91ad3082292f11ca %}

For the deposit(uint256 \_amount) function, it will receive as parameter the amount the user wants to deposit and it will mint and transfer FarmTokens to the user:

{% gist https://gist.github.com/strykerin/c1386b51bccd11a40442d8a8411a57eb %}

For the withdraw(uint256 \_amount) function, we will receive as parameter the amount of FarmTokens the user wants to burn and then transfer the same amount of MyTokens back to the user:

{% gist https://gist.github.com/strykerin/8e3af416467afe5643268ca9d1d438a3 %}

Now we will deploy our smart contract. To do so, we will go back to the file 2\_deploy\_Tokens.js and add the new contract to be deployed:

{% gist https://gist.github.com/strykerin/f8c54ca2b16d465d445c1752852df474 %}

Note that when deploying the FarmToken, we pass as parameter the address of the deployed MyToken contract.

Now, run truffle compile and truffle migrate to deploy our contracts.

Let’s test our smart contract. Instead of using the truffle console to interact with our smart contract, we will create a script to automate this process. Create a folder called scripts and add the following file getMyTokenBalance.js. It will check the balance of MyTokens on the FarmToken smart contract:

{% gist https://gist.github.com/strykerin/e1dbf8c1850806bcc13bc9ef07d55e24 %}

To execute this script, run the following cli command:

truffle exec .\scripts\getMyTokenBalance.js

We will get the expected result that is 0.

Now, let’s stake the MyToken to the smart contract. Since the function deposit(uint256 \_amount) calls the function safeTransferFrom from the ERC20, the user must first approve the smart contract to transfer MyToken on the user’s behalf. So on the script below, we will first approve this step then we will call the function:

{% gist https://gist.github.com/strykerin/ecadb5633f2c8fb0ac8df87189dfb962 %}

To run this script: truffle exec .\scripts\transferMyTokenToFarmToken.js. You should see on your console:

![](https://cdn-images-1.medium.com/max/392/1*MoekE2QCw7vB98u5dl7ang.png)<figcaption>output of transferMyTokenToFarmToken.js</figcaption>

As we can see, we have successfully deposited MyTokens to the smart contract as the first account has now FarmTokens.

In order to withdraw:

{% gist https://gist.github.com/strykerin/02dbd201b1fd5fb573035940e54964ef %}

To run this script: truffle exec .\scripts\withdrawMyTokenFromTokenFarm.js. As we can see on the output below, we have successfully got the MyTokens back and we have burned the FarmTokens:

![](https://cdn-images-1.medium.com/max/383/1*jHYlTFg0NgGbhASpsRvc0w.png)<figcaption>output of withdrawMyTokenFromTokenFarm.js</figcaption>

### Conclusion

In this article we have set our development environment with Truffle and Ganache, and created a DeFi application where users can deposit MyTokens and get FarmTokens and they can withdraw their MyTokens by burning their FarmTokens.

If you are interested in learning more about DeFi, in the References section below there are some interesting articles about the subject.

All this code is available on the GitHub repo below:

[strykerin/DeFi-Token-Farm (github.com)](https://github.com/strykerin/DeFi-Token-Farm)

### References

[Contracts — OpenZeppelin Docs](https://docs.openzeppelin.com/contracts/3.x/)

[Sweet Tools for Smart Contracts | Truffle Suite](https://www.trufflesuite.com/)

[Ganache | Truffle Suite](https://www.trufflesuite.com/ganache)

[What is DeFi? A Begginer’s Guide (2021 Updated)](https://99bitcoins.com/what-is-defi/)

[DeFi — The Decentralized Finance Leaderboard at DeFi Pulse](https://defipulse.com/)

#### Also, Read

- [Learn Ethereum and Web3 development](http://blog.coincodecap.com/go/learn)
- The Best [Crypto Trading Bot](https://medium.com/coinmonks/crypto-trading-bot-c2ffce8acb2a)
- [3Commas Review](https://medium.com/coinmonks/3commas-review-an-excellent-crypto-trading-bot-2020-1313a58bec92)
- [Pionex Review](https://medium.com/coinmonks/pionex-review-exchange-with-crypto-trading-bot-1e459d0191ea)
- [AAX Exchange Review](https://medium.com/coinmonks/aax-exchange-review-2021-67c5ea09330c) | Referral Code, Trading Fee, Pros and Cons
- [Deribit Review](https://medium.com/coinmonks/deribit-review-options-fees-apis-and-testnet-2ca16c4bbdb2) | Options, Fees, APIs and Testnet
- [FTX Crypto Exchange Review](https://medium.com/coinmonks/ftx-crypto-exchange-review-53664ac1198f)
- [NGRAVE ZERO review](https://medium.com/coinmonks/ngrave-zero-review-c465cf8307fc)
- [Bybit Exchange Review](https://medium.com/coinmonks/bybit-exchange-review-dbd570019b71)
- [3Commas vs Cryptohopper](https://medium.com/coinmonks/3commas-vs-pionex-vs-cryptohopper-best-crypto-bot-6a98d2baa203)
- The Best Bitcoin [Hardware wallet](https://medium.com/coinmonks/the-best-cryptocurrency-hardware-wallets-of-2020-e28b1c124069?source=friends_link&sk=324dd9ff8556ab578d71e7ad7658ad7c)
- [Crypto Copy Trading Platforms](https://medium.com/coinmonks/top-10-crypto-copy-trading-platforms-for-beginners-d0c37c7d698c)
- Best [monero wallet](https://blog.coincodecap.com/best-monero-wallets)
- [ledger nano s vs x](https://blog.coincodecap.com/ledger-nano-s-vs-x)
- [Bitsgap vs 3Commas vs Quadency](https://blog.coincodecap.com/bitsgap-3commas-quadency)
- The Best [Crypto Tax Software](https://medium.com/coinmonks/best-crypto-tax-tool-for-my-money-72d4b430816b)
- [Best Crypto Trading Platforms](https://medium.com/coinmonks/the-best-crypto-trading-platforms-in-2020-the-definitive-guide-updated-c72f8b874555)
- Best [Crypto Lending Platforms](https://medium.com/coinmonks/top-5-crypto-lending-platforms-in-2020-that-you-need-to-know-a1b675cec3fa)
- [Ledger Nano S vs Trezor one vs Trezor T vs Ledger Nano X](https://blog.coincodecap.com/ledger-nano-s-vs-trezor-one-ledger-nano-x-trezor-t)
- [BlockFi vs Celsius](https://medium.com/coinmonks/blockfi-vs-celsius-vs-hodlnaut-8a1cc8c26630) vs Hodlnaut
- [Bitsgap review](https://medium.com/coinmonks/bitsgap-review-a-crypto-trading-bot-that-makes-easy-money-a5d88a336df2) — A Crypto Trading Bot That Makes Easy Money
- [Quadency Review](https://medium.com/coinmonks/quadency-review-a-crypto-trading-automation-platform-3068eaa374e1)- A Crypto Trading Bot Made For Professionals
- [PrimeXBT Review](https://medium.com/coinmonks/primexbt-review-88e0815be858) | Leverage Trading, Fee and Covesting
- [Altrady review](https://blog.coincodecap.com/altrady-reivew)
- [Ellipal Titan Review](https://medium.com/coinmonks/ellipal-titan-review-85e9071dd029)
- [SecuX Stone Review](https://blog.coincodecap.com/secux-stone-hardware-wallet-review)
- [BlockFi Review](https://medium.com/coinmonks/blockfi-review-53096053c097) | Earn up to 8.6% interests on your Crypto
- [Coinrule review](https://blog.coincodecap.com/coinrule-review-a-perfect-trading-bot)
- [Best Blockchain Analysis Tools](https://bitquery.io/blog/best-blockchain-analysis-tools-and-software)
- [Crypto arbitrage](https://medium.com/coinmonks/crypto-arbitrage-guide-how-to-make-money-as-a-beginner-62bfe5c868f6) guide: How to make money as a beginner
- Best [Crypto Charting Tool](https://medium.com/coinmonks/what-are-the-best-charting-platforms-for-cryptocurrency-trading-85aade584d80)
- What are the [best books to learn about Bitcoin](https://medium.com/coinmonks/what-are-the-best-books-to-learn-bitcoin-409aeb9aff4b)?

> [Get Best Software Deals Directly In Your Inbox](https://medium.com/coinmonks/newsletters/coinmonks)

[![](https://cdn-images-1.medium.com/max/584/1*BoDnKUyK8p4hitHAJZ5Pdw.png)](https://medium.com/coinmonks/newsletters/coinmonks)

* * *