Deploy a Serverless Maker Bot on AirSwap (Part 1)

In this two-part tutorial, learn how to quickly set up a maker for AirSwap Instant using the new AirSwap Maker Kit and zero-config deployment with Vercel.

Graham Perich
Fluidity

--

AirSwap is a peer-to-peer trading network for Ethereum tokens. Traders connect to each other based on common interest, agree on price through mutual cryptographic signatures, and settle trades without intermediaries. It’s a good system for makers, with no deposits or costly price updates to on-chain order books.

The Swap protocol facilitates a wide variety of trading methods trustlessly. The most popular method to date is the RFQ style system that powers AirSwap Instant. When you request a price on Instant, responses come from automated bots built by developers. This guide will show you how quickly you can get started with a bot of your own!

We’re going to leverage two awesome tools in this tutorial, so I’ll touch on them both briefly before we dive in.

Serverless with Vercel

Until recently, AirSwap Instant peers only communicated using JSON-RPC over websockets. This was okay, but frankly not great. Websockets can be fragile and hard to work with, plus most developers don’t have a lot of experience building on top of them. With AirSwap 2.0, peers can now communicate with JSON-RPC over HTTP. This means AirSwap developers can use all of the latest and greatest in web tooling — like Vercel!

Of course, we could always whip up vanilla web server, but then we’d have to containerize it, host it in the cloud, and setup some health checks or process monitoring tools in case something ever goes wrong. That’s a lot of work, and that’s why Serverless really shines here. All you have to do is write your code, and Vercel will take care of the rest.

Quick Start with the AirSwap CLI

We recently released the AirSwap CLI. This command line tool provides helpful utilities to aid developers in building on top of the Swap Protocol. The CLI also includes some helpful scripts for administrative tasks. We’ll use these scripts to approve tokens, interact with indexers, and test our maker locally.

Setup

Before we get started, you’ll need to make sure you have Node.js >= v10.13.0 and Yarn installed. You’ll also need the latest version of Google Chrome with the MetaMask extension installed. If you ever get stuck or lost, you can find the complete source code for this tutorial here.

Clone down the airswap-vercel-example repo and checkout the tutorial starting point branch.

https://github.com/airswap/airswap-vercel-example/tree/zeit-tutorial-starting-point

$ git clone git@github.com:airswap/airswap-vercel-example.git
$ git checkout zeit-tutorial-starting-point

Then, install dependencies.

$ yarn

Building the Maker

We’re going to start by setting up an environment variable. Vercel has great built-in support for environment variables with their Secrets system.

The only environment variable that we need for this tutorial is ETHEREUM_ACCOUNT, which should be a 64 character Ethereum account private key. If you want to generate a new private key for the purpose of this tutorial you can follow the steps below. If you already know how to create a private key or have a spare one handy, skip ahead to the section titled “Configure Vercel Secret and .env file.”

Generating a new Private Key

The AirSwap CLI provides helpful many helpful utilities, including Ethereum account generation. Follow the steps below to get your private key.

First, install the AirSwap CLI.

$ yarn global add airswap

Now, generate a private key.

$ airswap account:generate

Your result should look like this:

Copy this private key to your clipboard and use it in the next section below.

WARNING: You should never reuse this private key outside of this tutorial. Anyone with access to your private key can access all funds associated with the account.

Configure Vercel Secret and .env file

We’re going to use the Vercel CLI to set up our Secret. Enter the following command, making sure to replace the template with your actual private key:

$ vercel secrets add ethereum-account 64_CHAR_PRIVATE_KEY_HERE

We also need to add a .env file for local development. You can look at the .env.example file for reference. Your .env file should just have one line that looks like this:

ETHEREUM_ACCOUNT=64_CHAR_PRIVATE_KEY_HERE

That’s all we need to do. Now the secret will be available to our maker as an environment variable called ETHEREUM_ACCOUNT. This is configured by the now.json file provided in the tutorial template. You can learn more by reading the Vercel documentation.

Acquiring testnet tokens

Our example maker is going to serve orders for DAI on the Rinkeby test network, so we’ll need to acquire some test DAI before we begin. Follow the steps below:

First, import the private key that you made for this tutorial into MetaMask

Click this button in the MetaMask extension to import your private key

Then, visit the Rinkeby ETH Faucet and follow instructions to get some ETH

Finally, visit the Compound Rinkeby DAI Faucet to get some DAI. You’ll need to click on the “FAUCET” button like in the photo below.

Click the “FAUCET” button and follow the prompts

Code

Now we’re ready to write some code. We’re going to navigate to the api/ directory, which is where the Vercel build system looks for files. Open the api/index.ts file in your text editor, and let’s get started.

We’ll start by importing some dependencies.

import jayson from 'jayson' // JSON-RPC helper
import winston from 'winston' // logger
import connect from 'connect' // expressJS-like middleware helper
import cors from 'cors' // CORS middleware
import bodyParser from 'body-parser' // body parsing middleware
import initHandlers from './handlers' // airswap maker logic

Let’s also add a check for the environment variable, since our maker can’t run without it.

// Make sure environment variables are ready
if (!process.env.ETHEREUM_ACCOUNT) {
throw new Error('ETHEREUM_ACCOUNT must be set')
}

We’ll also configure our logger. This will be helpful later on if we want to debug our maker in real time using Vercel’s built in log monitoring features.

// Setup logger
const logger = winston.createLogger({
level: 'info',
transports: [new winston.transports.Console()],
format: winston.format.printf(({ level, message }) => {
return `${level}: ${message}`
}),
})

Next, we’re going to instantiate the example order and pricing handlers from AirSwap Maker Kit. By default, the Maker Kit provides some hard-coded handlers to get you up and running quickly. Once you reach the end of the tutorial, you should come back here and try customizing the handlers with your own pricing strategies.

// Initialize pricing handlers with our private key
const handlers = initHandlers(process.env.ETHEREUM_ACCOUNT)

These handlers are now used to power a JSON-RPC server with the help of the jayson package. This means that when a prospective counter-party calls a method on our maker like getMaxQuote or getSenderSideOrder, it will be processed and responded to automatically.

// Listen and respond to incoming JSON-RPC over HTTP requests
const server = new jayson.Server(handlers, {
router: function(method) {
try {
logger.info(`Received ${method} request`)
return this._methods[method]
} catch (e) {
return new jayson.Method((params, callback) => {
callback(true, null)
})
}
},
})

Lastly, we just need to add some middleware and export our code. We don’t have to worry about configuring ports or transpiling the TypeScript. Vercel’s build system will take care of everything else from here.

// Instantiate our express-style middleware helper
const app = connect()
// Parse JSON request body
app.use(bodyParser.json())
// Do preflight OPTIONS check before the jayson middleware
app.use(cors())
// Apply our order handlers
app.use(server.middleware())
export default app

Now that we have our index.ts file finished, let’s take it for a spin. We’re going to need two terminal shells for this part.

In the first window, navigate to the airswap-vercel-example/ directory if you’re not there already. Then start your maker locally by running:

$ vercel dev

In the second window, run airswap quote:get. This script allows us to query any maker. Make sure to query your own maker by typing http://localhost:3000 in the locator prompt. Ask for a price quote to buy 100 DAI in exchange for WETH.

You should see your maker log the request in the first window, and the quote will come back in the second window. Everything is working!

Now that we have our maker working locally, the last phase is to deploy it and make it discoverable by other traders on AirSwap Instant. There are just a few final steps required to make that happen: approving our DAI balance to be transferred by the Swap contract, setting an intent to trade on the indexer contract, and deploying our maker to Vercel. These steps are covered in Part 2 of the Deploy a Serverless Maker Bot on AirSwap tutorial series.

Note: The information contained in this blog post is solely for information purposes and does not constitute financial or legal advice. Users agree that their activity and conduct in connection with their use of AirSwap or any tools described in this post, including any resultant transactions, will be in compliance with all applicable laws, rules, regulations, requirements, guidelines, policies, economic or financial sanctions.

About AirSwap

AirSwap enables peer-to-peer trading on the Ethereum blockchain. Built on a decentralized protocol, traders can add or remove liquidity through a suite of trustless products that are easy to use and free. Our mission is to empower the world with frictionless trade.

Blog | Twitter | Discord | Developers | Makers | Reddit | Facebook | Linkedin | Subscribe | Support | Request a Feature | FAQ | Trade Now

--

--

Graham Perich
Fluidity

👨‍💻 Software Engineer - building the future of trade @AirSwap