Cashu-TS - v4.0.0-rc3
    Preparing search index...

    Class Wallet

    Class that represents a Cashu wallet.

    This class should act as the entry point for this library. Can be instantiated with a mint instance or mint url.

    import { Wallet } from '@cashu/cashu-ts';
    const wallet = new Wallet('http://localhost:3338', { unit: 'sat' });
    await wallet.loadMint(); // Initialize mint info, keysets, and keys
    // Wallet is now ready to use, eg:
    const proofs = [...]; // your array of unspent proofs
    const { keep, send } = await wallet.send(32, proofs);
    Index

    Constructors

    • Create a wallet for a given mint and unit. Call loadMint before use.

      Binding, if options.keysetId is omitted, the wallet binds to the cheapest active keyset for this unit during loadMint.

      Caching, preload mint info and keychain data by calling loadMintFromCache after construction.

      The keychain stores all loaded keysets and filters query results by the wallet unit.

      Deterministic secrets, pass bip39seed and optionally secretsPolicy. Deterministic outputs reserve counters from counterSource, or an ephemeral in memory source if not supplied. initialCounter applies only with a supplied keysetId and the ephemeral source.

      Splitting, denominationTarget guides proof splits, default is 3. Override coin selection with selectProofs if needed. Logging defaults to a null logger.

      Parameters

      • mint: string | Mint

        Mint instance or URL.

      • Optionaloptions: {
            authProvider?: AuthProvider;
            bip39seed?: Uint8Array<ArrayBufferLike>;
            counterInit?: Record<string, number>;
            counterSource?: CounterSource;
            denominationTarget?: number;
            keysetId?: string;
            logger?: Logger;
            secretsPolicy?: SecretsPolicy;
            selectProofs?: SelectProofs;
            unit?: string;
        }

        Optional settings.

        • OptionalauthProvider?: AuthProvider
        • Optionalbip39seed?: Uint8Array<ArrayBufferLike>

          BIP39 seed for deterministic secrets.

        • OptionalcounterInit?: Record<string, number>

          Seed values for the built-in EphemeralCounterSource. Ignored if counterSource is also provided.

        • OptionalcounterSource?: CounterSource

          Counter source for deterministic outputs. If provided, this takes precedence over counterInit. Use when you need persistence across processes or devices.

        • OptionaldenominationTarget?: number

          Target proofs per denomination, default 3.

        • OptionalkeysetId?: string

          Bind to this keyset id, else bind on loadMint.

        • Optionallogger?: Logger

          Logger instance, default null logger.

        • OptionalsecretsPolicy?: SecretsPolicy

          Secrets policy, default 'auto'.

        • OptionalselectProofs?: SelectProofs

          Custom proof selection function.

        • Optionalunit?: string

          Wallet unit, default 'sat'.

      Returns Wallet

    Properties

    counters: WalletCounters

    Developer-friendly counters API.

    mint: Mint

    Mint instance - allows direct calls to the mint.

    Convenience wrapper for events.

    Entry point for the builder.

    const { keep, send } = await wallet.ops
    .send(5, proofs)
    .asDeterministic() // counter: 0 = auto
    .keepAsRandom()
    .includeFees(true)
    .run();

    const proofs = await wallet.ops
    .receive(token)
    .asDeterministic()
    .keyset(wallet.keysetId)
    .run();

    Accessors

    Methods

    • Restores batches of deterministic proofs until no more signatures are returned from the mint.

      Parameters

      • OptionalgapLimit: number = 300

        The amount of empty counters that should be returned before restoring ends (defaults to 300). Default is 300

      • OptionalbatchSize: number = 100

        The amount of proofs that should be restored at a time (defaults to 100). Default is 100

      • Optionalcounter: number = 0

        The counter that should be used as a starting point (defaults to 0). Default is 0

      • OptionalkeysetId: string

        Which keysetId to use for the restoration. If none is passed the instance's default one will be used.

      Returns Promise<{ lastCounterWithSignature?: number; proofs: Proof[] }>

    • Bind this wallet to a specific keyset id.

      Parameters

      • id: string

        The keyset identifier to bind to.

      Returns void

      This changes the default keyset used by all operations that do not explicitly pass a keysetId. The method validates that the keyset exists in the keychain, matches the wallet unit, and has keys loaded.

      Typical uses:

      1. After loadMint, to pin the wallet to a particular active keyset.
      2. After a refresh, to rebind deliberately rather than falling back to cheapest.

      If keyset not found, if it has no keys loaded, or if its unit is not the wallet unit.

    • Checks an existing melt quote for any payment method.

      Type Parameters

      Parameters

      • method: string

        The payment method (e.g., 'bolt11', 'bolt12', 'bacs', 'swift').

      • quote: string | Pick<TRes, "quote">

        Quote ID or quote object (must have a quote field).

      • Optionaloptions: { normalize?: (raw: Record<string, unknown>) => TRes }
        • Optionalnormalize?: (raw: Record<string, unknown>) => TRes

          Optional callback to normalize method-specific response fields.

      Returns Promise<TRes>

      The melt quote response.

      Generic method for checking a melt quote status. An optional normalize callback can be used to coerce method-specific response fields.

      For first-class methods, prefer the typed helpers: checkMeltQuoteBolt11(), checkMeltQuoteBolt12().

    • Checks an existing mint quote for any payment method.

      Type Parameters

      Parameters

      • method: string

        The payment method (e.g., 'bolt11', 'bolt12', 'bacs', 'swift').

      • quote: string | Pick<TRes, "quote">

        Quote ID or quote object (must have a quote field).

      • Optionaloptions: { normalize?: (raw: Record<string, unknown>) => TRes }
        • Optionalnormalize?: (raw: Record<string, unknown>) => TRes

          Optional callback to normalize method-specific response fields.

      Returns Promise<TRes>

      The mint quote response.

      Generic method for checking a mint quote status. An optional normalize callback can be used to coerce method-specific response fields.

      For first-class methods, prefer the typed helpers: checkMintQuoteBolt11(), checkMintQuoteBolt12().

    • Get an array of the states of proofs from the mint (as an array of CheckStateEnum's)

      Parameters

      • proofs: Pick<Proof, "secret">[]

        (only the secret field is required)

      Returns Promise<ProofState[]>

      NUT-07 state for each proof, in same order.

    • Completes a pending melt by calling the melt endpoint and constructing change proofs.

      Type Parameters

      Parameters

      • meltPreview: MeltPreview<TQuote>

        The preview from prepareMelt().

      • Optionalprivkey: string | string[]

        The private key(s) for signing.

      • OptionalpreferAsync: boolean

        Optional override to request NUT-06 asynchronous melt.

      Returns Promise<MeltProofsResponse<TQuote>>

      Updated MeltProofsResponse.

      Use with a MeltPreview returned from prepareMelt(). This method lets you sign P2PK locked proofs before melting. If the payment is pending or unpaid, the change array will be empty.

      If melt fails or signatures don't match output count.

    • Complete a prepared swap transaction.

      Parameters

      • swapPreview: SwapPreview

        With metadata for swap transaction.

      • Optionalprivkey: string | string[]

        The private key(s) for signing.

      Returns Promise<SendResponse>

      SendResponse with keep/send proofs.

      // Prepare transaction
      const txn = await wallet.prepareSwapToSend(5, proofs, { includeFees: true });

      // Complete transaction
      const result = await wallet.completeSwap(txn);
    • Requests a mint quote from the mint that is locked to a public key.

      Parameters

      • amount: AmountLike

        Amount requesting for mint.

      • pubkey: string

        Public key to lock the quote to.

      • Optionaldescription: string

        Optional description for the mint quote.

      Returns Promise<MintQuoteBolt11Response>

      The mint will return a mint quote with a Lightning invoice for minting tokens of the specified amount and unit. The quote will be locked to the specified pubkey.

    • Creates a melt quote for any payment method.

      Type Parameters

      Parameters

      • method: string

        The payment method (e.g., 'bolt11', 'bolt12', 'bacs', 'swift').

      • payload: Record<string, unknown>

        The request body to POST. unit is always set to the wallet's unit.

      • Optionaloptions: { normalize?: (raw: Record<string, unknown>) => TRes }
        • Optionalnormalize?: (raw: Record<string, unknown>) => TRes

          Optional callback to normalize method-specific response fields.

      Returns Promise<TRes>

      The melt quote response.

      Generic method for requesting a melt quote. The payload is method-specific but must at minimum include the fields required by the mint for the given method. An optional normalize callback can be used to coerce method-specific response fields.

      For first-class methods, prefer the typed helpers: createMeltQuoteBolt11(), createMeltQuoteBolt12().

    • Requests a melt quote from the mint. Response returns amount and fees for a given unit in order to pay a Lightning invoice.

      Parameters

      • invoice: string

        LN invoice that needs to get a fee estimate.

      • OptionalamountMsat: AmountLike

        Optional amount in millisatoshis to attach for amountless invoices, must not be provided for invoices that already encode an amount.

      Returns Promise<MeltQuoteBolt11Response>

      The mint will create and return a melt quote for the invoice with an amount and fee reserve.

    • Requests a melt quote from the mint. Response returns amount and fees for a given unit in order to pay a BOLT12 offer.

      Parameters

      • offer: string

        BOLT12 offer that needs to get a fee estimate.

      • OptionalamountMsat: AmountLike

        Amount in millisatoshis for amount-less offers. If this is defined and the offer has an amount, they MUST be equal.

      Returns Promise<MeltQuoteBolt11Response>

      The mint will create and return a melt quote for the offer with an amount and fee reserve.

    • Creates a mint quote for any payment method.

      Type Parameters

      Parameters

      • method: string

        The payment method (e.g., 'bolt11', 'bolt12', 'bacs', 'swift').

      • payload: Record<string, unknown>

        The request body to POST. unit is always set to the wallet's unit.

      • Optionaloptions: { normalize?: (raw: Record<string, unknown>) => TRes }
        • Optionalnormalize?: (raw: Record<string, unknown>) => TRes

          Optional callback to normalize method-specific response fields.

      Returns Promise<TRes>

      The mint quote response.

      Generic method for requesting a mint quote. The payload is method-specific but must at minimum include the fields required by the mint for the given method. An optional normalize callback can be used to coerce method-specific response fields.

      For first-class methods, prefer the typed helpers: createMintQuoteBolt11(), createMintQuoteBolt12().

    • Requests a mint quote from the mint. Response returns a Lightning payment request for the requested given amount and unit.

      Parameters

      • amount: AmountLike

        Amount requesting for mint.

      • Optionaldescription: string

        Optional description for the mint quote.

      Returns Promise<MintQuoteBolt11Response>

      The mint will return a mint quote with a Lightning invoice for minting tokens of the specified amount and unit.

    • Requests a mint quote from the mint. Response returns a Lightning BOLT12 offer for the requested given amount and unit.

      Parameters

      • pubkey: string

        Public key to lock the quote to.

      • Optionaloptions: { amount?: AmountLike; description?: string }
        • Optionalamount?: AmountLike

          BOLT12 offer amount requesting for mint. If not specified, the offer will be amountless.

        • Optionaldescription?: string

          Description for the mint quote.

      Returns Promise<MintQuoteBolt12Response>

      The mint will return a mint quote with a BOLT12 offer for minting tokens of the specified amount and unit.

    • Decodes a string token.

      Parameters

      • token: string

        The token in string format (cashuB...)

      Returns Token

      Token object.

      Rehydrates a token from the space-saving CBOR format, including mapping short keyset ids to their full representation.

    • Returns the default OutputType for this wallet, based on its configured secrets policy (options?.secretsPolicy) and seed state.

      • If the secrets policy is 'random', returns { type: 'random' }.

      • If the policy is 'deterministic', requires a seed and returns { type: 'deterministic', counter: 0 }. Counter 0 is a flag meaning "auto-increment from current state".

      • If no explicit policy is set, falls back to:

        • Deterministic if a seed is present.
        • Random if no seed is present.

      Returns OutputType

      An OutputType object describing the default output strategy.

      Error if the policy is 'deterministic' but no seed has been set.

    • Calculates the fees based on inputs for a given keyset.

      Parameters

      • nInputs: number

        Number of inputs.

      • keysetId: string

        KeysetId used to lookup input_fee_ppk

      Returns Amount

      Fee amount.

    • Calculates the fees based on inputs (proofs)

      Parameters

      • proofs: Pick<Proof, "id">[]

        Input proofs to calculate fees for.

      Returns Amount

      Fee amount.

      Throws an error if the proofs keyset is unknown.

    • Gets the requested keyset or the keyset bound to the wallet.

      Parameters

      • Optionalid: string

        Optional keyset id to resolve. If omitted, the wallet's bound keyset is used.

      Returns Keyset

      The resolved Keyset.

      This method enforces wallet policies. If id is omitted, it returns the keyset bound to this wallet, including validation that:

      • The keyset exists in the keychain,
      • The unit matches the wallet's unit,
      • Keys are loaded for that keyset.

      Contrast with keyChain.getKeyset(id?), which, when called without an id, returns the cheapest active keyset for the unit, ignoring the wallet binding.

      If the keyset is not found, has no keys, or its unit differs from the wallet.

    • Get information about the mint.

      Returns MintInfo

      Mint info.

      Returns cached mint info. Call loadMint first to initialize the wallet.

      If mint info is not initialized.

    • Groups proofs by their corresponding state, preserving order within each group.

      Parameters

      • proofs: Proof[]

        (only the secret field is required)

      Returns Promise<{ pending: Proof[]; spent: Proof[]; unspent: Proof[] }>

      An object with arrays of proofs grouped by CheckStateEnum state.

    • Load mint information, keysets, and keys.

      Parameters

      • OptionalforceRefresh: boolean

        If true, re-fetches data even if cached.

      Returns Promise<void>

      Must be called before using other methods, unless loading mint from cache. See: loadMintFromCache.

      If fetching mint info, keysets, or keys fails.

    • Load mint information, keysets, and keys from cached data.

      Parameters

      Returns void

      Use this when you already have cached mint info and keychain cache and want to avoid network calls.

      The cache argument should usually come from wallet.keyChain.cache.

    • Melts proofs for any payment method.

      Type Parameters

      Parameters

      • method: string

        The payment method (e.g., 'bolt11', 'bolt12', 'bacs', 'swift').

      • meltQuote: TQuote

        The melt quote object (must have at least quote and amount fields).

      • proofsToSend: Proof[]

        Proofs to melt.

      • Optionalconfig: MeltProofsConfig

        Optional parameters.

      • OptionaloutputType: OutputType

        Configuration for proof generation. Defaults to wallet.defaultOutputType().

      Returns Promise<MeltProofsResponse<TQuote>>

      MeltProofsResponse with quote and change proofs.

      Generic convenience method that calls prepareMelt(method, …) followed by completeMelt().

      Intended primarily for custom payment methods. For first-class methods, prefer meltProofsBolt11() or meltProofsBolt12(), which keep the method-specific wallet ergonomics.

    • Mints proofs for any payment method.

      Type Parameters

      Parameters

      • method: string

        The payment method (e.g., 'bolt11', 'bolt12', 'bacs', 'swift').

      • amount: AmountLike

        Amount to mint.

      • quote: TQuote

        The mint quote object (must have at least a quote field).

      • Optionalconfig: MintProofsConfig

        Optional parameters (e.g. privkey for locked quotes).

      • OptionaloutputType: OutputType

        Configuration for proof generation. Defaults to wallet.defaultOutputType().

      Returns Promise<Proof[]>

      Minted proofs.

      Generic convenience method that calls prepareMint(method, …) followed by completeMint().

      Intended primarily for custom payment methods. For first-class methods, prefer mintProofsBolt11() or mintProofsBolt12(), which keep the method-specific wallet ergonomics and validation.

    • Mint proofs for a bolt11 quote.

      Parameters

      • amount: AmountLike

        Amount to mint.

      • quote: string | MintQuoteBolt11Response

        Mint quote ID or object (bolt11).

      • Optionalconfig: MintProofsConfig

        Optional parameters (e.g. privkey for locked quotes).

      • OptionaloutputType: OutputType

        Configuration for proof generation. Defaults to wallet.defaultOutputType().

      Returns Promise<Proof[]>

      Minted proofs.

      Convenience helper for the common BOLT11 flow. Internally this uses prepareMint('bolt11',…) followed by completeMint(). Use prepareMint() directly when you need the generic method based API or want to persist a replay-safe preview before completion.

    • Mints proofs for a bolt12 quote.

      Parameters

      • amount: AmountLike

        Amount to mint.

      • quote: MintQuoteBolt12Response

        Bolt12 mint quote.

      • privkey: string

        Private key to unlock the quote.

      • Optionalconfig: { keysetId?: string }

        Optional parameters (e.g. keysetId).

      • OptionaloutputType: OutputType

        Configuration for proof generation. Defaults to wallet.defaultOutputType().

      Returns Promise<Proof[]>

      Minted proofs.

      Convenience helper for the common BOLT12 flow. Internally this uses prepareMint('bolt12',…) followed by completeMint(). Use prepareMint() directly when you need the generic method based API or want to persist a replay-safe preview before completion.

    • Prepare A Melt Transaction.

      Type Parameters

      Parameters

      • method: string

        Payment method of the quote.

      • meltQuote: TQuote

        The melt quote. Only quote (ID) and amount are required — a full MeltQuoteBolt11Response works, but { quote: string, amount: Amount } is sufficient.

      • proofsToSend: Proof[]

        Proofs to melt.

      • Optionalconfig: MeltProofsConfig

        Optional configuration (keysetId, privkey, etc.).

      • OptionaloutputType: OutputType

        Configuration for proof generation. Defaults to wallet.defaultOutputType().

      Returns Promise<MeltPreview<TQuote>>

      MeltPreview.

      Allows you to preview fees for a melt, get concrete outputs for P2PK SIG_ALL melts, and do any pre-melt tasks (such as marking proofs in-flight etc). Creates NUT-08 blanks (1-sat) for Lightning fee return and returns a MeltPreview, which you can melt using completeMelt.

      If params are invalid.

    • Prepare a mint transaction for replay and later completion.

      Type Parameters

      Parameters

      • method: string
      • amount: AmountLike
      • quote: TQuote

        The mint quote. Only quote (ID) is required — a full MintQuoteBolt11Response works, but { quote: string } is sufficient. Pass config.privkey to produce a NUT-20 signature regardless of whether the quote carries a pubkey field.

      • Optionalconfig: MintProofsConfig
      • OptionaloutputType: OutputType

      Returns Promise<MintPreview<TQuote>>

      Generic method-oriented mint API. This supports current methods such as bolt11 and bolt12 as well as future custom methods exposed by the mint. For first-class typed ergonomics with the built-in methods, prefer mintProofsBolt11(), mintProofsBolt12(), or wallet.ops.mintBolt11()/mintBolt12().

      Returns a MintPreview that contains the exact mint payload and output data needed to construct proofs. Persist this preview to support NUT-19 replay safety.

    • Prepare A Receive Transaction.

      Parameters

      • token: string | Proof[] | Token

        Token string, decoded token, or raw proof array.

      • Optionalconfig: ReceiveConfig

        Optional receive config.

      • OptionaloutputType: OutputType

        Configuration for proof generation. Defaults to wallet.defaultOutputType().

      Returns Promise<SwapPreview>

      SwapPreview with metadata for swap transaction.

      Allows you to preview fees for a receive, get concrete outputs for P2PK SIG_ALL transactions, and do any pre-swap tasks (such as marking proofs in-flight etc)

      // Prepare transaction
      const txn = await wallet.prepareSwapToReceive(token, { requireDleq: true });
      const fees = txn.fees;

      // Complete transaction
      const { keep } = await wallet.completeSwap(txn);
    • Prepare A Send Transaction.

      Parameters

      • amount: AmountLike

        Amount to send (receiver gets this net amount).

      • proofs: Proof[]

        Array of proofs to split.

      • Optionalconfig: SendConfig

        Optional parameters for the swap.

      • OptionaloutputConfig: OutputConfig

      Returns Promise<SwapPreview>

      SwapPreview with metadata for swap transaction.

      Allows you to preview fees for a send, get concrete outputs for P2PK SIG_ALL transactions, and do any pre-swap tasks (such as marking proofs in-flight etc)

      // Prepare transaction
      const txn = await wallet.prepareSwapToSend(5, proofs, { includeFees: true });
      const fees = txn.fees;

      // Complete transaction
      const { keep, send } = await wallet.completeSwap(txn);

      Throws if the send cannot be completed offline or if funds are insufficient.

    • Receive a token (swaps with mint for new proofs)

      Parameters

      • token: string | Proof[] | Token

        Token string, decoded token, or raw proof array.

      • Optionalconfig: ReceiveConfig

        Optional receive config.

      • OptionaloutputType: OutputType

        Configuration for proof generation. Defaults to wallet.defaultOutputType().

      Returns Promise<Proof[]>

      Newly minted proofs.

      const result = await wallet.receive(
      token,
      { requireDleq: true },
      { type: 'deterministic', counter: 0 },
      );
    • Regenerates.

      Parameters

      • start: number

        Set starting point for count (first cycle for each keyset should usually be 0)

      • count: number

        Set number of blinded messages that should be generated.

      • Optionalconfig: RestoreConfig

      Returns Promise<{ lastCounterWithSignature?: number; proofs: Proof[] }>

      keyChain)

    • Selects proofs to send based on amount and fee inclusion.

      Parameters

      • proofs: Proof[]

        Array of Proof objects available to select from.

      • amountToSend: AmountLike

        The target amount to send.

      • includeFees: boolean = false

        Optional boolean to include fees; Default: false.

      • exactMatch: boolean = false

        Optional boolean to require exact match; Default: false.

      Returns SendResponse

      SendResponse containing proofs to keep and proofs to send.

      Uses an adapted Randomized Greedy with Local Improvement (RGLI) algorithm, which has a time complexity O(n log n) and space complexity O(n).

      Throws an error if an exact match cannot be found within MAX_TIMEMS.

    • Send proofs with online swap if necessary.

      Parameters

      • amount: AmountLike

        Amount to send (receiver gets this net amount).

      • proofs: Proof[]

        Array of proofs to split.

      • Optionalconfig: SendConfig

        Optional parameters for the swap.

      • OptionaloutputConfig: OutputConfig

      Returns Promise<SendResponse>

      SendResponse with keep/send proofs.

      // Simple send
      const result = await wallet.send(5, proofs);

      // With a SendConfig
      const result = await wallet.send(5, proofs, { includeFees: true });

      // With Custom output configuration
      const customConfig: OutputConfig = {
      send: { type: 'p2pk', options: { pubkey: '...' } },
      keep: { type: 'deterministic', counter: 0 },
      };
      const customResult = await wallet.send(5, proofs, { includeFees: true }, customConfig);

      Throws if the send cannot be completed offline or if funds are insufficient.

    • Sends proofs of a given amount from provided proofs.

      Parameters

      • amount: AmountLike

        Amount to send.

      • proofs: Proof[]

        Array of proofs (must sum >= amount; pre-sign if P2PK-locked).

      • Optionalconfig: SendOfflineConfig

        Optional parameters for the send.

      Returns SendResponse

      SendResponse with keep/send proofs.

      If proofs are P2PK-locked to your public key, call signP2PKProofs first to sign them. The default config uses exact match selection, and does not includeFees or requireDleq. Because the send is offline, the user will unlock the signed proofs when they receive them online.

      Throws if the send cannot be completed offline.

    • Prepares proofs for sending by signing P2PK-locked proofs.

      Parameters

      • proofs: Proof[]

        The proofs to sign.

      • privkey: string | string[]

        The private key(s) for signing.

      • OptionaloutputData: OutputDataLike[]

        Optional. For signing of SIG_ALL transactions.

      • OptionalquoteId: string

        Optional. For signing SIG_ALL melt transactions.

      Returns Proof[]

      Signed proofs.

      Call this method before operations like send if the proofs are P2PK-locked and need unlocking. This is a public wrapper for signing.

    • Creates a new Wallet bound to a different keyset, sharing the same CounterSource.

      Use this to operate on multiple keysets concurrently without mutating your original wallet. Counters remain monotonic across instances because the same CounterSource is reused.

      Do NOT pass a fresh CounterSource for the same seed unless you know exactly why. Reusing counters can recreate secrets that a mint will reject.

      Parameters

      • id: string

        The keyset identifier to bind to.

      • Optionalopts: { counterSource?: CounterSource }

      Returns Wallet

      If keyset not found, if it has no keys loaded, or if its unit is not the wallet unit.