@varnir/chain-client
v0.7.0
Published
The Varnir SDK - VarnirClient (onboard an identity, get a wallet, read balances, send, raise invoices) plus the low-level signing/transport primitives it is built from.
Readme
@varnir/chain-client
The Varnir SDK: onboard an identity, get a wallet, read balances, send funds, and raise invoices against a Varnir ledger network, plus the low-level signing and transport primitives it's built from.
This is what docs.varnir.site's SDK reference documents, and the same client this monorepo's own wallet and scanner applications are built on — not a thin wrapper kept separate from the "real" implementation.
Why it exists
A business that builds Varnir payments and custody into its own product does
it through an SDK: send across chains (settling on the ledger when the
recipient is on Varnir, over the chain when not), raise invoices, and verify
webhook deliveries, with every transaction signed by a key that stays in the
caller's own process. That integration is how customers on the paid plans
(Hobbyist, Trader) use Varnir, and what it moves is metered in plan credits
(docs/subscription-pricing.md).
This package is the reference of the seven SDKs. The Python, Kotlin/Java, .NET, Go, PHP and Rust ports are pinned to golden vectors generated from it, so a behaviour change starts here. Varnir's own apps (the scanner and its web wallet, the browser extension, the mobile wallet, the playground, the agent server) are built on it too.
Custody model
Every transaction this SDK sends is signed with a private key that stays
in the calling process. VarnirClient takes your privateKeyHex (or an
already-onboarded identity's key) as a constructor argument and signs
locally, using either @activeledger/sdk-node (real Node.js) or pure-JS
@noble/curves (browsers, React Native) depending on which transport you
import — see Four entry points below.
The key is never sent to a Varnir-hosted server, and no method on this
client transmits it anywhere; the ledger only ever receives an already-signed
transaction. This is custody, not a hosted signing service: whoever holds
the private key controls the funds, and this SDK is how that holder signs
without handing the key to anyone else.
An already-onboarded caller supplies both halves — the private key and the
identity it's paired with. The SDK does not re-derive the identity from the
key for you (it could — computeIdentity does exactly that), because
treating a locally computed id as authoritative is how a caller ends up
holding an identity that exists nowhere on the ledger.
Install
npm install @varnir/chain-clientNode 20.19.4 or later (engines). Ships compiled ESM (dist/) with type
declarations. Inside this monorepo, depend on it as "workspace:*" instead.
Quick start
import {VarnirClient} from '@varnir/chain-client';
import {generateRecoveryPhrase, derivePrivateKeyFromPhrase} from '@varnir/chain-client/keys';
const {privateKeyHex} = derivePrivateKeyFromPhrase(generateRecoveryPhrase());
const client = await VarnirClient.onboard({network: 'testnet', privateKeyHex});
const wallet = await client.getWallet('niles');
const invoice = await client.createInvoice({wallets: [wallet], name: 'Invoice', amount: '10'});'testnet' is the entire network configuration — node URLs, gateway URLs,
deployed contract stream ids, each chain's ledger-side network spelling,
and native decimals are all resolved internally. A caller never needs to
know a hostname or a hex contract id.
Payout speed
An L1 withdrawal can say how quickly it should go out: speed is one of
PAYOUT_SPEEDS, 'economy' (within 24 hours, the default), 'standard'
(within an hour) or 'instant' (straight away, on its own).
const sent = await client.send({chain: 'niles', to: 'TSC9KBw...', amount: '1.5', speed: 'instant'});
sent.speed; // 'instant' ('economy' when omitted); unset on a ledger settlement or a held proposal
sent.speedRecorded; // true/false when you passed speed; undefined when you did notPayout speeds are not built on the network yet: every withdrawal still goes
out immediately and is charged at the Standard rate, and the choice is only
recorded (a separate, best-effort POST /api/withdrawals/speed after the
withdrawal is accepted). The speed is never signed into the transaction, so
it changes neither the umid nor the repeat-payment fingerprint. An unknown
value throws VarnirError('VALIDATION') before anything is sent.
speedRecorded === false does not mean the send failed.
Committed but not confirmed: OUTCOME_UNKNOWN
send can throw after the transaction already committed: if the stream it
created can't be read back in time (read-after-write lag, more likely under
Activeledger v5's P2P commit), the SDK doesn't know whether it moved money or
is held for co-sign. Never resend on this error — confirm first:
import {VarnirError} from '@varnir/chain-client';
try {
await client.send({chain: 'niles', to: 'TSC9KBw...', amount: '1.5', ref: 'invoice-42'});
} catch (err) {
if (err instanceof VarnirError && err.code === 'OUTCOME_UNKNOWN') {
console.error('commit unknown:', err.committedUmid);
// err.message names the created stream to check with getTransferProposal,
// or look err.committedUmid up in the transaction history.
} else {
throw err;
}
}See the error taxonomy.
Verifying webhooks
A webhook receiver needs only the signing secret
((await client.getWebhookSettings()).secret), not a client or a key:
import {verifyWebhookRequest} from '@varnir/chain-client';
// rawBody: the request body EXACTLY as received (a string here; a Uint8Array also works), before JSON.parse.
// headers: a Fetch Headers, or Node's req.headers.
if (!verifyWebhookRequest(secret, rawBody, req.headers)) {
res.statusCode = 401; // not from Varnir, or stale: do not process it
return res.end();
}
const event = JSON.parse(rawBody);Deliveries carry X-Varnir-Timestamp (unix seconds) and
X-Varnir-Signature: v1=<hex HMAC-SHA256 of "{timestamp}." + body>.
verifyWebhookSignature({secret, body, timestamp, signature}) takes the two
header values directly. Both return false, never throw, on a missing or
malformed header, a timestamp more than WEBHOOK_TOLERANCE_SECONDS (300)
either side of your clock, or a mismatch; the comparison is constant-time.
First payments to a new recipient (off by default)
New-recipient protection is built into Varnir.CryptoTransfer but switched
off by default on the network (a contract kill switch; see
docs/new-address-hold-design.md).
When it is on, the first payment an identity makes to an address or identity
it has never paid is held for 24 hours: send() still succeeds, but the result carries hold and nothing
has reached the recipient. The owner is emailed a cancel link and a speed-up
code.
const sent = await client.send({chain: 'niles', to, amount: '5'});
if (sent.hold) {
console.log(`held until ${sent.hold.until}`); // waitForTransfer throws WITHDRAWAL_HELD
// await client.speedUpTransfer(sent.hold.id, code); // owner key + the emailed code
// await client.cancelHeldTransfer(sent.hold.id); // money back to your balance
}A payout bot that pays new recipients all the time can turn it off once with
await client.setWithdrawalHold(false) - owner key only, and it takes
effect 24 hours later (effectiveAt). learnKnownAddresses(signStreamIds)
teaches it the recipients you have already paid.
These hold methods exist only in this SDK so far. None of the six ports has them, or reads a hold off a send result.
The full method reference — onboard / new VarnirClient({privateKeyHex, identity}),
identityExists, getIdentityStream, listWallets, getWallet,
createWallet, getBalances, send, getTransfer, waitForTransfer,
createInvoice, listTransactions, getDeposit, getReceipt, and the
statics generateKey / computeIdentity — lives
at docs.varnir.site.
Four entry points, one package
// The SDK, plus every low-level primitive it is built from.
import {VarnirClient, signPayloadBase64, sendToAnyNode, gatewayGet} from '@varnir/chain-client';
// Recovery phrases and BIP32/BIP44 derivation, re-exported from
// @varnir/signing. A subpath because it pulls in bip39 and its wordlist,
// which callers of the main entry point have no use for.
import {generateRecoveryPhrase, derivePrivateKeyFromPhrase} from '@varnir/chain-client/keys';
// Direct-to-node, real Node.js only — @activeledger/sdk-node, signs via
// node:crypto.
import {NodeTransport, importEllipticCurveKey} from '@varnir/chain-client/node';
// Direct-to-node, browsers and React Native — @activeledger/sdk-web,
// signs via @noble/curves (pure JS, no native/WebCrypto dependency).
import {WebTransport, importEllipticCurveKey} from '@varnir/chain-client/web';Pick the transport by where your code runs, not by habit:
@varnir/chain-client(default import) —VarnirClient, the network/chain registry, a typed gateway HTTP client, and the manual-sign helpers. No dependency on either ledger SDK, so it's safe to import from anywhere, including a React Native bundler.@varnir/chain-client/node—NodeTransport: generic direct-to-node ledger operations (key generation, onboarding, signing, sending) via@activeledger/sdk-node. Real Node.js only.@varnir/chain-client/web—WebTransport: the same method shape asNodeTransport, via@activeledger/sdk-web. Safe in browsers and React Native — no Node core-module dependency, so it needs no polyfills.
Each transport lives behind its own subpath (via package.json's
exports map) so a bundler never needs to tree-shake the other ledger SDK
out — it's simply never imported unless you ask for it.
Importing an externally-derived key
If you already derive a secp256k1 key pair yourself (your own BIP32/BIP44
path, a hardware wallet, anything that isn't this package's own key
generation), importEllipticCurveKey (from /node or /web) wraps an
already-derived compressed secp256k1 key pair into the shape
NodeTransport/WebTransport's signTransaction/onboardKey expect,
without going through this package's own key generation:
import {importEllipticCurveKey, WebTransport} from '@varnir/chain-client/web';
const key = importEllipticCurveKey({privateKeyHex, publicKeyHex}); // your own key pair
const transport = new WebTransport();
await transport.onboardKey(key);publicKeyHex must be the compressed form (33 bytes) — the uncompressed
form is not supported.
Examples
examples/wallet-and-invoice-flow.ts is a complete external-automation
walkthrough — onboard an identity, get a testnet wallet, and raise an
invoice against it, entirely client-signed. Run it with
npx tsx examples/wallet-and-invoice-flow.ts from this package's directory.
Known limitations
listTransactionsis served by any gateway and does not require the centralized scanner: the gateway answers from the scanner's D1 activity feed when it can reach it, and from its own rolling ~7-day cache otherwise — the scanner's feed is the durable, cross-gateway archive, not a hard dependency. The feed's rows are the user-facing projection (kind,status,from/toas identities or addresses) — deliberately NOT the raw ledger event stream, so key lifecycle events (key generation/assignment, onboarding) are not in it.- Most reads are served by any gateway too (balances, transfers, deposits, the order book). Only the Varnir API methods — invoices, webhooks, and the wallet index — genuinely require the scanner's API origin; see docs.varnir.site/sdk/backends.
- The React Native / native-mobile path (
WebTransporton Hermes) has been verified on the web target; direct on-device iOS/Android signing behavior has not been separately confirmed.
Commands
Run from the repository root with pnpm --filter @varnir/chain-client <script>.
| Command | What it does |
|---|---|
| build | tsc -p tsconfig.json, emitting ESM and declarations to dist/ |
| dev | The same build in watch mode |
| prepare | Builds on install |
| typecheck | Type-checks src/ and examples/ without emitting |
| test | Runs every file in test/ with tsx, one after another |
| lint | Prints "no lint configured yet" |
| clean | Removes dist/ |
Consumers (and the golden-vector generators) import the built dist/, so run
build after changing src/. @varnir/signing and @varnir/network-codes
are workspace dependencies; build them first on a fresh checkout
(pnpm build at the root does it in order).
Tests
pnpm --filter @varnir/chain-client testThe suite includes the core-contract golden-vector test, send routing, payout
speed, the repeat-payment guard, the webhook verifier and the withdrawal
hold. The vectors every port is pinned to are generated from this package's
build; see packages/sdk-python.
Against a live network, scripts/sdk-e2e/run.sh --only typescript runs the
shared end-to-end scenario (Docker only; it brings up infra/local-dev if
needed).
Releasing
Published to npm as @varnir/chain-client. 0.6.0 is the latest version on
the registry; this monorepo's package.json is at 0.7.0, which is
unreleased pending publish (see CHANGELOG.md). There is no
release workflow in .github/workflows, so a release is manual:
- Move the
## Unreleasednotes inCHANGELOG.mdunder the new version and bumpversioninpackage.json. - Publish
@varnir/plan-limits(first release -0.7.0is the first version to depend on it), then@varnir/signingand@varnir/network-codesif they changed: the builtdist/imports all three by name. - Publish with
pnpm publishfrom this directory, notnpm publish: the dependencies are declaredworkspace:*, and only pnpm rewrites them to real versions.preparebuildsdist/, and onlydist/andCHANGELOG.mdare infiles.
Anything that changes what the SDK computes or sends also needs the vectors
regenerated and the six ports updated; see
docs/sdk-maintenance.md.
Related docs
- SDK core contract: the language-agnostic spec this package is the reference for
- Getting started and the rest
of
apps/docs/docs/sdk/ docs/sdk-maintenance.mdscripts/sdk-e2e/SCENARIO.mdCHANGELOG.md
License
MIT
