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.
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.
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#
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:6711andhttp://127.0.0.1:6712. Without it the client uses the endpoints fromGET /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,proveanddemoProof. - appUrlstring
- The app origin private link URLs are made on.
Default
http://127.0.0.1:6700 - nameServiceNameService
- Where
.solnames resolve:'local', the local build's tableLOCAL_NAMES;'sns', the SPL Name Service read overrpcUrl; or a table of your own, name to address. SeeresolveName.Default
'local' - rpcUrlstring
- The client's own Solana RPC. Used only to read SPL Name Service accounts when
nameServiceis'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.
| Member | Kind | Section |
|---|---|---|
wallet, unlocked | properties | wallet, unlocked |
unlock, inbox, findInbox, syncDirectory, directoryReady, lookup, openInbox, rotateInboxKey | keys and inboxes | unlock |
buyPass, passes | passes | buyPass |
send, retry, pendingMessages, countParts | sending | send |
scan, restore | reading | scan |
threads, messages, acceptRequest, blockWallet, unblockWallet, blocked, markRead | threads | threads |
rooms, createRoom, acceptRoom, declineRoom, addRoomMember, removeRoomMember, leaveRoom | rooms | rooms |
privateLinks, createPrivateLink, revokePrivateLink | private links | privateLinks |
prove, demoProof, close | proofs and lifetime | prove |
wallet#
readonly wallet: Address
The signer's address, checked when the client was created.
unlocked#
readonly unlocked: boolean
true once this client has derived its keys, false before and after close.
unlock#
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#
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#
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.
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#
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
loadedEventsequal tototalEvents. - signalAbortSignal
- Aborts the download.
Call it when an app starts, so the directory is on the device before the first lookup:
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#
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#
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.
status | Other fields | When |
|---|---|---|
found | wallet, 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_found | query, name | A valid .sol name with no owner in the name service |
invalid | query | Neither a .sol name nor a base58 address |
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#
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.
| Stage | When |
|---|---|
building | Before the API builds the transaction |
signing | The build is in build; the signer is asked |
confirming | Submitted; repeats with each status read |
indexed | The Inbox reads back with the new key |
failed | Any 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#
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#
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,dailyorfrequent.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#
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#
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
.solname, or a target object for a wallet, a room or a private link. SeeSendTarget.Required
- textstring
- The message. Split into parts of at most 700 UTF-8 bytes, one post each.
Required
- optionsSendOptions
For each part the client:
- encrypts to the reader's key with two key slots, one for the reader and one for this wallet's own inbox key;
- picks the oldest unexpired pass with a message left today and its lowest unused counter;
- records the part's payload, pass and counter as an attempt, so a retry reuses them;
- 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.
| Stage | Fields beyond part and totalParts |
|---|---|
encrypting | |
proving | |
relaying | relayUrl, attempt (1-based) |
landed | signature |
failed | error |
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#
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.
for (const pending of await talaria.pendingMessages()) {
const receipt = await talaria.retry(pending)
console.log(pending.id, receipt.signatures)
}
pendingMessages#
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#
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#
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
- See
ScanProgress. - signalAbortSignal
- Stops the scan.
| Stage | When |
|---|---|
downloading | A round starts downloading the Log |
scanning | After each entry is tried |
following | A round ended at the head and follow is set |
complete | The 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:
| Message | Effect |
|---|---|
| A room invitation that lists this wallet and its writer as members | Adds 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 room | Sets the room to removed and drops its key. |
| A message this wallet sent to a room | Sets an invited room to joined. |
| A message this wallet sent to a wallet | Sets a pending thread with that wallet to accepted. |
| A message opened by a private link key the device did not hold | Adds 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 itself | Adds the link with its index, name and URL, if the device does not hold that index. |
A link-revoked note this wallet wrote to itself | Sets that link's revokedAt to the note's send time. |
| A room key update this wallet wrote that leaves it out of the members | Sets 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.
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#
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#
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#
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#
acceptRequest(wallet: Address): Promise<void>
Marks the thread with wallet as accepted. Local to this device.
blockWallet#
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#
unblockWallet(wallet: Address): Promise<void>
Removes wallet from the blocked list; its thread goes back to pending.
blocked#
blocked(): Promise<readonly Address[]>
The wallets blocked on this device.
markRead#
markRead(threadOrRoomId: string): Promise<void>
Sets the unread count of a thread or room to zero.
rooms#
rooms(): Promise<readonly Room[]>
This device's rooms, in every state. See Rooms.
createRoom#
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.
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#
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#
declineRoom(roomId: string): Promise<void>
Sets an invited room to declined.
addRoomMember#
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#
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#
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.
privateLinks#
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.
createPrivateLink#
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.
const link = await talaria.createPrivateLink('Contact form')
console.log(link.url)
revokePrivateLink#
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#
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#
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#
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#
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#
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#
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.
import { countParts, splitParts } from '@talaria/sdk'
console.log(countParts(text), splitParts(text).map((part) => new TextEncoder().encode(part).length))
proveDemonstration#
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.
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#
function memoryStorage(): EncryptedStorage
An EncryptedStorage in a Map. The default in Node; its contents end with the process.
indexedDbStorage#
function indexedDbStorage(name?: string): EncryptedStorage
An EncryptedStorage in the IndexedDB database name (default talaria), object store encrypted. The default in a browser.
resolveName#
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.
service | How the name resolves |
|---|---|
'local' | From LOCAL_NAMES. |
| a table | From 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.
import { resolveName } from '@talaria/sdk'
const owner = await resolveName('ari.sol', 'local')
LOCAL_NAMES#
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#
function keyDerivationMessage(wallet: string): Uint8Array
The message a wallet signs to derive its keys, as UTF-8 bytes:
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#
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#
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#
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#
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#
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#
function privateLinkKey(seed: Uint8Array, index: string): InboxKeyPair
The key pair of private link index, derived from DerivedKeys.privateLinkSeed.
parsePrivateLink#
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#
function commitment(secret: bigint): bigint
A pass's id commitment, Poseidon(secret).
passLeaf#
function passLeaf(secret: bigint, limit: number, expiryDay: string): bigint
A pass's leaf, Poseidon(commitment(secret), limit, expiryDay).
nullifier#
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#
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#
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#
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#
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, ornull.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:
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
demoProofonly. - 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#
stage | Other fields |
|---|---|
building | |
signing | build: TxBuild |
confirming | transaction: TxStatus |
indexed | transaction: TxStatus |
failed | error: 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#
type NameService = 'local' | 'sns' | Readonly<Record<string, string>>
See resolveName.
LookupResult#
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
sendwould use, as described inpasses.Required
- purchasesreadonly PassPurchase[]
- Every purchase this device knows.
Required
SendTarget#
type SendTarget = Address | `${string}.sol` | MessageTarget
MessageTarget#
kind | Other field |
|---|---|
wallet | wallet: Address |
room | roomId: string |
private-link | link: string, the full link URL |
SendOptions#
OperationOptions plus:
- relayUrlstring
- Send through this relay only.
- onProgress(progress: SendProgress) => void
- See
SendProgress.
SendProgress#
Every stage carries part (zero-based) and totalParts.
stage | Other fields |
|---|---|
encrypting | |
proving | |
relaying | relayUrl: string, attempt: number |
landed | signature: Signature |
failed | error: 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'
sentwhen 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
.solname it was added by.Required
- inboxInbox | null
- Its Inbox as this device found it when adding the member;
nullin 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'
Required
- completednumber
- Invitations sent.
Required
- totalnumber
- Invitations to send. With
resolving, the members given.Required
- memberAddress
- The member being sent to.
PrivateLink#
- 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
ParsedPrivateLink#
- 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
- See SDK errors.
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:
status | Other fields |
|---|---|
no-wallet | |
deriving-keys | |
no-inbox | |
scanning | progress: ScanProgress |
empty | pass: PassState |
ready | threads, rooms, pass: PassState |
unreachable | error: SdkFailure |