@nostr-dev-kit/ndk-wallet
Version:
907 lines (885 loc) • 32.3 kB
text/typescript
import { CashuWallet, GetInfoResponse, MintKeys, Proof, SendResponse } from '@cashu/cashu-ts';
import * as NDK from '@nostr-dev-kit/ndk';
import NDK__default, { NDKEvent, NDKRelay, NDKWalletInterface, NDKZapDetails, LnPaymentInfo, NDKPaymentConfirmationLN, CashuPaymentInfo, NDKPaymentConfirmationCashu, NDKZapSplit, NDKPaymentConfirmation, NDKNutzap, NDKEventId, NDKNutzapState, NdkNutzapStatus, NDKRelaySet, NDKCashuMintList, NDKPrivateKeySigner, NDKUser, NDKFilter, NDKSubscriptionOptions, NDKKind, NostrEvent, NDKCashuToken, Hexpubkey, NDKTag, NDKPool } from '@nostr-dev-kit/ndk';
import { EventEmitter } from 'tseep';
import { WebLNProvider } from '@webbtc/webln-types';
type MintInfoNeededCb = (mint: string) => Promise<GetInfoResponse | undefined>;
type MintInfoLoadedCb = (mint: string, info: GetInfoResponse) => void;
type MintKeysNeededCb = (mint: string) => Promise<MintKeys[] | undefined>;
type MintKeysLoadedCb = (mint: string, keysets: Map<string, MintKeys>) => void;
interface MintInterface {
cashuWallets: Map<string, CashuWallet>;
/**
* Called when the wallet needs to load mint info. Use this
* to load mint info from a database or other source.
*/
onMintInfoNeeded?: MintInfoNeededCb;
/**
* Called when the wallet has loaded mint info.
*/
onMintInfoLoaded?: MintInfoLoadedCb;
/**
* Called when the wallet needs to load mint keys. Use this
* to load mint keys from a database or other source.
*/
onMintKeysNeeded?: MintKeysNeededCb;
/**
* Called when the wallet has loaded mint keys.
*/
onMintKeysLoaded?: MintKeysLoadedCb;
/**
* Get a cashu wallet for a mint.
*/
getCashuWallet(mint: string): Promise<CashuWallet>;
}
/**
* Different types of wallets supported.
*/
type NDKWalletTypes = "nwc" | "nip-60" | "webln";
declare enum NDKWalletStatus {
INITIAL = "initial",
/**
* The wallet tokens are being loaded.
* Queried balance will come from the wallet event cache
*/
LOADING = "loading",
/**
* Token have completed loading.
* Balance will come from the computed balance from known tokens
*/
READY = "ready",
FAILED = "failed"
}
type NDKWalletBalance = {
amount: number;
};
type NDKWalletEvents = {
ready: () => void;
balance_updated: (balance?: NDKWalletBalance) => void;
insufficient_balance: (info: {
amount: number;
pr: string;
}) => void;
warning: (warning: {
msg: string;
event?: NDKEvent;
relays?: NDKRelay[];
}) => void;
};
declare class NDKWallet extends EventEmitter<NDKWalletEvents> implements NDKWalletInterface, MintInterface {
cashuWallets: Map<string, CashuWallet>;
onMintInfoNeeded?: MintInfoNeededCb;
onMintInfoLoaded?: MintInfoLoadedCb;
onMintKeysNeeded?: MintKeysNeededCb;
onMintKeysLoaded?: MintKeysLoadedCb;
getCashuWallet: MintInterface["getCashuWallet"];
ndk: NDK__default;
constructor(ndk: NDK__default);
status: NDKWalletStatus;
get type(): NDKWalletTypes;
/**
* An ID of this wallet
*/
walletId: string;
/**
* Pay a LN invoice
* @param payment - The LN payment info
*/
lnPay?(payment: NDKZapDetails<LnPaymentInfo>): Promise<NDKPaymentConfirmationLN | undefined>;
/**
* Pay a Cashu invoice
* @param payment - The Cashu payment info
*/
cashuPay?(payment: NDKZapDetails<CashuPaymentInfo>): Promise<NDKPaymentConfirmationCashu | undefined>;
/**
* A callback that is called when a payment is complete
*/
onPaymentComplete?(results: Map<NDKZapSplit, NDKPaymentConfirmation | Error | undefined>): void;
/**
* Force-fetch the balance of this wallet
*/
updateBalance?(): Promise<void>;
/**
* Get the balance of this wallet
*/
get balance(): NDKWalletBalance | undefined;
/**
* Redeem a set of nutzaps into an NWC wallet.
*
* This function gets an invoice from the NWC wallet until the total amount of the nutzaps is enough to pay for the invoice
* when accounting for fees.
*
* @param cashuWallet - The cashu wallet to redeem the nutzaps into
* @param nutzapIds - The IDs of the nutzaps to redeem
* @param proofs - The proofs to redeem
* @param privkey - The private key needed to redeem p2pk proofs.
*/
redeemNutzaps(_nutzaps: NDKNutzap[], _privkey: string, _opts: RedeemNutzapsOpts): Promise<number>;
}
interface RedeemNutzapsOpts {
cashuWallet?: CashuWallet;
proofs?: Proof[];
mint?: string;
}
/**
* This interface should be provided by the application to save and load
* state that the nutzap monitor can reuse.
*/
interface NDKNutzapMonitorStore {
/**
* Get all nutzaps that the monitor knows about.
*/
getAllNutzaps: () => Promise<Map<NDKEventId, NDKNutzapState>>;
/**
* Update the state of a nutzap.
*/
setNutzapState: (id: NDKEventId, stateChange: Partial<NDKNutzapState>) => Promise<void>;
}
/**
* This class monitors a user's nutzap inbox relays
* for new nutzaps and processes them.
*/
declare class NDKNutzapMonitor extends EventEmitter<{
/**
* Emitted when a nutzap is seen minted in a mint
* not specified in the user's mint list event.
*/
seen_in_unknown_mint: (event: NDKNutzap) => void;
/**
* Emitted when the state of a nutzap changes
*/
state_changed: (nutzapId: NDKEventId, state: NdkNutzapStatus) => void;
/**
* Emitted when a new nutzap is successfully redeemed
*/
redeemed: (events: NDKNutzap[], amount: number) => void;
/**
* Emitted when a nutzap has been seen
*/
seen: (event: NDKNutzap) => void;
/**
* Emitted when a nutzap has failed to be redeemed
*/
failed: (event: NDKNutzap, error: string) => void;
}> implements MintInterface {
store?: NDKNutzapMonitorStore;
ndk: NDK__default;
private user;
relaySet?: NDKRelaySet;
private sub?;
nutzapStates: Map<string, NDKNutzapState>;
private _wallet?;
mintList?: NDKCashuMintList;
privkeys: Map<string, NDKPrivateKeySigner>;
cashuWallets: Map<string, CashuWallet>;
getCashuWallet: MintInterface["getCashuWallet"];
onMintInfoNeeded?: MintInfoNeededCb;
onMintInfoLoaded?: MintInfoLoadedCb;
onMintKeysNeeded?: MintKeysNeededCb;
onMintKeysLoaded?: MintKeysLoadedCb;
/**
* Create a new nutzap monitor.
* @param ndk - The NDK instance.
* @param user - The user to monitor.
* @param mintList - An optional mint list to monitor zaps on, if one is not provided, the monitor will use the relay set from the mint list, which is the correct default behavior of NIP-61 zaps.
* @param store - An optional store to save and load nutzap states to.
*/
constructor(ndk: NDK__default, user: NDKUser, { mintList, store }: {
mintList?: NDKCashuMintList;
store?: NDKNutzapMonitorStore;
});
set wallet(wallet: NDKWallet | undefined);
get wallet(): NDKWallet | undefined;
/**
* Provide private keys that can be used to redeem nutzaps.
*
* This is particularly useful when a NWC wallet is used to receive the nutzaps,
* since it doesn't have a private key, this allows keeping the private key in a separate
* place (ideally a NIP-60 wallet event).
*
* Multiple keys can be added, and the monitor will use the correct key for the nutzap.
*/
addPrivkey(signer: NDKPrivateKeySigner): Promise<void>;
private addUserPrivKey;
/**
* Loads kind:375 backup events from this user to find all backup keys this user might have used.
*/
getBackupKeys(): Promise<void>;
/**
* Start the nutzap monitor. The monitor will initially look back
* for nutzaps it doesn't know about and will try to redeem them.
*
* @param knownNutzaps - An optional set of nutzaps the app knows about. This is an optimization so that we don't try to redeem nutzaps we know have already been redeemed.
* @param pageSize - The number of nutzaps to fetch per page.
*
*/
start({ filter, opts }: {
filter?: NDKFilter;
opts?: NDKSubscriptionOptions;
}): Promise<boolean>;
/**
* Checks if the group of nutzaps can be redeemed and redeems the ones that can be.
*/
private checkAndRedeemGroup;
/**
* Processes nutzaps that have been accumulated while the monitor was offline.
* @param startOpts
* @param opts
*/
processAccumulatedNutzaps(filter?: NDKFilter, opts?: NDKSubscriptionOptions): Promise<void>;
stop(): void;
private updateNutzapState;
private eventHandler;
/**
* Gathers the necessary information to redeem a nutzap and then redeems it.
* @param nutzap
*/
redeemNutzap(nutzap: NDKNutzap): Promise<NDKNutzapState>;
/**
* This function redeems a list of proofs.
*
* Proofs will be attempted to be redeemed in a single call, so they will all work or none will.
* Either call this function with proofs that have been verified to be redeemable or don't group them,
* and provide a single nutzap per call.
*
* All nutzaps MUST be p2pked to the same pubkey.
*
* @param mint
* @param nutzaps
* @param proofs
* @param privkey Private key that is needed to redeem the nutzaps.
* @returns
*/
redeemNutzaps(mint: string, nutzaps: NDKNutzap[], proofs: Proof[]): Promise<void>;
shouldTryRedeem(nutzap: NDKNutzap): boolean;
/**
* Process nutzaps from the store that are in a redeemable state.
* This includes nutzaps in INITIAL state and those in MISSING_PRIVKEY state
* for which we now have the private key.
*/
private processRedeemableNutzapsFromStore;
/**
* Common method to process a collection of nutzaps:
* - Group them by mint
* - Check and redeem each group
*
* @param nutzaps The nutzaps to process
* @param oldestUnspentNutzapTime Optional timestamp to track the oldest unspent nutzap
* @returns The updated oldestUnspentNutzapTime if any nutzaps were processed
*/
private processNutzaps;
}
declare class NDKCashuQuote extends NDKEvent {
quoteId: string | undefined;
mint: string | undefined;
amount: number | undefined;
unit: string | undefined;
private _wallet;
static kind: NDKKind;
constructor(ndk?: NDK__default, event?: NostrEvent | NDKEvent);
static from(event: NDKEvent): Promise<NDKCashuQuote | undefined>;
set wallet(wallet: NDKCashuWallet);
set invoice(invoice: string);
save(): Promise<void>;
}
declare class NDKCashuDeposit extends EventEmitter<{
success: (token: NDKCashuToken) => void;
error: (error: string) => void;
}> {
mint: string;
amount: number;
quoteId: string | undefined;
private wallet;
checkTimeout: NodeJS.Timeout | undefined;
checkIntervalLength: number;
finalized: boolean;
private quoteEvent?;
constructor(wallet: NDKCashuWallet, amount: number, mint?: string);
static fromQuoteEvent(wallet: NDKCashuWallet, quote: NDKCashuQuote): NDKCashuDeposit;
/**
* Creates a quote ID and start monitoring for payment.
*
* Once a payment is received, the deposit will emit a "success" event.
*
* @param pollTime - time in milliseconds between checks
* @returns
*/
start(pollTime?: number): Promise<string>;
/**
* This generates a 7374 event containing the quote ID
* with an optional expiration set to the bolt11 expiry (if there is one)
*/
private createQuoteEvent;
private runCheck;
private delayCheck;
/**
* Check if the deposit has been finalized.
* @param timeout A timeout in milliseconds to wait before giving up.
*/
check(timeout?: number): Promise<void>;
finalize(): Promise<void>;
private destroyQuoteEvent;
}
/**
* This class tracks the active deposits and emits a "change" event when there is a change.
*/
declare class NDKCashuDepositMonitor extends EventEmitter<{
change: () => void;
}> {
deposits: Map<string, NDKCashuDeposit>;
addDeposit(deposit: NDKCashuDeposit): boolean;
removeDeposit(quoteId: string): void;
}
type MintUrl = string;
type MintUsage = {
/**
* All the events that are associated with this mint.
*/
events: NDKEvent[];
pubkeys: Set<Hexpubkey>;
};
type NDKCashuMintRecommendation = Record<MintUrl, MintUsage>;
/**
* Provides a list of mint recommendations.
* @param ndk
* @param filter optional extra filter to apply to the REQ
*/
declare function getCashuMintRecommendations(ndk: NDK__default, filter?: NDKFilter): Promise<NDKCashuMintRecommendation>;
type PaymentWithOptionalZapInfo<T extends LnPaymentInfo | CashuPaymentInfo> = T & {
target?: NDKEvent | NDKUser;
comment?: string;
tags?: NDKTag[];
amount?: number;
unit?: string;
recipientPubkey?: string;
paymentDescription?: string;
};
declare class PaymentHandler {
private wallet;
constructor(wallet: NDKCashuWallet);
/**
* Pay a LN invoice with this wallet. This will used cashu proofs to pay a bolt11.
*/
lnPay(payment: PaymentWithOptionalZapInfo<LnPaymentInfo>, createTxEvent?: boolean): Promise<NDKPaymentConfirmationLN | undefined>;
/**
* Swaps tokens to a specific amount, optionally locking to a p2pk.
*/
cashuPay(payment: NDKZapDetails<CashuPaymentInfo>): Promise<NDKPaymentConfirmationCashu | undefined>;
}
type UpdateStateResult = {
/**
* Tokens that were created as the result of a state change
*/
created?: NDKCashuToken;
/**
* Tokens that were reserved as the result of a state change
*/
reserved?: NDKCashuToken;
/**
* Tokens that were deleted as the result of a state change
*/
deleted?: NDKEventId[];
};
/**
*
* @param this
* @param stateChange
*/
declare function update(this: WalletState, stateChange: WalletProofChange, _memo?: string): Promise<UpdateStateResult>;
declare function calculateNewState(walletState: WalletState, stateChange: WalletProofChange): WalletTokenChange;
type GetOpts = {
mint?: MintUrl;
onlyAvailable?: boolean;
includeDeleted?: boolean;
};
type ProofC = string;
type ProofState = "available" | "reserved" | "deleted";
type TokenState = "available" | "deleted";
type JournalEntry = {
memo: string;
timestamp: number;
metadata: {
type?: string;
mint?: MintUrl;
id: string;
relayUrl?: string;
cache?: boolean;
amount?: number;
};
};
/**
* A description of the changes that need to be made to the wallet state
* to reflect changes that have occurred.
*/
type WalletProofChange = {
reserve?: Proof[];
destroy?: Proof[];
store?: Proof[];
mint: MintUrl;
};
/**
* A description of tokens that need to be changed to reflect the changes that have occurred.
*/
type WalletTokenChange = {
deletedTokenIds: Set<string>;
deletedProofs: Set<string>;
reserveProofs: Proof[];
saveProofs: Proof[];
};
type ProofEntry = {
proof: Proof;
mint: MintUrl;
tokenId?: NDKEventId;
state: ProofState;
/**
* The timestamp of the last time the proof state was updated
*/
timestamp: number;
};
type TokenEntry = {
/**
* We want this optional because we might just be marking a deletion of a token
* we never loaded (or haven't attempted to load yet)
*/
token?: NDKCashuToken;
state: TokenState;
proofEntries?: ProofEntry[];
};
type GetTokenEntry = {
tokenId: NDKEventId | null;
token?: NDKCashuToken;
mint: MintUrl;
proofEntries: ProofEntry[];
};
/**
* This class represents the state of the wallet at any given time.
* It uses information coming from relays, as well as optimistic assumptions
* about the changing state of the wallet.
*/
declare class WalletState {
wallet: NDKCashuWallet;
reservedProofCs: Set<string>;
/**
* the amounts that are intended to be reserved
* this is the net amount we are trying to pay out,
* excluding fees and coin sizes
* e.g. we might want to pay 5 sats, have 2 sats in fees
* and we're using 2 inputs that add up to 8, the reserve amount is 5
* while the reserve proofs add up to 8
*/
reserveAmounts: number[];
/**
* Source of truth of the proofs this wallet has/had.
*/
proofs: Map<string, ProofEntry>;
/**
* The tokens that are known to this wallet.
*/
tokens: Map<string, TokenEntry>;
journal: JournalEntry[];
constructor(wallet: NDKCashuWallet, reservedProofCs?: Set<string>);
/** This is a debugging function that dumps the state of the wallet */
dump(): {
proofs: ProofEntry[];
balances: Record<string, number>;
totalBalance: number;
tokens: TokenEntry[];
};
/***************************
* Tokens
***************************/
addToken: (token: NDKCashuToken) => void;
removeTokenId: (tokenId: string) => void;
/***************************
* Proof management
***************************/
addProof: (proofEntry: ProofEntry) => void;
/**
* Reserves a number of selected proofs and a specific amount.
*
* The amount and total of the proofs don't need to match. We
* might want to use 5 sats and have 2 proofs of 4 sats each.
* In that case, the reserve amount is 5, while the reserve proofs
* add up to 8.
*/
reserveProofs: (proofs: Proof[], amount: number) => void;
/**
* Unreserves a number of selected proofs and a specific amount.
*/
unreserveProofs: (proofs: Proof[], amount: number, newState: "available" | "deleted") => void;
/**
* Returns all proof entries, optionally filtered by mint and state
*/
getProofEntries: (opts?: GetOpts | undefined) => ProofEntry[];
/**
* Updates information about a proof
*/
updateProof: (proof: Proof, state: Partial<ProofEntry>) => void;
/**
* Returns all proofs, optionally filtered by mint and state
* @param opts.mint - optional mint to filter by
* @param opts.onlyAvailable - only include available proofs @default true
* @param opts.includeDeleted - include deleted proofs @default false
*/
getProofs(opts: GetOpts): Proof[];
getTokens(opts?: GetOpts): Map<NDKEventId | null, GetTokenEntry>;
/**
* Gets a list of proofs for each mint
* @returns
*/
getMintsProofs({ validStates, }?: {
validStates?: Set<ProofState>;
}): Map<MintUrl, Proof[]>;
/***************************
* Balance
***************************/
/**
* Returns the balance of the wallet, optionally filtered by mint and state
*
* @params opts.mint - optional mint to filter by
* @params opts.onlyAvailable - only include available proofs @default true
*/
getBalance: (opts?: GetOpts | undefined) => number;
/**
* Returns the balances of the different mints
*
* @params opts.onlyAvailable - only include available proofs @default true
*/
getMintsBalance: (args_0?: GetOpts | undefined) => Record<string, number>;
/***************************
* State update
***************************/
update: (stateChange: WalletProofChange, _memo?: string | undefined) => Promise<UpdateStateResult>;
}
type WalletWarning = {
msg: string;
event?: NDKEvent;
relays?: NDKRelay[];
};
/**
* This class tracks state of a NIP-60 wallet
*/
declare class NDKCashuWallet extends NDKWallet {
get type(): NDKWalletTypes;
_p2pk: string | undefined;
private sub?;
status: NDKWalletStatus;
static kind: NDKKind;
static kinds: NDKKind[];
mints: string[];
privkeys: Map<string, NDKPrivateKeySigner>;
signer?: NDKPrivateKeySigner;
walletId: string;
depositMonitor: NDKCashuDepositMonitor;
/**
* Warnings that have been raised
*/
warnings: WalletWarning[];
paymentHandler: PaymentHandler;
state: WalletState;
relaySet?: NDKRelaySet;
constructor(ndk: NDK__default);
/**
* Generates a backup event for this wallet
*/
backup(publish?: boolean): Promise<NDKCashuWalletBackup>;
consolidateTokens: () => Promise<void>;
/**
* Generates nuts that can be used to send to someone.
*
* Note that this function does not send anything, it just generates a specific amount of proofs.
* @param amounts
* @returns
*/
mintNuts(amounts: number[]): Promise<SendResponse | undefined>;
/**
* Loads a wallet information from an event
* @param event
*/
loadFromEvent(event: NDKEvent): Promise<void>;
static from(event: NDKEvent): Promise<NDKCashuWallet | undefined>;
/**
* Starts monitoring the wallet.
*
* Use `since` to start syncing state from a specific timestamp. This should be
* used by storing at the app level a time in which we know we were able to communicate
* with the relays, for example, by saving the time the wallet has emitted a "ready" event.
*/
start(opts?: NDKSubscriptionOptions & {
pubkey?: Hexpubkey;
since?: number;
}): Promise<void>;
stop(): void;
/**
* Returns the p2pk of this wallet or generates a new one if we don't have one
*/
getP2pk(): Promise<string>;
/**
* If this wallet has access to more than one privkey, this will return all of them.
*/
get p2pks(): string[];
addPrivkey(privkey: string): Promise<string>;
get p2pk(): string;
set p2pk(pubkey: string);
/**
* Generates the payload for a wallet event
*/
private walletPayload;
publish(): Promise<Set<NDKRelay>>;
/**
* Prepares a deposit
* @param amount
* @param mint
*
* @example
* const wallet = new NDKCashuWallet(...);
* const deposit = wallet.deposit(1000, "https://mint.example.com", "sats");
* deposit.on("success", (token) => {
* });
* deposit.on("error", (error) => {
* });
*
* // start monitoring the deposit
* deposit.start();
*/
deposit(amount: number, mint?: string): NDKCashuDeposit;
/**
* Receives a token and adds it to the wallet
* @param token
* @returns the token event that was created
*/
receiveToken(token: string, description?: string): Promise<NDK.NDKCashuToken | undefined>;
/**
* Pay a LN invoice with this wallet
*/
lnPay(payment: PaymentWithOptionalZapInfo<LnPaymentInfo>, createTxEvent?: boolean): Promise<NDKPaymentConfirmationLN | undefined>;
/**
* Swaps tokens to a specific amount, optionally locking to a p2pk.
*
* This function has side effects:
* - It swaps tokens at the mint
* - It updates the wallet state (deletes affected tokens, might create new ones)
* - It creates a wallet transaction event
*
* This function returns the proofs that need to be sent to the recipient.
* @param amount
*/
cashuPay(payment: NDKZapDetails<CashuPaymentInfo>): Promise<NDKPaymentConfirmationCashu | undefined>;
wallets: Map<string, CashuWallet>;
redeemNutzaps(nutzaps: NDKNutzap[], privkey: string, { mint, proofs, cashuWallet }: RedeemNutzapsOpts): Promise<number>;
warn(msg: string, event?: NDKEvent, relays?: NDKRelay[]): void;
get balance(): NDKWalletBalance | undefined;
/**
* Gets the total balance for a specific mint, including reserved proofs
*/
mintBalance(mint: MintUrl): number;
/**
* Gets all tokens, grouped by mint with their total balances
*/
get mintBalances(): Record<MintUrl, number>;
/**
* Returns a list of mints that have enough available balance (excluding reserved proofs)
* to cover the specified amount
*/
getMintsWithBalance(amount: number): MintUrl[];
}
declare class NDKCashuWalletBackup extends NDKEvent {
privkeys: string[];
mints: string[];
constructor(ndk: NDK__default, event?: NDKEvent);
static from(event: NDKEvent): Promise<NDKCashuWalletBackup | undefined>;
save(relaySet?: NDKRelaySet): Promise<Set<NDKRelay>>;
}
/**
* Checks for spent proofs and consolidates all unspent proofs into a single token, destroying all old tokens
*/
declare function consolidateTokens(this: NDKCashuWallet): Promise<void>;
declare function consolidateMintTokens(mint: string, wallet: NDKCashuWallet, allProofs?: Proof[], onResult?: (walletChange: WalletProofChange) => void, onFailure?: (error: string) => void): Promise<UpdateStateResult | undefined>;
/**
* This function checks if the user had legacy cashu wallets, if they do, it migrates them to the new format.
*/
declare function migrateCashuWallet(ndk: NDK__default): Promise<void>;
type NutPayment = CashuPaymentInfo & {
amount: number;
};
declare class NDKWebLNWallet extends NDKWallet {
get type(): NDKWalletTypes;
walletId: string;
status: NDKWalletStatus;
provider?: WebLNProvider;
private _balance?;
constructor(ndk: NDK__default);
pay(payment: LnPaymentInfo): Promise<NDKPaymentConfirmationLN | undefined>;
lnPay(payment: LnPaymentInfo): Promise<NDKPaymentConfirmationLN | undefined>;
cashuPay(payment: NDKZapDetails<NutPayment>): Promise<NDKPaymentConfirmationCashu>;
updateBalance?(): Promise<void>;
get balance(): NDKWalletBalance | undefined;
}
type NDKNWCMethod = "pay_invoice" | "multi_pay_invoice" | "pay_keysend" | "multi_pay_keysend" | "make_invoice" | "lookup_invoice" | "list_transactions" | "get_balance" | "get_info";
interface NDKNWCRequestBase {
method: NDKNWCMethod;
params: Record<string, any>;
}
interface NDKNWCResponseBase<T = any> {
result_type: NDKNWCMethod;
error?: {
code: NDKNWCErrorCode;
message: string;
};
result: T | null;
}
type NDKNWCErrorCode = "RATE_LIMITED" | "NOT_IMPLEMENTED" | "INSUFFICIENT_BALANCE" | "QUOTA_EXCEEDED" | "RESTRICTED" | "UNAUTHORIZED" | "INTERNAL" | "OTHER" | "PAYMENT_FAILED" | "NOT_FOUND";
interface NDKNWCTransaction {
type: "incoming" | "outgoing";
invoice?: string;
description?: string;
description_hash?: string;
preimage?: string;
payment_hash: string;
amount: number;
fees_paid?: number;
created_at: number;
expires_at?: number;
settled_at?: number;
metadata?: Record<string, any>;
}
interface NDKNWCPayInvoiceParams {
invoice: string;
amount?: number;
}
interface NDKNWCMakeInvoiceParams {
amount: number;
description?: string;
description_hash?: string;
expiry?: number;
}
interface NDKNWCLookupInvoiceParams {
payment_hash?: string;
invoice?: string;
}
interface NDKNWCListTransactionsParams {
from?: number;
until?: number;
limit?: number;
offset?: number;
unpaid?: boolean;
type?: "incoming" | "outgoing";
}
interface NDKNWCPayInvoiceResult {
preimage: string;
fees_paid?: number;
}
interface NDKNWCMakeInvoiceResult {
invoice: string;
preimage: string;
payment_hash: string;
amount: number;
description: string;
description_hash: string;
expiry: number;
metadata?: Record<string, any>;
}
interface NDKNWCGetBalanceResult {
balance: number;
}
interface NDKNWCGetInfoResult {
alias: string;
color: string;
pubkey: string;
network: "mainnet" | "testnet" | "signet" | "regtest";
block_height: number;
block_hash: string;
methods: NDKNWCMethod[];
notifications?: string[];
}
type NDKNWCRequestMap = {
pay_invoice: NDKNWCPayInvoiceParams;
make_invoice: NDKNWCMakeInvoiceParams;
lookup_invoice: NDKNWCLookupInvoiceParams;
list_transactions: NDKNWCListTransactionsParams;
get_balance: Record<string, never>;
get_info: Record<string, never>;
};
type NDKNWCResponseMap = {
pay_invoice: NDKNWCPayInvoiceResult;
make_invoice: NDKNWCMakeInvoiceResult;
lookup_invoice: NDKNWCTransaction;
list_transactions: {
transactions: NDKNWCTransaction[];
};
get_balance: NDKNWCGetBalanceResult;
get_info: NDKNWCGetInfoResult;
};
type NDKNWCWalletEvents = NDKWalletEvents & {
connecting: () => void;
error: () => void;
timeout: (method: keyof NDKNWCRequestMap) => void;
};
declare class NDKNWCWallet extends NDKWallet {
get type(): NDKWalletTypes;
status: NDKWalletStatus;
walletId: string;
pairingCode?: string;
walletService?: NDKUser;
relaySet?: NDKRelaySet;
signer?: NDKPrivateKeySigner;
private _balance?;
private cachedInfo?;
pool?: NDKPool;
timeout?: number;
/**
*
* @param ndk
* @param timeout A timeeout to use for all operations.
*/
constructor(ndk: NDK__default, { timeout, pairingCode, pubkey, relayUrls, secret, }: {
timeout?: number;
pairingCode?: string;
pubkey?: string;
relayUrls?: string[];
secret?: string;
});
private getPool;
lnPay(payment: LnPaymentInfo): Promise<NDKPaymentConfirmationLN | undefined>;
/**
* Pay by minting tokens.
*
* This creates a quote on a mint, pays it using NWC and then mints the tokens.
*
* @param payment - The payment to pay
* @param onLnPayment - A callback that is called when an LN payment will be processed
* @returns The payment confirmation
*/
cashuPay(payment: NutPayment, onLnInvoice?: (pr: string) => void, onLnPayment?: (mint: string, invoice: string) => void): Promise<NDKPaymentConfirmationCashu | undefined>;
/**
* Redeem a set of nutzaps into an NWC wallet.
*
* This function gets an invoice from the NWC wallet until the total amount of the nutzaps is enough to pay for the invoice
* when accounting for fees.
*
* @param cashuWallet - The cashu wallet to redeem the nutzaps into
* @param nutzaps - The nutzaps to redeem
* @param proofs - The proofs to redeem
* @param mint - The mint to redeem the nutzaps into
* @param privkey - The private key needed to redeem p2pk proofs.
*/
redeemNutzaps: (nutzaps: NDK.NDKNutzap[], privkey: string, args_2: RedeemNutzapsOpts) => Promise<number>;
/**
* Fetch the balance of this wallet
*/
updateBalance(): Promise<void>;
/**
* Get the balance of this wallet
*/
get balance(): NDKWalletBalance | undefined;
req: <M extends keyof NDKNWCRequestMap>(method: M, params: NDKNWCRequestMap[M]) => Promise<NDKNWCResponseBase<NDKNWCResponseMap[M]>>;
getInfo(refetch?: boolean): Promise<NDKNWCGetInfoResult>;
listTransactions(): Promise<{
transactions: NDKNWCTransaction[];
}>;
makeInvoice(amount: number, description: string): Promise<NDKNWCMakeInvoiceResult>;
}
declare function getBolt11ExpiresAt(bolt11: string): number | undefined;
declare function getBolt11Amount(bolt11: string): number | undefined;
declare function getBolt11Description(bolt11: string): string | undefined;
export { type GetTokenEntry, type JournalEntry, type MintUrl, type MintUsage, NDKCashuDeposit, type NDKCashuMintRecommendation, NDKCashuWallet, NDKCashuWalletBackup, type NDKNWCErrorCode, type NDKNWCGetBalanceResult, type NDKNWCGetInfoResult, type NDKNWCListTransactionsParams, type NDKNWCLookupInvoiceParams, type NDKNWCMakeInvoiceParams, type NDKNWCMakeInvoiceResult, type NDKNWCMethod, type NDKNWCPayInvoiceParams, type NDKNWCPayInvoiceResult, type NDKNWCRequestBase, type NDKNWCRequestMap, type NDKNWCResponseBase, type NDKNWCResponseMap, type NDKNWCTransaction, NDKNWCWallet, type NDKNWCWalletEvents, NDKNutzapMonitor, type NDKNutzapMonitorStore, NDKWallet, type NDKWalletBalance, type NDKWalletEvents, NDKWalletStatus, type NDKWalletTypes, NDKWebLNWallet, type ProofC, type ProofEntry, type ProofState, type RedeemNutzapsOpts, type TokenEntry, type TokenState, type UpdateStateResult, type WalletProofChange, WalletState, type WalletTokenChange, type WalletWarning, calculateNewState, consolidateMintTokens, consolidateTokens, getBolt11Amount, getBolt11Description, getBolt11ExpiresAt, getCashuMintRecommendations, migrateCashuWallet, update };