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.
npm install @remit/sdkThe 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
| Variable | Read by | Value |
|---|---|---|
REMIT_AGENT_KEY | createRemit | The agent's secret key, 64 bytes in base58. |
REMIT_PAYEE_KEY | gate, settle | The payee's secret key, 64 bytes in base58. |
REMIT_ENGINE_URL | all three | The engine's base URL. |
REMIT_API_URL | createRemit | The 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.
import { createRemit } from '@remit/sdk'
const remit = createRemit()
const response = await remit.fetch('https://api.example.com/quote')| Option | Type | Meaning |
|---|---|---|
agentKey | string | The agent's secret key. Default: REMIT_AGENT_KEY. |
engineUrl | string | Default: REMIT_ENGINE_URL. |
apiUrl | string | Default: REMIT_API_URL. |
remitId | string | The remit to spend from. Default: the newest live remit opened for this key. |
fetch | typeof fetch | The 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.
- It sends the request as given.
- Any answer other than
402is returned untouched. So is a402that is not a Remit payment request. - On a Remit
402it pays the firstacceptsentry withscheme: "remit"by callingremit.pay. - It sends the request again with the header
X-Remit-Paymentand 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.
| Argument | Type | Meaning |
|---|---|---|
requirements | PaymentRequirements | One entry of a 402 body's accepts: scheme, network, mint, payTo, price, deadlineSeconds, requestHash, resource. |
Returns a PaidPayment:
| Field | Type | Meaning |
|---|---|---|
signature | string | The pay transaction. This is the value of X-Remit-Payment. |
holdOpening | string | The hold's opening, base64. |
payee, amount, mint, requestHash | string | What 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.
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' }))import express from 'express'
import { gate } from '@remit/sdk'
const app = express()
const paid = gate({ price: '40000', mint: process.env.MINT!, network: 'solana-mainnet' })
app.get('/quote', paid.express(), (req, res) => {
res.json({ bid: '184.20', ask: '184.25' })
})import { gate } from '@remit/sdk'
const paid = gate({ price: '40000', mint: process.env.MINT!, network: 'solana-mainnet' })
export const GET = paid.next(async () => Response.json({ bid: '184.20', ask: '184.25' }))| Option | Type | Meaning |
|---|---|---|
price | string or bigint | The price of one call in base units of mint. Greater than zero. |
mint | string | The mint the price is in. |
network | string | solana-mainnet, solana-devnet or solana-localnet. Sent in the 402 body. |
payeeKey | string or keys object | The payee's secret key. Default: REMIT_PAYEE_KEY. |
payTo | string | The payee's address. Default: derived from payeeKey. |
engineUrl | string | Default: REMIT_ENGINE_URL. |
deadlineSeconds | number | How long a hold stays open for settlement. 1 to 86,400, default 300. |
minSettleBufferSeconds | number | A hold with less than this left before its deadline is refused. Default 15. |
onSettled | (result) => void | Called after each settlement with paySignature, settleSignature and responseHash. |
onSettleError | (error, payment) => void | Called when a settlement fails, with the hold it was for. |
fetch | typeof fetch | Default: the global one. |
now | () => number | The 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:
| Member | Type | Meaning |
|---|---|---|
hono() | middleware | For a Hono route. |
express() | middleware | For an Express route. |
next(handler) | route handler | Wraps 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. |
payTo | string | The 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)
| Argument | Type | Meaning |
|---|---|---|
header | string, null or undefined | The value of X-Remit-Payment. |
request | GateRequest | method, url (the full URL) and body (bytes or a string, optional). |
Returns one of:
| Result | Meaning |
|---|---|
{ 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.
import { createOwner } from '@remit/sdk'
const owner = createOwner({ keys: process.env.OWNER_SECRET_KEY! })
const remits = await owner.remits()| Option | Type | Meaning |
|---|---|---|
keys | string or keys object | A 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. |
engineUrl | string | Default: REMIT_ENGINE_URL. |
fetch | typeof fetch | Default: 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.
| Method | Returns | What 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) | RemitView | One 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) | ReceiptView | Checks 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)
| Field | Type | Meaning |
|---|---|---|
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. |
mint | string | |
amount | string or bigint | What the remit holds. |
perPaymentCap | string or bigint | |
dailyCap | string or bigint | |
payees | string[] or "any" | Up to 32 addresses. |
expiresAt | number | Unix seconds. |
agentFeeLamports | string or bigint | SOL 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:
| Field | Type | Meaning |
|---|---|---|
code | string | A stable code. |
message | string | |
status | number | The HTTP status the engine answered with, when it did. |
details | object | Extra 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.
| Class | code | Thrown when |
|---|---|---|
OverPaymentCap | OVER_PAYMENT_CAP | The price is over the remit's cap per payment. |
OverDailyCap | OVER_DAILY_CAP | The price would take today's spend over the cap per day. |
PayeeNotAllowed | PAYEE_NOT_ALLOWED | The payee is not on the remit's list. |
RemitExpired | REMIT_EXPIRED | The remit's expiry has passed. |
InsufficientRemit | INSUFFICIENT_REMIT | The remit holds less than the price. |
HoldExpired | HOLD_EXPIRED | A hold's deadline has passed, so it cannot be settled. |
PaymentMismatch | PAYMENT_MISMATCH | A hold is not for this payee, amount, mint or request. |
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.