Skip to content

Request access

Tell us about your processing, and we'll reply by email.

SDKs

TypeScript SDK

The TypeScript SDK has the same features as the Go SDK. It is ESM, runs on Node.js 20 or later, and depends only on viem, as a peer dependency.

Terminal window
(cd <sdk>/ts && npm ci) # dependencies and the build in dist/
npm install viem <sdk>/ts # in your project
AreaAPI
API clientnew Client(...), with a method for each request of the API; errors are ApiError
AuthorizationsauthorizationDigest, authorizationFromSignature, parseRawSignature, normalizeS, verifyAuthorization
RevocationsrevocationDigest, revocationFromSignature, verifyRevocation
Listssweeps, revocations, transactions, ledgerEntries, webhookDeliveries a page at a time; allSweeps and the like through every page
WebhooksverifyWebhook and parseWebhook on Web Crypto; verifyWebhookSync and parseWebhookSync on node:crypto, from @portuna/sdk/node; sweepItems, revocationItems and isFinalStatus from both
Delegate checkverifyDeployment, factoryAddress, batcherAddress, delegateAddress for a set of hot wallets, canonicalHotWallets, and the verify-delegate command
Typesevery request and response of the API, with the API’s field names: Sweep, HotWallet, Event…
import { Client } from '@portuna/sdk'
const client = new Client({ baseUrl: 'https://api-testnet.portuna.io', apiKey: process.env.PORTUNA_API_KEY! })
const balance = await client.balance({ signal: AbortSignal.timeout(10_000) })

Options: baseUrl, apiKey and, optionally, your own fetch. Every method takes { signal } for cancellation and timeouts. Methods: balance, tariff, settings, updateSettings, hotWallets, createHotWallet, delegates, createDelegate, tokens, checkToken, enableToken, disableToken, createSweep, sweep, sweeps, createSweepList, sweepList, createRevocation, revocation, revocations, transaction, transactions, ledgerEntries, usage, monthlyReport, webhook, setWebhook, deleteWebhook, webhookDeliveries, sendTestWebhook, health and openapi. createSweep and createRevocation return { sweep, created } and { revocation, created }, and createSweepList { list, created }: created is false when the request repeats an earlier one, by its external_id or, for a list, the set of them, and the existing object came back.

Tokens: checkToken({ chain_id, address }) returns a token’s card, a TokenCard. enableToken({ chain_id, address }) turns a base token on again; with confirm: true it adds a token of your own, once you compared its card, and returns { token, created }, with created true for a token added for the first time. disableToken(chainId, address) turns a base token off or removes your own. In all three the native coin is 'native'. See Tokens.

sweeps, revocations, transactions, ledgerEntries and webhookDeliveries take a filter with the API’s query parameters, such as { status: 'failed', limit: 100 }, and return one page, { items, next_cursor }. The all methods, allSweeps and the like, go through every page as an async iterator:

for await (const sweep of client.allSweeps({ status: 'failed' })) {
console.log(`sweep ${sweep.id} failed: ${sweep.reason}`)
}

createSweepList(request) sends sweeps in one transaction of their own and returns { list, created }, the list with its transaction when your gas wallet was free. The request may wait up to its wait, 10 seconds if left out: give it 60 seconds, for example with { signal: AbortSignal.timeout(60_000) }. sweepList(id) gives a list as it is now, and sweeps({ list_id }) and transactions({ list_id }) its sweeps and transactions. See Sweep lists.

const request: SweepListRequest = {
chain_id: chainId,
wait: 10,
items: deposits.map((d) => ({
external_id: d.id, // required; repeating the request with the same ids returns this same list
hot_wallet: hotWallet,
account: d.account,
token: 'USDT', // the whole balance: no amount
})),
}
// The request waits up to its wait for the transaction: give it 60 seconds.
const result = await client.createSweepList(request, { signal: AbortSignal.timeout(60_000) }).catch(refused)
if (result) {
const { list, created } = result
if (!created) console.log('a repeat: the list as it is now, nothing sent again')
if (list.transaction) {
// sent: the transaction it rides; done: every item has its outcome, and this is the last one it rode. Keep the
// transaction's id: a replacement at a higher fee changes its hash.
console.log(list.status, list.transaction.id, list.transaction.hash)
} else if (list.status === 'done') {
console.log('every item was rejected before sending')
} else {
// queued or processing: the transaction comes in transaction.sent, with this list's list_id.
console.log('on its way:', list.id)
}
for (const item of list.items) {
// Its external_id is used up: to sweep the address again, use a new one.
if (item.status === 'rejected') console.log(item.external_id, 'rejected:', item.reason)
}
}

A response other than 2xx throws ApiError with status, code and message; code is empty if the response was not the API’s error format, for example from a proxy. With a 429 or a 503, retryAfter gives the seconds of its Retry-After. Codes and what to do: Errors and retries.

authorizationDigest gives the digest your custody signs. authorizationFromSignature takes the raw signature, DER or r‖s, as hex or bytes, with any s, normalizes it, finds y_parity and throws unless the deposit address signed. Chain 0 is refused.

export async function signAuthorization(
sign: Signer,
keyId: string,
deposit: Address,
chainId: number,
delegate: Address,
nonce: number,
): Promise<Authorization> {
const digest = authorizationDigest({ chainId, address: delegate, nonce }) // refuses chain 0
const signature = await sign(keyId, digest)
// Reads DER or r‖s, moves s to the lower half and finds y_parity. Throws unless the deposit address signed
// this very digest, so a wrong key never reaches the API.
return authorizationFromSignature({ chainId, address: delegate, nonce, deposit, signature })
}

More in Signing authorizations.

parseWebhookSync(secret, header, body) from @portuna/sdk/node verifies the Portuna-Signature header against the raw body, within five minutes, and returns the typed Event; it throws WebhookSignatureError otherwise. Outside Node.js, use the async parseWebhook from @portuna/sdk.

Event is a union by type. In a transaction.* event, data is a TransactionEvent: the transaction as it was at the event, part of parts, test in the sample sendTestWebhook asks for, and its items. sweepItems(data) gives them as SweepItem[] in batch order, and revocationItems(data) as RevocationItem[], as data.transaction.kind says; each throws for the other kind. isFinalStatus(status) tells a status that never changes: swept, revoked, failed, rejected. In sweep.* and revocation.* events, for those no transaction carried, data is a Sweep or a Revocation. See Webhooks for what a receiver must do.

// Records a sweep's status, unless it already has a final one: events may come out of order, and a processing or
// queued that comes after swept or failed is older news.
function apply(id: string, status: string): void {
const old = statuses.get(id)
if (old === undefined || !isFinalStatus(old)) statuses.set(id, status)
}
function handle(event: Event): void {
switch (event.type) {
case 'transaction.sent':
case 'transaction.mined':
case 'transaction.reverted':
case 'transaction.dropped': {
// One event per transaction, with every sweep it carries; revocations: revocationItems.
const { transaction } = event.data
if (transaction.kind !== 'sweep') break
for (const s of sweepItems(event.data)) {
// processing in transaction.sent; swept or failed in transaction.mined; queued or failed in
// transaction.reverted and transaction.dropped.
apply(s.id, s.status)
console.log(`sweep ${s.id} (${s.external_id}), transaction ${transaction.id} #${s.batch_index}: ${s.status}`)
}
break
}
case 'sweep.rejected':
case 'sweep.failed':
// A sweep that ended before any transaction carried it.
apply(event.data.id, event.data.status)
console.log(`sweep ${event.data.id} (${event.data.external_id}): ${event.data.status} ${event.data.reason}`)
break
case 'balance.low':
console.log(`top up the gas wallet on chain ${event.data.chain_id}: ${event.data.balance} wei left`)
break
case 'balance.payout':
console.log(`payout ${event.data.id} of ${event.data.amount} wei to ${event.data.to}: ${event.data.status}`)
break
default:
// Other and future event types: accept them.
}
}
createServer((req, res) => {
const chunks: Buffer[] = []
req.on('data', (chunk: Buffer) => chunks.push(chunk))
req.on('end', () => {
// Verify the body exactly as it arrived, before parsing it. Bodies go up to 256 KiB: node:http has no limit,
// while Express's body parsers stop at 100 KB unless told otherwise:
// express.raw({ type: 'application/json', limit: '1mb' }).
const body = Buffer.concat(chunks)
let event: Event
try {
event = parseWebhookSync(secret, String(req.headers[signatureHeader.toLowerCase()] ?? ''), body)
} catch {
res.writeHead(401).end()
return
}
// Delivery is at least once: an event may come again, with the same id.
if (!handled.has(event.id)) {
handle(event)
handled.add(event.id)
}
res.writeHead(204).end()
})
}).listen(8080)

verifyDeployment takes any client with getChainId and getCode, such as a viem PublicClient:

const chain = createPublicClient({ transport: http(process.env.RPC_URL) })
const report = await verifyDeployment(chain, {
gasWallet: process.env.GAS_WALLET as Address,
hotWallets: (process.env.HOT_WALLETS ?? '').split(',').map((h) => h.trim() as Address),
expectDelegate: process.env.DELEGATE as Address,
})
for (const c of report.checks) console.log(c.ok ? 'PASS' : 'FAIL', c.name, c.detail)
if (!report.ok) throw new Error('do not sign authorizations for this delegate')

The verify-delegate command does the same from the command line: see Verifying the delegate.