Skip to content

Commit

Permalink
remove dexie from docs?
Browse files Browse the repository at this point in the history
  • Loading branch information
pablof7z committed Nov 28, 2024
1 parent 162ed25 commit 78200ee
Show file tree
Hide file tree
Showing 14 changed files with 181 additions and 98 deletions.
2 changes: 0 additions & 2 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,6 @@ jobs:
uses: actions/configure-pages@v4
- name: Install dependencies
run: pnpm install # or pnpm install / yarn install / bun install
- name: Build dexie typedoc
run: cd ndk-cache-dexie && pnpm typedoc && cat docs/interfaces/NDKCacheAdapterDexieOptions.md >> ../docs/cache/dexie.md
- name: Build with VitePress
run: pnpm docs:build # or pnpm docs:build / yarn docs:build / bun run docs:build
- name: Build typedoc
Expand Down
2 changes: 1 addition & 1 deletion ndk-cache-dexie/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@
"ts-jest": "^29.2.5",
"tsup": "^8.3.0",
"typedoc": "^0.26.7",
"typedoc-plugin-markdown": "^4.2.8"
"typedoc-plugin-markdown": "^4.3.0"
},
"dependencies": {
"@nostr-dev-kit/ndk": "workspace:*",
Expand Down
2 changes: 1 addition & 1 deletion ndk-wallet/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
},
"homepage": "https://github.com/nostr-dev-kit/ndk",
"dependencies": {
"@cashu/cashu-ts": "2.0.0-rc4",
"@cashu/cashu-ts": "2.0.0",
"@getalby/sdk": "^3.6.1",
"@nostr-dev-kit/ndk": "workspace:*",
"debug": "^4.3.4",
Expand Down
24 changes: 21 additions & 3 deletions ndk-wallet/src/cashu/deposit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ export class NDKCashuDeposit extends EventEmitter<{
public finalized = false;
public unit?: string;

private quoteEvent?: NDKEvent;

constructor(wallet: NDKCashuWallet, amount: number, mint?: string, unit?: string) {
super();
this.wallet = wallet;
Expand All @@ -38,15 +40,24 @@ export class NDKCashuDeposit extends EventEmitter<{
this.unit = unit;
}

async start() {
/**
* 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
*/
async start(pollTime: number = 2500) {
this._wallet ??= await this.wallet.walletForMint(this.mint);
const quote = await this._wallet.createMintQuote(this.amount);
d("created quote %s for %d %s", quote.quote, this.amount, this.mint);

this.quoteId = quote.quote;

this.check();
this.createQuoteEvent(quote.quote, quote.request);
this.check(pollTime);
this.createQuoteEvent(quote.quote, quote.request)
.then((event) => this.quoteEvent = event);

return quote.request;
}
Expand Down Expand Up @@ -149,6 +160,13 @@ export class NDKCashuDeposit extends EventEmitter<{
historyEvent.publish(this.wallet.relaySet);

this.emit("success", tokenEvent);

// delete the quote event if it exists
if (this.quoteEvent) {
const deleteEvent = await this.quoteEvent.delete(undefined, false);
deleteEvent.publish(this.wallet.relaySet);
}

} catch (e: any) {
console.log("relayset", this.wallet.relaySet);
this.emit("error", e.message);
Expand Down
12 changes: 12 additions & 0 deletions ndk-wallet/src/cashu/wallet.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,18 @@ export class NDKCashuWallet extends EventEmitter<NDKWalletEvents> implements NDK
this.ndk = ndk;
}

/**
* Creates a new NIP-60 wallet
* @param ndk
* @param mints
* @param relayUrls
* @returns
*/
static create(ndk: NDK, mints: string[] = [], relayUrls: string[] = []) {
const wallet = new NDKCashuWallet(ndk);
return wallet;
}

set event(e: NDKEvent | undefined) {
this.walletId = e?.dTag ?? "";
this._event = e;
Expand Down
1 change: 1 addition & 0 deletions ndk-wallet/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,6 @@ export * from "./cashu/mint/utils";
export * from "./ln/index.js";

export * from "./nwc/index.js";
export * from "./nwc/types.js";

export default NDKWalletService;
2 changes: 1 addition & 1 deletion ndk-wallet/src/ln/pay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ export class NDKLnPay {
// get quotes from the mints the recipient has
const quotesPromises = mints.map(async (mint) => {
const wallet = new CashuWallet(new CashuMint(mint), { unit: unit });
const quote = await wallet.mintQuote(amount);
const quote = await wallet.createMintQuote(amount);
return { quote, mint };
});

Expand Down
88 changes: 76 additions & 12 deletions ndk-wallet/src/nwc/index.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { EventEmitter } from "tseep";
import { NDKWalletBalance, NDKWalletEvents, NDKWalletStatus, type NDKWallet } from "../wallet/index.js";
import NDK, { NDKPool, LnPaymentInfo, NDKEvent, NDKPaymentConfirmationCashu, NDKPaymentConfirmationLN, NDKRelaySet, NDKUser, NDKPrivateKeySigner } from "@nostr-dev-kit/ndk";
import NDK, { NDKPool, LnPaymentInfo, NDKPaymentConfirmationCashu, NDKPaymentConfirmationLN, NDKRelaySet, NDKUser, NDKPrivateKeySigner } from "@nostr-dev-kit/ndk";
import { NutPayment } from "../cashu/pay/nut.js";
import { hexToBytes } from "@noble/hashes/utils";
import { NWCResponseBase, sendReq } from "./req.js";
import { NWCRequestMap, NWCResponseMap } from "./types.js";
import { sendReq } from "./req.js";
import createDebug from "debug";
import { NDKNWCGetInfoResult, NDKNWCRequestMap, NDKNWCResponseBase, NDKNWCResponseMap } from "./types.js";
import { CashuMint, CashuWallet } from "@cashu/cashu-ts";

const d = createDebug("ndk-wallet:nwc");

export class NDKNWCWallet extends EventEmitter<NDKWalletEvents> implements NDKWallet {
readonly type = "nwc";
Expand All @@ -20,6 +24,8 @@ export class NDKNWCWallet extends EventEmitter<NDKWalletEvents> implements NDKWa

private _balance?: NDKWalletBalance[];

private cachedInfo?: NDKNWCGetInfoResult;

public pool?: NDKPool;

constructor(ndk: NDK) {
Expand All @@ -28,9 +34,13 @@ export class NDKNWCWallet extends EventEmitter<NDKWalletEvents> implements NDKWa
}

async init(pubkey: string, relayUrls: string[], secret: string) {
d('initializing wallet', pubkey, relayUrls, secret);

this.walletService = this.ndk.getUser({ pubkey });
this.pool = new NDKPool(relayUrls, [], this.ndk);
await this.pool.connect();
await this.pool.connect(1000);

d('connected to pool', this.pool.connectedRelays());

// Initialize signer
this.signer = new NDKPrivateKeySigner(
Expand Down Expand Up @@ -59,11 +69,14 @@ export class NDKNWCWallet extends EventEmitter<NDKWalletEvents> implements NDKWa

async lnPay(payment: LnPaymentInfo): Promise<NDKPaymentConfirmationLN | undefined> {
if (!this.signer) throw new Error("Wallet not initialized");

d('lnPay', payment.pr);

// Create and sign NWC request event
const res = await this.req("pay_invoice", { invoice: payment.pr });
d('lnPay res', res);

if (res.result?.preimage) {
if (res.result) {
return {
preimage: res.result.preimage
};
Expand All @@ -73,25 +86,57 @@ export class NDKNWCWallet extends EventEmitter<NDKWalletEvents> implements NDKWa
}

async cashuPay(payment: NutPayment): Promise<NDKPaymentConfirmationCashu | undefined> {
throw "not implemented";
for (const mint of payment.mints) {
let unit = payment.unit;
let amount = payment.amount;

if (unit === 'msat') {
unit = 'sat';
amount = amount / 1000;
}

const wallet = new CashuWallet(new CashuMint(mint), { unit });
try {
const quote = await wallet.createMintQuote(amount);
d('cashuPay quote', quote);

const res = await this.req("pay_invoice", { invoice: quote.request });
d('cashuPay res', res);

// todo check that the amount of the invoice matches the amount we want to pay

// mint the tokens
const mintProofs = await wallet.mintProofs(amount, quote.quote, {
pubkey: payment.p2pk
});
d('minted tokens', mintProofs);

return {
proofs: mintProofs,
mint: mint
};
} catch (e) {
console.error('error creating mint quote', e);
}
}
}

/**
* Fetch the balance of this wallet
*/
async updateBalance?(): Promise<void> {
async updateBalance(): Promise<void> {
d('updating balance');
const res = await this.req("get_balance", {});
d('balance', res);

if (!res.result) throw new Error("Failed to get balance");

if (res.error) throw new Error(res.error.message);



// update the cached balance property
this._balance = [{
unit: "sat",
amount: res.result.balance
unit: "msats",
amount: res.result?.balance ?? 0
}];

this.emit("balance_updated");
Expand All @@ -104,5 +149,24 @@ export class NDKNWCWallet extends EventEmitter<NDKWalletEvents> implements NDKWa
return this._balance;
}

req = sendReq.bind(this) as <M extends keyof NWCRequestMap>(method: M, params: NWCRequestMap[M]) => Promise<NWCResponseBase<NWCResponseMap[M]>>;
req = sendReq.bind(this) as <M extends keyof NDKNWCRequestMap>(method: M, params: NDKNWCRequestMap[M]) => Promise<NDKNWCResponseBase<NDKNWCResponseMap[M]>>;

async getInfo(refetch: boolean = false) {
if (refetch) {
this.cachedInfo = undefined;
}

if (this.cachedInfo) return this.cachedInfo;

const res = await this.req("get_info", {});
d('info', res);

if (!res.result) throw new Error("Failed to get info");

if (res.error) throw new Error(res.error.message);

this.cachedInfo = res.result;

return res.result;
}
}
18 changes: 9 additions & 9 deletions ndk-wallet/src/nwc/req.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { NDKEvent, NDKKind, NostrEvent } from "@nostr-dev-kit/ndk";
import type { NDKNWCWallet } from "./index.js";
import { NWCMethod, NWCRequestMap, NWCResponseMap } from "./types.js";
import { NDKNWCErrorCode, NDKNWCMethod, NDKNWCRequestMap, NDKNWCResponseMap } from "./types.js";
import { waitForResponse } from "./res.js";

// Base types for requests and responses
export interface NWCRequestBase {
method: NWCMethod;
method: NDKNWCMethod;
params: Record<string, any>;
}

export interface NWCResponseBase<T = any> {
result_type: NWCMethod;
result_type: NDKNWCMethod;
error?: {
code: NWCErrorCode;
code: NDKNWCErrorCode;
message: string;
};
result: T | null;
Expand Down Expand Up @@ -70,11 +70,11 @@ export interface ListTransactionsParams {
until?: number;
}

export async function sendReq<M extends keyof NWCRequestMap>(
export async function sendReq<M extends keyof NDKNWCRequestMap>(
this: NDKNWCWallet,
method: M,
params: NWCRequestMap[M]
): Promise<NWCResponseBase<NWCResponseMap[M]>> {
params: NDKNWCRequestMap[M]
): Promise<NWCResponseBase<NDKNWCResponseMap[M]>> {
if (!this.walletService || !this.signer) {
throw new Error("Wallet not initialized");
}
Expand All @@ -89,8 +89,8 @@ export async function sendReq<M extends keyof NWCRequestMap>(
await event.sign(this.signer);

// Wait for response
return new Promise<NWCResponseBase<NWCResponseMap[M]>>((resolve, reject) => {
waitForResponse.call<NDKNWCWallet, [string], Promise<NWCResponseBase<NWCResponseMap[M]>>>(
return new Promise<NWCResponseBase<NDKNWCResponseMap[M]>>((resolve, reject) => {
waitForResponse.call<NDKNWCWallet, [string], Promise<NWCResponseBase<NDKNWCResponseMap[M]>>>(
this,
event.id
).then(resolve).catch(reject);
Expand Down
10 changes: 5 additions & 5 deletions ndk-wallet/src/nwc/res.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { NDKEvent } from "@nostr-dev-kit/ndk";
import { NDKKind } from "@nostr-dev-kit/ndk";
import { NDKNWCWallet } from ".";
import { NWCResponseBase } from "./types";
import { NWCResponseMap } from "./types";
import { NDKNWCResponseBase } from "./types";
import { NDKNWCResponseMap } from "./types";

export async function waitForResponse<M extends keyof NWCResponseMap>(
export async function waitForResponse<M extends keyof NDKNWCResponseMap>(
this: NDKNWCWallet,
requestId: string
): Promise<NWCResponseBase<NWCResponseMap[M]>> {
): Promise<NDKNWCResponseBase<NDKNWCResponseMap[M]>> {

if (!this.pool) throw new Error("Wallet not initialized");

Expand All @@ -30,7 +30,7 @@ export async function waitForResponse<M extends keyof NWCResponseMap>(
if (content.error) {
reject(content);
} else {
resolve(content.result);
resolve(content);
}
} catch (e: any) {
sub.stop();
Expand Down
Loading

0 comments on commit 78200ee

Please sign in to comment.