Reference

SDK

Every export of the SDK: the agent's paid fetch, the provider's gate, the owner's calls, the types and the errors.

@remit/sdk is one TypeScript package with three entry points: createRemit for an agent, gate for a provider and createOwner for an owner. It is an ES module for Node 18 or later.

Shell
npm install @remit/sdk

The SDK builds, proves and reads through Remit's engine. Every entry point takes the engine's URL as engineUrl or from REMIT_ENGINE_URL. GET /v1/config on the API returns it as engineUrl.

Environment

VariableRead byValue
REMIT_AGENT_KEYcreateRemitThe agent's secret key, 64 bytes in base58.
REMIT_PAYEE_KEYgate, settleThe payee's secret key, 64 bytes in base58.
REMIT_ENGINE_URLall threeThe engine's base URL.
REMIT_API_URLcreateRemitThe API's base URL. Optional: with it, each payment's hold is handed to the keeper for refund at its deadline.

An option passed in code wins over its variable.

Agent

createRemit(options?)

Returns the agent's handle on its remit.

TypeScript
import { createRemit } from '@remit/sdk'

const remit = createRemit()
const response = await remit.fetch('https://api.example.com/quote')
OptionTypeMeaning
agentKeystringThe agent's secret key. Default: REMIT_AGENT_KEY.
engineUrlstringDefault: REMIT_ENGINE_URL.
apiUrlstringDefault: REMIT_API_URL.
remitIdstringThe remit to spend from. Default: the newest live remit opened for this key.
fetchtypeof fetchThe fetch to use for every request. Default: the global one.

Throws RemitError with code INVALID_KEYS when no agent key is given and CONFIGURATION_REQUIRED when no engine URL is.

remit.fetch(input, init?)

A fetch that pays. Same arguments and return as the global fetch.

  1. It sends the request as given.
  2. Any answer other than 402 is returned untouched. So is a 402 that is not a Remit payment request.
  3. On a Remit 402 it pays the first accepts entry with scheme: "remit" by calling remit.pay.
  4. It sends the request again with the header X-Remit-Payment and returns that response.

It pays at most once per call. A payment the remit's terms do not allow throws one of the refusals before any transaction exists.

remit.pay(requirements)

Pays one accepts entry and returns the payment. Use it when you handle the 402 yourself.

ArgumentTypeMeaning
requirementsPaymentRequirementsOne entry of a 402 body's accepts: scheme, network, mint, payTo, price, deadlineSeconds, requestHash, resource.

Returns a PaidPayment:

FieldTypeMeaning
signaturestringThe pay transaction. This is the value of X-Remit-Payment.
holdOpeningstringThe hold's opening, base64.
payee, amount, mint, requestHashstringWhat was paid, to whom and for which request.

When apiUrl is set, pay also hands the hold's opening to the keeper. A failure of that hand-off does not fail the payment.

remit.terms()

Returns the remit's Terms: mint, perPaymentCap, dailyCap, payees (addresses or "any") and expiresAt (unix seconds). Amounts are base-unit strings.

remit.balance()

Returns remitId, mint, opened, remaining, spentToday and day (the UTC day number spentToday belongs to).

Both throw RemitError with code REMIT_NOT_FOUND when the key has no live remit.

Provider

gate(options)

Returns a gate for one price. A gate verifies payments, serves, and settles.

Hono
import { Hono } from 'hono'
import { gate } from '@remit/sdk'

const app = new Hono()
const paid = gate({ price: '40000', mint: process.env.MINT!, network: 'solana-mainnet' })

app.get('/quote', paid.hono(), (c) => c.json({ bid: '184.20', ask: '184.25' }))
OptionTypeMeaning
pricestring or bigintThe price of one call in base units of mint. Greater than zero.
mintstringThe mint the price is in.
networkstringsolana-mainnet, solana-devnet or solana-localnet. Sent in the 402 body.
payeeKeystring or keys objectThe payee's secret key. Default: REMIT_PAYEE_KEY.
payTostringThe payee's address. Default: derived from payeeKey.
engineUrlstringDefault: REMIT_ENGINE_URL.
deadlineSecondsnumberHow long a hold stays open for settlement. 1 to 86,400, default 300.
minSettleBufferSecondsnumberA hold with less than this left before its deadline is refused. Default 15.
onSettled(result) => voidCalled after each settlement with paySignature, settleSignature and responseHash.
onSettleError(error, payment) => voidCalled when a settlement fails, with the hold it was for.
fetchtypeof fetchDefault: the global one.
now() => numberThe clock, in unix seconds. Default: the system's.

Throws RemitError with code VALIDATION_ERROR for a price that is not a positive integer string or a deadline outside its range, INVALID_KEYS without a payee key, and CONFIGURATION_REQUIRED without an engine URL.

The gate returns:

MemberTypeMeaning
hono()middlewareFor a Hono route.
express()middlewareFor an Express route.
next(handler)route handlerWraps a Next.js App Router handler.
verifyPayment(header, request)Promise<VerifyResult>The check on its own.
settle(payment, response)Promise<SettleResult>The settlement on its own.
payTostringThe address the gate is paid at.

Each adapter answers 402 with the payment request when there is no usable payment and 409 when the payment was already used. Otherwise it runs your handler, adds X-Remit-Receipt to the response, and settles after the response is sent, with the hash of the response body. The HTTP payment scheme has the wire format.

With Express, a request body is hashed from req.rawBody when it is set, and from the parsed body otherwise. For routes that take a body, keep the raw bytes on req.rawBody so the hash is over exactly what the client sent.

gate.verifyPayment(header, request)

ArgumentTypeMeaning
headerstring, null or undefinedThe value of X-Remit-Payment.
requestGateRequestmethod, url (the full URL) and body (bytes or a string, optional).

Returns one of:

ResultMeaning
{ ok: true, payment }The hold is good. payment is its HoldView. Serve, then settle.
{ ok: false, status: 402, body }Answer 402 with body. body.error is payment required, payment not found, payment does not match or hold expires too soon.
{ ok: false, status: 409, body }The signature was already served, or its hold is already settled.

A signature that passes is remembered by the gate and refused if it comes again.

gate.settle(payment, response)

Settles a verified hold. payment needs only paySignature. response is the body you served: bytes, a string, or a Response. Returns paySignature, settleSignature and responseHash.

verifyPayment(header, request, options) and settle(payment, response, options)

The same two calls as plain functions, for a server that does not keep a gate. verifyPayment takes the full gate options. settle takes payeeKey, engineUrl, fetch and onSettled.

computeRequestHash(method, url, body?)

The request hash of the scheme: sha256(METHOD + " " + URL + "\n" + hex(sha256(body))) as lowercase hex. body is bytes and defaults to empty.

sha256Hex(data)

SHA-256 of bytes or a string as lowercase hex. The response hash is sha256Hex of the response body.

pubkeyFromSecretKey(secretKey)

The address of a 64-byte base58 secret key. Throws INVALID_KEYS when the key is not base58 or not 64 bytes.

Owner

createOwner(options)

Returns the owner's handle. It is also how a payee registers and withdraws.

TypeScript
import { createOwner } from '@remit/sdk'

const owner = createOwner({ keys: process.env.OWNER_SECRET_KEY! })
const remits = await owner.remits()
OptionTypeMeaning
keysstring or keys objectA base58 secret key, { kind: "secret", secretKey }, or { kind: "wallet", wallet, seed }.
signTransaction(tx: string) => Promise<string>With wallet keys: takes the unsigned transaction in base64 and returns it signed, in base64.
engineUrlstringDefault: REMIT_ENGINE_URL.
fetchtypeof fetchDefault: the global one.

With wallet keys, seed is the wallet's signature over the key-derivation message, in base64, and every transaction goes through signTransaction. With a secret key the engine signs.

MethodReturnsWhat it does
register(){ signature }Registers the key for a private balance.
deposit({ mint, amount }){ signature }Moves amount from the public token account into the private balance.
withdraw({ mint, amount, destination }){ signature }Moves amount from the private balance to the public account destination.
balances(){ mint, amount }[]The private balance per mint.
open(terms){ remitId, signature }Opens a remit.
remits()RemitView[]Every remit this owner opened.
statement(remitId)RemitViewOne remit with its payments, newest first.
revoke(remitId){ signature }Closes the remit and returns what it holds.
disclose(paySignature){ receipt }The receipt string for one payment. Works for the owner and for the payee of that payment.
verifyReceipt(receipt)ReceiptViewChecks a receipt against the chain.
registerPayee(record){ signature }Creates the directory record.
updatePayee(record){ signature }Rewrites it.

Amounts are base-unit strings or bigint.

open(terms)

FieldTypeMeaning
agent{ shieldedAddress } or { pubkey, viewingPubkey }The agent key: its private address, as POST /v1/engine/keys/address returns it for the key, or the public key of a key that has registered for a private balance.
mintstring
amountstring or bigintWhat the remit holds.
perPaymentCapstring or bigint
dailyCapstring or bigint
payeesstring[] or "any"Up to 32 addresses.
expiresAtnumberUnix seconds.
agentFeeLamportsstring or bigintSOL for the agent key's transaction fees.

registerPayee(record), updatePayee(record): name (1 to 64 bytes), url (up to 200), description (up to 280), priceHint and mint.

Plain functions

open, revoke, statement, disclose, deposit, withdraw and registerPayee are also exported as functions that take the owner options first: open(options, terms), revoke(options, remitId) and so on.

verifyReceipt(receipt, { engineUrl? }) needs no keys.

Types

RemitView, PaymentView, HoldView, SettlementView, ReceiptView, AgentRemitView and Terms are the shapes in The API. PaymentRequirements and PaymentRequiredBody are the 402 body in The HTTP payment scheme.

Errors

Every failure is a RemitError:

FieldTypeMeaning
codestringA stable code.
messagestring
statusnumberThe HTTP status the engine answered with, when it did.
detailsobjectExtra values for the code.

Refusals

A payment or settlement that a term refuses throws a subclass named for the term. Each is exported, so instanceof works.

ClasscodeThrown when
OverPaymentCapOVER_PAYMENT_CAPThe price is over the remit's cap per payment.
OverDailyCapOVER_DAILY_CAPThe price would take today's spend over the cap per day.
PayeeNotAllowedPAYEE_NOT_ALLOWEDThe payee is not on the remit's list.
RemitExpiredREMIT_EXPIREDThe remit's expiry has passed.
InsufficientRemitINSUFFICIENT_REMITThe remit holds less than the price.
HoldExpiredHOLD_EXPIREDA hold's deadline has passed, so it cannot be settled.
PaymentMismatchPAYMENT_MISMATCHA hold is not for this payee, amount, mint or request.
TypeScript
import { createRemit, PayeeNotAllowed, OverPaymentCap } from '@remit/sdk'

const remit = createRemit()
try {
  await remit.fetch('https://api.example.com/jobs')
} catch (error) {
  if (error instanceof PayeeNotAllowed) {
    // the remit's payee list does not include this API
  } else if (error instanceof OverPaymentCap) {
    // the price is above the cap per payment
  } else {
    throw error
  }
}

Other codes

A plain RemitError carries any other code: INVALID_KEYS, CONFIGURATION_REQUIRED, VALIDATION_ERROR, REMIT_NOT_FOUND, NOT_REGISTERED, INSUFFICIENT_BALANCE, CHAIN_REFUSED, UPSTREAM_UNAVAILABLE when the engine cannot be reached, and the rest of the API's error codes.

Loading the index