Asentum

Build on Asentum

Writing Contracts

Start here · Estimated read time: 14 minutes

TL;DR

An Asentum contract is one plain JavaScript script whose last expression is an object literal. The object's methods are the contract's callable methods. Seven injected globals (storage, emit, msg, chain, assert, transfer and E) give you state, logs, call context, block context, checks, payments and cross-contract calls. Everything else is just JavaScript, running inside a Hardened JavaScript sandbox.

Two things catch almost everyone: storage keeps strings only, so you encode numbers and objects yourself, and this is undefined inside methods.

Anatomy of a contract

The smallest useful contract:

// A contract is one script. Its last expression is an object literal,
// and that object's methods are the contract's interface.
const KEY = 'count';

({
  increment() {
    const next = BigInt(storage.get(KEY) || '0') + 1n;
    storage.set(KEY, next.toString());
    emit('Incremented', { value: next.toString() });
    return next.toString();
  },

  get() {
    return storage.get(KEY) || '0';
  },
});
  • Constants and helper functions can sit above the object. Only the object's own methods are callable from outside.
  • The parentheses around the object matter: without them, { starts a block, not an object.
  • A file of top-level function declarations with no object at the end deploys, but every call then fails with contract did not export an object interface. export, import and Solidity-style contract X { } are syntax errors and the deploy fails.
  • Methods run synchronously. Do not make them async: the VM does not wait for a Promise, so work after an await is not part of the call.
  • Inside a method, this is undefined. Use msg.contractAddress for the contract's own address, and call helpers directly rather than through this.
  • Any method can be read for free with POST /view on the RPC host (or the SDK's viewCall). A view runs the method and throws its writes away. To change state, send a signed transaction, which costs gas.

The injected globals

These are all the VM adds to the sandbox. There is no cron, console, Date.now() or Math.random().

GlobalWhat it is
storageget, set, delete, has and keys over this contract's key-value store. Values are strings.
emit(name, data)Record an event in the receipt. data must be JSON-serialisable (BigInts become decimal strings).
msgsender, value and contractAddress for the current call.
chainblockNumber, blockTimestamp (milliseconds) and chainId. All BigInt.
assert(condition, message)Throw Error(message) when condition is falsy.
transfer(to, amount)Send ASE from this contract's balance. Settled after the call returns; the whole call reverts if the balance is short.
E(address)Call another contract: E(addr).method(...args) returns its result. E(addr, { value }) sends ASE with the call.

The storage API

Each contract gets its own key-value store. Keys and values are strings. storage.set runs String(value) on whatever you pass, so anything that is not already a string is converted on the way in, and storage.get always hands back a string (or undefined). This happens at once, not only after the transaction: a get right after a set in the same call already returns the string.

  • storage.get(key) returns the stored string, or undefined if the key is unset.
  • storage.set(key, value) stores String(value).
  • storage.delete(key) removes the key and returns true if it existed.
  • storage.has(key) returns whether the key is set.
  • storage.keys(prefix) lists keys. See Listing keys.

What a value looks like when you read it back:

You writestorage.get(k) returns
storage.set(k, 'hello')'hello'
storage.set(k, 42)'42'
storage.set(k, true)'true'
storage.set(k, 7n)'7'
storage.set(k, [1, 2, 3])'1,2,3'
storage.set(k, { a: 1, b: 'two' })'[object Object]' (the data is gone)
storage.get(unsetKey)undefined

Watch out for +. Because the value comes back as a string, storage.get(k) + 1n is string concatenation: a stored '7' becomes '71', with no error. The same goes for + 1. Always convert first: BigInt(storage.get(k) || '0') + 1n. Likewise 'false' is a non-empty string and so is truthy, which means if (storage.get('paused')) is true for a stored false.

Gas: a read or has costs 800, writing a new key 20,000, updating an existing key 2,900, and a delete 5,000. A write costs the same whatever the size of the value. See the fee market for how gas is priced.

Storing numbers and objects

Encode on write and decode on read. The patterns that every production contract on Asentum uses:

// BigInt: store the decimal string, parse with BigInt().
const bal = BigInt(storage.get('bal:' + who) || '0');
storage.set('bal:' + who, (bal + amount).toString());

// Booleans: store a fixed string and compare against it.
storage.set('paused', 'true');
const paused = storage.get('paused') === 'true';

// Objects and arrays: JSON.stringify and JSON.parse.
// JSON.stringify throws on a BigInt, so keep BigInt fields as strings.
storage.set('order:' + id, JSON.stringify({ id, amount: amount.toString(), filled: false }));
const order = JSON.parse(storage.get('order:' + id));
const orderAmount = BigInt(order.amount);

If you store many structured values, two small helpers keep it tidy. The replacer turns every BigInt into a decimal string, so you can pass objects with BigInt fields straight in. They come back as strings, so wrap them in BigInt() where you need numbers again.

function save(key, value) {
  storage.set(key, JSON.stringify(value, (k, v) => (typeof v === 'bigint' ? v.toString() : v)));
}

function load(key) {
  const raw = storage.get(key);
  return raw === undefined ? undefined : JSON.parse(raw);
}

({
  place(id, amount) {
    save('order:' + id, { id, amount: BigInt(amount), filled: false });
  },
  amountOf(id) {
    return BigInt(load('order:' + id).amount);
  },
});

Changing a decoded object does not change storage. After you edit order.filled = true, write it back with storage.set (or save).

Listing keys

storage.keys(prefix) returns an array of every key that starts with prefix, sorted in string order. Leave the prefix out to list every key. It returns keys only; read each value with storage.get. There is no storage.entries.

({
  listOrders() {
    const out = [];
    for (const key of storage.keys('order:')) {
      out.push(JSON.parse(storage.get(key)));
    }
    return out;
  },
});
  • Gas is 800 for the call plus 800 for every key returned, so a large prefix costs real gas. Keep prefixes narrow.
  • The sort is by string, so item:10 comes before item:9. Pad numbers to a fixed width (String(n).padStart(12, '0')) when order matters.
  • Keys written earlier in the same call are included, and deleted keys are left out.

Emitting events

emit('Transfer', { from, to, amount: amount.toString() });

Events are stored in the receipt and queryable via eth_getLogs. Each event becomes one log with a single topic, the BLAKE3 hash of the event name, and the JSON-encoded data as the log's data. Fields are not indexed as separate topics, so filter by name and decode the data. This is how explorers and dapps listen for on-chain activity. The data must be JSON-serialisable; BigInts are written as decimal strings.

msg and chain

msg describes the current call:

  • msg.sender: the caller's address as a lowercase hex string. When another contract calls you through E(), it is that contract's address. In a scheduled run it is the cron registry.
  • msg.value: the ASE sent with the call, in wei, as a BigInt.
  • msg.contractAddress: this contract's own address, lowercase hex. Use it wherever you might reach for this.address.

chain describes the block the call runs in:

  • chain.blockNumber: the block height, a BigInt.
  • chain.blockTimestamp: the block time in milliseconds since the Unix epoch, a BigInt. One day is 86_400_000n.
  • chain.chainId: the chain id, a BigInt (1423 on testnet).

That is all. There is no msg.block, chain.timestamp or chain.baseFee; reading them gives undefined. Because these values are BigInts, mix them only with BigInts: chain.blockTimestamp + 1000n, not + 1000 (that throws a TypeError).

assert and throw

assert(condition, message) throws Error(message) when condition is falsy, and the call reverts. Without a message the error reads assertion failed. It is the same as if (!condition) throw new Error(message).

The check is plain JavaScript truthiness, not a strict true test. assert('false') and assert('0') pass, because they are non-empty strings. assert(0n), assert(''), assert(undefined) and assert(null) fail. Since storage returns strings, compare explicitly:

assert(storage.get('paused') !== 'true', 'paused');
assert(BigInt(storage.get('bal:' + msg.sender) || '0') >= amount, 'insufficient balance');

Any uncaught exception reverts the call: none of its storage writes, events or transfers are kept. Callers see contract method 'name' failed: your message.

Calling other contracts

E(address).method(...args) calls another contract and returns its result directly. It is synchronous: no await.

({
  payout(token, to, amount) {
    const balance = BigInt(E(token).balanceOf(msg.contractAddress));
    assert(balance >= BigInt(amount), 'insufficient');
    E(token).transfer(to, amount);
  },
});
  • E() and transfer() take a hex address and throw on an ase1 string. Pass addresses in as method arguments: the SDK's sendCall and viewCall convert ase1 arguments to hex for you. With raw POST /view, convert them yourself with ase1ArgsToHex.
  • Reentrancy is blocked: a call to a contract that is already on the call stack reverts.
  • E(addr, { value }) sends ASE with the call.
  • If a sub-call throws, the error comes back to you. Catch it to carry on: the failed sub-call's own writes are rolled back. Leave it uncaught and your whole call reverts.

For the mental model, see Smart Contracts.

Constructors and init

Deploying stores the code and does not run anything. By convention a contract has an init method that you call in a normal transaction right after the deploy. Anyone can call it, so guard it against a second call:

({
  init(owner) {
    assert(!storage.has('owner'), 'already initialised');
    storage.set('owner', owner || msg.sender);
  },
});

Send init straight after the deploy so nobody else gets there first. The SDK can bundle deploy and init into one flow.

Scheduled calls

There is no cron global. To have the chain call a method on a schedule, call schedule on the cron registry system contract (ase1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqxgkr943) with ASE attached as gas escrow, either from a wallet or from a contract through E(). Times are in milliseconds. See Scheduled Contract Calls.

Gotchas

  • Storage returns strings. Convert before you compute: BigInt(storage.get(k) || '0'). storage.get(k) + 1n concatenates.
  • Use BigInt for amounts. Numbers are never safe for token math. Use 0n, amount + 1n, and store the result with .toString().
  • Never store an object directly. It becomes '[object Object]'. Use JSON.stringify.
  • No this. It is undefined in methods. Use msg.contractAddress.
  • Time is in milliseconds. chain.blockTimestamp is a BigInt of ms. There is no Date.now() and deliberately no randomness primitive.
  • No fetch, no setTimeout, no filesystem. Contracts are deterministic functions of their inputs. For real-world calls, see Vault and Workers.
  • Throw to revert. Any uncaught exception reverts the call. Use descriptive messages.

For the complete list of allowed language features, see Hardened JavaScript.

A worked example: tip jar

({
  init() {
    assert(!storage.get('owner'), 'already initialised');
    storage.set('owner', msg.sender);
    storage.set('total', '0');
  },

  tip() {
    assert(msg.value > 0n, 'send some ASE');
    const total = BigInt(storage.get('total')) + msg.value;
    storage.set('total', total.toString());
    emit('Tipped', { from: msg.sender, amount: msg.value.toString() });
  },

  withdraw() {
    assert(msg.sender === storage.get('owner'), 'not owner');
    const total = BigInt(storage.get('total'));
    assert(total > 0n, 'nothing to withdraw');
    storage.set('total', '0');
    transfer(msg.sender, total);
    emit('Withdrawn', { to: msg.sender, amount: total.toString() });
  },

  getTotal() {
    return storage.get('total') || '0';
  },
});

Try it live in the IDE. Ready to deploy for real? See Deploy Your First Contract.

Read next