@alba/sdk is the TypeScript package an agent pays with and an owner's app is built on. It runs in Node 22 or later and in the browser, and it is an ES module.
npm install @alba/sdkEvery amount the SDK takes or returns is a decimal string in the mint's raw units, so 10000 of a 6-decimal mint is 0.01. Keys, field elements and the fields of a decoded credential are bigint.
Entry points#
| Import | Holds |
|---|---|
@alba/sdk | The agent API, the owner API, keys, addresses, credentials and every type on this page. It imports no Node built-in, so it bundles for the browser. |
@alba/sdk/seller | The seller middleware. |
@alba/sdk/mcp | The MCP server. |
@alba/sdk/protocol | Notes, commitments, spend tags, encryption and proveSpend, the functions under the circuit. |
@alba/sdk/idl | ALBA_IDL, the program's interface as plain data. |
alba-mcp | The package's executable: the MCP server over stdio. |
The agent API#
An agent holds one grant credential and uses three calls.
import { alba } from '@alba/sdk'
const res = await alba.fetch('https://api.example/v1/search?q=lithium')
const grant = await alba.grantStatus()alba.fetch and alba.grantStatus read the credential from the ALBA_GRANT environment variable each time they are called. Without it they throw INVALID_CREDENTIAL. alba.with binds a credential in code and returns an Agent with the same two methods:
import { alba } from '@alba/sdk'
const agent = alba.with(credential)
const res = await agent.fetch('https://api.example/v1/search?q=lithium', { method: 'GET' })alba.with(credential, options?)#
| Parameter | Type | Meaning |
|---|---|---|
credentialrequired | string | A grant credential. A string that is not a version 1 credential throws INVALID_CREDENTIAL. |
options | SdkOptions | See SdkOptions. Without facilitatorUrl the agent talks to the facilitator named in the credential. |
Returns an Agent.
fetch(url, init?, options?)#
| Parameter | Type | Meaning |
|---|---|---|
urlrequired | string | URL | The resource. |
init | RequestInit | The same object the global fetch takes: method, headers, body, signal. |
options | OperationOptions | A signal and a progress callback. See OperationOptions. |
Returns a Promise<Response>. What happens, in order:
The request goes out unpaid
A response with any status other than
402is returned as it is.The requirements are read
The SDK decodes the
PAYMENT-REQUIREDheader and looks for an entry ofacceptsthat is a validalbarequirement, whoseassetis the grant's mint and whoseextra.facilitatoris the grant's facilitator. If the header is missing or no entry matches, the402response is returned as it is and nothing is paid.The terms are checked
Before any proof the SDK checks the price against the credential and the grant's current note, and throws an
AlbaSdkErrorwhen the payment cannot be inside the grant. The codes are in the table below.The payment is proved
The SDK reads the fee rates and the relayer from the facilitator, syncs the pool's note tree, and proves a spend of the grant's current note: the price to the pay-to address, the protocol fee and the relay fee, and the remainder into the grant's next note. The proof's deadline is now plus
maxTimeoutSecondsfrom the requirements, at most 120 seconds, and never later than the grant's expiry. The request's method and URL are encrypted to the owner as the memo, with the seller's Alba address when the pay-to is one. A URL too long for the memo is cut and ended with an ellipsis. The payment carries noresourceobject, so the facilitator is not sent the URL.The request goes out once more, paid
The same request is sent with the payment in a
PAYMENT-SIGNATUREheader. Whatever the seller answers is returned: the resource with aPAYMENT-RESPONSEheader when the payment settled, or a new402whose body carries anerrorreason when it was refused.fetchpays at most once per call.
| Thrown before any proof | When |
|---|---|
AMOUNT_OVER_CAP | The price is above the grant's cap per payment. |
GRANT_EXPIRED | The grant's expiry has passed. |
SELLER_NOT_ALLOWED | The grant lists sellers and the pay-to address is not one of them. |
INVALID_ARGUMENT | The seller's network is not the facilitator's network. |
GRANT_REVOKED | The owner has revoked the grant. |
INSUFFICIENT_GRANT_BALANCE | The grant holds less than the price plus the fees. |
Payments from one grant run one at a time within a process. Calls to fetch on the same credential queue behind each other, because each payment spends the note the previous one created. Run one process per grant.
grantStatus(options?)#
Returns a Promise<GrantView>: the grant's remaining amount, its terms, its label and its state, rebuilt from the chain. It spends nothing. See GrantView.
The owner API#
An owner's balance is opened from one wallet signature. Everything after that happens on the Owner handle. The owner's keys stay in memory and are never sent anywhere.
import { connectBalance } from '@alba/sdk'
const owner = await connectBalance((message) => wallet.signMessage(message), { facilitatorUrl })
const balance = await owner.scan()connectBalance(signMessage, options?)#
Asks the wallet to sign the fixed message and opens the balance. signMessage is (message: Uint8Array) => Promise<Uint8Array> and must return the raw 64-byte signature. Returns Promise<Owner>.
openBalance(signature, options?)#
The same, from a signature already in hand. Returns Owner. A signature that is not 64 bytes throws INVALID_SIGNATURE.
The handle needs the facilitator's base URL: facilitatorUrl in the options of either call, or the ALBA_FACILITATOR_URL environment variable when the option is left out. It is the facilitator every method of the handle talks to, and the URL written into each grant credential the handle creates. With neither set, the first method that needs it throws INVALID_ARGUMENT.
Owner#
| Member | Type | Meaning |
|---|---|---|
address | string | The owner's Alba address. |
scan(options?) | Promise<BalanceView> | Reads the pools' feeds, decrypts the owner's notes and rebuilds the balance. options is a ScanOptions. |
deposit(input, options?) | Promise<TransactionBuild> | Proves a deposit and returns an unsigned transaction for the wallet. |
submitDeposit(input, options?) | Promise<Transaction> | Sends the wallet-signed deposit and follows it. |
createGrant(input, options?) | Promise<CreateGrantResult> | Creates a grant and returns it with its credential. |
topUp(input, options?) | Promise<Transaction> | Adds value to a grant. |
revoke(grantId, options?) | Promise<Transaction> | Returns what a grant has left to the balance. |
withdraw(input, options?) | Promise<Transaction> | Pays an amount out to a public token account. |
transfer(input, options?) | Promise<Transaction> | Sends an amount to another Alba address inside the pool. |
listGrants(options?) | Promise<GrantView[]> | Every grant the owner has created, in order of creation. |
grant(grantId, options?) | Promise<GrantView> | One grant. |
readLedger(grantId, options?) | Promise<LedgerView> | The grant's payments with their memos decrypted. |
showCredential(grantId, options?) | Promise<string> | The grant's credential, derived again. |
Except where noted, options is an OperationOptions. A grantId is the id of a GrantView. A grantId that is not one of the owner's grants throws INVALID_ARGUMENT.
Every method that spends takes the relay fee from the owner's notes on top of the amount, and uses at most two of the owner's notes as inputs. When the notes it can use hold less than the amount plus the fee, it throws INSUFFICIENT_BALANCE.
deposit and submitDeposit#
A deposit is the one action the owner's wallet signs as a transaction. It takes two calls with the wallet between them.
const build = await owner.deposit({ mint, amount: '5000000', depositor: wallet.address })
const signedTransactionBase64 = await wallet.signTransaction(build.transactionBase64)
const tx = await owner.submitDeposit({ buildId: build.id, signedTransactionBase64 })| DepositInput | Type | Meaning |
|---|---|---|
mintrequired | string | The pool's mint. |
amountrequired | string | The amount to deposit, a positive u64. |
depositorrequired | string | The wallet that signs and pays. |
depositorTokenAccount | string | The wallet's token account the amount comes from. Defaults to its associated token account for the mint. |
deposit returns a TransactionBuild. Its transactionBase64 is an unsigned version 0 transaction with the depositor as fee payer. The wallet signs those bytes, and the signed transaction goes to submitDeposit:
| SubmitDepositInput | Type | Meaning |
|---|---|---|
buildIdrequired | string | The build's id. |
signedTransactionBase64required | string | The signed transaction, base64. |
A deposit pays no protocol fee and no relay fee. The new note appears in the next scan.
createGrant#
const { grant, credential } = await owner.createGrant({
mint,
amount: '50000000',
terms: { cap: '50000', expiry: String(Math.floor(Date.now() / 1000) + 30 * 86400), sellers: [] },
label: 'research-agent',
})| CreateGrantInput | Type | Meaning |
|---|---|---|
mintrequired | string | The pool the grant lives in. |
amountrequired | string | What the grant holds when created, a positive u64. |
termsrequired | GrantTerms | The cap per payment, the expiry and the sellers. See GrantTerms. |
labelrequired | string | The owner's name for the grant, at most 256 bytes of UTF-8. |
index | string | The grant's index. It can only be the next unused index, which is also the default. |
The method stores the grant's encrypted record with the facilitator, proves a spend of the owner's notes into the grant note and change, relays it, and returns once it settles:
| CreateGrantResult | Type | Meaning |
|---|---|---|
grant | GrantView | The new grant. |
credential | string | The grant credential to hand to the agent. |
transaction | Transaction | The settled transaction. |
It throws GRANT_EXPIRED when terms.expiry is not in the future, INVALID_ARGUMENT when index is not the next unused index, and INSUFFICIENT_BALANCE when the notes cannot cover the amount and the relay fee.
topUp#
| TopUpInput | Type | Meaning |
|---|---|---|
grantIdrequired | string | The grant. |
amountrequired | string | The amount to add, a positive u64. |
Spends the grant's current note and one of the owner's notes into the grant's next note. That one note has to cover the amount and the relay fee. A grant that is spent or revoked throws INVALID_ARGUMENT: create a new grant for it.
revoke#
Spends the grant's current note back into the owner's balance, less the relay fee. A grant that is already spent or revoked throws INVALID_ARGUMENT.
withdraw#
| WithdrawInput | Type | Meaning |
|---|---|---|
mintrequired | string | The pool's mint. |
amountrequired | string | The amount to pay out, a positive u64. |
recipientrequired | string | The wallet that receives it. |
recipientTokenAccount | string | The receiving token account. Defaults to the recipient's associated token account for the mint. |
transfer#
| TransferInput | Type | Meaning |
|---|---|---|
mintrequired | string | The pool's mint. |
amountrequired | string | The amount to send, a positive u64. |
recipientrequired | string | The receiving Alba address. Another value throws INVALID_ALBA_ADDRESS. |
The recipient finds the note in their next scan.
readLedger#
Follows the grant's spend tags, keeps the spends that paid a seller, and decrypts each memo with the owner's key. Returns a LedgerView.
const ledger = await owner.readLedger(grant.id)
for (const row of ledger.rows) {
console.log(row.at, row.seller, row.amount, row.memo?.url)
}Options#
SdkOptions#
| Option | Type | Meaning |
|---|---|---|
facilitatorUrl | string | The facilitator's base URL. An agent without it uses the URL in its credential. An owner's handle and the seller middleware without it use the ALBA_FACILITATOR_URL environment variable, and throw INVALID_ARGUMENT when that is not set either. |
fetch | typeof fetch | The transport for every request the SDK makes. Defaults to the global fetch. |
artifactBaseUrl | string | A base URL to load spend.wasm and spend.zkey from. By default the SDK reads the facilitator's artifact manifest and checks each file's SHA-256 against it. |
OperationOptions#
| Option | Type | Meaning |
|---|---|---|
signal | AbortSignal | Cancels the operation. |
onProgress | (progress: ProvingProgress) => void | Called as the operation moves through its stages. |
A ProvingProgress is { stage, progress, message }, with progress from 0 to 1 within the stage:
stage | What is happening |
|---|---|
syncing | Reading the pool's note tree from the facilitator. |
loading_artifacts | Downloading the circuit's WASM and proving key. |
witness | Computing the witness. |
proving | Computing the Groth16 proof. |
submitting | The proof is with the facilitator, or with the seller for a payment. |
ScanOptions#
OperationOptions and:
| Option | Type | Meaning |
|---|---|---|
mints | string[] | Scan only these pools. By default every open pool. |
onUpdate | (balance: BalanceView) => void | Called with the balance so far: once at the start and once after each pool. |
Views#
The objects the SDK rebuilds locally from public data and the owner's keys.
BalanceView#
| Field | Type | Meaning |
|---|---|---|
state | string | scanning while a scan runs, then ready, or empty when the owner holds no notes. |
address | string | null | The owner's Alba address. |
assets | AssetBalance[] | One entry per pool scanned. |
notes | NoteView[] | The owner's unspent notes and live grants. |
scannedLeaves | number | Tree leaves read so far. |
totalLeaves | number | Tree leaves in the pools being scanned. |
error | object | null | null from a scan that returned. |
An AssetBalance:
| Field | Type | Meaning |
|---|---|---|
mint | string | The pool's mint. |
symbol | string | The mint's symbol. |
decimals | number | The mint's decimals. |
available | string | The sum of the owner's plain notes. |
granted | string | What the owner's live grants have left. |
total | string | available plus granted. |
A NoteView:
| Field | Type | Meaning |
|---|---|---|
commitment | string | The note's commitment. |
mint | string | The pool's mint. |
amount | string | The note's amount. |
leafIndex | number | Its position in the note tree. |
kind | string | plain for a deposit or change, received for a payment that arrived at the owner's Alba address, grant for a grant's current note. |
spent | boolean | false for every note a scan returns. |
GrantView#
| Field | Type | Meaning |
|---|---|---|
id | string | The grant's identifier, 64 hex characters derived from its seed. Pass it as grantId. |
index | string | The grant's index in the owner's sequence, from 0. |
label | string | The owner's name for it. |
mint | string | The pool it lives in. |
startingAmount | string | What it held when created. |
granted | string | Everything put into the grant: the starting amount plus every top-up. |
remaining | string | What it holds now. 0 once revoked. |
spent | string | The sum of the prices it has paid. |
feesPaid | string | The sum of the fees on those payments. |
terms | GrantTerms | The cap, the expiry and the sellers. |
state | string | active, expired, spent or revoked. |
createdAt | string | When its record was last written, ISO 8601 in UTC. |
GrantTerms#
| Field | Type | Meaning |
|---|---|---|
caprequired | string | The most one payment may send to a seller, a u64. |
expiryrequired | string | The last second the agent may pay, Unix seconds as a u64. |
sellersrequired | string[] | Up to 32 wallet addresses or Alba addresses. An empty array allows any seller. |
LedgerView#
| Field | Type | Meaning |
|---|---|---|
state | string | ready, or empty when the grant has paid nothing yet. |
grantId | string | The grant. |
rows | LedgerRow[] | The payments, oldest first. |
totalPaid | string | The sum of the prices. |
totalFees | string | The sum of the fees. |
error | object | null | null from a read that returned. |
A LedgerRow:
| Field | Type | Meaning |
|---|---|---|
id | string | The spend's identifier. |
at | string | The block time, ISO 8601 in UTC. |
seller | string | The pay-to address the payment went to. For a wallet it is read from the chain. For an Alba address it is read from the memo, and it is an empty string when the memo does not hold it and no Alba address on the grant's seller list has a settlement with this transaction. |
amount | string | The seller's price. |
protocolFee | string | The protocol fee on the payment. |
relayFee | string | The relay fee on the payment. |
memo | { method, url } | null | The request the agent paid for, decrypted. |
signature | string | The transaction. |
Transaction#
| Field | Type | Meaning |
|---|---|---|
id | string | The transaction's identifier at the facilitator. |
status | string | built, submitted, settled or failed. |
signature | string | null | The transaction signature. |
slot | string | null | The slot it landed in. |
error | { code, message } | null | Why it failed. |
TransactionBuild#
| Field | Type | Meaning |
|---|---|---|
id | string | The build's identifier. Pass it as buildId. |
transactionBase64 | string | The unsigned version 0 transaction. |
blockhash | string | The blockhash it was built on. |
lastValidBlockHeight | string | The last block height at which it can land. |
contextSlot | string | The slot the build was made at. |
expiresAt | string | When the build expires. |
fee | string | The network fee in lamports, paid by the depositor. |
Keys, addresses and credentials#
The functions the two APIs are built from. An app that uses connectBalance and alba.fetch does not need to call them.
| Export | Type | Meaning |
|---|---|---|
OPEN_BALANCE_MESSAGE | string | The fixed message a wallet signs to open a balance. |
openBalanceMessage() | Uint8Array | The same message as bytes, for a wallet's signMessage. |
deriveOwnerKeys(signature) | OwnerKeys | The owner's keys from the 64-byte signature: sk, pk, nk, encryptionSecretKey, encryptionPublicKey. Throws INVALID_SIGNATURE. |
deriveGrantSecrets(keys, index) | GrantSecrets | One grant's seed, agentSk, agentPk, encryptionKey, recordWriteToken and locator from the owner's sk and the grant's index. Throws INVALID_ARGUMENT. |
encodeAlbaAddress(data) | string | An Alba address from pk and encryptionPublicKey. Throws INVALID_ALBA_ADDRESS. |
decodeAlbaAddress(address) | AlbaAddressData | { version, pk, encryptionPublicKey }. Throws INVALID_ALBA_ADDRESS. |
encodeGrantCredential(credential) | string | The alba_grant_ string from its fields. Throws INVALID_CREDENTIAL. |
decodeGrantCredential(value) | GrantCredential | The fields of a credential. Throws INVALID_CREDENTIAL. |
associatedTokenAccount(owner, mint, tokenProgram?) | string | The associated token account of a wallet for a mint. tokenProgram defaults to SPL Token. |
A decoded GrantCredential:
| Field | Type | Meaning |
|---|---|---|
version | 1 | The credential version. |
seed | bigint | The grant's seed. |
agentSk | bigint | The agent's secret key. |
ownerPk | bigint | The owner's public key. |
ownerEncryptionPublicKey | Uint8Array | The key memos are encrypted to, 32 bytes. |
cap | bigint | The cap per payment. |
expiry | bigint | The expiry, Unix seconds. |
sellers | string[] | The seller list, at most 32, empty for any seller. |
mint | string | The pool's mint. |
facilitatorUrl | string | The facilitator's base URL. |
startingAmount | bigint | What the grant held when created. |
import { decodeGrantCredential } from '@alba/sdk'
const { cap, expiry, sellers, mint } = decodeGrantCredential(credential)Errors#
The SDK throws AlbaSdkError for what it decides locally. It is an Error with a code:
code | Raised when |
|---|---|
INVALID_CREDENTIAL | A string is not a version 1 grant credential, or ALBA_GRANT is not set. |
INVALID_ALBA_ADDRESS | A string is not a version 1 Alba address. |
INVALID_SIGNATURE | The wallet's signature is not 64 bytes. |
INVALID_ARGUMENT | A grant is not found, a grant index is not the next one, a top-up or revoke targets a grant with no live note, the seller is on another network, or no facilitator URL is set. |
INSUFFICIENT_BALANCE | The owner's notes cannot cover an amount and its relay fee with two inputs. |
INSUFFICIENT_GRANT_BALANCE | A grant cannot cover a price and its fees. |
GRANT_EXPIRED | A payment is attempted after the grant's expiry, or a new grant's expiry is not in the future. |
GRANT_REVOKED | A payment is attempted from a revoked grant. |
AMOUNT_OVER_CAP | A price is above the grant's cap. |
SELLER_NOT_ALLOWED | A pay-to address is not on the grant's seller list. |
import { alba, AlbaSdkError } from '@alba/sdk'
try {
await alba.fetch(url)
} catch (e) {
if (e instanceof AlbaSdkError && e.code === 'AMOUNT_OVER_CAP') {
// the seller asks more than this grant pays per request
}
}A failure answered by the facilitator is thrown as ApiClientError from @alba/contract, with the facilitator's status, code and error envelope. The owner methods throw it when a relayed spend is refused.
MCP server#
@alba/sdk/mcp serves the agent API to an MCP client over stdio. The package's executable starts it:
npx -p @alba/sdk alba-mcpIt reads the grant credential from ALBA_GRANT in its environment. To start it from code:
import { startMcpServer } from '@alba/sdk/mcp'
await startMcpServer({ credential })startMcpServer(options?) takes an McpOptions: the SdkOptions and an optional credential. Without credential the server uses ALBA_GRANT, and it rejects when neither is set. The other options apply in both cases. MCP_TOOLS is the tuple of the two tool names.
fetch_paid#
Calls fetch on the grant, with the same checks and the same one-at-a-time queue.
| Input | Type | Meaning |
|---|---|---|
urlrequired | string | The resource's URL. |
method | string | The HTTP method. |
headers | Record<string, string> | Request headers. |
body | string | The request body. |
The tool returns one text item holding JSON, a FetchPaidResult:
| Field | Type | Meaning |
|---|---|---|
status | number | The HTTP status of the final response. |
headers | Record<string, string> | Its headers. |
body | string | Its body as text. |
grant_status#
Takes no input. Returns one text item holding the grant's GrantView as JSON.