Implementing Asset Contracts on Tezos

A walkthrough of an asset ledger implementation

In this post, we describe our first implementation of a managed asset ledger based on an initial asset interface standard proposed recently.

The start of our asset contract using Lorentz

We implement the managed asset ledger in Lorentz, an embedded DSL for Michelson written in Haskell. Using Lorentz allows us to take advantage of Haskell’s type system and gain some constructions from high-level languages relatively cheaply.

Our implementation extends the functionality of a simple asset ledger with Mint , Burn , and Pause operations. This enables contract deployers to customize how or if the asset ledger is managed, whether by a trusted third party, a multisig, a DAO, or no administrator at all.

In fact, we are putting this implementation to use in our work with Elevated Returns and Securitize.

Future implementations will look to future interface standards which improve on the initial model. We also look forward to seeing other developers write and deploy similar asset contract implementations using native Michelson, LIGO, and SmartPy. In fact, a very preliminary SmartPy implementation is already available here.

We also dive into our efforts to property and unit test the asset contract using the Morley framework. As mentioned in last week’s post, efforts by Nomadic Labs are also underway to specify this standard and to formally prove the implementation respects the specification.

Nomadic Labs also plans to integrate a verified implementation natively into the Tezos client, making it easier for any user to create and manage assets safely on Tezos. This would complement the verified multisig contract recently incorporated into the Tezos client, making it simple to create and manage assets on Tezos securely.

Key Resources

Contract overview

In creating this contract, we followed the initial asset interface standard proposed on 21 June. As discussed, this initial interface standard proposal is inspired by ERC-20. As an implementation it provides transfer and approval operations, along with related methods to view balances distribution among the participants.

Unlike ERC-20: transfer and transferFrom endpoints are merged into one transfer for simplicity. It is still possible to distinguish them internally: if the transfer source account is exactly the sender of the current transaction, then the transfer logic is used, and otherwise we perform transferFrom .

The resulting interface in Michelson has been published under the FA1.2 standard. It describes the expected pattern of a contract parameter, approach to errors, and so on.

Having only transfer operations is not enough for all functionality of an asset ledger and at least we need a way to produce those tokens which will be used by ledger participants.

Thus our contract keeps an administrator address. It is set by the contract originator and refers to a contract with an exclusive right to mint funds.

Additional operations available for the administrator include:

Mint produces funds on someone’s account;

produces funds on someone’s account; Burn destroys a portion of funds;

destroys a portion of funds; Pause allows temporarily preventing transfers and approvals from happening.

An asset ledger can also be implemented with a dummy address as the administrator, eliminating any administrator’s right to control the ledger via Mint , Burn , and Pause . This can be done either at the time of the contract origination or the contract’s administrator can be updated to a dummy address afterwards.

Below we present the technical description of the contract’s code and tests.

Contract implementation types

Every Tezos smart contract is divided in three parts:

storage – an on-chain piece of memory space that the contract uses to store its data;

– an on-chain piece of memory space that the contract uses to store its data; parameter type – a data type that the contract expects the caller to pass;

– a data type that the contract expects the caller to pass; code– the contract’s implementation.

In this section, we will concentrate on the types of the contract’s storage and parameter. We will also describe the special Error type used to inform the contract users of a certain error condition. These types will serve as a base for our implementation.

Storage

The storage of every complex Michelson contract consists of two parts: a big_map keeping a data registry (for instance, balances of token participants) and a set of individual fields. Our contract is no exception.

Let’s start with the latter.

Our contract keeps the address of a token administrator, whether the contract is currently paused, and total balance of all the participants.

For this purpose, we declare a plain Haskell datatype:

Note the following part in the end:

It puts StorageFields type in line with some Michelson type. In the given case, this type will be a pair address (pair bool nat) . If our datatype contained more fields, a best effort attempt to balance the resulting tree of pair s would be taken.

Next, we need to use big_map which, for each participant, stores its balances and approvals allocated to other accounts.

The values of the map are represented as

This definition is very similar to that of a Haskell datatype. We declare LedgerValue to be an alias for a pair, each element of which is labeled with a name. Using this kind of definition rather than a datatype definition is simpler when the type has only a few fields.

The entire storage looks like:

Such object declarations are close to the notion of records used in Liquidity - a high-level functional language which compiles to Michelson.

However, as will be shown further, we stick to the stack-based nature of Michelson, which potentially allows for more efficient implementations.

Parameter

The parameter should be formed in a way that allows the contract to provide multiple “functions” or entry points.

According to FA1.2, the parameter should be a comb of Or s, each standing for a single entry point. Then each leaf of this comb contains arguments for this entry point.

Herewith, our parameter should be presented as follows (we omit some of the entry points for clarity)

where entry points’ arguments are defined as

View in GetBalanceParams designates a getter and means that if you provide an Address argument and another contract accepting Natural , this entry point will execute the provided contract with evaluated balance. (As long as Michelson contracts do not return values, this is the most straightforward implementation for getters).

For more details, see the “Michelson Contract Interfaces and Conventions” document.

Errors

Our contract declares a set of errors which are raised via FAILWITH instruction in case of bad user input.

We assume that each exceptional situation should be labeled with

information about error kind and maybe some error details if serializing them is cheap.

Thus, errors are represented as pairs of type (string, data) , where the first argument is a unique error tag and the second argument is data carried by the given error. The same approach to errors is taken in FA1.2.

In our case, the following errors are declared (here we mention only the most interesting error kinds):

The last line defines association between our errors and Michelson types

as mentioned above. This way, we gain the following representations:

OperationsArePaused is converted to ("OperationsArePaused", Unit) ;

is converted to ; NotEnoughBalance (50, 30) is converted to ("NotEnoughBalance", (50, 30)) .

Implementation

And here we come to the actual contract code.

Let’s start from the simple SetPause entry point.

As the Haskell naming convention assumes, we write instructions in lower-case.

Considering step by step:

dip is plain old Michelson instruction which skips the top of the stack.

is plain old Michelson instruction which skips the top of the stack. authorizeAdmin - calls a function declared externally, we will return to its definition later.

- calls a function declared externally, we will return to its definition later. getField #fields performs a sequence of CAR and CDR to get

storage’s fields element.

performs a sequence of and to get storage’s element. setField #paused picks Bool and StorageFields from stack and using CAR , CDR and PAIR instructions sets paused field of the latter.

picks and from stack and using , and instructions sets field of the latter. nil; pair is just a common end of entry point producing no operation.

Note how much more legible the contract looks compared to the version where we would have to use only bare CAR and PAIR instructions/macros.

Now let’s take a look at authorizeAdmin definition:

As the first line suggests, this Haskell function defines a piece of code which accepts and returns a stack with Storage at top.

Instruction failUsing pushes the given error value and fails with it.

As FA1.2 suggests, we tend to use SENDER instruction for authorization rather than SOURCE .

Now let’s take a look at a more interesting entry point — transfer .

Its code is presented in the following snippet:

Dissecting its contents:

At lines 3–5, we check whether an account tries to transfer money to itself.

You could notice unusual if then else construction usage, in which IsEq takes the place of the condition. This is possible due to the RebindableSyntax Haskell extension, which allows redefining basic parts of the language.

Since, in a stack-based language, one cannot pick a value to put into if 's condition, we instead specify a predicate on value at the top of the stack, similarly to what assembly language does for registers.

stackType is an instruction from Morley extension, it has the semantics of NOP but constraints type of the current stack.

Expression @... is Haskell type annotation syntax, and its meaning depends on the instruction it is applied to. For stackType developer specifies the type of stack, while (as you can notice at line 8 below) for dup one can specify the type of duplicated element, for drop - type of removed element.

A developer is free to omit type annotations fully or partially. Nevertheless, they not only help a reader to track what is happening, but also cause type checker to fail earlier when modifying the code incorrectly thus speeding up the development process.

At lines 7–8, we consume allowance if an attempt to spend foreign funds is performed.

dupT instruction is a variation of DUUP macro where a programmer specifies the desired type rather than stack index.

Finally, we increase funds of the destination account and decrease funds of the source.

The contract’s Lorentz code can be found here. A dump into plain Michelson resides here.

Testing

To check that our contract indeed does what it is intended to do, we have

implemented a bunch of integration tests.

Each test case is a scenario consisting of operations which users usually do with contracts — originate them, transfer money to them and so on. Let’s take a look at an example:

Line by line:

We originate our Managed Ledger contract.

We originate a contract which will be used to receive the result of a call to

GetBalance .

. We send some marginal amount of funds to the Managed Ledger, executing the GetBalance entry point.

entry point. Finally, we write down a condition for a successful test — consumer should have been called once with 0 argument. Right argument in validate means that we expect the given steps to finish without exceptions.

Function integrationalTestProperty just runs an interpretation of the given scenario.

Tentatively, we do some preparations:

Test writers can specify an address which he operates on behalf of.

Here is an example where we pretend that the token administrator performs a transaction:

Other building blocks for testing scenarios include changing the current time visible by a contract via a NOW instruction or setting a currently remaining gas limit, which allows for more comprehensive validation.

Testing that user actions are correct is certainly a good idea. Nonetheless, best practices suggest that every exceptional scenario should also have a test covering it.

One of the reasons we use a datatype to represent errors (instead of just a string) is to make it possible to reliably match against produced errors.

Let’s illustrate this with an example:

This time we used an originateManagedLedger function, which initially allocates a given amount of funds to our wallets.

Left argument in validate means that we expect the scenario to fail, and further goes a predicate on the produced error - failure should indicate “insufficient balance” error and carry a bit of information explaining why.

The full set of unit tests can be found here.

In the presented code snippets, we have slightly simplified function naming compared to the actual implementation for clarity.

Another common approach involves state machine tests, in which we reimplement the contract logic in the simplest possible way using our favorite language.

Next, we will ensure that these implementations behave the same way on arbitrary sequences of calls to our contract. We have implemented such tests for simpler contracts, and the Managed Ledger is the next in line.

Conclusion (and Next Steps)

Assets offer a prime use case for smart contract platforms. Establishing a common interface is crucial for a wide range of projects and businesses that want to create and manage assets on Tezos. It’s worth noting that the interface standard and implementation described throughout this piece are our initial proposals.

We also demonstrate Lorentz development using this sample contract, and how our testing framework can be used to write tests for Lorentz contracts.

This work, at its core, is about more than a standard proposal. Rather, it is a step towards extending Tezos infrastructure and making it more developer-friendly and sustainable for the long run.

We also intend to build on this work by contributing to future asset standards (e.g. taking some inspiration from ERC-777 or ERC-1155) and writing new implementations which both expand functionality and improve on this initial work.