logoAcademy

Overview

Learn how to create a Calculator precompile.

Reference Implementation

In this section, we will showcase how to build a more complex precompile that offers selected simple math operations. Our calculator will support the following operations:

  1. Add two numbers and return the result (3 + 5 = 8)
  2. Get the next two greater numbers (7 => 8, 9)
  3. Repeat a string x times (4, b => bbbb)

This is somewhat odd calculator and real-life usability might not be the best, but as you will see in a bit the operations have been chosen to demonstrate some different scenarios we might face while building precompiles.

What You Are Building

Similar to the Calculator precompile, you will be building a precompile called CalculatorPlus which contains the following mathematical functions:

  • Powers of Three: takes in as input an integer base; returns the square, cube, and 4th power of the input
  • Modulo+: takes in as input two arguments: the dividend and the divisor. Returns how many times the dividend fits in the divisor, and the remainder.
  • Simplify Fraction: takes in two arguments: the numerator and the denominator. Returns the simplfied version of the fraction (if the denominator is 0, we return 0)

Overview of Steps

Compared to the process before, we will now also add tests for our precompile. Here's a quick overview of the steps we're going to follow:

Create a Solidity interface for the precompile

Generate the ABI

Write the precompile code in Go

Configure and register the precompile

Add and run tests

Build and run your customized EVM

Connect Remix to your customized EVM and interact with the precompile

This tutorial will help you understand how to create more complex precompiles. Let's begin!

Updated:

On this page

Edit on Github