@cashu/cashu-ts
    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. The keychain only loads keysets for this unit.

      Caching, to preload, provide both keysets and keys, otherwise the cache is ignored.

      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;
            keys?: MintKeys | MintKeys[];
            keysetId?: string;
            keysets?: MintKeyset[];
            logger?: Logger;
            mintInfo?: GetInfoResponse;
            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.

        • Optionalkeys?: MintKeys | MintKeys[]

          Cached keys for this unit, only used when keysets is also provided.

        • OptionalkeysetId?: string

          Bind to this keyset id, else bind on loadMint.

        • Optionalkeysets?: MintKeyset[]

          Cached keysets for this unit, only used when keys is also provided.

        • Optionallogger?: Logger

          Logger instance, default null logger.

        • OptionalmintInfo?: GetInfoResponse

          Optional cached mint info.

        • 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.

    keyChain: KeyChain

    KeyChain instance - contains wallet keysets/keys.

    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();
    swap: (
        amount: number,
        proofs: Proof[],
        config?: SendConfig,
        outputConfig?: OutputConfig,
    ) => Promise<SendResponse> = ...

    Swap is an alias of send.

    Type Declaration

      • (
            amount: number,
            proofs: Proof[],
            config?: SendConfig,
            outputConfig?: OutputConfig,
        ): Promise<SendResponse>
      • Send proofs with online swap if necessary.

        Parameters

        • amount: number

          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.

        If proofs are P2PK-locked to your public key, call signP2PKProofs first to sign them.

        // 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.

    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.

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

      Parameters

      • proofs: Proof[]

        (only the secret field is required)

      Returns Promise<ProofState[]>

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

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

      Type Parameters

      Parameters

      • blanks: MeltBlanks<T>

        The blanks from onChangeOutputsCreated.

      Returns Promise<MeltProofsResponse>

      Updated MeltProofsResponse.

      Use with blanks from onChangeOutputsCreated to retry pending melts. Works for Bolt11/Bolt12. Returns change proofs if paid, else empty change.

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

    • Requests a mint quote from the mint that is locked to a public key.

      Parameters

      • amount: number

        Amount requesting for mint.

      • pubkey: string

        Public key to lock the quote to.

      • Optionaldescription: string

        Optional description for the mint quote.

      Returns Promise<LockedMintQuoteResponse>

      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.

    • 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.

      Returns Promise<MeltQuoteResponse>

      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: number

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

      Returns Promise<MeltQuoteResponse>

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

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

      Parameters

      • amount: number

        Amount requesting for mint.

      • Optionaldescription: string

        Optional description for the mint quote.

      Returns Promise<MintQuoteResponse>

      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?: number; description?: string }
        • Optionalamount?: number

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

        • Optionaldescription?: string

          Description for the mint quote.

      Returns Promise<Bolt12MintQuoteResponse>

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

    • Requests a multi path melt quote from the mint.

      Parameters

      • invoice: string

        LN invoice that needs to get a fee estimate.

      • millisatPartialAmount: number

      Returns Promise<MeltQuoteResponse>

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

      Uses NUT-15 Partial multi-path payments for BOLT11.

    • 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 number

      Fee amount.

    • Calculates the fees based on inputs (proofs)

      Parameters

      • proofs: Proof[]

        Input proofs to calculate fees for.

      Returns number

      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. Must be called before using other methods.

      Parameters

      • OptionalforceRefresh: boolean

        If true, re-fetches data even if cached.

      Returns Promise<void>

      If fetching mint info, keysets, or keys fails.

    • Mints proofs for a bolt12 quote.

      Parameters

      • amount: number

        Amount to mint.

      • quote: Bolt12MintQuoteResponse

        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.

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

      Parameters

      • token: string | Token

        Token string or decoded token.

      • 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,
      { includeFees: 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: number

        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: number

        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.

      If proofs are P2PK-locked to your public key, call signP2PKProofs first to sign them.

      // 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: number

        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 for signing.

      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.