Skip to content
Open app

SDK and APISDK reference

SDK reference

Every export of the SDK, every method of a client, their options, progress stages, results and errors.

Everything on this page is imported from @talaria/sdk. The SDK quickstart shows the methods in order of use.

TypeScript
import { createTalaria, createKeypairSigner, TalariaError, type Talaria } from '@talaria/sdk'

Amounts are lamports as decimal strings, Log positions, slots and days are decimal strings, keys and ciphertexts are base64, addresses and signatures are base58, and times are UTC ISO strings.

How a client behaves#

Keys. A client derives its keys the first time a call needs them, from one wallet signature (see unlock). Every method below except wallet, unlocked, inbox, findInbox, lookup, syncDirectory, directoryReady, countParts, prove, demoProof and close unlocks first, so the first such call opens the wallet's signing prompt.

One operation at a time. buyPass, send, retry, createRoom, addRoomMember, removeRoomMember, leaveRoom, createPrivateLink and revokePrivateLink run one after another on a client, in the order they were called. A second send waits for the first to finish, so two messages never pick the same counter. Reads run at once.

Waiting for the Log. Calls that change the chain return after the API has read the change back: the new key in the inbox directory after openInbox and rotateInboxKey, a pool leaf after buyPass, a Log entry after each part of send. They poll every 600 ms.

Inboxes and names. The client reads every Inbox, its own included, from its own copy of the inbox directory: every open_inbox and rotate_inbox_key, downloaded whole from GET /inboxes/head and GET /inboxes/segments/:n and folded on the device (see syncDirectory). A .sol name resolves on the device too, through the nameService option (see lookup). No request names a wallet the device looks up, writes to or hears from, or a name it resolves.

Relays. A post goes to the relay in SendOptions.relayUrl if given. Otherwise the list is TalariaOptions.relayUrls, or the endpoints GET /relays lists, and each part starts at the next relay in that list in turn, then tries the others in list order after it. When a relay fails, the client first looks for the part's nullifier in the Log: if the post landed, the part counts as landed. Otherwise, if the failure is retryable or the relay could not be reached, it proves again for the next relay with the same payload and the same nullifier. A retry never spends a new counter.

Storage. A client keeps one record per wallet in its EncryptedStorage, under the wallet's address: messages, threads, rooms and their keys, private links, blocked wallets, pass purchases, pending messages and the scan position. The record is sealed with XChaCha20-Poly1305 under the local history key before it is written, and written after every change. Pass secrets are never stored; they are derived again. The default store is IndexedDB in a browser and memory in Node.

Errors. A method throws a TalariaError for what the client decides itself (no pass, no inbox, a rejected signature), and an ApiClientError from @talaria/contract carrying the API's or the relay's error envelope. Both carry a code; SDK errors and API errors give every code. A progress callback's failed stage carries the same failure as an SdkFailure.

TypeScript
import { TalariaError, type Talaria } from '@talaria/sdk'
import { ApiClientError } from '@talaria/contract'

try {
  await talaria.send(to, text)
} catch (error) {
  if (error instanceof TalariaError) console.error(error.code, error.retryable, error.message)
  else if (error instanceof ApiClientError) console.error(error.status, error.code, error.body.error.stage)
  else throw error
}

createTalaria#

TypeScript
function createTalaria(options: TalariaOptions): Talaria

Creates a client for one wallet. It makes no network call and asks for no signature; it throws a validation error if signer.address is not a base58 address.

apiUrlstring
The API's base URL. Development default http://127.0.0.1:6710.

Required

signerWalletSigner
The wallet that signs. See WalletSigner.

Required

relayUrlsreadonly string[]
Relay base URLs, tried in order. Development defaults http://127.0.0.1:6711 and http://127.0.0.1:6712. Without it the client uses the endpoints from GET /relays.
storageEncryptedStorage
Where the encrypted local record is kept.

Default IndexedDB or memory

fetchtypeof fetch
The fetch used for the API, the relays and a verification key URL.

Default globalThis.fetch

proverProverArtifacts
The circuit files. Required by send, retry, room calls, createPrivateLink, revokePrivateLink, prove and demoProof.
appUrlstring
The app origin private link URLs are made on.

Default http://127.0.0.1:6700

nameServiceNameService
Where .sol names resolve: 'local', the local build's table LOCAL_NAMES; 'sns', the SPL Name Service read over rpcUrl; or a table of your own, name to address. See resolveName.

Default 'local'

rpcUrlstring
The client's own Solana RPC. Used only to read SPL Name Service accounts when nameService is 'sns'; every other chain read and write goes through the API.

Returns a Talaria client.

Talaria#

The client createTalaria returns. Each method has its own section below.

MemberKindSection
wallet, unlockedpropertieswallet, unlocked
unlock, inbox, findInbox, syncDirectory, directoryReady, lookup, openInbox, rotateInboxKeykeys and inboxesunlock
buyPass, passespassesbuyPass
send, retry, pendingMessages, countPartssendingsend
scan, restorereadingscan
threads, messages, acceptRequest, blockWallet, unblockWallet, blocked, markReadthreadsthreads
rooms, createRoom, acceptRoom, declineRoom, addRoomMember, removeRoomMember, leaveRoomroomsrooms
privateLinks, createPrivateLink, revokePrivateLinkprivate linksprivateLinks
prove, demoProof, closeproofs and lifetimeprove

wallet#

TypeScript
readonly wallet: Address

The signer's address, checked when the client was created.

unlocked#

TypeScript
readonly unlocked: boolean

true once this client has derived its keys, false before and after close.

unlock#

TypeScript
unlock(options?: OperationOptions): Promise<DerivedKeys>

Asks the signer to sign the key message once and derives every key from the signature. The message is the UTF-8 text keyDerivationMessage returns. The client then finds the wallet's Inbox in a fresh copy of the inbox directory to learn its key version, derives the inbox key of that version and of every earlier version (older keys open older messages), and opens the stored record. A second call returns the same keys without a prompt.

Returns DerivedKeys. Throws WALLET_REJECTED if the signer throws, and the API's error if the inbox directory can't be read.

inbox#

TypeScript
inbox(): Promise<Inbox | null>

The wallet's own Inbox, or null before it is opened: findInbox for this wallet with fresh, so the directory is brought up to date first. It needs no signature.

findInbox#

TypeScript
findInbox(wallet: Address, options?: OperationOptions & { fresh?: boolean }): Promise<Inbox | null>

Any wallet's Inbox, with its key history, or null when the wallet has not opened one. It answers from this client's copy of the inbox directory, and syncs it first with syncDirectory when the copy is empty, when fresh is set, or when the wallet is not in the copy and the copy is more than 2 seconds old. No request names the wallet. It needs no signature and no keys.

freshboolean
Sync the directory before answering.

Default false

signalAbortSignal
Aborts the sync.
TypeScript
const inbox = await talaria.findInbox(wallet)
if (inbox) console.log(inbox.keyVersion, inbox.inboxKey)

send, scan and the room calls use it for every wallet they look up; unlock, inbox, openInbox and rotateInboxKey use it with fresh for the client's own wallet. Throws the API's error if the directory can't be read.

syncDirectory#

TypeScript
syncDirectory(options?: DirectoryOptions): Promise<void>

Brings this client's copy of the inbox directory up to date. It reads GET /inboxes/head, downloads each sealed segment it does not hold yet from GET /inboxes/segments/:n, takes the head's tail, and folds every event in order into each wallet's Inbox: the latest event sets the key and version, and each key is valid from its event's slot until the slot of the wallet's next event. A sealed segment is downloaded once per client. The copy lives in memory, so a new client downloads it again. A call made while a sync is running waits for that sync. It needs no signature and no keys.

onProgress(progress: { loadedEvents: U64; totalEvents: U64 }) => void
Called after each sealed segment, and once at the end with loadedEvents equal to totalEvents.
signalAbortSignal
Aborts the download.

Call it when an app starts, so the directory is on the device before the first lookup:

TypeScript
await talaria.syncDirectory({
  onProgress: ({ loadedEvents, totalEvents }) => console.log(loadedEvents, '/', totalEvents),
})
console.log(talaria.directoryReady)

Throws the API's error if the head or a segment can't be read.

directoryReady#

TypeScript
readonly directoryReady: boolean

true once a sync of the inbox directory has finished on this client, through syncDirectory or any call that syncs. It stays true.

lookup#

TypeScript
lookup(query: string, options?: OperationOptions): Promise<LookupResult>

What someone typed, a wallet address or a .sol name, resolved on the device with its inbox state. The query is trimmed. One ending in .sol is lowercased, checked as a .sol name and resolved through resolveName with the client's nameService and rpcUrl; anything else must be a base58 address. The wallet's Inbox then comes from findInbox. Neither the name nor the wallet reaches the API.

statusOther fieldsWhen
foundwallet, name (the .sol name, or null for an address), inbox (Inbox, or null when the wallet has no inbox)The address is valid, or the name has an owner
not_foundquery, nameA valid .sol name with no owner in the name service
invalidqueryNeither a .sol name nor a base58 address
TypeScript
const result = await talaria.lookup('ari.sol')
if (result.status === 'found') console.log(result.wallet, result.inbox ? 'has an inbox' : 'no inbox')

It needs no signature. With nameService: 'sns' and no rpcUrl, a name throws CONFIGURATION_REQUIRED. send and the room calls resolve names through it and throw NAME_NOT_FOUND for any result other than found.

openInbox#

TypeScript
openInbox(options?: TransactionOptions): Promise<InboxResult>

Opens this wallet's inbox with its current inbox key. The API builds the open_inbox transaction, the signer signs it, the API submits it, and the client follows it to confirmation, then waits until the Inbox reads back with this key.

StageWhen
buildingBefore the API builds the transaction
signingThe build is in build; the signer is asked
confirmingSubmitted; repeats with each status read
indexedThe Inbox reads back with the new key
failedAny step failed; error holds it

Returns InboxResult. Throws WALLET_REJECTED, TRANSACTION_EXPIRED (the transaction expired without landing; nothing was spent), CHAIN_REFUSED, and the API's errors for the build or the submission. The wallet pays the Inbox's rent and the fee; Measured figures gives the rent.

rotateInboxKey#

TypeScript
rotateInboxKey(options?: TransactionOptions): Promise<InboxResult>

Moves the inbox to the key of the next version, derived from the same signature, with a rotate_inbox_key transaction. Progress and errors are those of openInbox, plus INBOX_NOT_FOUND when the wallet has no inbox. After it returns, new messages are written to the new key and the client keeps every older key to open older messages.

buyPass#

TypeScript
buyPass(input: BuyPassInput, options?: TransactionOptions): Promise<Pass>

Buys a pass. The client takes the next unused pass index, derives that pass's secret, and sends its commitment in a buy_pass transaction. It returns once the pass's leaf is in the pool. Runs one at a time with the other exclusive calls.

tierstring
A tier id from GET /pool: light, daily or frequent.

Required

daysnumber
A length from GET /pool, in days.

Required

A pass of days days sends on the day it is bought and on the days - 1 days after it: its expiry day is the purchase day plus days - 1, and that day is included.

Progress stages are those of openInbox; indexed is reported when the leaf is found. Returns the new Pass. Throws VALIDATION_ERROR before any signature if the tier and length are not a price GET /pool lists, then the errors of openInbox. The price is the tier's daily limit times the days times the message fee; Passes covers what a purchase pays.

passes#

TypeScript
passes(): Promise<PassState>

Reads every pool leaf and the whole Log, finds this wallet's passes and today's use of each, and returns them as a PassState. current is the pass send would use: the oldest unexpired pass with a message left today, or when none has one, the newest pass. It is null when the wallet has no pass.

send#

TypeScript
send(to: SendTarget, text: string, options?: SendOptions): Promise<SendReceipt>

Writes text to to and returns when every part is in the Log. Runs one at a time with the other exclusive calls.

toSendTarget
A wallet address, a .sol name, or a target object for a wallet, a room or a private link. See SendTarget.

Required

textstring
The message. Split into parts of at most 700 UTF-8 bytes, one post each.

Required

optionsSendOptions
relayUrl, onProgress, signal. See SendOptions.

For each part the client:

  1. encrypts to the reader's key with two key slots, one for the reader and one for this wallet's own inbox key;
  2. picks the oldest unexpired pass with a message left today and its lowest unused counter;
  3. records the part's payload, pass and counter as an attempt, so a retry reuses them;
  4. proves for a relay, posts, and waits until the API serves the entry.

A wallet target resolves a .sol name first with lookup, then finds the reader's Inbox with findInbox. A room target needs a room this client has joined; the payload is encrypted to the room key and carries a writer tag for each member whose Inbox the directory holds. A private link target encrypts to the link's key.

StageFields beyond part and totalParts
encrypting
proving
relayingrelayUrl, attempt (1-based)
landedsignature
failederror

part is zero-based. proving and relaying repeat for each relay tried.

Returns a SendReceipt. Throws NAME_NOT_FOUND, COUNTERPARTY_NO_INBOX, VALIDATION_ERROR (a room not joined), NO_PASS, PASS_EXPIRED (every pass has expired), DAILY_LIMIT_REACHED, UNKNOWN_ROOT (the leaves and the pool root disagree; retryable), SPENT_NULLIFIER, RELAY_UNAVAILABLE, CONFIGURATION_REQUIRED (no prover), and the relay's refusals (RELAY_MISMATCH, WRONG_DAY, PROOF_INVALID, INVALID_PAYLOAD, PAYLOAD_TOO_LARGE, TRANSACTION_EXPIRED). A failed message is kept in pendingMessages with the parts that landed.

retry#

TypeScript
retry(message: PendingMessage, options?: SendOptions): Promise<SendReceipt>

Sends what is left of a pending message under its original id. Parts that landed are kept and not posted again; a part with a recorded attempt is sent with the same payload, pass and counter, so its nullifier stays the same. A part whose attempt was recorded on a day that has ended is looked up in the Log by that day's nullifier: if it landed, the part counts as landed; if not, the attempt is dropped and the part is posted again today, with a new payload and today's next free counter. Pass relayUrl to choose the relay. Progress, result and errors are those of send.

TypeScript
for (const pending of await talaria.pendingMessages()) {
  const receipt = await talaria.retry(pending)
  console.log(pending.id, receipt.signatures)
}

pendingMessages#

TypeScript
pendingMessages(): Promise<readonly PendingMessage[]>

Messages whose send has not finished, from the stored record: each with its target, text, last progress and landed parts. A message leaves this list when it lands in full.

countParts#

TypeScript
countParts(text: string): number

How many posts text takes, and so how many messages of the day it uses. The same function is exported on its own, with splitParts. It makes no call and needs no keys.

scan#

TypeScript
scan(options?: ScanOptions): AsyncIterable<Message>

Reads the Log and yields every message this client can open. Each round downloads every sealed segment and the head's tail, then tries each entry from the scan position with the inbox keys, the room keys, the keys of unrevoked private links, and the keys of the next private link indexes this device does not hold yet (indexes 0 up to eight past the number of links it holds). A message is yielded once all its parts are found, after its writer's inbox key is checked against the writer's Inbox key history at the entry's slot, read from the inbox directory through findInbox, and its authentication tag is checked. Entries from blocked wallets are dropped.

fromLogIndexU64
The zero-based Log position to start from.

Default the stored position

followboolean
Keep reading new entries after reaching the head, every 1.5 s.

Default false

onProgress(progress: ScanProgress) => void
signalAbortSignal
Stops the scan.
StageWhen
downloadingA round starts downloading the Log
scanningAfter each entry is tried
followingA round ended at the head and follow is set
completeThe round ended at the head and the scan ends

The scan saves its position after each round; a message whose parts are not all in yet is read again from its first part next time. What a message found in the Log changes on the device:

MessageEffect
A room invitation that lists this wallet and its writer as membersAdds the room as invited, or as joined when this wallet wrote the invitation or had already joined. For a room already on the device, it counts only when its writer is a member there and its key version is higher.
A removal notice from a member of a roomSets the room to removed and drops its key.
A message this wallet sent to a roomSets an invited room to joined.
A message this wallet sent to a walletSets a pending thread with that wallet to accepted.
A message opened by a private link key the device did not holdAdds the link, with its index and with the name read from the link URL inside the message.
A link-created note this wallet wrote to itselfAdds the link with its index, name and URL, if the device does not hold that index.
A link-revoked note this wallet wrote to itselfSets that link's revokedAt to the note's send time.
A room key update this wallet wrote that leaves it out of the membersSets the room to left and drops its key: the wallet left from another device.

Throws INDEXER_UNREACHABLE (retryable) when the Log can't be downloaded, and the signal's reason when signal aborts or close is called.

TypeScript
const stop = new AbortController()
setTimeout(() => stop.abort(), 60_000)
try {
  for await (const message of talaria.scan({ follow: true, signal: stop.signal })) console.log(message.text)
} catch (error) {
  if (!stop.signal.aborted) throw error
}

restore#

TypeScript
restore(options?: RestoreOptions): Promise<RestoreResult>

Scans the whole Log from position 0 and finds every pass again. On a new device this brings back every thread and room, sent messages included through their self slot: rooms this wallet created or wrote in come back joined, threads it replied in come back accepted, and private links come back as they were made, names and revocations included, from their notes. Blocked wallets stay on the device they were blocked on. Progress is the scan's. Returns a RestoreResult.

threads#

TypeScript
threads(): Promise<readonly Thread[]>

This device's threads, each with the counterparty's inbox filled from the inbox directory (synced first when this client has no copy yet). A thread is made by the first message in it: one this wallet sent starts accepted, one it received from an unknown wallet starts as a request, pending. A reply this wallet sends in a pending thread makes it accepted.

messages#

TypeScript
messages(threadOrRoomId: string): Promise<readonly Message[]>

The stored messages of one conversation, oldest first. The id is the counterparty's wallet for a thread, the room id for a room, or link: followed by the link's inbox key for messages this device wrote to a private link.

acceptRequest#

TypeScript
acceptRequest(wallet: Address): Promise<void>

Marks the thread with wallet as accepted. Local to this device.

blockWallet#

TypeScript
blockWallet(wallet: Address): Promise<void>

Drops every later message from wallet on this device and marks its thread blocked. Throws a validation error for an address that is not base58.

unblockWallet#

TypeScript
unblockWallet(wallet: Address): Promise<void>

Removes wallet from the blocked list; its thread goes back to pending.

blocked#

TypeScript
blocked(): Promise<readonly Address[]>

The wallets blocked on this device.

markRead#

TypeScript
markRead(threadOrRoomId: string): Promise<void>

Sets the unread count of a thread or room to zero.

rooms#

TypeScript
rooms(): Promise<readonly Room[]>

This device's rooms, in every state. See Rooms.

createRoom#

TypeScript
createRoom(input: CreateRoomInput, options?: RoomOptions): Promise<Room>

Makes a room with a new 32-byte key, joined by this wallet, and sends the key to every other member as a message in their thread: one message each from this wallet's pass. The invitation carries the room's id, name and key version, and each member's wallet and name only. Members are wallet addresses or .sol names, and each needs an inbox. Runs one at a time with the other exclusive calls.

Progress: resolving, then sending-invites before each invitation with completed, total and member, then done. onSendProgress receives each invitation's SendProgress. Returns the Room. Throws the errors of send.

TypeScript
const room = await talaria.createRoom({ name: 'Crew', members }, {
  onProgress: ({ stage, completed, total }) => console.log(stage, completed, '/', total),
})
await talaria.send({ kind: 'room', roomId: room.id }, 'Hello, room')

acceptRoom#

TypeScript
acceptRoom(roomId: string): Promise<Room>

Joins a room this device was invited to; it can then send to it. Throws NOT_FOUND for an unknown room.

declineRoom#

TypeScript
declineRoom(roomId: string): Promise<void>

Sets an invited room to declined.

addRoomMember#

TypeScript
addRoomMember(roomId: string, member: Address | `${string}.sol`, options?: RoomOptions): Promise<Room>

Adds a member, raises the room's key version and sends the room key to every other member, the new one included, one message each. Throws NOT_FOUND and the errors of send.

removeRoomMember#

TypeScript
removeRoomMember(roomId: string, member: Address, options?: RoomOptions): Promise<Room>

Removes a member and makes a new room key. Progress reports rotating-key first. The client then sends the removed wallet a removal notice, one message, and sends the new key to the remaining members, one message each, reported as in createRoom. The removed wallet's device sets the room to removed when its scan finds the notice; it keeps the old key and opens nothing written after. Throws NOT_FOUND and the errors of send.

leaveRoom#

TypeScript
leaveRoom(roomId: string, options?: RoomOptions): Promise<void>

Removes this wallet as removeRoomMember does, which sends every other member a new key, one message each, and no removal notice, then sets the room to left and forgets its key. The key update's self slot carries the leaving to this wallet's other devices, which set the room to left when their scan finds it.

TypeScript
privateLinks(): Promise<readonly PrivateLink[]>

This wallet's private links, revoked ones included: the ones made on this device and the ones its scans found in the wallet's own notes.

TypeScript
createPrivateLink(name?: string, options?: SendOptions): Promise<PrivateLink>

Scans the Log first, so every link made on another device is known, then derives the key of the next link index and makes its URL: /l on appUrl, with the public key and the name in the fragment, so the URL never reaches a server. It records the link in a link-created note, one message from this wallet's pass written to its own inbox, carrying the index, the name and the URL; every device of this wallet adds the link when its scan finds the note. The note is also kept as a message in the thread with this wallet's own address. Scans from then on try the link's key. Progress and errors are those of send. Runs one at a time with the other exclusive calls. Returns the PrivateLink. See Private links.

TypeScript
const link = await talaria.createPrivateLink('Contact form')
console.log(link.url)
TypeScript
revokePrivateLink(id: string, options?: SendOptions): Promise<void>

Posts a link-revoked note with the link's index to this wallet's own inbox, one message from its pass, then sets the link's revokedAt. Scans on every device of this wallet stop trying its key once they find the note. An unknown or already revoked id posts nothing. Progress and errors are those of send.

prove#

TypeScript
prove(input: ProofInput, options?: ProofOptions): Promise<ProofResult>

Runs the prover with this client's artifacts. send calls it for each part; call it directly to prove with inputs of your own. Progress: loading-artifacts, proving, complete. Throws CONFIGURATION_REQUIRED without prover, and an error if the prover's public signals differ from the inputs. See provePass.

demoProof#

TypeScript
demoProof(options?: ProofOptions): Promise<DemoProofResult>

Proves and verifies a demonstration pass with this client's artifacts, as proveDemonstration does. It makes no API, relay or wallet call. Throws CONFIGURATION_REQUIRED without prover or without prover.verificationKey.

close#

TypeScript
close(): Promise<void>

Ends every scan this client is running, writes the stored record and drops the keys from memory. A closed client's scans end at once; create a new client to scan again.

TalariaError#

TypeScript
class TalariaError extends Error implements SdkFailure {
  readonly code: ErrorCode | LocalErrorCode
  readonly retryable: boolean
  readonly relayUrl?: string
  constructor(code: ErrorCode | LocalErrorCode, message: string, retryable?: boolean, relayUrl?: string)
}

The error a client throws for its own checks. name is TalariaError and retryable defaults to false. Codes are in SDK errors.

createKeypairSigner#

TypeScript
function createKeypairSigner(secretKey: Uint8Array): WalletSigner

A WalletSigner over an Ed25519 key, for Node and scripts. secretKey is 64 bytes (a Solana keypair) or its 32-byte seed; any other length throws. signTransaction signs a serialized versioned transaction in the slot of this address and throws if the address is not a required signer.

splitParts#

TypeScript
function splitParts(text: string): string[]

The parts send would post, split between Unicode characters at 700 UTF-8 bytes at most. An empty text is one empty part. countParts(text) is its length.

TypeScript
import { countParts, splitParts } from '@talaria/sdk'

console.log(countParts(text), splitParts(text).map((part) => new TextEncoder().encode(part).length))

proveDemonstration#

TypeScript
function proveDemonstration(options: ProofOptions & { prover: ProverArtifacts; fetch?: typeof fetch }): Promise<DemoProofResult>

The proof the Proof page runs, without a client. It builds a one-leaf pool in memory holding a fixed pass (daily limit 25, expiring 30 days from today), proves its first message of today with payload hash 1 and relay 11111111111111111111111111111111, and verifies the proof with the verifying key. A verificationKey given as a string is read with readArtifact when there is one, otherwise fetched as a URL. Throws CONFIGURATION_REQUIRED without a verification key.

TypeScript
import { readFile } from 'node:fs/promises'
import { proveDemonstration } from '@talaria/sdk'

const result = await proveDemonstration({
  prover: {
    wasm: 'prover/talaria.wasm',
    zkey: 'prover/final.zkey',
    verificationKey: 'prover/verification_key.json',
    readArtifact: async (path) => new Uint8Array(await readFile(path)),
  },
  onProgress: ({ stage }) => console.log(stage),
})
console.log(result.verified, result.proofBytes, result.durationMs, result.verificationMs)

memoryStorage#

TypeScript
function memoryStorage(): EncryptedStorage

An EncryptedStorage in a Map. The default in Node; its contents end with the process.

indexedDbStorage#

TypeScript
function indexedDbStorage(name?: string): EncryptedStorage

An EncryptedStorage in the IndexedDB database name (default talaria), object store encrypted. The default in a browser.

resolveName#

TypeScript
function resolveName(name: string, service: NameService, rpcUrl?: string): Promise<string | null>

The wallet that owns a .sol name, or null when it has none. lookup calls it after checking and lowercasing the name; call it directly to resolve without a client.

serviceHow the name resolves
'local'From LOCAL_NAMES.
a tableFrom that table, name to address.
'sns'From the SPL Name Service on the cluster rpcUrl serves. The name account is the program address of namesLPneVptA9Z5rqUDD9tMTWEJwofgaYwp8cawRkX with seeds SHA-256 of SPL Name Service followed by the label, 32 zero bytes, and the .sol root account 58PwtjSDuFHuUkYjH9BYnnQKHfwo9reZhC2zMJv9JPkx. It is read at confirmed, and its owner is bytes 32 to 63 of the record.

With 'sns', a name with more than one label before .sol resolves to null, as does a name account that does not exist or is not owned by the Name Service program. 'sns' without rpcUrl throws an Error here; through lookup it is CONFIGURATION_REQUIRED.

TypeScript
import { resolveName } from '@talaria/sdk'

const owner = await resolveName('ari.sol', 'local')

LOCAL_NAMES#

TypeScript
const LOCAL_NAMES: Readonly<Record<string, string>>

The local build's names: ari.sol, bo.sol and cy.sol, each the address of a fixed development wallet of the local setup, and talaria.sol, the wallet that writes every new inbox its welcome. It is the default nameService.

keyDerivationMessage#

TypeScript
function keyDerivationMessage(wallet: string): Uint8Array

The message a wallet signs to derive its keys, as UTF-8 bytes:

Text
Talaria private inbox
Version: 1
Wallet: <the wallet address>
Sign to derive your inbox and local history keys. This does not send a transaction.

deriveKeys#

TypeScript
function deriveKeys(wallet: string, signature: Uint8Array, keyVersion?: number): Promise<DerivedKeys>

Derives the DerivedKeys of wallet from its 64-byte signature of the key message, with the inbox key of keyVersion (default 1). Throws for a signature of another length or a version below 1. Cryptography gives each derivation.

encodePayload#

TypeScript
function encodePayload(plain: Uint8Array, recipient: Uint8Array, self: Uint8Array): Uint8Array

Encrypts plain under a new content key and wraps that key for two X25519 public keys: the first slot for recipient, the second for self. Returns the version 1 payload described in Log entry format.

decodePayload#

TypeScript
function decodePayload(payloadBase64: string): PayloadParts

Splits a payload into its version, two key slots and ciphertext, as the PayloadParts of a Log entry. Throws for bytes that are not a version 1 payload.

decryptPayload#

TypeScript
function decryptPayload(payloadBase64: string, keys: readonly InboxKeyPair[]): { plaintext: Uint8Array; key: InboxKeyPair } | null

Tries each key on each slot, skipping a slot whose view tag doesn't match, and returns the plaintext with the key that opened it, or null.

payloadHash#

TypeScript
function payloadHash(payload: Uint8Array): string

The payload hash public input: the first 31 bytes of the payload's SHA-256, as a decimal integer.

privateLinkKey#

TypeScript
function privateLinkKey(seed: Uint8Array, index: string): InboxKeyPair

The key pair of private link index, derived from DerivedKeys.privateLinkSeed.

TypeScript
function parsePrivateLink(url: string): ParsedPrivateLink

Reads the key and name from a private link URL's fragment. Throws when the path is not /l or the key is not 32 bytes of base64.

commitment#

TypeScript
function commitment(secret: bigint): bigint

A pass's id commitment, Poseidon(secret).

passLeaf#

TypeScript
function passLeaf(secret: bigint, limit: number, expiryDay: string): bigint

A pass's leaf, Poseidon(commitment(secret), limit, expiryDay).

nullifier#

TypeScript
function nullifier(secret: bigint, day: string, counter: number): string

The nullifier of message counter of day, Poseidon(secret, day, counter), as a decimal string.

merkleTree#

TypeScript
function merkleTree(leaves: readonly PoolLeaf[]): { root: string; path(index: number): { elements: string[]; indices: number[] } }

The pool's Poseidon tree of height 26 built from the leaves, with empty positions filled by the zero subtrees. path gives the 26 siblings and left or right bits of one leaf, from the leaf up. See The pool.

proofBytes#

TypeScript
function proofBytes(proof: GrothProof): Uint8Array

A snarkjs Groth16 proof as the 256 bytes the program reads: A negated, then B and C, uncompressed and big-endian.

provePass#

TypeScript
function provePass(input: ProofInput, artifacts: ProverArtifacts, options?: ProofOptions): Promise<ProofResult>

Proves one message: the pass, its counter, its Merkle path and the public inputs. The relay address enters the circuit as two 128-bit limbs. Throws if the prover's public signals differ from the inputs. Circuit gives the signals.

verifyProof#

TypeScript
function verifyProof(result: ProofResult, verificationKey: object): Promise<boolean>

Verifies a proof against a parsed verifying key with snarkjs. Calls run one at a time.

Types#

Types from @talaria/contract are re-exported as they are: Address, Signature, BaseUnits, U64, Day, Timestamp, ErrorCode, Inbox, LogEntry, PoolLeaf, PublicInputs, TxBuild, TxStatus. API reference gives their fields.

WalletSigner#

addressAddress
The wallet's address.

Required

signMessage(message: Uint8Array) => Promise<Uint8Array>
Returns the 64-byte Ed25519 signature of the raw message.

Required

signTransaction(transaction: Uint8Array) => Promise<Uint8Array>
Signs a serialized versioned transaction and returns it serialized.

Required

EncryptedStorage#

read(key: string) => Promise<Uint8Array | null>
The bytes stored under key, or null.

Required

write(key: string, encryptedBytes: Uint8Array) => Promise<void>
Stores the bytes, replacing what was there.

Required

remove(key: string) => Promise<void>
Deletes the key.

Required

The client only ever hands a store bytes it has already encrypted. A store on disk for Node:

TypeScript
import { mkdir, readFile, rm, writeFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { EncryptedStorage } from '@talaria/sdk'

export function fileStorage(dir: string): EncryptedStorage {
  const file = (key: string) => join(dir, `${key}.bin`)
  return {
    async read(key) {
      try { return new Uint8Array(await readFile(file(key))) } catch { return null }
    },
    async write(key, encryptedBytes) {
      await mkdir(dir, { recursive: true })
      await writeFile(file(key), encryptedBytes)
    },
    async remove(key) {
      await rm(file(key), { force: true })
    },
  }
}

TalariaOptions#

The options of createTalaria.

ProverArtifacts#

wasmstring | Uint8Array
The circuit's talaria.wasm: a URL or path, or its bytes.

Required

zkeystring | Uint8Array
The proving key final.zkey: a URL or path, or its bytes.

Required

verificationKeyobject | string
The verifying key, parsed or as a URL or path. Needed by demoProof only.
readArtifact(path: string) => Promise<Uint8Array>
Reads a path given as a string. Pass it in Node.

OperationOptions#

signalAbortSignal
Aborts the call.

TransactionOptions#

OperationOptions plus onProgress?: (progress: TransactionProgress) => void.

TransactionProgress#

stageOther fields
building
signingbuild: TxBuild
confirmingtransaction: TxStatus
indexedtransaction: TxStatus
failederror: SdkFailure

InboxResult#

inboxInbox
The Inbox as the device's copy of the inbox directory holds it once the transaction is in.

Required

transactionTxStatus
The confirmed transaction.

Required

NameService#

TypeScript
type NameService = 'local' | 'sns' | Readonly<Record<string, string>>

See resolveName.

LookupResult#

TypeScript
type LookupResult =
  | { status: 'found'; wallet: Address; name: `${string}.sol` | null; inbox: Inbox | null }
  | { status: 'not_found'; query: string; name: string }
  | { status: 'invalid'; query: string }

See lookup.

DirectoryOptions#

OperationOptions plus onProgress?: (progress: { loadedEvents: U64; totalEvents: U64 }) => void. See syncDirectory.

BuyPassInput#

tierstring
A tier id from GET /pool.

Required

daysnumber
A pass length from GET /pool.

Required

Pass#

idstring
The pass index this wallet derived it at, as a string.

Required

leafPoolLeaf
Its leaf in the pool.

Required

purchasePassPurchase
Its purchase.

Required

secretUint8Array, 32 bytes
The pass secret. It stays on the device.

Required

PassPurchase#

idstring
The pass index.

Required

tierstring
The tier id.

Required

daysnumber
The length bought.

Required

priceLamportsBaseUnits
The price paid.

Required

transactionTxStatus
The purchase transaction.

Required

leafPoolLeaf | null
The leaf, once indexed.

Required

A purchase made on another device is rebuilt from its leaf, with days counted from the day of the leaf's block time through the expiry day, both included.

PassMeter#

passIdstring
The pass this meter reads.

Required

dayDay
Today, in the program's days.

Required

usednumber
Messages this pass sent today.

Required

dailyLimitnumber
Its daily limit.

Required

expiryDayDay
The last day it can send. The expiry day is included.

Required

expiresAtTimestamp
The end of the expiry day, UTC.

Required

daysRemainingnumber
Days it can still send on, today included.

Required

status'active' | 'limit-reached' | 'expired'
Its state today.

Required

PassState#

currentPassMeter | null
The pass send would use, as described in passes.

Required

purchasesreadonly PassPurchase[]
Every purchase this device knows.

Required

SendTarget#

TypeScript
type SendTarget = Address | `${string}.sol` | MessageTarget

MessageTarget#

kindOther field
walletwallet: Address
roomroomId: string
private-linklink: string, the full link URL

SendOptions#

OperationOptions plus:

relayUrlstring
Send through this relay only.
onProgress(progress: SendProgress) => void

SendProgress#

Every stage carries part (zero-based) and totalParts.

stageOther fields
encrypting
proving
relayingrelayUrl: string, attempt: number
landedsignature: Signature
failederror: SdkFailure

SendReceipt#

messageMessage
The message as sent.

Required

signaturesreadonly Signature[]
One transaction signature per part, in order.

Required

Message#

idstring
The message id, a UUID shared by its parts.

Required

targetMessageTarget
Where it was written.

Required

writerAddress
The writer's wallet, from inside the ciphertext.

Required

writerInboxKeystring
The writer's inbox key, base64.

Required

textstring
The text, parts joined.

Required

sentAtTimestamp
When the writer sent it, by the writer's clock.

Required

direction'sent' | 'received'
sent when this wallet wrote it.

Required

partsreadonly MessagePart[]
Its posts, in order.

Required

privateLinkNamestring
The name of the private link it arrived through, on the owner's device.

MessagePart#

indexnumber
Zero-based part position.

Required

signatureSignature
The post's transaction signature.

Required

logIndexU64 | null
Its Log position.

Required

relayAddress
The relay that submitted it.

Required

PendingMessage#

idstring
The message id.

Required

targetSendTarget
The target as given to send.

Required

textstring
The whole text.

Required

progressSendProgress
The last progress reported.

Required

landedPartsreadonly MessagePart[]
Parts already in the Log; a retry does not post them again.

Required

ScanOptions#

The options of scan.

ScanProgress#

stage'downloading' | 'scanning' | 'following' | 'complete'
See scan.

Required

nextLogIndexU64
The next zero-based position to try.

Required

headLogIndexU64
The end of the Log as last downloaded, exclusive.

Required

scannedEntriesU64
Entries tried by this scan.

Required

foundMessagesnumber
Messages yielded by this scan.

Required

RestoreOptions#

OperationOptions plus onProgress?: (progress: ScanProgress) => void.

RestoreResult#

messagesnumber
Messages found.

Required

threadsnumber
Threads on the device after the restore.

Required

roomsnumber
Rooms on the device after the restore.

Required

nextLogIndexU64
Where the next scan starts.

Required

Thread#

idstring
The counterparty's wallet.

Required

walletAddress
The counterparty's wallet.

Required

namestring | null
A display name.

Required

inboxInbox | null
The counterparty's Inbox.

Required

request'pending' | 'accepted' | 'blocked'
Its request state on this device.

Required

lastMessageMessage | null
The latest message.

Required

unreadCountnumber
Messages received since markRead.

Required

Room#

idstring
The room id, a UUID.

Required

namestring
Its name.

Required

membersreadonly RoomMember[]
Its members, this wallet included.

Required

keyVersionnumber
Raised at each membership change.

Required

state'invited' | 'joined' | 'declined' | 'removed' | 'left'
This device's state in it.

Required

lastMessageMessage | null
The latest message.

Required

unreadCountnumber
Messages received since markRead.

Required

RoomMember#

walletAddress
The member's wallet.

Required

namestring | null
The .sol name it was added by.

Required

inboxInbox | null
Its Inbox as this device found it when adding the member; null in a room joined by invitation, which carries wallets and names only.

Required

CreateRoomInput#

namestring
The room's name.

Required

membersreadonly (Address | `${string}.sol`)[]
The other members.

Required

RoomOptions#

OperationOptions plus onProgress?: (progress: RoomProgress) => void and onSendProgress?: (progress: SendProgress) => void.

RoomProgress#

stage'resolving' | 'sending-invites' | 'rotating-key' | 'done'
See createRoom; rotating-key is reported by removeRoomMember and leaveRoom.

Required

completednumber
Invitations sent.

Required

totalnumber
Invitations to send. With resolving, the members given.

Required

memberAddress
The member being sent to.
idstring
A UUID.

Required

indexU64
The derivation index.

Required

namestring | null
Its name.

Required

urlstring
The link to share.

Required

inboxKeystring
Its public key, base64.

Required

createdAtTimestamp
When it was made.

Required

revokedAtTimestamp | null
When it was revoked.

Required

inboxKeystring
The link's public key, base64.

Required

namestring | null
The name in the link.

Required

ProofInput#

passPass
The pass proving.

Required

counternumber
The message's counter today, below the daily limit.

Required

merklePathreadonly string[]
The leaf's siblings, from merkleTree(...).path.

Required

merklePathIndicesreadonly number[]
Their left or right bits.

Required

publicInputsPublicInputs
Root, day, nullifier, payload hash and relay.

Required

ProofResult#

proofBase64string
The proof, 256 bytes as base64.

Required

publicInputsPublicInputs
The inputs proved.

Required

publicSignalsreadonly string[]
The six circuit signals, the relay as two limbs.

Required

durationMsnumber
Proving time.

Required

ProofOptions#

OperationOptions plus onProgress?: (progress) => void, with stage one of loading-artifacts, proving, complete.

DemoProofResult#

ProofResult plus verified: boolean, verificationMs: number and proofBytes: number.

DerivedKeys#

walletAddress
The wallet.

Required

inboxInboxKeyPair
The current inbox key pair.

Required

passSeedUint8Array, 32 bytes
The seed of every pass secret.

Required

privateLinkSeedUint8Array, 32 bytes
The seed of every private link key.

Required

localHistoryKeyUint8Array, 32 bytes
The key the stored record is sealed with.

Required

InboxKeyPair#

publicKeyUint8Array, 32 bytes
X25519 public key.

Required

secretKeyUint8Array, 32 bytes
X25519 secret key.

Required

versionnumber
The inbox key version.

Required

SdkFailure#

codeErrorCode | LocalErrorCode

Required

messagestring
A sentence to show.

Required

retryableboolean
Whether trying again can succeed.

Required

relayUrlstring
The relay involved.
walletAddress
The wallet involved.

LocalErrorCode#

The codes the SDK adds to the API's: WALLET_REJECTED, KEYS_LOCKED, NO_PASS, DAILY_LIMIT_REACHED, PASS_EXPIRED, COUNTERPARTY_NO_INBOX, INVALID_PRIVATE_LINK, DECRYPTION_FAILED, WRITER_VERIFICATION_FAILED, PROVING_FAILED, RELAY_UNAVAILABLE, INDEXER_UNREACHABLE. Their meanings are in SDK errors.

AppState#

The states an app built on the SDK moves through, as one union keyed by status:

statusOther fields
no-wallet
deriving-keys
no-inbox
scanningprogress: ScanProgress
emptypass: PassState
readythreads, rooms, pass: PassState
unreachableerror: SdkFailure