Skip to content

Commit f3902d8

Browse files
committed
add more snippets
1 parent 844fe23 commit f3902d8

File tree

11 files changed

+294
-140
lines changed

11 files changed

+294
-140
lines changed

docs/markdown-examples.md

-85
This file was deleted.

docs/snippets/event/basic.md

+6-5
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,16 @@
33
NDK uses `NDKEvent` as the basic interface to generate and handle nostr events.
44

55
## Generating a basic event
6+
67
```ts
7-
import { NDKEvent, NDKKind } from "@nostr-dev-kit/ndk";
8+
import NDK, { NDKEvent, NDKKind } from "@nostr-dev-kit/ndk";
89

9-
const ndk = new NDK( /* initialization options for the ndk singleton */ )
10+
const ndk = new NDK(/* initialization options for the ndk singleton */);
1011

1112
const event = new NDKEvent(ndk, {
1213
kind: NDKKind.Text,
13-
content: "Hello world"
14-
})
14+
content: "Hello world",
15+
});
1516
```
1617

17-
There is no need to fill in the event's `id`, `tags`, `pubkey`, `created_at`, `sig` -- when these are empty, NDK will automatically fill them in with the appropriate values.
18+
There is no need to fill in the event's `id`, `tags`, `pubkey`, `created_at`, `sig` -- when these are empty, NDK will automatically fill them in with the appropriate values.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
# Signing events with different signers
2+
3+
NDK uses the default signer `ndk.signer` to sign events.
4+
5+
But you can specify the use of a different signer to sign with different pubkeys.
6+
7+
```ts
8+
import { NDKPrivateKeySigner, NDKEvent } from "@nostr-dev-kit/ndk";
9+
10+
const signer1 = NDKPrivateKeySigner.generate();
11+
const pubkey1 = signer1.pubkey;
12+
13+
const event1 = new NDKEvent();
14+
event1.kind = 1;
15+
event1.content = "Hello world";
16+
await event1.sign(signer1);
17+
18+
event1.pubkey === pubkey1 // true
19+
20+
const signer2 = NDKPrivateKeySigner.generate();
21+
const pubkey2 = signer2.pubkey;
22+
23+
const event2 = new NDKEvent();
24+
event2.kind = 1;
25+
event2.content = "Hello world";
26+
await event2.sign(signer2);
27+
28+
event2.pubkey === pubkey2 // true
29+
```

docs/snippets/index.md

+5
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,8 @@ Snippets are organized into the following categories:
2121
- [Rendering Event Content](./mobile/events/rendering-event-content.md) - Rich text rendering of Nostr event content with mentions, hashtags, and media
2222
- [Session](./mobile/session/)
2323
- [Login](./mobile/session/login.md) - Handle user authentication with NDK Mobile using various methods (NIP-46, nsec)
24+
- [Wallet](./wallet/)
25+
- [Connect Nostr Wallet Connect](./wallet/connect-nwc.md) - Connect to an NWC wallet and set it up for zapping
26+
- [Using Cashu Wallet](./wallet/using-cashu-wallet.md) - Create and use a Cashu wallet for managing e-cash tokens
27+
- [Nutzap Monitor](./wallet/nutzap-monitor.md) - Track and process Cashu tokens sent via Nostr zaps
28+
- [Cashu Deposits](./wallet/cashu-deposits.md) - Fund your Cashu wallet using Lightning invoices

docs/snippets/user/generate-keys.md

+8-5
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,18 @@
33
This snippet demonstrates how to generate a new key pair and obtain all its various formats (private key, public key, nsec, npub).
44

55
```typescript
6+
import { NDKPrivateKeySigner } from "@nostr-dev-kit/ndk";
7+
68
const signer = NDKPrivateKeySigner.generate();
7-
const privateKey = signer.privateKey!; // Get the hex private key
8-
const publicKey = signer.pubkey; // Get the hex public key
9-
const nsec = signer.nsec; // Get the private key in nsec format
10-
const npub = signer.userSync.npub; // Get the public key in npub format
9+
const privateKey = signer.privateKey!; // Get the hex private key
10+
const publicKey = signer.pubkey; // Get the hex public key
11+
const nsec = signer.nsec; // Get the private key in nsec format
12+
const npub = signer.userSync.npub; // Get the public key in npub format
1113
```
1214

1315
You can use these different formats for different purposes:
16+
1417
- `privateKey`: Raw private key for cryptographic operations
1518
- `publicKey`: Raw public key (hex format) for verification
1619
- `nsec`: Encoded private key format (bech32) - used for secure sharing when needed
17-
- `npub`: Encoded public key format (bech32) - used for user identification
20+
- `npub`: Encoded public key format (bech32) - used for user identification

docs/snippets/wallet/connect-nwc.md

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Connect Nostr Wallet Connect (NWC)
2+
3+
This snippet demonstrates how to connect a Nostr Wallet Connect (NWC) wallet to NDK and use it for zapping.
4+
5+
```typescript
6+
import NDK from "@nostr-dev-kit/ndk";
7+
import {
8+
NDKNWCWallet,
9+
NDKWalletStatus
10+
} from "@nostr-dev-kit/ndk-wallet";
11+
12+
// Connect using NWC pairing code
13+
// Format: nostr+walletconnect://{pubkey}?relay={relay_url}&secret={secret}
14+
const pairingCode = "nostr+walletconnect://npub...?relay=wss://relay.example.com&secret=nsec...";
15+
16+
// Initialize NWC wallet with pairing code
17+
const wallet = new NDKNWCWallet(ndk, {
18+
pairingCode,
19+
// Optional timeout for operations
20+
timeout: 30000
21+
});
22+
23+
// Set up event listeners
24+
wallet.on("ready", () => {
25+
console.log("NWC wallet is ready for zapping");
26+
});
27+
28+
// Listen for balance updates
29+
wallet.on("balance_updated", (balance) => {
30+
console.log("Balance updated:", balance?.amount || 0, "sats");
31+
});
32+
33+
// Assign wallet to NDK instance for zapping
34+
ndk.wallet = wallet;
35+
36+
// Wait for wallet to be ready
37+
if (wallet.status !== NDKWalletStatus.READY) {
38+
await new Promise<void>((resolve) => {
39+
wallet.once("ready", () => resolve());
40+
});
41+
}
42+
43+
console.log("NWC wallet connected successfully");
44+
45+
## Notes
46+
47+
- The wallet must be assigned to the NDK instance with `ndk.wallet = wallet` for zaps to work properly
+120
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
# Using a Cashu Wallet (NIP-60) with NDK
2+
3+
This snippet demonstrates how to create, configure, and use an NDKCashuWallet for managing Cashu tokens.
4+
5+
```typescript
6+
import NDK, { NDKKind, NDKCashuMintList } from "@nostr-dev-kit/ndk";
7+
import { NDKCashuWallet, NDKWalletStatus } from "@nostr-dev-kit/ndk-wallet";
8+
9+
/**
10+
* Example function to set up an NDKCashuWallet
11+
*/
12+
async function setupCashuWallet(ndk: NDK, mints: string[], relays: string[]) {
13+
// Create the Cashu wallet instance
14+
const wallet = new NDKCashuWallet(ndk);
15+
16+
// Add mints to the wallet
17+
wallet.mints = mints;
18+
wallet.relays = relays;
19+
20+
// Generate or load a p2pk (Pay-to-Public-Key) token
21+
// This is used for receiving payments with NIP-61 (nutzaps)
22+
const p2pk = await wallet.getP2pk();
23+
console.log(`Wallet p2pk: ${p2pk}`);
24+
25+
await wallet.publish();
26+
console.log('published the wallet event')
27+
28+
// configure reception of NIP-61 nutzaps for the user
29+
// this publishes an event that tells others who want to zap
30+
// this user the information they need to publish a NIP-61 nutzap.
31+
const mintlistForNutzapReception = new NDKCashuMintList(ndk);
32+
mintlistForNutzapReception.relays = wallet.relays;
33+
mintlistForNutzapReception.mints = wallet.mints;
34+
mintlistForNutzapReception.p2pk = wallet.p2pk;
35+
await mintlistForNutzapReception.publish();
36+
console.log('published he nutzap mintlist event to receive nutzaps', mintlistForNutzapReception.rawEvent())
37+
38+
return wallet;
39+
}
40+
41+
/**
42+
* Get balance for a specific mint
43+
*/
44+
function getMintBalance(wallet: NDKCashuWallet, mintUrl: string) {
45+
const balance = wallet.mintBalance(mintUrl);
46+
console.log(`Balance for mint ${mintUrl}: ${balance} sats`);
47+
return balance;
48+
}
49+
50+
/**
51+
* Check if the user already has a nutsack (NIP-60) wallet.
52+
**/
53+
async function findExistingWallet(ndk: NDK): Promise<NDKCashuWallet | undefined> {
54+
const activeUser = ndk.activeUser;
55+
56+
if (!activeUser) throw "we need a user first, set a signer in ndk";
57+
58+
const event = await ndk.fetchEvent([
59+
{ kinds: [ NDKKind.CashuWallet], authors: [activeUser.pubkey] }
60+
])
61+
62+
// if we receive a CashuWallet event we load the wallet
63+
if (event) return await NDKCashuWallet.from(event);
64+
}
65+
66+
/**
67+
* Example usage
68+
*/
69+
async function main() {
70+
// we assume ndk is already connected and ready
71+
// ...
72+
73+
let wallet: NDKCashuWallet | undefined;
74+
75+
wallet = await findExistingWallet(ndk);
76+
77+
// if we don't have a wallet, we create one
78+
if (!wallet) {
79+
// List of mints to use
80+
const mints = [ "https://8333.space:3338" ];
81+
82+
// Setup the wallet
83+
wallet = await setupCashuWallet(ndk, mints);
84+
}
85+
86+
wallet.on("balance_updated", (balance) => {
87+
console.log(`Wallet balance updated: ${balance?.amount} sats`);
88+
// You might want to update your UI here
89+
});
90+
91+
wallet.start();
92+
93+
// Example: Check wallet balance
94+
const totalBalance = wallet.balance?.amount || 0;
95+
console.log(`Total wallet balance: ${totalBalance} sats`);
96+
97+
// Example: Need to fund wallet?
98+
// See the Cashu Deposits snippet for funding your wallet with lightning
99+
100+
// Example: Get balance for specific mint
101+
for (const mint of mints) {
102+
getMintBalance(wallet, mint);
103+
}
104+
105+
// Note: For monitoring nutzaps, see the Nutzap Monitor snippet
106+
107+
// Keep the connection open for monitoring
108+
// In a real app, you'd use proper lifecycle management
109+
}
110+
```
111+
112+
## Notes
113+
114+
- The Cashu wallet implements the NIP-60 specification for Nostr eCash
115+
- The wallet needs to be assigned to the NDK instance with `ndk.wallet = wallet` for full integration
116+
- To receive tokens, you need to generate a p2pk (Pay-to-Public-Key) identifier
117+
- The wallet monitors and processes events continuously while active
118+
- Always handle wallet operations with proper error handling
119+
- For handling nutzaps (Cashu tokens sent via Nostr), see the Nutzap Monitor snippet
120+
- For depositing funds to your wallet, see the Cashu Deposits snippet

docs/wallet/nutsack.md

+1-2
Original file line numberDiff line numberDiff line change
@@ -17,14 +17,13 @@ const ndk = new NDK({
1717
ndk.connect();
1818

1919
// create a new NIP-60 wallet
20-
const unit = "sat"; // unit of the wallet
2120
const mints = [ 'https://testnut.cashu.space' ] // mints the wallet will use
2221
const relays = [ 'wss://f7z.io', 'ws://localhost:4040' ]; // relays where proofs will be stored
2322
const wallet = NDKCashuWallet.create(ndk, unit, mints, relays);
2423
await wallet.publish();
2524
```
2625

27-
This will publish a wallet `kind:37375` event, which contains the wallet information.
26+
This will publish a wallet `kind:17375` event, which contains the wallet information.
2827

2928
We now have a NIP-60 wallet -- this wallet will be available from any nostr client that supports NIP-60.
3029

ndk-core/src/signers/private-key/index.test.ts

+2-6
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { generateSecretKey } from "nostr-tools";
2-
import NDK, { NDKEvent, type NostrEvent } from "../../index.js";
2+
import { type NostrEvent } from "../../index.js";
33
import { NDKPrivateKeySigner } from "./index";
4-
import { bytesToHex, hexToBytes } from "@noble/hashes/utils";
4+
import { bytesToHex } from "@noble/hashes/utils";
55
import { nip19 } from "nostr-tools";
66

77
describe("NDKPrivateKeySigner", () => {
@@ -72,9 +72,5 @@ describe("NDKPrivateKeySigner", () => {
7272
expect(knownSigner.pubkey).toBe(
7373
"c44f2be1b2fb5371330386046e60207bbd84938d4812ee0c7a3c11be605a7585"
7474
);
75-
76-
// Test error case when signer is not ready
77-
const emptySigner = new NDKPrivateKeySigner();
78-
expect(() => emptySigner.pubkey).toThrow("Not ready");
7975
});
8076
});

0 commit comments

Comments
 (0)