Build on Asentum
Build a Token Contract
End-to-end tutorial · Estimated read time: 15 minutes
What we're building
A fully functional fungible token — the Asentum equivalent of an ERC-20. By the end of this guide you'll have a token contract deployed on the testnet with mint, transfer, approve, transferFrom, and all the standard view methods. Plain JavaScript, no compiler, no Solidity.
Prerequisites: you should have read Writing Contracts and have the SDK installed (npm i @asentum/sdk).
The contract
Here's the complete token contract. We'll break down every method below.
// AsentumToken: an ARC-20 compatible fungible token.
//
// A contract is a script whose last expression is an object.
// Its methods are what callers can invoke. Storage values are
// strings, so amounts are stored as decimal strings and read
// back with BigInt().
const ZERO = '0x' + '0'.repeat(40); // the mint "from" address
function bal(addr) {
return BigInt(storage.get('bal:' + addr) || '0');
}
({
// init is an ordinary method. It does not run at deploy, so call it
// once right after deploying, and guard it against a second call.
init(name, symbol, decimals) {
assert(!storage.has('initialized'), 'already initialized');
storage.set('initialized', '1');
storage.set('owner', msg.sender);
storage.set('name', String(name || 'AsentumToken'));
storage.set('symbol', String(symbol || 'ATK'));
storage.set('decimals', String(decimals ?? 18));
storage.set('totalSupply', '0');
},
mint(to, amount) {
assert(msg.sender === storage.get('owner'), 'only owner can mint');
const amt = BigInt(amount);
assert(amt > 0n, 'amount must be positive');
storage.set('bal:' + to, (bal(to) + amt).toString());
const supply = BigInt(storage.get('totalSupply'));
storage.set('totalSupply', (supply + amt).toString());
emit('Transfer', { from: ZERO, to, amount: amt.toString() });
},
transfer(to, amount) {
const sender = msg.sender;
const amt = BigInt(amount);
assert(amt > 0n, 'amount must be positive');
const senderBal = bal(sender);
assert(senderBal >= amt, 'insufficient balance');
storage.set('bal:' + sender, (senderBal - amt).toString());
storage.set('bal:' + to, (bal(to) + amt).toString());
emit('Transfer', { from: sender, to, amount: amt.toString() });
return true;
},
approve(spender, amount) {
const amt = BigInt(amount);
storage.set('allow:' + msg.sender + ':' + spender, amt.toString());
emit('Approval', { owner: msg.sender, spender, amount: amt.toString() });
return true;
},
transferFrom(from, to, amount) {
const amt = BigInt(amount);
const key = 'allow:' + from + ':' + msg.sender;
const allowed = BigInt(storage.get(key) || '0');
assert(allowed >= amt, 'allowance exceeded');
const fromBal = bal(from);
assert(fromBal >= amt, 'insufficient balance');
storage.set('bal:' + from, (fromBal - amt).toString());
storage.set('bal:' + to, (bal(to) + amt).toString());
storage.set(key, (allowed - amt).toString());
emit('Transfer', { from, to, amount: amt.toString() });
return true;
},
// View methods (free through /view, no gas)
balanceOf(address) { return storage.get('bal:' + address) || '0'; },
allowance(owner, spender) { return storage.get('allow:' + owner + ':' + spender) || '0'; },
name() { return storage.get('name'); },
symbol() { return storage.get('symbol'); },
decimals() { return Number(storage.get('decimals')); },
totalSupply() { return storage.get('totalSupply'); },
})Storage patterns
Asentum contracts have a flat key-value store. Token contracts use prefixed keys to namespace different types of data:
| Key pattern | Value | Example |
|---|---|---|
| bal:ADDRESS | Balance (string bigint) | bal:<address> → "1000000" |
| allow:OWNER:SPENDER | Approved spending limit | allow:<owner>:<spender> → "500" |
| name | Token name | "AsentumToken" |
| symbol | Token symbol | "ATK" |
| decimals | Decimal places | "18" |
| totalSupply | Current total supply | "1000000000" |
| owner | Deployer address | <deployer address> |
Always use BigInt for amounts. JavaScript Numbers lose precision above 253. Token balances in wei routinely exceed that. Store as strings, compute as BigInt. Storage only holds strings: storage.set(k, 7n) stores "7", and storage.get(k) + 1n then gives "71", not 8n. Always wrap reads in BigInt(storage.get(k) || '0').
Events
Two events, same as ERC-20:
Transfer { from, to, amount }— emitted on every mint, transfer, and transferFrom.Approval { owner, spender, amount }— emitted on every approve.
These are indexable via eth_getLogs and visible in the explorer's transaction detail.
Testing locally
import { test, expect } from 'vitest';
import { Vm } from '@asentum/vm';
import { readFileSync } from 'node:fs';
const source = readFileSync('./contracts/token.js', 'utf8');
// Storage adapter: the VM reads and writes strings through it.
class MemoryStorage {
data = new Map();
get(k) { return this.data.get(k); }
set(k, v) { this.data.set(k, v); }
delete(k) { return this.data.delete(k); }
has(k) { return this.data.has(k); }
keys(prefix = '') { return [...this.data.keys()].filter((k) => k.startsWith(prefix)).sort(); }
}
// Inside the VM, addresses are lowercase hex strings.
const ALICE = '0x' + 'a1'.repeat(20);
const BOB = '0x' + 'b0'.repeat(20);
const CAROL = '0x' + 'c0'.repeat(20);
function setup() {
const vm = new Vm();
const storage = new MemoryStorage();
const as = (sender) => (method, args = []) =>
vm.call({
source, storage, gasLimit: 1_000_000n,
context: { sender, contractAddress: '0x' + '22'.repeat(20), value: 0n,
blockNumber: 1n, blockTimestamp: 1_760_000_000_000n, chainId: 1423n },
}, method, args).returnValue;
return as;
}
test('mint and transfer', () => {
const as = setup();
as(ALICE)('init', ['TestToken', 'TST', 18]); // Alice is the owner
as(ALICE)('mint', [ALICE, '1000']);
expect(as(ALICE)('balanceOf', [ALICE])).toBe('1000');
expect(as(ALICE)('totalSupply')).toBe('1000');
as(ALICE)('transfer', [BOB, '300']);
expect(as(ALICE)('balanceOf', [ALICE])).toBe('700');
expect(as(ALICE)('balanceOf', [BOB])).toBe('300');
});
test('approve + transferFrom', () => {
const as = setup();
as(ALICE)('init', ['TestToken', 'TST', 18]);
as(ALICE)('mint', [ALICE, '1000']);
as(ALICE)('approve', [BOB, '500']);
expect(as(ALICE)('allowance', [ALICE, BOB])).toBe('500');
as(BOB)('transferFrom', [ALICE, CAROL, '200']);
expect(as(ALICE)('balanceOf', [CAROL])).toBe('200');
expect(as(ALICE)('allowance', [ALICE, BOB])).toBe('300');
expect(() => as(BOB)('mint', [BOB, '1'])).toThrow('only owner can mint');
});Run with pnpm vitest. Tests run in-process: no network, millisecond feedback. @asentum/vm is not on npm yet; build it from the AsentumChain repo. See Testing Contracts.
Deploying to testnet
import { AsentumClient, AsentumWallet } from '@asentum/sdk';
import { readFileSync } from 'node:fs';
const client = new AsentumClient('https://explorer.asentum.com');
const wallet = AsentumWallet.create(client);
await wallet.requestFaucet();
const source = readFileSync('./contracts/token.js', 'utf8');
const token = await wallet.deploy(source);
console.log('deployed at:', token.address);
// Initialize
await (await token.send('init', ['MyToken', 'MTK', 18])).wait();
// Mint 1,000,000 tokens to yourself
const amount = (1_000_000n * 10n ** 18n).toString();
await (await token.send('mint', [wallet.address, amount])).wait();
console.log('balance:', await token.view('balanceOf', [wallet.address]));Interacting with your token
Once deployed, anyone can interact with it:
// Read (free — no gas, no signing)
const name = await token.view('name');
const supply = await token.view('totalSupply');
const bal = await token.view('balanceOf', ['ase1…']);
// Write (costs gas — needs a connected wallet)
await (await token.send('transfer', ['ase1…recipient', '500'])).wait();
await (await token.send('approve', ['ase1…spender', '1000'])).wait();You can also interact from the IDE — paste your contract address, connect a wallet, and call any method from the browser.
Viewing on the explorer
Navigate to explorer.asentum.com/address/YOUR_CONTRACT_ADDRESS. You'll see:
- The full JavaScript source, syntax-highlighted.
- A Read panel — call
name(),balanceOf(), etc. for free. - A Write panel — send transactions via your connected wallet.
- Every transfer shows as a
Transferevent in the transaction detail. No bytecode decoding needed — it's plain JSON.
Verification is a single BLAKE3 hash compare — see Verifying Contracts.
Next in the series