### Running Examples with tsx Source: https://github.com/cashubtc/cashu-ts/blob/main/examples/README.md Demonstrates how to run TypeScript examples directly using `tsx` from the repository root. Ensure `tsx` is installed as a dev dependency. ```sh npx tsx examples/.ts ``` -------------------------------- ### Clone and Setup Project Source: https://github.com/cashubtc/cashu-ts/blob/main/CONTRIBUTING.md Clone the repository, navigate into the directory, and install exact dependencies used by CI. Optionally, prepare Playwright browsers for integration tests. ```bash git clone https://github.com/cashubtc/cashu-ts.git cd cashu-ts # install exact deps used by CI npm ci # optional: prepare Playwright browsers for integration tests npm run test:prepare ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Use these commands to clone the cashu-ts repository and install the exact dependencies used by CI for a reproducible environment. This is a one-time setup step. ```bash git clone https://github.com/cashubtc/cashu-ts.git cd cashu-ts npm ci npm run test:prepare ``` -------------------------------- ### Start and Stop Nutshell Mint Source: https://github.com/cashubtc/cashu-ts/blob/main/CONTRIBUTING.md Use these Make targets to start and tear down a local Nutshell Mint instance. Ensure Docker is installed and the DEV=1 environment variable is set. ```bash # Nutshell DEV=1 make nutshell-stable-up # tear down DEV=1 make nutshell-stable-down ``` -------------------------------- ### Install Dependencies and Prepare for Tests Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Installs project dependencies using npm ci. Optionally prepares for integration tests. ```bash npm ci # optional for integration tests npm run test:prepare ``` -------------------------------- ### Start and Stop CDK Mint Source: https://github.com/cashubtc/cashu-ts/blob/main/CONTRIBUTING.md Use these Make targets to start and tear down a local CDK Mint instance. Ensure Docker is installed and the DEV=1 environment variable is set. ```bash # CDK Mint DEV=1 make cdk-stable-up # tear down DEV=1 make cdk-stable-down ``` -------------------------------- ### Simple Wallet Example Source: https://github.com/cashubtc/cashu-ts/blob/main/examples/README.md An end-to-end example demonstrating BOLT11 mint, send, receive, and melt operations against a fake-wallet LN backend. Requires a local Nutshell mint. ```typescript // simpleWallet_example.ts // End-to-end BOLT11 mint, send, receive, and melt against a fake-wallet LN backend. ``` -------------------------------- ### Run Node Integration Tests Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Starts a local Cashu mint (cdk-stable) and runs Node.js integration tests against it. Ensure you have Docker installed and running. ```bash DEV=1 make cdk-stable-up ``` ```bash npm run test-integration ``` ```bash DEV=1 make cdk-stable-down ``` -------------------------------- ### P2PKBuilder Example Usage Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/p2pk_builder.md An example demonstrating how to use the P2PKBuilder to create P2PK options and then use them in a send operation. ```APIDOC ## Example Usage ### Description This example shows how to instantiate `P2PKBuilder`, configure it with a lock public key and lock time, and then use the resulting options in a send operation. ### Code ```ts import { P2PKBuilder } from '@cashu/cashu-ts'; // Assume 'wallet' and 'proofs' are defined elsewhere // const wallet = new CashuWallet(...); // const proofs = [...] const p2pkOptions = new P2PKBuilder() .addLockPubkey('02abc...') // Replace with an actual public key .lockUntil(1_712_345_678) // Example lock time in Unix seconds .toOptions(); // Use the generated P2PK options in a send operation // await wallet.ops.send(5, proofs).asP2PK(p2pkOptions).run(); ``` ``` -------------------------------- ### Onchain Example Source: https://github.com/cashubtc/cashu-ts/blob/main/examples/README.md An interactive example for onchain (NUT-30) mint and melt against a public test mint. Requires funding an address from the Mutinynet faucet. ```typescript // onchain_example.ts // Onchain (NUT-30) mint and melt against https://onchain.cashudevkit.org on Mutinynet. // **Interactive** — pauses while you fund the printed address from the Mutinynet faucet, then continues automatically once the mint detects 2 confirmations. ``` -------------------------------- ### Start Local Mint using Docker Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Bring up a stable local mint instance using Docker for integration testing. Use `DEV=1` for development mode. ```bash DEV=1 make cdk-stable-up ``` ```bash DEV=1 make nutshell-stable-up ``` -------------------------------- ### Load Mint and Get Info Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/mint_capabilities.md Initializes a wallet, loads mint information, and retrieves the mint's capabilities. This is the first step before querying specific methods. ```typescript import { Wallet } from '@cashu/cashu-ts'; const wallet = new Wallet('http://localhost:3338'); await wallet.loadMint(); const info = wallet.getMintInfo(); ``` -------------------------------- ### Spinning up Local Mints Source: https://github.com/cashubtc/cashu-ts/blob/main/examples/README.md Commands to start local CDK or Nutshell mints using the `Makefile`. Requires `DEV=1` and optionally allows overriding the port. ```sh DEV=1 make cdk-up # then: DEV=1 make cdk-down DEV=1 make nutshell-up # then: DEV=1 make nutshell-down ``` -------------------------------- ### Install Cashu TS Source: https://github.com/cashubtc/cashu-ts/blob/main/README.md Install the Cashu TS library using npm. Note that since v4, the package is ESM-only. ```shell npm i @cashu/cashu-ts ``` -------------------------------- ### Auth Mint CDK Example Source: https://github.com/cashubtc/cashu-ts/blob/main/examples/README.md Demonstrates OAuth2 / OIDC blind-auth (NUT-21 / NUT-22) with a CDK mint and Keycloak. Uses `make up` and `make demo` commands. ```sh # auth_mint/Makefile (CDK variant) make up make demo # (or demo-device / demo-pkce) make down ``` -------------------------------- ### Local Integration Test Checklist Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md A practical checklist for setting up and running integration tests locally. Ensures all prerequisites are met before starting tests. ```bash npm ci ``` ```bash npm run test:prepare ``` ```bash DEV=1 make cdk-stable-up ``` ```bash DEV=1 make nutshell-stable-up ``` ```bash DEV=1 make cdk-rc-up ``` ```bash DEV=1 make nutshell-rc-up ``` ```bash npm run test-integration ``` ```bash DEV=1 make cdk-stable-down ``` ```bash DEV=1 make nutshell-stable-down ``` -------------------------------- ### BOLT12 Wallet Example Source: https://github.com/cashubtc/cashu-ts/blob/main/examples/README.md Demonstrates a reusable BOLT12 offer flow, including minting via BOLT11 and paying an offer. Requires a local CDK mint. ```typescript // bolt12Wallet_example.ts // Reusable BOLT12 offer flow: mint via BOLT11, pay the offer, mint again from accumulated payments. ``` -------------------------------- ### Start Development Watch Mode Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Enable TypeScript watch mode for continuous development. ```bash npm run dev ``` -------------------------------- ### Get Mint Info Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Fetches general information about the mint. ```typescript getMintInfo(): MintInfo; ``` -------------------------------- ### Example P2PKBuilder Usage Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/p2pk_builder.md Demonstrates how to instantiate P2PKBuilder, add a lock public key, set a lock time, and convert it to P2PKOptions for use with the wallet's send operation. Ensure the public key format is correct (02|03 compressed, or x only for Nostr). ```typescript import { P2PKBuilder } from '@cashu/cashu-ts'; const p2pk = new P2PKBuilder().addLockPubkey('02abc...').lockUntil(1_712_345_678).toOptions(); await wallet.ops.send(5, proofs).asP2PK(p2pk).run(); ``` -------------------------------- ### Start Local Cashu Mints Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Manages the lifecycle of local Cashu mint instances using Makefile targets. Supports cdk and nutshell mints in stable or release candidate versions. ```bash DEV=1 make cdk-stable-up ``` ```bash DEV=1 make cdk-stable-down ``` ```bash DEV=1 make nutshell-stable-up ``` ```bash DEV=1 make nutshell-stable-down ``` -------------------------------- ### Auth Mint Nutshell BLS Example Source: https://github.com/cashubtc/cashu-ts/blob/main/examples/README.md Demonstrates OAuth2 / OIDC blind-auth with a Nutshell BLS mint and Keycloak. Requires a sibling `../nutshell` checkout and uses specific `make` commands. ```sh # auth_mint/Makefile (Nutshell BLS variant) make nutshell-up make nutshell-demo # (or nutshell-demo-device / nutshell-demo-pkce) make nutshell-down # -- requires a sibling `../nutshell` checkout on a branch with cashubtc/nutshell#1004 (override path via `NUT_BLS_PATH=…`). ``` -------------------------------- ### Restore Proofs Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Restores proofs from a given start index and count. This is useful for recovering wallet data. ```typescript restore(start: number, count: number, config?: RestoreConfig): Promise<{ proofs: Proof[]; lastCounterWithSignature?: number; }>; ``` -------------------------------- ### Run Local Browser Integration Tests Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Starts a local Cashu mint and runs integration tests within a browser environment. This is necessary for browser-facing changes as it ensures unique LN invoices per run. ```bash npm run test-integration:browser:local:cdk ``` ```bash npm run test-integration:browser:local:cdk -- firefox ``` -------------------------------- ### Stop Local Mint using Docker Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Tear down the stable local mint instance started with Docker. ```bash DEV=1 make cdk-stable-down ``` ```bash DEV=1 make nutshell-stable-down ``` -------------------------------- ### Clean Install Dependencies After Branch Switch Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Always run `npm ci` after switching between major branches to ensure your `node_modules` directory matches the checked-in lockfile. This prevents confusing build or extractor errors. ```bash # after checkout npm ci ``` -------------------------------- ### Handle `once*` Wallet Events with AbortSignal and Timeout Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_events/cancel_abort.md The `once*` event helpers automatically cancel after resolution, rejection, timeout, or abort. This example demonstrates waiting for a mint to be paid, with a timeout and abort signal. ```typescript try { const paid = await wallet.on.onceMintPaid(quoteId, { signal: ac.signal, timeoutMs: 60_000, }); console.log('Paid', paid.amount); } catch (e) { console.warn('Not paid in time or aborted', e); } ``` -------------------------------- ### Implement Custom CounterSource with IndexedDB Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/deterministic_counters.md Example of a custom `CounterSource` implementation using IndexedDB for durable storage. This class needs to implement the `reserve` and `advanceToAtLeast` methods for atomic read-and-increment operations in your database. ```typescript import type { CounterSource, CounterRange } from '@cashu/cashu-ts'; class IndexedDbCounterSource implements CounterSource { async reserve(keysetId: string, n: number): Promise { // atomic read-and-increment in your DB } async advanceToAtLeast(keysetId: string, minNext: number): Promise { // conditional update: SET next = max(next, minNext) } // Optional: snapshot(), setNext() } ``` -------------------------------- ### wallet.decodeToken Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/get_token.md Once you have a wallet loaded for the correct mint and unit, call `wallet.decodeToken` to get the fully hydrated `Token` with complete `Proof[]` (keyset IDs resolved). Validate `meta.mint` before any network call, especially in server-side code. ```APIDOC ## wallet.decodeToken ### Description Decodes a token string into a fully hydrated `Token` object, including resolved keyset IDs, after a wallet has been initialized and loaded for the correct mint and unit. ### Method `wallet.decodeToken(token: string): Token` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript import { Wallet } from '@cashu/cashu-ts'; const meta = getTokenMetadata(tokenString); // Validate meta.mint before any network call, especially in server-side code. const wallet = new Wallet(meta.mint, { unit: meta.unit }); await wallet.loadMint(); const token = wallet.decodeToken(tokenString); // token.proofs — full Proof[] with resolved keyset IDs // token.mint, token.unit, token.memo ``` ### Response #### Success Response (Token) - **mint** (string) - The URL of the mint. - **unit** (string) - The currency unit of the token. - **memo** (string) - The memo associated with the token. - **proofs** (Proof[]) - An array of Proof objects with resolved keyset IDs. #### Response Example ```json { "mint": "https://mint.example.com", "unit": "sat", "memo": "", "proofs": [ { "id": "some_keyset_id", "amount": 64, "secret": "...", "commitment": "..." } ] } ``` ``` -------------------------------- ### Create a Wallet (Simplest) Source: https://github.com/cashubtc/cashu-ts/blob/main/README.md Instantiate a new Wallet with a mint URL. Always call `loadMint()` after instantiation to prepare the wallet for use. The unit defaults to 'sat'. ```typescript import { Wallet } from '@cashu/cashu-ts'; // Simplest: With a mint URL const mintUrl = 'http://localhost:3338'; const wallet1 = new Wallet(mintUrl); // unit is 'sat' await wallet1.loadMint(); // wallet is now ready to use // Persist these in your app const keychainCache = wallet1.keyChain.cache; // KeyChainCache const mintInfoCache = wallet1.getMintInfo().cache; // GetInfoResponse ``` -------------------------------- ### Two-Step Melt with `prepare()` Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/melt.md Creates a `MeltPreview` and any NUT-08 blanks without immediate payment, allowing for safe retries. `run()` is equivalent to calling `prepare()` and then `wallet.completeMelt()`. ```typescript const preview = await wallet.ops.meltBolt11(meltQuote, myProofs).asDeterministic().prepare(); // Persist `preview` if you want to retry safely later. const { quote, change } = await wallet.completeMelt(preview); ``` -------------------------------- ### Prepare and Run Integration Tests Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Commands to prepare the environment and run integration tests. ```bash npm run test:prepare npm run test-integration ``` -------------------------------- ### Payment API Example (Firebase Cloud Function) Source: https://github.com/cashubtc/cashu-ts/blob/main/examples/README.md A JavaScript code snippet illustrating how to receive locked ecash within a Firebase Cloud Function. This example is not runnable standalone. ```javascript // paymentApi_example.js // Code snippet for receiving locked ecash inside a Firebase Cloud Function. Not runnable standalone. ``` -------------------------------- ### CounterRange Type Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Represents a range of counters, including the starting point and the count. ```APIDOC ## CounterRange Type ### Description Represents a range of counters, including the starting point and the count. ### Fields - **count**: The number of counters in the range. - **start**: The starting number of the counter range. ``` -------------------------------- ### Get Unit Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Returns the currency unit used by the mint (e.g., satoshis). ```typescript get unit(): string; ``` -------------------------------- ### Get Keyset Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Retrieves a specific keyset by its ID, or the default keyset if no ID is provided. ```typescript getKeyset(id?: string): Keyset; ``` -------------------------------- ### Get Fees for Proofs Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Calculates the fees required for a set of proofs, identified by their IDs. ```typescript getFeesForProofs(proofs: Array>): Amount; ``` -------------------------------- ### Get Default Output Type Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Returns the default output type configured for the wallet. ```typescript defaultOutputType(): OutputType; ``` -------------------------------- ### Two-Step BOLT11 Mint with Prepare Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/mint.md This method allows preparing the mint payload first, which can be persisted for safe retries. `run()` is a shortcut for preparing and completing the mint. ```typescript const preview = await wallet.ops.mintBolt11(100, quote).asDeterministic(0).prepare(); // Persist `preview` if you want to retry safely later. const newProofs = await wallet.completeMint(preview); ``` -------------------------------- ### Get Fees for Keyset Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Calculates the fees required for a given number of inputs and a specific keyset ID. ```typescript getFeesForKeyset(nInputs: number, keysetId: string): Amount; ``` -------------------------------- ### Get Data Field from Secret Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Extracts the data field from a Secret object or string representation. Useful for retrieving the payload of a secret. ```typescript export function getDataField(secret: Secret | string): string; ``` -------------------------------- ### Wallet Constructor Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Initializes a new Wallet instance. Accepts a mint URL or object and various configuration options. ```typescript export class Wallet { constructor(mint: Mint | string, options?: { unit?: string; authProvider?: AuthProvider; keysetId?: string; bip39seed?: Uint8Array; secretsPolicy?: SecretsPolicy; counterSource?: CounterSource; counterInit?: Record; denominationTarget?: number; selectProofs?: SelectProofs; outputDataCreator?: OutputDataCreator; requireSigDleq?: boolean; customRequest?: RequestFn; requestFetch?: RequestFetch; logger?: Logger; }); } ``` -------------------------------- ### Get Decoded Token from Binary Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Decodes a Cashu token from its binary (Uint8Array) representation. This is an efficient way to process tokens received over the network. ```typescript export function getDecodedTokenBinary(bytes: Uint8Array): Token; ``` -------------------------------- ### Initialize and Use Deterministic Counters Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/deterministic_counters.md Initialize a wallet with saved counter states and subscribe to counter reservations for persistence. Inspect the next available counter and advance it after restores. ```typescript // 1) Seed once at app start if you have previously saved "next" per keyset const wallet = new Wallet(mintUrl, { unit: 'sat', bip39seed, keysetId: preferredKeysetId, // e.g. '0111111' counterInit: loadCountersFromDb(), // e.g. { '0111111': 128 } }); await wallet.loadMint(); // Alternative to using counterInit for individual keyset allocation await wallet.counters.advanceToAtLeast('0111111', 128); // 2) Subscribe once, persist future reservations wallet.on.countersReserved(({ keysetId, start, count, next }) => { // next is start + count (i.e: next available) saveNextToDb(keysetId, next); // do an atomic upsert per keysetId }); // 3) Inspect current state, what will be reserved next const nextCounter = await wallet.counters.peekNext('0111111'); // 128 // 4) After a restore or cross device sync, bump the cursor forward const { lastCounterWithSignature } = await wallet.batchRestore(); if (lastCounterWithSignature != null) { const next = lastCounterWithSignature + 1; // e.g. 137 await wallet.counters.advanceToAtLeast('0111111', next); await saveNextToDb('0111111', next); } ``` -------------------------------- ### Two-Step BOLT11 Mint with prepare() Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/mint.md Allows preparing the mint payload first, which can be persisted and used later to complete the minting process. This is useful for retrying mint operations safely. ```APIDOC ## Two-Step BOLT11 Mint with prepare() ### Description Prepares the mint payload without immediate minting, allowing for persistence and safe retries. The mint is completed in a subsequent step. ### Method Signatures - `wallet.ops.mintBolt11(amount: number, quote: string | MintQuoteBolt11Response): MintBuilder` - `MintBuilder.prepare(): Promise` - `wallet.completeMint(payload: MintPayload): Promise` ### Parameters - **amount** (number) - The amount of tokens to mint. - **quote** (string | MintQuoteBolt11Response) - The BOLT11 quote information. - **payload** (MintPayload) - The prepared mint payload from `prepare()`. ### Usage 1. Prepare the mint payload: `const preview = await wallet.ops.mintBolt11(100, quote).asDeterministic(0).prepare();` 2. Complete the mint: `const newProofs = await wallet.completeMint(preview);` ### Notes - `prepare()` builds the mint payload without calling the mint. - `run()` is a shortcut equivalent to calling `prepare()` and then `wallet.completeMint()`. ``` -------------------------------- ### Get Encoded Token from Binary Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Encodes a Cashu Token object into its binary (Uint8Array) representation. This is useful for network transmission where binary formats are preferred. ```typescript export function getEncodedTokenBinary(token: Token): Uint8Array; ``` -------------------------------- ### Create a Wallet (With Cached Data) Source: https://github.com/cashubtc/cashu-ts/blob/main/README.md Instantiate a wallet using cached mint data to avoid network calls on startup. Ensure `loadMintFromCache` is called with previously saved `mintInfoCache` and `keychainCache`. ```typescript // Advanced: With cached mint data (avoids network calls on startup) const wallet2 = new Wallet(keychainCache.mintUrl); // unit defaults to 'sat' wallet2.loadMintFromCache(mintInfoCache, keychainCache); // wallet2 is now ready to use ``` -------------------------------- ### Get Blind Auth Token Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Retrieve a blind authentication token for a specific HTTP request method and path. Useful for authenticated API calls. ```typescript await authManager.getBlindAuthToken({ method: 'GET', path: '/info' }); ``` -------------------------------- ### Run Local Browser Integration Tests Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Use this wrapper command for local full-browser integration test runs, particularly with the CDK. ```bash npm run test-integration:browser:local:cdk ``` -------------------------------- ### getKeys Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Fetches all keys for the available keysets from the mint. ```APIDOC ## GetKeysResponse ### Description Represents the response containing mint keys for various keysets. ### Type `type GetKeysResponse = { keysets: MintKeys[] }` ``` -------------------------------- ### Two-Step BOLT11 Mint with prepareMint() / completeMint() Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/mint_token.md This two-step process allows for persisting a preview before minting, which is beneficial for retries and safe recovery if the application restarts. The invoice must be paid before proceeding to mint proofs. ```typescript import { Wallet, MintQuoteState } from '@cashu/cashu-ts'; const wallet = new Wallet('http://localhost:3338'); await wallet.loadMint(); const mintQuote = await wallet.createMintQuoteBolt11(64); // pay the invoice here before continuing... const mintQuoteChecked = await wallet.checkMintQuoteBolt11(mintQuote.quote); if (mintQuoteChecked.state !== MintQuoteState.PAID) { throw new Error('Mint quote is not paid yet'); } const preview = await wallet.prepareMint('bolt11', 64, mintQuoteChecked, undefined, { type: 'deterministic', counter: 0, }); // Persist an app-defined snapshot here if you want to retry safely later. // Do not call JSON.stringify(preview) directly; preview objects contain non-JSON-safe values. const proofs = await wallet.completeMint(preview); ``` -------------------------------- ### Add Dependency and Update Lockfile Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Use npm install to add a new package and update the package-lock.json. For development dependencies, use the --save-dev flag. ```bash npm install --save # or for dev dependencies npm install --save-dev ``` -------------------------------- ### Prepare Mint and Melt Operations using Wallet Ops Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/nut19.md An alternative method to prepare mint and melt operations using the `wallet.ops` interface, which follows a similar pattern for preparing previews that need to be persisted for replay safety. ```typescript const mintPreview = await wallet.ops.mintBolt11(64, quoteId).prepare(); const meltPreview = await wallet.ops.meltBolt11(meltQuote, proofsToSend).prepare(); ``` -------------------------------- ### Export DEV Environment Variable Source: https://github.com/cashubtc/cashu-ts/blob/main/CONTRIBUTING.md Export the DEV=1 environment variable to enable the Make targets for starting mint instances. This can be done before running Make commands. ```bash export DEV=1 make cdk-stable-up make nutshell-stable-up ``` -------------------------------- ### getKeysets Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Fetches all available keysets from the mint. ```APIDOC ## GetKeysetsResponse ### Description Represents the response containing a list of mint keysets. ### Type `type GetKeysetsResponse = { keysets: MintKeyset[] }` ``` -------------------------------- ### Mint Class Constructor Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Initializes a new Mint instance. It requires the mint URL and accepts optional configuration for custom requests, fetch functions, authentication providers, and logging. ```typescript new Mint(mintUrl, options?: { customRequest?: RequestFn; requestFetch?: RequestFetch; authProvider?: AuthProvider; logger?: Logger; }); ``` -------------------------------- ### Get HTLC Witness Preimage Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Extracts the preimage from a Proof's witness data if it corresponds to an HTLC. This is used to reveal the secret that unlocks HTLC funds. ```typescript export function getHTLCWitnessPreimage(witness: Proof['witness']): string | undefined; ``` -------------------------------- ### Get Encoded Token Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Encodes a Cashu Token object into a string format, with an option to remove DLEQ proofs. This is used to serialize tokens for transmission or storage. ```typescript export function getEncodedToken(token: Token, opts?: { removeDleq?: boolean }): string; ``` -------------------------------- ### Create an Authentication Wallet Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Initializes a wallet with authentication capabilities, allowing interaction with a Cashu mint. Useful for applications requiring user authentication or OIDC flows. ```typescript export function createAuthWallet(mintUrl: string, options?: { authPool?: number; oidc?: OIDCAuthOptions; customRequest?: RequestFn; requestFetch?: RequestFetch; logger?: Logger; }): Promise<{ mint: Mint; auth: AuthManager; oidc: OIDCAuth; wallet: Wallet; }>; ``` -------------------------------- ### Get Decoded Token Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Decodes a Cashu token string using a list of known keyset IDs. This function parses the token and verifies its integrity against the provided keys. ```typescript export function getDecodedToken(tokenString: string, keysetIds: readonly string[]): Token; ``` -------------------------------- ### Initialize Wallet and Create Secret in IIFE Source: https://github.com/cashubtc/cashu-ts/blob/main/test/consumer/iife/index.html This snippet shows how to import and use the Wallet and createP2PKsecret functions from the cashu-ts library within an IIFE. It's useful for quick testing or direct browser integration. ```javascript const { Wallet, createP2PKsecret } = window.cashuts; const mintUrl = 'http://localhost:3338'; const wallet = new Wallet(mintUrl); const secret = createP2PKsecret('foo'); console.log(wallet, secret); ``` -------------------------------- ### Get G2 Public Key from Private Key Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Derives the G2 public key from a given private key using BLS cryptography. This is a utility function for BLS-based operations. ```typescript export function getG2PubKeyFromPrivKey(privKey: Uint8Array): Uint8Array; ``` -------------------------------- ### Initialize AuthManager Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Instantiate the AuthManager with a mint URL and optional configuration. Use this to manage authentication tokens and keysets. ```typescript new AuthManager("https://cashu-mint.example.com/"); ``` -------------------------------- ### Run Browser Integration Tests (Firefox) Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Execute browser integration tests specifically for the Firefox browser against a running mint instance. ```bash npm run test-integration:browser:firefox ``` -------------------------------- ### Run Integration Tests Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Execute integration tests, which require a local mint to be running. ```bash npm run test-integration ``` -------------------------------- ### Receive Raw Proofs Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/receive.md Accept an array of raw proofs directly into your wallet. This is useful when you already have the proofs in a decoded format. ```typescript const oldProofs: Proof[] = [proof1, proof2, proof3, ...]; const freshProofs = await wallet.ops.receive(oldProofs).run(); ``` -------------------------------- ### Connect WebSocket Method Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Establishes a WebSocket connection to the mint. This method is asynchronous and returns a Promise that resolves when the connection is established. ```typescript connectWebSocket(): Promise; ``` -------------------------------- ### Enable Console Logging for Mint and Wallet Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/logging.md Instantiate `ConsoleLogger` with a desired log level (e.g., 'error', 'debug') and pass it to the `logger` option when creating a `Mint` or `Wallet` instance. This enables console output for debugging. ```typescript import { Mint, Wallet, ConsoleLogger, LogLevel } from '@cashu/cashu-ts'; const mintUrl = 'http://localhost:3338'; const mintLogger = new ConsoleLogger('error'); const mint = new Mint(mintUrl, undefined, { logger: mintLogger }); // Enable logging for the mint const walletLogger = new ConsoleLogger('debug'); const wallet = new Wallet(mint, { logger: walletLogger }); // Enable logging for the wallet await wallet.loadMint(); // wallet with logging is now ready to use ``` -------------------------------- ### Custom Output Data Creator Implementation Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/create_wallet.md Implement the `OutputDataCreator` interface to customize how output data is generated, for example, to use platform-specific deterministic secrets. Custom creators can delegate to default methods for standard behavior. ```typescript import { OutputData, type OutputDataCreator, Wallet } from '@cashu/cashu-ts'; class CustomOutputDataCreator implements OutputDataCreator { createP2PKData(...args: Parameters) { const [p2pk, amount, keyset, customSplit] = args; return OutputData.createP2PKData(p2pk, amount, keyset, customSplit); } createSingleP2PKData(...args: Parameters) { const [p2pk, amount, keysetId] = args; return OutputData.createSingleP2PKData(p2pk, amount, keysetId); } createRandomData(...args: Parameters) { const [amount, keyset, customSplit] = args; return OutputData.createRandomData(amount, keyset, customSplit); } createSingleRandomData(...args: Parameters) { const [amount, keysetId] = args; return OutputData.createSingleRandomData(amount, keysetId); } createDeterministicData(...args: Parameters) { const [amount, seed, counter, keyset, customSplit] = args; // Replace this with your runtime-specific implementation. return OutputData.createDeterministicData(amount, seed, counter, keyset, customSplit); } createSingleDeterministicData( ...args: Parameters ) { const [amount, seed, counter, keysetId] = args; // Replace this with your runtime-specific implementation. return OutputData.createSingleDeterministicData(amount, seed, counter, keysetId); } } const wallet = new Wallet('http://localhost:3338', { outputDataCreator: new CustomOutputDataCreator(), }); await wallet.loadMint(); ``` -------------------------------- ### Run Unit Tests Source: https://github.com/cashubtc/cashu-ts/blob/main/DEVELOPER.md Execute all unit tests for both Node.js and browser environments. ```bash npm test ``` -------------------------------- ### Decode Token Data After Wallet Initialization Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/get_token.md Once a wallet is loaded for the correct mint and unit, use `wallet.decodeToken` to get the fully hydrated `Token` object with resolved keyset IDs. Ensure you validate the mint before any network calls. ```typescript import { Wallet } from '@cashu/cashu-ts'; const meta = getTokenMetadata(tokenString); // Validate meta.mint before any network call, especially in server-side code. const wallet = new Wallet(meta.mint, { unit: meta.unit }); await wallet.loadMint(); const token = wallet.decodeToken(tokenString); // token.proofs — full Proof[] with resolved keyset IDs // token.mint, token.unit, token.memo ``` -------------------------------- ### Default Receive Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/receive.md Receives tokens or raw proofs using the default method. You can either run it directly or use `prepare()` for a dry run. ```APIDOC ## Default Receive This operation accepts an encoded token string, a decoded `Token`, or raw `Proof[]`. ### Method Signature `wallet.ops.receive(token | Proof[]).run()` ### Description Receives tokens or raw proofs into the wallet. ### Parameters - `token | Proof[]`: An encoded token string, a decoded `Token` object, or an array of raw `Proof` objects. ### Request Example ```ts // Using an encoded token string const proofs = await wallet.ops.receive(token).run(); // Using raw proofs const oldProofs: Proof[] = [proof1, proof2, proof3, ...]; const freshProofs = await wallet.ops.receive(oldProofs).run(); ``` ### Dry Run Example ```ts // Using prepare() for a dry run preview const preview = await wallet.ops.receive(token).prepare(); const { keep } = await wallet.completeSwap(preview); ``` ``` -------------------------------- ### Inspect Raw Support for Other NUTs Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/mint_capabilities.md Checks the support status for various other NUTs, which may return a simple boolean or an object with additional parameters. Examples include locked mint quotes (NUT-20), MPP methods (NUT-15), and cached endpoints (NUT-19). ```typescript info.isSupported(20); // { supported: boolean } — locked mint quotes (NUT-20) info.isSupported(15); // { supported: boolean; params? } — MPP methods (NUT-15) info.isSupported(19); // { supported: boolean; params? } — cached endpoints (NUT-19) ``` -------------------------------- ### Prepare Swap to Send Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Prepares a swap operation to send tokens, returning a preview of the send transaction. Used for atomic swaps. ```typescript prepareSwapToSend(amount: AmountLike, proofs: ProofLike[], config?: SendConfig, outputConfig?: OutputConfig): Promise; ``` -------------------------------- ### Run Consumer Smoke Tests Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Execute smoke tests for the consumer functionality. ```bash npm run test:consumer ``` -------------------------------- ### Default Receive Tokens Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/receive.md Use this for standard token reception. You can either run the operation directly or use `prepare()` for a dry run preview before completing the swap. ```typescript const proofs = await wallet.ops.receive(token).run(); ``` ```typescript const preview = await wallet.ops.receive(token).prepare(); const { keep } = await wallet.completeSwap(preview); ``` -------------------------------- ### Two-Step Melt with Prepare and Complete Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/melt_token.md Use the two-step melt flow to prepare the melt and persist the preview before completing the payment. This is recommended for replay-safe recovery and NUT-19 transport retries. ```typescript import { Wallet } from '@cashu/cashu-ts'; const wallet = new Wallet('http://localhost:3338'); await wallet.loadMint(); const meltQuote = await wallet.createMeltQuoteBolt11(invoice); const amountToSend = meltQuote.amount.add(meltQuote.fee_reserve); const { send: proofsToSend } = await wallet.send(amountToSend, proofs, { includeFees: true, }); const meltPreview = await wallet.prepareMelt('bolt11', meltQuote, proofsToSend); // Persist an app-defined snapshot here. // Do not call JSON.stringify(meltPreview) directly; preview objects contain non-JSON-safe values. const meltResponse = await wallet.completeMelt(meltPreview); ``` -------------------------------- ### Create a Bolt12 Offer Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/bolt12.md Use this to create a reusable Bolt12 offer. Omit the amount to create an amountless offer. The mint must support offers with descriptions. ```typescript const bolt12Quote = await wallet.createMintQuoteBolt12(bytesToHex(pubkey), { amount: 1000, // Optional: omit to create an amountless offer description: 'My reusable offer', // The mint must signal in their settings that offers with a description are supported }); ``` -------------------------------- ### Prepare Batch Mint Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Prepares a batch mint operation by specifying multiple entries, each with an amount and quote. Returns a preview of the batch mint. ```typescript prepareBatchMint>(method: string, entries: Array<{ amount: AmountLike; quote: TQuote; }>, config?: MintProofsConfig, outputType?: OutputType): Promise>; ``` -------------------------------- ### Run Repo-wide Lint Checks Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Perform comprehensive linting and formatting checks across the entire repository. ```bash npm run check-lint ``` ```bash npm run check-format ``` -------------------------------- ### Prepare Swap to Receive Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Prepares a swap operation to receive tokens, returning a preview of the receive transaction. This is used for atomic swaps. ```typescript prepareSwapToReceive(token: Token | string | ProofLike[], config?: ReceiveConfig, outputType?: OutputType): Promise; ``` -------------------------------- ### Compile Project to ESM Output Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Build the project and generate ECMAScript Module (ESM) output. ```bash npm run compile ``` -------------------------------- ### Run CI Tasks Source: https://github.com/cashubtc/cashu-ts/blob/main/AGENTS.md Execute linting, formatting, API updates, and tests for CI checks. ```bash npm run prtasks ``` -------------------------------- ### Prepare Mint Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Prepares a mint operation, returning a preview of the mint transaction. Useful for pre-calculating mint details before commitment. ```typescript prepareMint>(method: string, amount: AmountLike, quote: TQuote, config?: MintProofsConfig, outputType?: OutputType): Promise>; ``` -------------------------------- ### getKeySets Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Retrieves all available keysets from the mint, with an optional custom request function. ```APIDOC ## getKeySets ### Description Retrieves all available keysets from the mint. ### Method `Promise` ### Endpoint N/A (SDK method) ### Parameters #### Query Parameters - **customRequest** (RequestFn) - Optional - A custom function to handle the request. ### Response #### Success Response (200) - **GetKeysetsResponse** (object) - An object containing the keysets. ``` -------------------------------- ### Handle Errors in proofStatesStream with try/catch Source: https://github.com/cashubtc/cashu-ts/blob/main/migration-5.0.0.md Wrap `for await` loops consuming `wallet.on.proofStatesStream` in a `try/catch` block to handle WebSocket or mint-side RPC errors. Abort signals still end the stream cleanly. ```typescript // Before — silent end on error for await (const update of wallet.on.proofStatesStream(proofs)) { // ... } // (a websocket failure here exited the loop cleanly; you'd never know) // After — error throws try { for await (const update of wallet.on.proofStatesStream(proofs, { signal: ac.signal })) { // ... } } catch (e) { if ((e as Error).name === 'AbortError') return; // abort, not a real error // surface the websocket / mint failure however your app prefers console.error('Proof state stream failed', e); } ``` -------------------------------- ### Create and Receive Token with Cashu TS Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/usage/create_token.md Use `getEncodedToken` to create a token from proofs and then `receive` to decode and load it into another wallet. Ensure proofs are available or fetched before sending. ```typescript import { getEncodedToken } from '@cashu/cashu-ts'; // we assume that `wallet` already minted `proofs`, as above // or you fetched existing proofs from your app database const proofs = [...]; // array of proofs const { keep, send } = await wallet.send(32, proofs); const token = getEncodedToken({ mint: mintUrl, proofs: send }); console.log(token); const wallet2 = new Wallet(mintUrl); // receiving wallet await wallet2.loadMint(); // wallet2 is now ready to use const receiveProofs = await wallet2.receive(token); // store receiveProofs in your app .. ``` -------------------------------- ### getInfo Source: https://github.com/cashubtc/cashu-ts/blob/main/etc/cashu-ts.api.md Retrieves general information about the mint, optionally with a custom request function. ```APIDOC ## getInfo ### Description Retrieves general information about the mint. ### Method `Promise` ### Endpoint N/A (SDK method) ### Parameters #### Query Parameters - **customRequest** (RequestFn) - Optional - A custom function to handle the request. ### Response #### Success Response (200) - **GetInfoResponse** (object) - An object containing mint information. ``` -------------------------------- ### Deterministic Mint with Keyset and Callback Source: https://github.com/cashubtc/cashu-ts/blob/main/docs-src/wallet_ops/mint.md Mints tokens deterministically using a specific keyset and allows for a callback function to be notified when counters are reserved. ```APIDOC ## Deterministic Mint with Keyset + Callback ### Description Mints tokens deterministically by specifying a keyset and optionally providing a callback for counter reservation events. This method allows for fine-grained control over the minting process. ### Method Signature `wallet.ops.mintBolt11(amount: number, quote: string | MintQuoteBolt11Response).asDeterministic(counter: number, split?: number[]): KeysetMintBuilder` `KeysetMintBuilder.keyset(keysetId: string): KeysetMintBuilder` `KeysetMintBuilder.onCountersReserved(callback: (info: any) => void): KeysetMintBuilder` `KeysetMintBuilder.run(): Promise` ### Parameters - **amount** (number) - The amount of tokens to mint. - **quote** (string | MintQuoteBolt11Response) - The BOLT11 quote information. - **counter** (number) - The counter to use for deterministic minting. - **split** (number[]) - Optional array of denominations for splitting the minted tokens. - **keysetId** (string) - The ID of the keyset to use for minting. - **callback** ((info: any) => void) - A function to call when counters are reserved. ### Request Example ```ts const newProofs = await wallet.ops .mintBolt11(250, quote) .asDeterministic(0, [128, 64]) // counter=0 => auto-reserve, split must include denoms .keyset('0123456') .onCountersReserved((info) => console.log(info)) .run(); ``` ```