Skip to content

Commit b279b5c

Browse files
committed
remove responsbility of serializing/loading wallet configurations -- apps should own that responsibility
1 parent ac6cb6e commit b279b5c

File tree

10 files changed

+27
-72
lines changed

10 files changed

+27
-72
lines changed

docs/mobile/session.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -83,8 +83,8 @@ return (<View>
8383
Now say you want to allow the user to bookmark something with the click of a button:
8484
8585
```tsx
86-
const { imageCurationSet } = useNDKSessionEventKind<NDKList>(NDKList, NDKKind.ImageCurationSet, {
87-
create: true,
86+
const { imageCurationSet } = useNDKSessionEventKind<NDKList>(NDKKind.ImageCurationSet, {
87+
create: NDKList,
8888
});
8989

9090
const bookmark = async () => {

ndk-mobile/src/hooks/session.ts

Lines changed: 6 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import NDK, { NDKEvent, NDKKind, NDKUser } from '@nostr-dev-kit/ndk';
2-
import { useState, useEffect } from 'react';
32
import { useNDK } from './ndk.js';
4-
import { NDKEventWithFrom, NDKEventWithAsyncFrom } from './subscribe.js';
3+
import { NDKEventWithFrom } from './subscribe.js';
54
import { useNDKSession } from '../stores/session/index.js';
65

76
const useNDKSessionInit = () => {
@@ -24,51 +23,29 @@ const useWOT = () => useNDKSession(s => s.wot);
2423

2524
/**
2625
* This hook allows you to get a specific kind, wrapped in the event class you provide.
26+
* Note that the wrapping must be specified when requesting the event from the NDKSession initializer.
2727
* @param EventClass
2828
* @param kind
2929
* @param opts.create - If true, and the event kind is not found, an unpublished event will be provided.
3030
* @returns
3131
*/
3232
const useNDKSessionEventKind = <T extends NDKEvent>(
33-
EventClass: NDKEventWithFrom<any>,
34-
kind?: NDKKind,
35-
{ create }: { create: boolean } = { create: false }
33+
kind: NDKKind,
34+
{ create }: { create: NDKEventWithFrom<any> | false } = { create: false }
3635
): T | undefined => {
37-
kind ??= EventClass.kind;
3836
const { ndk } = useNDK();
3937
const events = useNDKSession(s => s.events);
4038
const kindEvents = events.get(kind) || [];
4139
const firstEvent = kindEvents[0];
4240

4341
if (create && !firstEvent) {
44-
const event = new EventClass(ndk, { kind });
42+
const event = new create(ndk, { kind });
4543
event.kind = kind;
4644
events.set(kind, [event]);
4745
return event;
4846
}
4947

50-
return firstEvent ? EventClass.from(firstEvent) : undefined;
51-
};
52-
53-
const useNDKSessionEventKindAsync = <T>(
54-
EventClass: NDKEventWithAsyncFrom<any>,
55-
kind?: NDKKind,
56-
{ create }: { create: boolean } = { create: false }
57-
): T | undefined => {
58-
kind ??= EventClass.kind;
59-
const events = useNDKSession(s => s.events);
60-
const kindEvents = events.get(kind) || [];
61-
const firstEvent = kindEvents[0];
62-
const [res, setRes] = useState<T | undefined>(undefined);
63-
64-
useEffect(() => {
65-
if (!firstEvent) return;
66-
EventClass.from(firstEvent).then((event) => {
67-
setRes(event);
68-
});
69-
}, [firstEvent]);
70-
71-
return res;
48+
return firstEvent as T;
7249
};
7350

7451
const useNDKSessionEvents = <T extends NDKEvent>(
@@ -94,5 +71,4 @@ export {
9471
useNDKSessionEventKind,
9572
useNDKSessionEvents,
9673
useNDKSessionInit,
97-
useNDKSessionEventKindAsync,
9874
};

ndk-mobile/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ export * from './cache-adapter/sqlite.js';
66
export * from './components/index.js';
77
export * from './components/relays/index.js';
88
export * from './signers/index.js';
9+
export * from './stores/session/index.js';
910
export * from '@nostr-dev-kit/ndk';
1011
export * as DBCache from './db/index.js';
1112
import NDK from '@nostr-dev-kit/ndk';

ndk-mobile/src/stores/ndk.ts

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -89,19 +89,10 @@ export const useNDKStore = create<State & Actions & EventHandler>((set, get) =>
8989
settingsStore.delete('wot.last_updated_at');
9090
settingsStore.delete('wot.length');
9191
settingsStore.delete('ndkMobileSessionLastEose');
92-
settingsStore.delete('wallet');
9392

9493
// nuke the database
9594
if (ndk.cacheAdapter instanceof NDKCacheAdapterSqlite) {
9695
ndk.cacheAdapter.clear();
9796
}
9897
}
9998
}))
100-
101-
function getUserFromSettingsStore(ndk: NDK, settingsStore?: SettingsStore) {
102-
const currentUser = settingsStore?.getSync('currentUser');
103-
if (currentUser) {
104-
return ndk.getUser({pubkey: currentUser});
105-
}
106-
return null;
107-
}

ndk-mobile/src/stores/session/actions/addEvent.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ export const addEvent = (event: NDKEvent, onAdded, set) => {
1818
const newEvents = new Map(state.events);
1919
let existing = newEvents.get(kind) || [];
2020

21+
console.log('\tadding event', event.kind);
22+
2123
if (event.isParamReplaceable()) {
2224
const existingEvent = existing.find((e) => e.dTag === event.dTag);
2325
if (existingEvent) {

ndk-mobile/src/stores/session/actions/init.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,6 @@ export const initSession = (
7373
// if we have already eosed, get the pubkeys that are not in the wotEntries and add them to the wotEntries
7474
if (eosed && opts.wot) {
7575
const newEntries = follows.filter((pubkey) => !wotEntries.has(pubkey));
76-
console.log('eosed, adding wot entries', follows.length, newEntries.length);
7776
addWotEntries(ndk, newEntries, settingsStore, set, () => {
7877
on.onWotReady?.();
7978
});
@@ -97,7 +96,6 @@ export const initSession = (
9796
settingsStore?.set?.('ndkMobileSessionLastEose', Math.floor(Date.now() / 1000).toString())
9897

9998
if (opts.wot) {
100-
console.log('shouldUpdateWot', shouldUpdateWot(ndk, settingsStore));
10199
if (shouldUpdateWot(ndk, settingsStore)) {
102100
addWotEntries(ndk, follows, settingsStore, set, () => {
103101
on.onWotReady?.();

ndk-wallet/src/wallets/cashu/wallet/index.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,8 @@ import NDK, { NDKEvent, NDKKind, NDKPrivateKeySigner, NDKRelaySet, NDKUser } fro
1616
import { NDKCashuDeposit } from "../deposit.js";
1717
import createDebug from "debug";
1818
import type { MintUrl } from "../mint/utils.js";
19-
import type { CashuWallet, MintKeys, Proof, SendResponse } from "@cashu/cashu-ts";
20-
import { getDecodedToken } from "@cashu/cashu-ts";
19+
import type { CashuWallet, GetInfoResponse, MintKeys, Proof, SendResponse } from "@cashu/cashu-ts";
20+
import { CashuMint, getDecodedToken } from "@cashu/cashu-ts";
2121
import { consolidateTokens } from "../validate.js";
2222
import { NDKWallet, NDKWalletBalance, NDKWalletEvents, NDKWalletStatus } from "../../index.js";
2323
import { EventEmitter } from "tseep";
@@ -36,7 +36,6 @@ export type WalletWarning = {
3636
import { PaymentHandler, PaymentWithOptionalZapInfo } from "./payment.js";
3737
import { createInTxEvent, createOutTxEvent } from "./txs.js";
3838
import { WalletState } from "./state/index.js";
39-
import { MintInfo } from "@cashu/cashu-ts/dist/lib/es5/model/MintInfo.js";
4039

4140
/**
4241
* This class tracks state of a NIP-60 wallet
@@ -79,12 +78,12 @@ export class NDKCashuWallet extends EventEmitter<NDKWalletEvents & {
7978
* Called when the wallet needs to load mint info. Use this
8079
* to load mint info from a database or other source.
8180
*/
82-
public onMintInfoNeeded?: (mint: string) => Promise<MintInfo | undefined>;
81+
public onMintInfoNeeded?: (mint: string) => Promise<GetInfoResponse | undefined>;
8382

8483
/**
8584
* Called when the wallet has loaded mint info.
8685
*/
87-
public onMintInfoLoaded?: (mint: string, info: MintInfo) => void;
86+
public onMintInfoLoaded?: (mint: string, info: GetInfoResponse) => void;
8887

8988
/**
9089
* Called when the wallet needs to load mint keys. Use this
@@ -412,12 +411,16 @@ export class NDKCashuWallet extends EventEmitter<NDKWalletEvents & {
412411
async cashuWallet(mint: string): Promise<CashuWallet> {
413412
if (this.wallets.has(mint)) return this.wallets.get(mint) as CashuWallet;
414413

415-
const mintInfo = await this.onMintInfoNeeded?.(mint);
414+
let mintInfo = await this.onMintInfoNeeded?.(mint);
416415
const mintKeys = await this.onMintKeysNeeded?.(mint);
417416

417+
if (!mintInfo && this.onMintInfoLoaded) {
418+
mintInfo = await CashuMint.getInfo(mint);
419+
this.onMintInfoLoaded?.(mint, mintInfo);
420+
}
421+
418422
const w = await walletForMint(mint, { mintInfo, mintKeys });
419423

420-
if (w?.mintInfo) this.onMintInfoLoaded?.(mint, w.mintInfo);
421424
if (w?.keys) this.onMintKeysLoaded?.(mint, w.keys);
422425

423426
if (!w) throw new Error("unable to load wallet for mint " + mint);

ndk-wallet/src/wallets/index.ts

Lines changed: 1 addition & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -96,17 +96,4 @@ export interface NDKWallet
9696
* Serializes the wallet configuration in a way that can be restored later.
9797
*/
9898
toLoadingString?(): string;
99-
}
100-
101-
export async function walletFromLoadingString(ndk: NDK, str: string): Promise<NDKNWCWallet | NDKCashuWallet | undefined> {
102-
const payload = JSON.parse(str);
103-
104-
switch (payload.type) {
105-
case 'nwc':
106-
return new NDKNWCWallet(ndk, { timeout: payload.timeout, pairingCode: payload.pairingCode });
107-
case 'nip60':
108-
const event = await ndk.fetchEvent(payload.bech32);
109-
if (!event) return undefined;
110-
return await NDKCashuWallet.from(event);
111-
}
112-
}
99+
}

ndk-wallet/src/wallets/nwc/index.ts

Lines changed: 0 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -86,13 +86,6 @@ export class NDKNWCWallet extends EventEmitter<NDKNWCWalletEvents> implements ND
8686
return new NDKPool(relayUrls, [], this.ndk, { name: 'NWC' });
8787
}
8888

89-
toLoadingString(): string {
90-
return JSON.stringify({
91-
type: 'nwc',
92-
pairingCode: this.pairingCode
93-
});
94-
}
95-
9689
async lnPay(payment: LnPaymentInfo): Promise<NDKPaymentConfirmationLN | undefined> {
9790
if (!this.signer) throw new Error("Wallet not initialized");
9891

ndk/src/ndk/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -598,7 +598,11 @@ export class NDK extends EventEmitter<{
598598
const sub = new NDKSubscription(this, filters);
599599
const events = this.cacheAdapter.query(sub);
600600
if (events instanceof Promise) throw new Error("Cache adapter is async");
601-
return events;
601+
return events
602+
.map(e => {
603+
e.ndk = this;
604+
return e;
605+
})
602606
}
603607

604608
/**

0 commit comments

Comments
 (0)