Reference

SDK (@alba/sdk)

Every export of the SDK: the agent, the owner, keys, types, errors and the MCP server.

@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.

text
npm install @alba/sdk

Every 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#

ImportHolds
@alba/sdkThe 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/sellerThe seller middleware.
@alba/sdk/mcpThe MCP server.
@alba/sdk/protocolNotes, commitments, spend tags, encryption and proveSpend, the functions under the circuit.
@alba/sdk/idlALBA_IDL, the program's interface as plain data.
alba-mcpThe package's executable: the MCP server over stdio.

The agent API#

An agent holds one grant credential and uses three calls.

ts
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:

ts
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?)#

ParameterTypeMeaning
credentialrequiredstringA grant credential. A string that is not a version 1 credential throws INVALID_CREDENTIAL.
optionsSdkOptionsSee SdkOptions. Without facilitatorUrl the agent talks to the facilitator named in the credential.

Returns an Agent.

fetch(url, init?, options?)#

ParameterTypeMeaning
urlrequiredstring | URLThe resource.
initRequestInitThe same object the global fetch takes: method, headers, body, signal.
optionsOperationOptionsA signal and a progress callback. See OperationOptions.

Returns a Promise<Response>. What happens, in order:

  1. The request goes out unpaid

    A response with any status other than 402 is returned as it is.

  2. The requirements are read

    The SDK decodes the PAYMENT-REQUIRED header and looks for an entry of accepts that is a valid alba requirement, whose asset is the grant's mint and whose extra.facilitator is the grant's facilitator. If the header is missing or no entry matches, the 402 response is returned as it is and nothing is paid.

  3. The terms are checked

    Before any proof the SDK checks the price against the credential and the grant's current note, and throws an AlbaSdkError when the payment cannot be inside the grant. The codes are in the table below.

  4. 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 maxTimeoutSeconds from 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 no resource object, so the facilitator is not sent the URL.

  5. The request goes out once more, paid

    The same request is sent with the payment in a PAYMENT-SIGNATURE header. Whatever the seller answers is returned: the resource with a PAYMENT-RESPONSE header when the payment settled, or a new 402 whose body carries an error reason when it was refused. fetch pays at most once per call.

Thrown before any proofWhen
AMOUNT_OVER_CAPThe price is above the grant's cap per payment.
GRANT_EXPIREDThe grant's expiry has passed.
SELLER_NOT_ALLOWEDThe grant lists sellers and the pay-to address is not one of them.
INVALID_ARGUMENTThe seller's network is not the facilitator's network.
GRANT_REVOKEDThe owner has revoked the grant.
INSUFFICIENT_GRANT_BALANCEThe 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.

ts
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#

MemberTypeMeaning
addressstringThe 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.

ts
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 })
DepositInputTypeMeaning
mintrequiredstringThe pool's mint.
amountrequiredstringThe amount to deposit, a positive u64.
depositorrequiredstringThe wallet that signs and pays.
depositorTokenAccountstringThe 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:

SubmitDepositInputTypeMeaning
buildIdrequiredstringThe build's id.
signedTransactionBase64requiredstringThe signed transaction, base64.

A deposit pays no protocol fee and no relay fee. The new note appears in the next scan.

createGrant#

ts
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',
})
CreateGrantInputTypeMeaning
mintrequiredstringThe pool the grant lives in.
amountrequiredstringWhat the grant holds when created, a positive u64.
termsrequiredGrantTermsThe cap per payment, the expiry and the sellers. See GrantTerms.
labelrequiredstringThe owner's name for the grant, at most 256 bytes of UTF-8.
indexstringThe 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:

CreateGrantResultTypeMeaning
grantGrantViewThe new grant.
credentialstringThe grant credential to hand to the agent.
transactionTransactionThe 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#

TopUpInputTypeMeaning
grantIdrequiredstringThe grant.
amountrequiredstringThe 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#

WithdrawInputTypeMeaning
mintrequiredstringThe pool's mint.
amountrequiredstringThe amount to pay out, a positive u64.
recipientrequiredstringThe wallet that receives it.
recipientTokenAccountstringThe receiving token account. Defaults to the recipient's associated token account for the mint.

transfer#

TransferInputTypeMeaning
mintrequiredstringThe pool's mint.
amountrequiredstringThe amount to send, a positive u64.
recipientrequiredstringThe 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.

ts
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#

OptionTypeMeaning
facilitatorUrlstringThe 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.
fetchtypeof fetchThe transport for every request the SDK makes. Defaults to the global fetch.
artifactBaseUrlstringA 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#

OptionTypeMeaning
signalAbortSignalCancels the operation.
onProgress(progress: ProvingProgress) => voidCalled as the operation moves through its stages.

A ProvingProgress is { stage, progress, message }, with progress from 0 to 1 within the stage:

stageWhat is happening
syncingReading the pool's note tree from the facilitator.
loading_artifactsDownloading the circuit's WASM and proving key.
witnessComputing the witness.
provingComputing the Groth16 proof.
submittingThe proof is with the facilitator, or with the seller for a payment.

ScanOptions#

OperationOptions and:

OptionTypeMeaning
mintsstring[]Scan only these pools. By default every open pool.
onUpdate(balance: BalanceView) => voidCalled 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#

FieldTypeMeaning
statestringscanning while a scan runs, then ready, or empty when the owner holds no notes.
addressstring | nullThe owner's Alba address.
assetsAssetBalance[]One entry per pool scanned.
notesNoteView[]The owner's unspent notes and live grants.
scannedLeavesnumberTree leaves read so far.
totalLeavesnumberTree leaves in the pools being scanned.
errorobject | nullnull from a scan that returned.

An AssetBalance:

FieldTypeMeaning
mintstringThe pool's mint.
symbolstringThe mint's symbol.
decimalsnumberThe mint's decimals.
availablestringThe sum of the owner's plain notes.
grantedstringWhat the owner's live grants have left.
totalstringavailable plus granted.

A NoteView:

FieldTypeMeaning
commitmentstringThe note's commitment.
mintstringThe pool's mint.
amountstringThe note's amount.
leafIndexnumberIts position in the note tree.
kindstringplain for a deposit or change, received for a payment that arrived at the owner's Alba address, grant for a grant's current note.
spentbooleanfalse for every note a scan returns.

GrantView#

FieldTypeMeaning
idstringThe grant's identifier, 64 hex characters derived from its seed. Pass it as grantId.
indexstringThe grant's index in the owner's sequence, from 0.
labelstringThe owner's name for it.
mintstringThe pool it lives in.
startingAmountstringWhat it held when created.
grantedstringEverything put into the grant: the starting amount plus every top-up.
remainingstringWhat it holds now. 0 once revoked.
spentstringThe sum of the prices it has paid.
feesPaidstringThe sum of the fees on those payments.
termsGrantTermsThe cap, the expiry and the sellers.
statestringactive, expired, spent or revoked.
createdAtstringWhen its record was last written, ISO 8601 in UTC.

GrantTerms#

FieldTypeMeaning
caprequiredstringThe most one payment may send to a seller, a u64.
expiryrequiredstringThe last second the agent may pay, Unix seconds as a u64.
sellersrequiredstring[]Up to 32 wallet addresses or Alba addresses. An empty array allows any seller.

LedgerView#

FieldTypeMeaning
statestringready, or empty when the grant has paid nothing yet.
grantIdstringThe grant.
rowsLedgerRow[]The payments, oldest first.
totalPaidstringThe sum of the prices.
totalFeesstringThe sum of the fees.
errorobject | nullnull from a read that returned.

A LedgerRow:

FieldTypeMeaning
idstringThe spend's identifier.
atstringThe block time, ISO 8601 in UTC.
sellerstringThe 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.
amountstringThe seller's price.
protocolFeestringThe protocol fee on the payment.
relayFeestringThe relay fee on the payment.
memo{ method, url } | nullThe request the agent paid for, decrypted.
signaturestringThe transaction.

Transaction#

FieldTypeMeaning
idstringThe transaction's identifier at the facilitator.
statusstringbuilt, submitted, settled or failed.
signaturestring | nullThe transaction signature.
slotstring | nullThe slot it landed in.
error{ code, message } | nullWhy it failed.

TransactionBuild#

FieldTypeMeaning
idstringThe build's identifier. Pass it as buildId.
transactionBase64stringThe unsigned version 0 transaction.
blockhashstringThe blockhash it was built on.
lastValidBlockHeightstringThe last block height at which it can land.
contextSlotstringThe slot the build was made at.
expiresAtstringWhen the build expires.
feestringThe 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.

ExportTypeMeaning
OPEN_BALANCE_MESSAGEstringThe fixed message a wallet signs to open a balance.
openBalanceMessage()Uint8ArrayThe same message as bytes, for a wallet's signMessage.
deriveOwnerKeys(signature)OwnerKeysThe owner's keys from the 64-byte signature: sk, pk, nk, encryptionSecretKey, encryptionPublicKey. Throws INVALID_SIGNATURE.
deriveGrantSecrets(keys, index)GrantSecretsOne grant's seed, agentSk, agentPk, encryptionKey, recordWriteToken and locator from the owner's sk and the grant's index. Throws INVALID_ARGUMENT.
encodeAlbaAddress(data)stringAn Alba address from pk and encryptionPublicKey. Throws INVALID_ALBA_ADDRESS.
decodeAlbaAddress(address)AlbaAddressData{ version, pk, encryptionPublicKey }. Throws INVALID_ALBA_ADDRESS.
encodeGrantCredential(credential)stringThe alba_grant_ string from its fields. Throws INVALID_CREDENTIAL.
decodeGrantCredential(value)GrantCredentialThe fields of a credential. Throws INVALID_CREDENTIAL.
associatedTokenAccount(owner, mint, tokenProgram?)stringThe associated token account of a wallet for a mint. tokenProgram defaults to SPL Token.

A decoded GrantCredential:

FieldTypeMeaning
version1The credential version.
seedbigintThe grant's seed.
agentSkbigintThe agent's secret key.
ownerPkbigintThe owner's public key.
ownerEncryptionPublicKeyUint8ArrayThe key memos are encrypted to, 32 bytes.
capbigintThe cap per payment.
expirybigintThe expiry, Unix seconds.
sellersstring[]The seller list, at most 32, empty for any seller.
mintstringThe pool's mint.
facilitatorUrlstringThe facilitator's base URL.
startingAmountbigintWhat the grant held when created.
ts
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:

codeRaised when
INVALID_CREDENTIALA string is not a version 1 grant credential, or ALBA_GRANT is not set.
INVALID_ALBA_ADDRESSA string is not a version 1 Alba address.
INVALID_SIGNATUREThe wallet's signature is not 64 bytes.
INVALID_ARGUMENTA 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_BALANCEThe owner's notes cannot cover an amount and its relay fee with two inputs.
INSUFFICIENT_GRANT_BALANCEA grant cannot cover a price and its fees.
GRANT_EXPIREDA payment is attempted after the grant's expiry, or a new grant's expiry is not in the future.
GRANT_REVOKEDA payment is attempted from a revoked grant.
AMOUNT_OVER_CAPA price is above the grant's cap.
SELLER_NOT_ALLOWEDA pay-to address is not on the grant's seller list.
ts
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:

text
npx -p @alba/sdk alba-mcp

It reads the grant credential from ALBA_GRANT in its environment. To start it from code:

ts
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.

InputTypeMeaning
urlrequiredstringThe resource's URL.
methodstringThe HTTP method.
headersRecord<string, string>Request headers.
bodystringThe request body.

The tool returns one text item holding JSON, a FetchPaidResult:

FieldTypeMeaning
statusnumberThe HTTP status of the final response.
headersRecord<string, string>Its headers.
bodystringIts body as text.

grant_status#

Takes no input. Returns one text item holding the grant's GrantView as JSON.