Build on Asentum
Build a Messaging System
Multi-contract tutorial · Estimated read time: 20 minutes
What we're building
An on-chain messaging system where users register usernames, send messages to each other, and read their inbox — all through smart contracts. We'll build two contracts:
- UserRegistry — maps wallet addresses to usernames (and back). A reusable identity layer.
- DirectMessages — stores, indexes, and retrieves messages between addresses.
This tutorial shows modular contract design on Asentum. Each contract handles one concern. The frontend (covered in the next guide) ties them together via the SDK.
Two contracts, one app
┌─────────────────┐ ┌─────────────────────┐
│ UserRegistry │ │ DirectMessages │
│ │ │ │
│ register() │ │ send() │
│ getUsername() │◄────│ getInbox() │
│ getAddress() │ SDK │ getOutbox() │
│ getUserCount() │reads│ getConversation() │
└─────────────────┘ └─────────────────────┘
▲ ▲
│ Frontend │
└────── orchestrates ────┘In this tutorial the contracts don't call each other directly — the frontend reads from both and orchestrates the flow. (They could use E(addr).method() for on-chain cross-calls, but frontend orchestration is a useful pattern to learn.) When a user sends a message to "alice", the frontend:
- Calls
registry.view('getAddress', ['alice'])to resolve the username. - Calls
messages.send('send', [resolvedAddress, content])to deliver the message.
This is how many production dApps compose contracts — atomic stores orchestrated by application logic. It's clean, testable, and each contract is independently deployable and reusable. For on-chain composition, Asentum also supports direct cross-contract calls via E() with a VM-enforced reentrancy guard — see Writing Contracts.
Contract 1: UserRegistry
// UserRegistry: two-way address <-> username mapping.
// The last expression is the object whose methods callers can invoke.
({
// init does not run at deploy: call it once afterwards.
init() {
assert(!storage.has('initialized'), 'already initialized');
storage.set('initialized', '1');
storage.set('userCount', '0');
},
register(username) {
const sender = msg.sender;
const name = String(username).toLowerCase().trim();
// Validation
assert(name.length >= 3, 'username must be at least 3 characters');
assert(name.length <= 20, 'username must be at most 20 characters');
assert(/^[a-z0-9_]+$/.test(name), 'username: only a-z, 0-9, underscore');
assert(!storage.has('user:' + sender), 'address already registered');
assert(!storage.has('name:' + name), 'username already taken');
// Store the mapping both ways
storage.set('user:' + sender, name);
storage.set('name:' + name, sender);
// Increment the counter (storage holds strings, so convert both ways)
const count = BigInt(storage.get('userCount') || '0') + 1n;
storage.set('userCount', count.toString());
emit('Registered', { address: sender, username: name });
},
// View methods
getUsername(address) { return storage.get('user:' + address) || null; },
getAddress(username) { return storage.get('name:' + String(username).toLowerCase()) || null; },
getUserCount() { return storage.get('userCount') || '0'; },
isRegistered(address) { return storage.has('user:' + address); },
})Key patterns:
- Bidirectional mapping —
user:ADDRESS → usernameandname:USERNAME → address. Two keys per registration, but O(1) lookup in both directions. - Guard clauses —
assert(!storage.has(...))prevents double-registration. A wallet can register once. A username can be claimed once. - Input normalization — lowercase + trim so "Alice" and "alice" resolve to the same account.
- Regex validation — only alphanumeric + underscore. No special chars, no spaces, no emoji.
Contract 2: DirectMessages
// DirectMessages: stores and indexes messages between addresses.
function readList(key) {
return JSON.parse(storage.get(key) || '[]');
}
function readMessage(id) {
return JSON.parse(storage.get('msg:' + id) || 'null');
}
({
init() {
assert(!storage.has('initialized'), 'already initialized');
storage.set('initialized', '1');
storage.set('messageCount', '0');
},
send(to, content) {
const text = String(content).trim();
assert(text.length > 0, 'message cannot be empty');
assert(text.length <= 500, 'message too long (max 500 chars)');
assert(to !== msg.sender, 'cannot message yourself');
// Storage only holds strings, so the message is stored as JSON.
// BigInts go in as decimal strings. blockTimestamp is in milliseconds.
const id = storage.get('messageCount') || '0';
const message = JSON.stringify({
id,
from: msg.sender,
to,
content: text,
timestamp: chain.blockTimestamp.toString(),
block: chain.blockNumber.toString(),
});
// Store the message by ID
storage.set('msg:' + id, message);
// Append the ID to the recipient's inbox
const inbox = readList('in:' + to);
inbox.push(id);
storage.set('in:' + to, JSON.stringify(inbox));
// Append the ID to the sender's outbox
const outbox = readList('out:' + msg.sender);
outbox.push(id);
storage.set('out:' + msg.sender, JSON.stringify(outbox));
// Increment the global counter
storage.set('messageCount', (BigInt(id) + 1n).toString());
emit('MessageSent', { id, from: msg.sender, to });
},
// View methods
getMessage(id) {
return readMessage(id);
},
getInbox(address) {
return readList('in:' + address).map(readMessage).filter(Boolean);
},
getOutbox(address) {
return readList('out:' + address).map(readMessage).filter(Boolean);
},
getConversation(addrA, addrB) {
// Merge A's inbox and outbox, dedupe, keep messages between A and B, sort by block.
const allIds = [...new Set([...readList('in:' + addrA), ...readList('out:' + addrA)])];
return allIds
.map(readMessage)
.filter(m => m && ((m.from === addrA && m.to === addrB) || (m.from === addrB && m.to === addrA)))
.sort((a, b) => Number(BigInt(a.block) - BigInt(b.block)));
},
getMessageCount() { return storage.get('messageCount') || '0'; },
})Storage patterns for lists
Storage values are always strings. storage.set(k, [1, 2]) stores "1,2" and an object becomes "[object Object]", so lists and records must be stored as JSON. The DirectMessages contract uses a JSON-array-in-a-key pattern:
// Reading the list
const inbox = JSON.parse(storage.get('in:' + address) || '[]');
// Appending to the list
inbox.push(newMessageId);
storage.set('in:' + address, JSON.stringify(inbox));Tradeoff: this is O(n) on the list size per write (re-serialize the whole array). For a messaging app with thousands of messages per user, you'd want a linked-list or pagination pattern. For a tutorial and low-volume use, the JSON array is fine and readable.
The message itself is stored separately at msg:ID. The inbox/outbox arrays store only IDs — lightweight references. View methods resolve the IDs into full message objects at read time.
Testing both contracts
import { test, expect } from 'vitest';
import { Vm } from '@asentum/vm';
import { readFileSync } from 'node:fs';
const registrySource = readFileSync('./contracts/user-registry.js', 'utf8');
const messagesSource = readFileSync('./contracts/direct-messages.js', 'utf8');
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(); }
}
// Each contract gets its own storage. Inside the VM, addresses are
// lowercase hex strings (the SDK converts ase1 arguments for you on chain).
function contract(source, address) {
const vm = new Vm();
const storage = new MemoryStorage();
return (sender) => (method, args = []) =>
vm.call({
source, storage, gasLimit: 1_000_000n,
context: { sender, contractAddress: address, value: 0n,
blockNumber: 1n, blockTimestamp: 1_760_000_000_000n, chainId: 1423n },
}, method, args).returnValue;
}
const ALICE = '0x' + 'a1'.repeat(20);
const BOB = '0x' + 'b0'.repeat(20);
test('register + send + read inbox', () => {
const registry = contract(registrySource, '0x' + '01'.repeat(20));
const messages = contract(messagesSource, '0x' + '02'.repeat(20));
registry(ALICE)('init');
messages(ALICE)('init');
// Register two users
registry(ALICE)('register', ['alice']);
registry(BOB)('register', ['bob']);
// Resolve username to address
const bobAddr = registry(ALICE)('getAddress', ['bob']);
expect(bobAddr).toBe(BOB);
// Alice sends Bob a message
messages(ALICE)('send', [bobAddr, 'Hey Bob!']);
// Bob's inbox has 1 message
const inbox = messages(BOB)('getInbox', [BOB]);
expect(inbox).toHaveLength(1);
expect(inbox[0].content).toBe('Hey Bob!');
expect(inbox[0].from).toBe(ALICE);
// Conversation view
expect(messages(BOB)('getConversation', [ALICE, BOB])).toHaveLength(1);
});
test('username validation', () => {
const registry = contract(registrySource, '0x' + '01'.repeat(20));
registry(ALICE)('init');
expect(() => registry(ALICE)('register', ['ab'])).toThrow('at least 3');
expect(() => registry(ALICE)('register', ['hello world'])).toThrow('only a-z');
});Deploying the pair
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();
// Deploy UserRegistry
const registrySrc = readFileSync('./contracts/user-registry.js', 'utf8');
const registry = await wallet.deploy(registrySrc);
await (await registry.send('init')).wait();
console.log('registry:', registry.address);
// Deploy DirectMessages
const messagesSrc = readFileSync('./contracts/direct-messages.js', 'utf8');
const messages = await wallet.deploy(messagesSrc);
await (await messages.send('init')).wait();
console.log('messages:', messages.address);
// Save these addresses — the frontend needs them.
console.log(JSON.stringify({
registry: registry.address,
messages: messages.address,
}));Save the two contract addresses. The frontend guide uses them to connect the SDK to both contracts.
Using them together
import { AsentumClient, AsentumContract } from '@asentum/sdk';
const client = new AsentumClient('https://explorer.asentum.com');
const registry = new AsentumContract(client, REGISTRY_ADDRESS);
const messages = new AsentumContract(client, MESSAGES_ADDRESS);
// Register a username (needs a wallet for signing)
const withSigner = registry.connect(wallet);
await (await withSigner.send('register', ['alice'])).wait();
// Resolve a username and send a message
const bobAddr = await registry.view('getAddress', ['bob']);
if (!bobAddr) throw new Error('user "bob" not found');
const msgContract = messages.connect(wallet);
await (await msgContract.send('send', [bobAddr, 'Hello from Alice!'])).wait();
// Read inbox
const inbox = await messages.view('getInbox', [wallet.address]);
console.log('inbox:', inbox);This is the pattern the frontend uses: resolve names via one contract, act via another. The SDK makes both calls look identical — the only difference is which contract address you point at.
Next in the series