Create and deploy a DeFi App
In this tutorial 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 and 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 allows 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.
Ganache UI desktop application
To create the project, run the following commands
mkdir your-project-namecd your-project-nametruffle 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 contractsmigrations
: Folder for the deployment scriptstest
: Folder for testing our smart contractstruffle-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 by writing to contracts/MyToken.sol
with the following solidity code:
1pragma solidity ^0.8.0;23import "@openzeppelin/contracts/token/ERC20/ERC20.sol";45contract MyToken is ERC20 {6 constructor() public ERC20("MyToken", "MTKN"){7 _mint(msg.sender, 1000000000000000000000000);8 }9}10Бәрін көрсетуКөшіру
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:
1string private _name;2string private _symbol;3uint8 private _decimals;45constructor (string memory name_, string memory symbol_) public {6 _name = name_;7 _symbol = symbol_;8 _decimals = 18;9}10Бәрін көрсетуКөшіру
Compile the ERC20 Token
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:
1// Configure your compilers2compilers: {3 solc: {4 version: "^0.8.0", // Fetch exact version from solc-bin (default: truffle's version)5 // docker: true, // Use "0.5.1" you've installed locally with docker (default: false)6 // settings: { // See the solidity docs for advice about optimization and evmVersion7 // optimizer: {8 // enabled: false,9 // runs: 20010 // },11 // evmVersion: "byzantium"12 // }13 }14}15Бәрін көрсету
Now we can compile our smart contract by running the following command:
truffle compile
Deploy ERC20 Token
After compiling, we can now deploy our 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:
1const MyToken = artifacts.require("MyToken")23module.exports = async function (deployer, network, accounts) {4 // Deploy MyToken5 await deployer.deploy(MyToken)6 const myToken = await MyToken.deployed()7}8
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:
Ganache desktop application
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 basic interactive console connecting to any Ethereum client.
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:
First address has 1000000 MyTokens
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:
1pragma solidity ^0.6.2;23import "@openzeppelin/contracts/token/ERC20/IERC20.sol";4import "@openzeppelin/contracts/utils/Address.sol";5import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";6import "@openzeppelin/contracts/token/ERC20/ERC20.sol";78contract FarmToken is ERC20 {9 using Address for address;10 using SafeMath for uint256; // As of Solidity v0.8.0, mathematical operations can be done safely without the need for SafeMath11 using SafeERC20 for IERC20;1213 IERC20 public token;1415 constructor(address _token)16 public17 ERC20("FarmToken", "FRM")18 {19 token = IERC20(_token);20 }21Бәрін көрсетуКөшіру
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:
1function balance() public view returns (uint256) {2 return token.balanceOf(address(this));3}4![]()