Skip to main content

Accessing assets

· 3 min read
Guillaume Duhamel

We present an improvement in the way assets data are accessed in version 1.3.0.

Problems

Until this version, the only way to access an asset data was the field accessor operator of the form A[k].f, where A is the asset collection, k the asset key and f the asset field.

The first problem was the access to multiple fields; for example, consider the following asset declaration:

asset vehicle {
vin : string;
manufacturer : string;
year : nat;
nbdoors : nat
}

Accessing several fields would end up accessing the underlying map several times:

const k = "1G1AF1F57A7192174";
const m = vehicle[k].manufacturer;
const y = vehicle[k].year;
const n = vehicle[k].nbdoors

Here the test and fail instructions are repeated three times.

The second problem is the implicit fail of the [] operator in situations where it is implicit that the asset exists.

It is typically the case when the asset field is accessed in the true branch of a contains test:

const k = "1G1AF1F57A7192174";
if vehicle.contains(k) then begin
const m = vehicle[k].manufacturer;
/* ... do something with m ... */
end

The []. operator treats the case when asset is not found while it has already been tested.

Solution

Version 1.3.0 provides new operator [] that returns an option of asset value.

Combined with the new ?= declaration instruction, the proper way to retrieve all vehicle data presented above, is now as follows:

const v ?= vehicle["1G1AF1F57A7192174"];
const m = v.manufacturer;
const y = v.year;
const n = v.nbdoors

The declaration of v fails with "OPTION_IS_NONE" if vehicle is not found. It is possible to specify an error message with:

const v ?= vehicle["1G1AF1F57A7192174"] : "VEHICLE_NOT_FOUND"

Single field access

Situations where a single asset field is accessed is very common though.

Version 1.3.0 provides a new operator []?. that returns an option of field value, so that the non existence case may be explicitely treated.

For example, the following retrieves an option of nat to treat more specifically the case when the asset is not found:

const opt_n = vehicle["1G1AF1F57A7192174"]?.nbdoors;
/* treat case when on is none ... */

opt_n is typed option<nat> and is none if the vehicle is not found.

Operator []. is still available: it fails when asset is not found, which is syntactically convenient when there is an implicit existence invariant on the asset:

const n = vehicle["1G1AF1F57A7192174"].nbdoors;

It implictely fails with ("ASSET_NOT_FOUND", "vehicle") if "1G1AF1F57A7192174" is not found.