Web3 Applications with AWS Illustrated by the Example of a Serverless Crypto Trading Bot

Kai Schmitz-Hofbauer
9 min readOct 1, 2022

--

TL;DR

Depending on the use case, blockchain applications require an automated processing of transactions. Customer-centric crypto wallets, commonly used in the web3 environment, are not suitable for such requirements. There we need a suitable architectural approach.

This document describes an architecture based on AWS services using a simple crypto trading bot as an example. The sample solution consists of a cost and operational efficient serverless architecture using

  • AWS Key Management Services (KMS) for secure key generation, key management and digital signatures
  • AWS Lambda and AWS DynamoDB for implementing the business logic
  • Celo blockchain for a sustainable and eco friendly blockchain and DeFi (Decentralized Finance) ecosystem

Introduction

Web3 and blockchain technology promise to take the digitization of business processes to a new level. In particular, tokenization — i.e. the mapping of digital or physical assets into standardized, digital crypto assets that are tradable without a middleman and document ownership in a transparent way — enables an unlimited number of new use cases.

Blockchain transactions are executed using asymmetric cryptography, where a key pair consisting of a private and a public key is used. The private key is used to sign transactions — e. g. the transferal of funds — while the public key can be used to prove that a transaction is actually originated by the sender.

Crypto wallets are a necessary tool for participating in the web3 ecosystem. Wallets are software applications that simplify the interaction with the blockchain and take care in particular of the handling of the key material. Wallets can be custodial or non-custodial. A custodial wallet is managed by an organization, the so-called custodian. The custodian stores and manages the private keys on their client’s behalf. In a non-custodial approach the user is responsible for the private key.

In the corporate environment, custodial wallets are mostly used. Those wallets are integrated into the IT landscape via APIs. Some use cases require a licensed custody provider for regulatory reasons. The licenses are usually issued by the national supervisory authorities. However, there are also use cases where the use of state-of-the-art enterprise technologies like standard cloud services from one of the hyperscale cloud providers are also suitable. One use case could be the minting of NFTs (Non Fungible Tokens), which is performed outside a licensed custodial wallet, but then transferred into it for trading.

This article describes how web3 approaches can be implemented leveraging cloud services from AWS. As a simple example, a crypto trading bot will be discussed, which autonomously swaps between a stable coin and a volatile crypto token.

Typical challenges

As typical for enterprise-level applications, the following non-functional requirements must also addressed in the web3 environment:

  • Sustainability: The implementation of any type of applications shall be based on sustainability principles. Of course, this is especially true for the blockchain infrastructure to be used. In addition to the blockchain infrastructure, it is also important that the application itself (in our example the trading bot) is using a sustainable infrastructure and is implemented in a sustainable way. This means that computing capacities in particular are used as economically as possible.
  • Security: Digital signatures are required to execute blockchain transactions. Blockchain signatures are based on asymmetric cryptography and require both the secure generation and management of the private key as well as the execution of digital signatures in a secure environment.
  • Cost-efficiency: A good architecture is designed to be cost efficient. This concerns transaction fees on the blockchain (“gas fees”) as well as the environment on which the application is operated.
  • Operational efficiency: It is important to run the application effectively without the need for manual interventions.

Blockchain technology & DeFi ecosystem

If a new use case is to be implemented, a decision must be made on which blockchain it should be based on. Due to Bitcoin’s poor energy efficiency, blockchain applications have an unjustified bad reputation for being environmentally unfriendly. This is due to the underlying proof-of-work consensus mechanism. However, state-of-the-art blockchains rely on the energy-efficient proof-of-stake protocol and have a much smaller Co2 footprint.

An interesting blockchain ecosystem is Celo. Celo in particular is environmentally friendly, has a socially responsible mission and low transaction fees (“gas fees”). Celo describes itself as a ReFi (Regenerative Finance) ecosystem and has a negative Co2 footprint. Another advantage is that Celo is technically compatible with the Ethereum virtual machine. Especially smart contracts and the interactions with them are technically done in the same way as with the leading ecosystem Ethereum. Furthermore, Celo offers a volatile token as well as stable coins, which are pegged to Dollar, Euro or Real. Therefore, Celo ist a very good choice for a DeFi/ReFi use case if you are not dependent on Ethereum itself — like in this example.

The basic principle of the trading bot discussed in this document works as follows: It buys the volatile Celo token with a stable coin — in particular Celo Euro stable coin — when the price is low and exchanges the stable coin against the Celo token when the price is high (“buy low, sell high”).

Simple trading strategy

There exist numerous trading strategies for automated trading. A very simple one is grid trading. A grid bot performs a grid trading strategy in an automated way. The grid bot buys and sells assets at predefined, evenly distributed positions. Whenever the current exchange rate reaches one of these positions, a corresponding buy or sell transaction is executed. In this way a kind of commercial grid is created. The following illustration shows how a grid is organized and how a grid bot works. Basic principle is buying lower and selling higher and thereby generating profit.

Step 1: Execute a trade when a grid line is reached
Step 2: Adjustment of the grid after a trade has been executed

After each transaction the grid is recalculated. No trading is planned for the current grid line and the sell and buy or for the grid lines above and below are recalculated. Grid trading works best in sideways markets. A javascript implementation for trading bot can be found here.

Cloud native, serverless implementation

Obtaining resources for operating the bot is quite easy: All the hyperscale cloud providers like Amazon Web Services (AWS), Microsoft Azure or Google Cloud provide suitable services. The following section describes an implementation based on AWS.

In order to achieve cost efficiency, operational efficiency and sustainability it is a best practice to rely on managed services where we do not need to manage any infrastructure by ourselves. In the specific example of the trading bot, the application is only active for a short time. During this time it checks the current rate, verifies whether a buy or sell grid line has been reached and executes the trade if required. This kind of runtime pattern is a good fit for a function-as-service approach which can be implemented using the AWS Lambda service. The execution can be scheduled via AWS Event Bridge. This avoids unnecessary provisioning of IT resources and charging is done according to the runtime in milliseconds.

A Lambda function is only running for a limited period of time and has itself no persistent data storage. To perform the grid trading it is necessary to store the actual grid configuration. This is stored serverless in a NoSQL Database (DynamoDB).

Sample solution architecture for a simple crypto trading bot

Secure handling of the private key

Every transaction on the blockchain is secured by a digital signature. Any person or system that is doing a transfer needs to sign the transaction with her/its own private key. Therefore, in any blockchain solution, a key challenge is the secure key generagtion, the scure key management and the secure execution of signatures. In case of the trading bot — and most of the business applications — those signatures need to be applied in an automated way. End user facing wallet solutions like Metamask cannot be used. Very well suited for this kind of automated trading is the AWS key management service (KMS) which creates and manages the corresponding key material and performs signatures in a secure environment. When deploying a KMS service instance it is important that it is configured properly for use with the underlying blockchain. In case of Celo (which EVM compatible as mentioned before) the following configuration parameters needs to be set:

AWS KMS — necessary cryptographic configuration

It is important to make sure that the correct key usage sign and verify and the corresponding Elliptic Curve Cryptography (ECC) key spec is selected. For later reference and usage it is also necessary to specify a key alias.

The simplest way to use AWS KMS with Celo is to make use of the Celo SDK, which provides a wrapper for interacting with AWS KMS and the Celo chain. The following code snippet shows how the AWS wallet API can be used. However, the prerequisite is that AWS KMS has been configured correctly as described above. The mapping to an AWS KMS instance is performed using the configured KMS key alias.

const celoAws = require('@celo/wallet-hsm-aws')
const AWS = require('aws-sdk')
const Web3 = require("web3")

const awsVaultName = "MY_AWS_KMS_KEY_ALIAS"
const awsWallet = await new celoAws.AwsHsmWallet(awsVaultName)
await awsWallet.init()
const walletAddress = awsWallet.getAccounts()[0]

It is also important to grant the AWS Lambda function the appropriate rights to access KMS and execute and verify signatures. Since these are standard AWS activities, no further details are provided here.

The following code snippet shows in simplified form how a sale of Celo Euro in favor of the Celo token can be executed using the AWS Wallet (via AWS KMS). It uses the abstractions provided by the Celo SDK for this purpose.

const ContractKit = require('@celo/contractkit')
const Web3 = require("web3")

const sourceCurrency = "cEUR"
const amountOfStableCoin = …
const web3 = new Web3("https://forno.celo.org")
const kit = await ContractKit.newKitFromWeb3(web3, awsWallet)

const stableToken = await
kit.contracts.getStableToken(sourceCurrency)
const exchange = await kit.contracts.getExchange(sourceCurrency)
// approve transaction
const approveTx = await stableToken.approve(exchange.address,
amountOfStableCoin).send({from:walletAddress})
const approveReceipt = await approveTx.waitReceipt()
//execute transaction
const goldAmount = await exchange.quoteStableSell(amountOfStableCoin)
const sellTx = await exchange.sellStable(amountOfStableCoin,
goldAmount).send({from:walletAddress})
const sellReceipt = await sellTx.waitReceipt()

Human readable reporting

Of course, it is also of interest to look at the results of the automated trading in a human-readable form from time to time. A spreadsheet is a good and easy choice for this. It is also necessary that the chosen tool is constantly available and easily accessible. For these reasons the choice fell on Google Sheets.

For the purpose of human readable reporting, another Lambda function was developed, which adds a line to the spreadsheet in the event of an executed trade. Each line contains the timestamp of the trade, balance of the Celo token and the balance of the Celo Euro stable coin and a total balance converted into euros. With the exception of the latter, this information is also available in Celo Explorer. As part of this implementation, the exchange rates were obtained via Coingecko.

Limitations

A limitation of the architecture is that the respective rates are checked on a time basis. If the rates change faster than the time interval of the scheduled executions, it might happen that grid lines are omitted.

Summary and conclusion

Using a simple trading bot as an example, it was shown how web3 approaches can be implemented in an automated business context. In particular, an efficient cloud-native serverless architecture, sustainability and security were emphasized. Even though this is a relatively simple example, production-quality web3 business applications can be developed following the same pattern, which meet the highest requirements for security, sustainability as well as cost and operational efficiency.

--

--