Running Perp-maker for Profits & Fun: Part 1
Tags: web3, typescript, javascript, aws
Published: 2022-06-03 13:41:35


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tbiuowyuaofzev3n53wv.png)
[Perp-maker](https://github.com/perpetual-protocol/perp-maker) is an open-source market-making template for [Perpetual Protocol v2](https://app.perp.com/?utm_source=devto&utm_medium=blog_post), the most popular dApp on [Optimism](https://optimism.io/) (a layer-2 scaling solution for Ethereum). Anyone can use or modify the template to facilitate trades on the protocol and earn fees. 

In this tutorial, we’ll go over what Perpetual Protocol is, the risks and rewards associated with running the bot, and how to run it locally. Due to the length of this article, we’ll cover how to run the bot on AWS and further modification suggestions in part 2. Stay tuned!

## Perpetual Protocol 101
First thing first, what is Perpetual Protocol?

Perpetual Protocol is a decentralized derivative exchange (DEX) where traders can use USDC (a USD-pegged stablecoin) to speculate on cryptocurrency’s price movement with up to 10x leverage. At the time of writing, the DEX supports 17 markets, including BTC, ETH, ATOM, BNB, and more! You can learn how it works in detail by watching this [10-minute video](https://www.youtube.com/watch?v=pBoKtkoNZEY) or reading [this article](https://cryptotesters.com/blog/perp-protocol).

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8mtnqgtmd8fj3dko0wt4.png)

But what does “market-making” mean?
Whenever a trade happens, there will always be two sides involved - a taker and a maker. **The takers initiate a trade, and the makers provide the inventory to let the taker take.**

Here is a real-life example. When buying a fish from a vendor, you’re the taker of this trade as you’re the one that takes what the vendor supplies. As for the vendor, he is the maker of this trade as he prepares the inventory (fish in this example) that makes this trade possible. 

Similarly, **being a market-maker, or “maker,” on Perp v2 means you [provide the liquidity](https://blog.perp.fi/how-to-provide-liquidity-on-perp-v2-9064ed085d7f) (the assets) that traders can take, making the market viable. In return, you receive 80% of the transaction fees paid by the trader.** For instance, if a trader opens a long position and this trade happens in the price range you set, you act as the other side of the trade - i.e., opening a short position as a result, and vice versa. 

**Makers on Perp v2 can choose the price range to which they provide liquidity.** For instance, in the screenshot below, this user wants to provide liquidity to the BTC market with a price range of $9,991.99 to $60,081. 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qj5oep0xh8bzwxq8bmsr.png)
Whenever a trade happens in that range, this user collects 80% of the transaction fees proportionately. One thing worth pointing out is that USDC is the only asset you need to deposit to start market-making on Perp v2. Once you deposit some USDC, the system will mint the virtual tokens (0.1 vBTC and 4316.31 vUSD in the screenshot) you need to trade or market-make with. 


## Risks and Rewards of Running Perp-maker

With perp-maker, anyone can automate their market-making strategy on Perp v2 to earn transaction fees and liquidity mining rewards (more on this later).

Out of the box, **perp-maker lets you choose which market you want to provide liquidity to and within what price range.** As a reminder, if the market price moves out of the range you set, you will not collect any transaction fees until it moves back in the range. **Perp-maker can automatically adjust your liquidity and realize the impermanent loss when the market price reaches the price level you set.**

But what is impermanent loss?
**On Perp v2, makers act as the other side of each trade. If a trader makes a profit, a maker loses money. This loss is impermanent as it will become 0 when the market price returns to the initial price.** Even if the market price moves away from the initial price, you can collect fees if the market price stays in the price range.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/71lo6olyag8yyrz7r4k5.png)

As a rule of thumb, the wider the price range you set, the less impermanent loss you suffer; however, the less transaction fees you can collect. And the more transaction fees generated on a market, the better for you as a maker. You can use the Perpetual Simulator to simulate different price ranges in any given market to gauge the profitability of your strategy.

Additionally, the developers behind the protocol provide its token, known as $PERP, as an extra reward to encourage more people to be makers. This reward is distributed weekly proportional to the transactions fees you collect for that market in that week. This weekly reward is known as liquidity mining rewards.

To recap - if the transaction fees plus liquidity mining rewards outweigh the impermanent loss, it’s a profitable strategy. If not, it can still be a profitable strategy in a more extended timeframe as it takes time for the value of the fees and liquidity mining rewards to catch up with the impermanent loss.


## Setting the Stage

> If you consider yourself an experienced programmer, you should have no problem setting up the bot using the readme in the [perp-maker repo](https://github.com/perpetual-protocol/perp-maker). 

In the previous sections, we learned how Perp v2 works and the risks and rewards of being a maker on the platform. This section will go through the steps to set up a perp-maker on your computer. You can join our Discord server where we have a [#coding-chat channel](https://discord.com/invite/M7y2VFqwCb) for questions you encounter when building on top of Perp v2.

First, you need to download and install Node.JS on your computer, which comes along with the Node Package Manager (npm) that we need. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jxg5xtgeufx36efhk64h.png)

Once installed, you can type the following commands in your terminal (Terminal for macOS or Command Prompt for Windows) to check both software versions on your computer.

`node -v
npm -v`

You should see similar responses on your screen, like the screenshot below. There might be some differences between your version and mine, but you’ll be fine if the npm version is at least seven and Node.js is at least 16.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1uht1lj89j4g4731wxin.png)

For Windows users, if you see an error message of “‘node’ is not recognized as an internal or external command,” you need to modify your Environment Variables. You can search “Environment Variables” on your PC and add the location where you installed Node.js in the PATH. My installed location is at “C:\Program Files\nodejs\”. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ura7g6ctkn4bstjr47x3.png)

Then you need to install Git on your computer. You can visit this site to see the install guide for each OS. For those who want to learn more about Git, you can watch this 100 second video to know more about it. Once installed, type the following command in your terminal to verify it’s working:

`git --version
`

> Again, for Windows users, if you run into an error that starts with “git is not recognized as an internal or external command…”, you need to edit your Environment Variables as we previously did for Node.js.

Now, we will clone the perp-maker repo and build it locally. You can do it with the following commands in your terminal:

```
git clone https://github.com/perpetual-protocol/perp-maker.git
cd perp-maker
npm i
npm run build
```

If everything works properly, you should see something on your terminal that’s similar to what’s displayed below:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/u1nclobdh6wdx3yzviz3.png)


The last thing in this section is that you need to download a cryptocurrency wallet. We recommend [MetaMask](https://chrome.google.com/webstore/detail/metamask/nkbihfbeogaeaoehlefnkodbefgpgknn) as it’s the world’s most popular browser wallet. During onboarding, you’ll be asked to save 12 recovery phrases. You should **never** share these with anyone under any circumstances. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l33f5ut7bun1gqsmg9ps.png)


## Configure the Bot: Local Variables and Strategy

At this point, we’re just a few adjustments away from running the bot locally. 

**1. Modify .env file**
You need to add a web3 endpoint and your wallet’s private key to the .env file in your perp-maker folder. Here is what it looks like once it’s done:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tpl5jkaqsw51edeyg7c2.png)

For a web3 endpoint, you can obtain it by creating a free account on [Infura](https://infura.io/) or [Alchemy](https://www.alchemy.com/). For testing purposes, you should get an endpoint for “Optimism Kovan”, not “Optimism Mainnet” or “Kovan”. 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/i8vuf9o39rbz1lykh6od.png)

> If you're wondering what a web3 endpoint is, it’s where this bot submits your transaction. The endpoint provider e.g. Infura will broadcast your transaction to blockchain miners/validators upon reception, who will later validate your transaction and add it to the blockchain's latest block.


As for the private key, you can export it from your MetaMask by clicking the more button (besides your wallet address), clicking “Account details,” then “Export Private Key.” Similar to recovery phrases, you should never share your private key. It’s recommended that you use a new MetaMask account rather than the one that you’ve been using for trades.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1fivmfdtk8bfh5238qen.png)

**2. Modify config.json file**
Next up, we need to modify the parameters in the config.json file, which sits in the configs subfolder of the src folder, to create our strategy.

Here are the parameters that you need to determine and the respective description in the config file:

```
PRICE_CHECK_INTERVAL_SEC: 
The frequency to check the price in seconds.
ADJUST_MAX_GAS_PRICE_GWEI: 
The maximum gas fee in Gwei which the bot will adjust liquidity. If the gas price exceeds this number, the liquidity won't be adjusted. Currently, the gas price on Optimism is fixed at 0.001 Gwei.
IS_ENABLED: 
Set to `true` to enable this market.
LIQUIDITY_AMOUNT: 
How much vUSD (after leverage) to provide as liquidity. Perp v2 supports up to 10x leverage, meaning that you can use up to 10x of your deposited USDC to provide liquidity.  
LIQUIDITY_RANGE_OFFSET: 
The offset to upper price and lower price of the liquidity range. For example, if it’s set to 0.05, it will provide liquidity from (current price / 1.05) to (current price * 1.05).
LIQUIDITY_ADJUST_THRESHOLD:
The threshold that the bot will remove your existing liquidity, realize the impermanent loss, and place a new price range. For example, if it’s set to 0.01, the bot will remove your existing liquidity when the current price goes out of the range below (initial price/ 1.01) or above (the initial price* 1.01), and subsequently provides liquidity with a new price range based on LIQUIDITY_RANGE_OFFSET and the current price.
```
 
We use vBTC (BTC market) and vPERP (PERP market) as the target markets in the config file by default. You can check the list of markets on Perp v2 from [the UI](https://app.perp.com/?utm_source=devto&utm_medium=blog_post) or this JSON file.

## Run Locally on Optimism Kovan (Testnet)

You need to get some test tokens before running the bot on Optimism testnet. Head to [Optifaucet](https://kovan.optifaucet.com/), type in your wallet address (which starts with 0x) and send out the request. 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aabxax1i9bd6bng3cfjs.png)

> If you run out of the test ETH to pay for transactions, you can go to Paradigm’s [faucet](https://faucet.paradigm.xyz/) to request more test ETH and then bridge them to Optimism Kovan via [Optimism Bridge](https://app.optimism.io/bridge).

We’re almost ready! The bot by default is set to run on Optimism. To run on Optimism Kovan, you need to add an endpoint for the testnet (as demonstrated above) and comments (add two “slashes” before the codes) the two lines below in the index.ts file which is located in the src folder. 

```
// process.env["STAGE"] = "production"
// process.env["NETWORK"] = "optimism"
```

For Windows users, you need to add additional two lines below above the initLog() in the index.ts file.

```
import dotenv from "dotenv";
dotenv.config();
```

If there is any error saying dotenv isn’t installed, you can run the command below in your terminal to install dotenv.

`npm install dotenv --save`

Now, we’re all set! For macOS users, type the command below to run the bot locally:

`env $(cat .env | grep -v '#' | xargs) npm run start`

For Windows users, type the command below in your terminal to do it:

`npm start`

If it runs successfully, you should be able to see similar responses on your terminal:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/11f60ana69mi7wceqdug.png)

Another way to validate if the template runs successfully is to check the target markets in the pool section on the UI. For testnet (Optimism Kovan), please visit [testnet.perp.exchange](https://testnet.perp.exchange/); As for mainnet (Optimism), visit [app.perp.com](https://app.perp.com/?utm_source=devto&utm_medium=blog_post). 

Alright! That’s all we have for today. Hope you have fun, or at least learned something in our journey. Stay tuned for part two! In the meantime, feel free to join our Discord server where we have a [#coding-chat channel](https://discord.com/invite/M7y2VFqwCb) dedicated to technical questions.

## Helpful Resources

- A third-party site to track your fees and APR: https://www.seedle.finance/
- Maker simulator for Perp v2: https://defi-lab.xyz/perpetualsimulator
- API for Perp v2: https://thegraph.com/hosted-service/subgraph/perpetual-protocol/perpetual-v2-optimism?query=Get%20Trader
- Contract addresses on Perp v2: https://metadata.perp.exchange/v2/optimism.json
- Perp v2 documentation: https://v2docs.perp.fi/