### Install Example Dependencies Source: https://github.com/getalby/js-sdk/blob/master/examples/README.md Command to install dependencies within the examples directory. ```bash cd examples yarn install ``` -------------------------------- ### Install and Build Alby SDK Source: https://github.com/getalby/js-sdk/blob/master/examples/README.md Commands to install dependencies and build the Alby SDK from the root directory. ```bash cd .. yarn install yarn build ``` -------------------------------- ### NWCWalletService Initialization and Subscription Example Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc-wallet-service.md Demonstrates how to initialize the NWCWalletService with a relay URL, publish wallet service information, and subscribe to client requests using a keypair. This example covers the basic setup for a wallet service to interact with NWC clients. ```javascript import { NWCWalletService } from "@getalby/sdk/nwc"; const walletService = new NWCWalletService({ relayUrl: "wss://relay.getalby.com/v1", }); // now for each client/app connection you can publish a NIP-47 info event and subscribe to requests await walletService.publishWalletServiceInfoEvent( walletServiceSecretKey, ["get_info"], // NIP-47 methods supported by your wallet service [], ); // each client connection will have a unique keypair const keypair = new nwc.NWCWalletServiceKeyPair( walletServiceSecretKey, clientPubkey, ); const unsub = await walletService.subscribe(keypair, { getInfo: () => { return Promise.resolve({ result: { methods: ["get_info"], alias: "Alby Hub", //... add other fields here }, error: undefined, }); }, // ... handle other NIP-47 methods here }); ``` -------------------------------- ### Launch NWC Client and Get Info Source: https://github.com/getalby/js-sdk/blob/master/examples/nwc/client/auth.html This snippet demonstrates how to launch the NWC client from an authorization URL, retrieve user information, and display it. It includes error handling for the process. ```javascript import { nwc } from "https://esm.sh/@getalby/sdk@5.1.0"; window.launchNwc = async () => { try { const authUrl = prompt("Auth URL", "https://my.albyhub.com/apps/new"); const nwcClient = await nwc.NWCClient.fromAuthorizationUrl(authUrl, { name: "Deeplink " + Date.now(), }); const result = await nwcClient.getInfo(); alert("Info response: " + JSON.stringify(result)); } catch (error) { console.error(error); alert("Something went wrong: " + error); } }; ``` -------------------------------- ### Run Legacy JavaScript Example Source: https://github.com/getalby/js-sdk/blob/master/examples/README.md Command to execute a legacy JavaScript example script using node. ```bash node ./nwc/client/get-balance.js ``` -------------------------------- ### Connect NWC and Get Info Source: https://github.com/getalby/js-sdk/blob/master/examples/nwc/client/auth_manual.html Establishes a connection to Nostr Wallet Connect using provided wallet public key and relay URL. It retrieves information about the connected wallet and displays it. Requires a saved secret in local storage. ```javascript import { nwc } from "https://esm.sh/@getalby/sdk@5.1.0"; import { generateSecretKey, getPublicKey, } from "https://esm.sh/nostr-tools@2.9.4"; import { bytesToHex, hexToBytes, } from "https://esm.sh/@noble/hashes@1.3.1/utils"; const params = new URL(window.location.href).searchParams; const walletPubkey = params.get("pubkey"); const relayUrl = params.get("relay"); const lud16 = params.get("lud16"); const secret = window.localStorage.getItem("demo_secret"); if (walletPubkey && relayUrl) { try { if (!secret) { throw new Error("No secret saved locally"); } window.document.getElementById("connect-button").remove(); const nwcClient = new nwc.NWCClient({ secret, walletPubkey, relayUrl, lud16, }); const result = await nwcClient.getInfo(); alert("Info response: " + JSON.stringify(result) + " lud16: " + lud16); } catch (error) { console.error(error); alert("Something went wrong: " + error); } } else { window.document.getElementById("reset-button").remove(); } ``` -------------------------------- ### Run TypeScript Example Source: https://github.com/getalby/js-sdk/blob/master/examples/README.md Command to execute a TypeScript example script using tsx. ```bash yarn tsx ./lnclient/pay_ln_address.ts ``` -------------------------------- ### Install Alby JS SDK Source: https://github.com/getalby/js-sdk/blob/master/README.md Instructions for installing the Alby JS SDK using npm or yarn package managers. ```bash npm install @getalby/sdk ``` ```bash yarn add @getalby/sdk ``` -------------------------------- ### Connect NWC and Get Info Source: https://github.com/getalby/js-sdk/blob/master/examples/nwc/auth_manual.html Establishes a connection to Nostr WebLN using NWC credentials and retrieves user information. It requires wallet public key and relay URL to be present in the URL parameters and a secret key stored locally. ```javascript import { webln, nwc } from "https://esm.sh/@getalby/sdk@5.1.0"; import { generateSecretKey, getPublicKey, } from "https://esm.sh/nostr-tools@2.9.4"; import { bytesToHex, hexToBytes, } from "https://esm.sh/@noble/hashes@1.3.1/utils"; const params = new URL(window.location.href).searchParams; const walletPubkey = params.get("pubkey"); const relayUrl = params.get("relay"); const lud16 = params.get("lud16"); const secret = window.localStorage.getItem("demo_secret"); if (walletPubkey && relayUrl) { try { if (!secret) { throw new Error("No secret saved locally"); } window.document.getElementById("connect-button").remove(); const nwcClient = new nwc.NWCClient({ secret, walletPubkey, relayUrl, lud16, }); const weblnProvider = new webln.NostrWebLNProvider({ client: nwcClient, }); await weblnProvider.enable(); const result = await weblnProvider.getInfo(); alert("Info response: " + JSON.stringify(result) + " lud16: " + lud16); } catch (error) { console.error(error); alert("Something went wrong: " + error); } } else { window.document.getElementById("reset-button").remove(); } ``` -------------------------------- ### Global Fetch Polyfill Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md Explains the SDK's dependency on a global `fetch()` function, which is standard in browsers and Node.js v18+. For older Node.js versions or environments lacking `fetch`, it provides examples of how to install and use polyfills like `cross-fetch`. ```js import fetch from "cross-fetch"; // or "@inrupt/universal-fetch" globalThis.fetch = fetch; // or as a polyfill: import "cross-fetch/polyfill"; ``` -------------------------------- ### Websocket Polyfill for Node.js Source: https://github.com/getalby/js-sdk/blob/master/README.md Instructions for installing and importing the websocket-polyfill for using the SDK in Node.js environments older than v18.x. ```javascript import "websocket-polyfill"; // or: require('websocket-polyfill'); ``` -------------------------------- ### Connect to Nostr WebLN and Launch NWC Source: https://github.com/getalby/js-sdk/blob/master/examples/nwc/auth.html This snippet demonstrates how to initialize a Nostr WebLN provider from an authorization URL, enable the connection, and retrieve information about the connected wallet. It includes error handling for the connection process. ```javascript import { webln } from "https://esm.sh/@getalby/sdk@5.1.0"; window.launchNwc = async () => { try { const authUrl = prompt("Auth URL", "https://my.albyhub.com/apps/new"); const nwcWebln = await webln.NostrWebLNProvider.fromAuthorizationUrl( authUrl, { name: "Deeplink " + Date.now(), }, ); await nwcWebln.enable(); const result = await nwcWebln.getInfo(); alert("Info response: " + JSON.stringify(result)); } catch (error) { console.error(error); alert("Something went wrong: " + error); } }; ``` -------------------------------- ### Launch NWC Connection Source: https://github.com/getalby/js-sdk/blob/master/examples/nwc/auth_manual.html Generates a new secret key, derives the public key, and initiates the NWC authorization flow by redirecting the user to an authorization URL. It prompts the user for the authorization base path. ```javascript window.launchNwc = async () => { try { if (!window.origin.startsWith("http")) { alert( "Please use a webserver from this directory e.g. python3 -m http.server", ); } const secret = bytesToHex(generateSecretKey()); const pubkey = getPublicKey(hexToBytes(secret)); window.localStorage.setItem("demo_secret", secret); const authorizationBasePath = prompt( "Auth URL", "https://my.albyhub.com/apps/new", ); const authUrl = await nwc.NWCClient.getAuthorizationUrl( authorizationBasePath, { name: "Deeplink " + Date.now(), returnTo: window.location.href, }, pubkey, ); window.location = authUrl; } catch (error) { console.error(error); alert("Something went wrong: " + error); } }; ``` -------------------------------- ### Setting window.webln with NostrWebLNProvider Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Provides an example of how to set the global `window.webln` object to use the NostrWebLNProvider, enabling universal WebLN API usage in web applications. ```javascript // you can set the window.webln object to use the universal API to send payments: if (!window.webln) { // prompt the user to connect to NWC window.webln = new webln.NostrWebLNProvider({ nostrWalletConnectUrl: loadNWCUrl, }); // now use any webln code } ``` -------------------------------- ### NostrWebLNProvider sendPayment Example Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md A detailed example of using the `sendPayment` function of the NostrWebLNProvider to send a Bitcoin Lightning payment using a Bolt11 invoice. ```javascript import { NostrWebLNProvider } from "@getalby/sdk/webln"; const nwc = new NostrWebLNProvider({ nostrWalletConnectUrl: loadNWCUrl }); await nwc.enable(); const response = await nwc.sendPayment(invoice); console.log(response); ``` -------------------------------- ### Launch NWC Authorization Flow Source: https://github.com/getalby/js-sdk/blob/master/examples/nwc/client/auth_manual.html Generates a new secret key, derives the public key, and initiates the NWC authorization process by redirecting the user to an authorization URL. It prompts the user for the authorization base path. ```javascript window.launchNwc = async () => { try { if (!window.origin.startsWith("http")) { alert( "Please use a webserver from this directory e.g. python3 -m http.server", ); } const secret = bytesToHex(generateSecretKey()); const pubkey = getPublicKey(hexToBytes(secret)); window.localStorage.setItem("demo_secret", secret); const authorizationBasePath = prompt( "Auth URL", "https://my.albyhub.com/apps/new", ); const authUrl = await nwc.NWCClient.getAuthorizationUrl( authorizationBasePath, { name: "Deeplink " + Date.now(), returnTo: window.location.href, }, pubkey, ); window.location = authUrl; } catch (error) { console.error(error); alert("Something went wrong: " + error); } }; ``` -------------------------------- ### Requesting a Lightning Payment Source: https://github.com/getalby/js-sdk/blob/master/examples/lnclient/paywall-esm.html This snippet shows how to initialize the Alby LN client with a connection secret, request a payment for a specified amount and description, and display the invoice to the user. It also includes handling for successful payments and timeouts. ```javascript import { LN, USD } from "https://esm.sh/@getalby/sdk@5.1.0"; const connectionSecret = prompt("Enter a read-only connection secret"); const client = new LN(connectionSecret); // request a lightning invoice that we show the user to pay const request = await client.requestPayment(USD(1.0), { description: "best content", }); prompt( "Please copy and pay the above invoice. Once you close the dialog, make sure to pay the invoice within 60 seconds.", request.invoice.paymentRequest, ); // once the invoice got paid by the user run this callback request .onPaid(() => { alert("received payment!"); client.close(); // when done and no longer needed close the wallet connection }) .onTimeout(60, () => { alert("didn't receive payment in time."); client.close(); // when done and no longer needed close the wallet connection }); ``` -------------------------------- ### Include Alby JS SDK via CDN Source: https://github.com/getalby/js-sdk/blob/master/README.md Example of how to include the Alby JS SDK in an HTML file using a CDN for module-based usage. ```html ``` -------------------------------- ### Sending Payments Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md Provides examples for sending payments using the Alby SDK, including standard payments via invoice and keysend payments to a node. ```js const token = loadTokenForUser(); // {access_token: string, refresh_token: string, expires_at: number} const authClient = new auth.OAuth2User({ client_id: process.env.CLIENT_ID, callback: "http://localhost:8080/callback", scopes: [ "invoices:read", "account:read", "balance:read", "invoices:create", "invoices:read", "payments:send", ], token: token, }); const client = new Client(authClient); // the authClient will automatically refresh the access token if expired using the refresh token await client.sendPayment({ invoice: bolt11 }); await client.keysend({ destination: nodekey, amount: 10, memo: memo, }); ``` -------------------------------- ### Reset NWC Connection Source: https://github.com/getalby/js-sdk/blob/master/examples/nwc/auth_manual.html Clears the locally stored NWC secret key and redirects the user to the origin page, effectively resetting the connection. ```javascript window.resetNwc = async () => { window.localStorage.removeItem("demo_secret"); window.location.href = window.origin; }; ``` -------------------------------- ### Send a Boostagram Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md Demonstrates how to send a single boostagram using the Alby SDK. It includes setting up an OAuth2 client for authentication and constructing the boostagram payload. The example also shows an alternative method using keysend with custom records. ```js const token = loadTokenForUser(); // {access_token: string, refresh_token: string, expires_at: number} const authClient = new auth.OAuth2User({ client_id: process.env.CLIENT_ID, callback: "http://localhost:8080/callback", scopes: ["payments:send"], token: token, }); const client = new Client(authClient); // the authClient will automatically refresh the access token if expired using the refresh token // pass in an array if you want to send multiple boostagrams with one call await client.sendBoostagram({ recipient: { address: "030a58b8653d32b99200a2334cfe913e51dc7d155aa0116c176657a4f1722677a3", customKey: "696969", customValue: "bNVHj0WZ0aLPPAesnn9M", }, amount: 10, // spec: https://github.com/lightning/blips/blob/master/blip-0010.md boostagram: { app_name: "Alby SDK Demo", value_msat_total: 49960, // TOTAL Number of millisats for the payment (all splits together, before fees. The actual number someone entered in their player, for numerology purposes.) value_msat: 2121, // Number of millisats for this split payment url: "https://feeds.buzzsprout.com/xxx.rss", podcast: "Podcast title", action: "boost", episode: "The episode title", episode_guid: "Buzzsprout-xxx", ts: 574, name: "Podcaster - the recipient name", sender_name: "Satoshi - the sender/listener name", }, }); // or manually through the keysend: // pass in an array if you want to do multiple keysend payments with one call await client.keysend({ destination: nodekey, amount: 10, customRecords: { 7629169: JSON.stringify(boostagram), 696969: "user", }, }); ``` -------------------------------- ### Reset NWC Connection Source: https://github.com/getalby/js-sdk/blob/master/examples/nwc/client/auth_manual.html Clears the saved NWC secret from local storage and reloads the page, effectively resetting the connection. ```javascript window.resetNwc = async () => { window.localStorage.removeItem("demo_secret"); window.location.href = window.origin; }; ``` -------------------------------- ### Node.js Compatibility for LNClient Source: https://github.com/getalby/js-sdk/blob/master/docs/lnclient.md Provides instructions for using the LN class in a Node.js environment. It requires installing and importing `websocket-polyfill` and may require manually polyfilling the `crypto` module if using older Node.js versions. ```js import "websocket-polyfill"; // or: require('websocket-polyfill'); import * as crypto from 'crypto'; // or 'node:crypto' globalThis.crypto = crypto as any; //or: global.crypto = require('crypto'); ``` -------------------------------- ### Node.js Crypto Polyfill Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Provides instructions for using Nostr Wallet Connect in Node.js environments. It requires installing `websocket-polyfill` and importing it. If a `crypto is not defined` error occurs, it suggests upgrading Node.js or manually importing the `crypto` module. ```js import "websocket-polyfill"; // or: require('websocket-polyfill'); import * as crypto from 'crypto'; // or 'node:crypto' globalThis.crypto = crypto as any; //or: global.crypto = require('crypto'); ``` -------------------------------- ### NostrWebLNProvider Initialization and Payment Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Illustrates initializing the NostrWebLNProvider and sending a payment. It also shows a short initialization syntax and enabling the connection. ```javascript import { NostrWebLNProvider } from "@getalby/sdk/webln"; const nwc = new NostrWebLNProvider({ nostrWalletConnectUrl: loadNWCUrl(), }); // loadNWCUrl is some function to get the NWC URL from some (encrypted) storage // or use the short version const nwc = new webln.NWC({ nostrWalletConnectUrl: loadNWCUrl }); // connect to the relay await nwc.enable(); // now you can send payments by passing in the invoice const response = await nwc.sendPayment(invoice); ``` -------------------------------- ### NWCClient Initialization and Payment Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Demonstrates how to initialize the NWCClient and send a payment using a Nostr Wallet Connect URL. Assumes a function `loadNWCUrl` exists to retrieve the URL. ```javascript import { NWCClient } from "@getalby/sdk/nwc"; const nwcClient = new NWCClient({ nostrWalletConnectUrl: loadNWCUrl(), }); // loadNWCUrl is some function to get the NWC URL from some (encrypted) storage // now you can send payments by passing in the invoice in an object const response = await nwcClient.payInvoice({ invoice }); ``` -------------------------------- ### Request Payment using LN Client Source: https://github.com/getalby/js-sdk/blob/master/README.md Shows how to request a payment using the LN client and handle the payment confirmation. ```javascript const request = await new LN(credentials).requestPayment(USD(1.0)); // give request.invoice to someone... request.onPaid(giveAccess); ``` -------------------------------- ### NWCWalletService Class Documentation Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc-wallet-service.md API documentation for the NWCWalletService class, detailing its initialization options and methods for interacting with Nostr Wallet Connect. This includes publishing wallet service info events and subscribing to client requests. ```APIDOC NWCWalletService: __init__(options: { relayUrl: string }) Initializes the NWCWalletService with the specified options. - options.relayUrl: URL of the Nostr relay to be used (e.g. wss://relay.getalby.com/v1). publishWalletServiceInfoEvent(secretKey: string, methods: string[], relays: string[]): Promise Publishes a NIP-47 info event to the specified relay. - secretKey: The secret key for the wallet service. - methods: An array of NIP-47 methods supported by the wallet service. - relays: An array of relay URLs to publish the event to. subscribe(keypair: NWCWalletServiceKeyPair, handlers: { [method: string]: (args: any) => Promise }): Promise<() => void> Subscribes to requests from a specific client connection. - keypair: The keypair for the client connection. - handlers: An object where keys are NIP-47 method names and values are handler functions that return a Promise resolving to the method's result or error. - Returns: A function to unsubscribe from the requests. ``` -------------------------------- ### NWCClient Initialization from Authorization URL Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Shows how to initialize NWCClient using `fromAuthorizationUrl`, which generates a new secret and requires user authorization. This can be done via redirection or a popup. ```javascript const nwcClient = await nwc.NWCClient.fromAuthorizationUrl( "https://my.albyhub.com/apps/new", { name: "My app name", }, ); The same options can be provided to getAuthorizationUrl() as fromAuthorizationUrl() - see [Manual Auth example](../examples/nwc/client/auth_manual.html) ``` -------------------------------- ### Full OAuth Authentication Flow Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md Demonstrates the complete OAuth2 authentication process, including generating an authorization URL, requesting an access token, and initializing the Alby client. ```js const authClient = new auth.OAuth2User({ client_id: process.env.CLIENT_ID, client_secret: process.env.CLIENT_SECRET, callback: "http://localhost:8080/callback", scopes: [ "invoices:read", "account:read", "balance:read", "invoices:create", "invoices:read", "payments:send", ], token: { access_token: undefined, refresh_token: undefined, expires_at: undefined, }, // initialize with existing token }); const authUrl = await authClient.generateAuthURL({ code_challenge_method: "S256", // authorizeUrl: "https://getalby.com/oauth" endpoint for authorization (replace with the appropriate URL based on the environment) }); // open auth URL // `code` is passed as a query parameter when the user is redirected back after authorization await authClient.requestAccessToken(code); // access the token response. You can store this securely for future client initializations console.log(authClient.token); // initialize a client const client = new Client(authClient); const result = await client.accountBalance(); ``` -------------------------------- ### Initialize Client from Existing Token Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md Shows how to initialize the Alby client using previously stored token details, enabling continued access without re-authentication. ```js const token = loadTokenForUser(); // {access_token: string, refresh_token: string, expires_at: number} const authClient = new auth.OAuth2User({ client_id: process.env.CLIENT_ID, callback: "http://localhost:8080/callback", scopes: [ "invoices:read", "account:read", "balance:read", "invoices:create", "invoices:read", "payments:send", ], token: token, }); const client = new Client(authClient); // the authClient will automatically refresh the access token if expired using the refresh token const result = await client.createInvoice({ amount: 1000 }); ``` -------------------------------- ### Pay Lightning Invoice or Address using LN Client Source: https://github.com/getalby/js-sdk/blob/master/README.md Demonstrates how to use the LN client to pay a lightning invoice or a lightning address with a specified amount. ```javascript import { LN, USD } from "@getalby/sdk/lnclient"; const credentials = "nostr+walletconnect://..."; // the NWC connection credentials await new LN(credentials).pay("lnbc..."); // pay a lightning invoice await new LN(credentials).pay("hello@getalby.com", USD(1)); // or pay $1 USD to a lightning address ``` -------------------------------- ### NostrWebLNProvider fromAuthorizationUrl Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Initiates a Nostr Wallet Connect connection by opening a new window prompt for user authorization. The promise resolves upon successful authorization or rejects if the prompt is closed. It requires the authorization URL and an optional name for the NWC provider. ```js import { NostrWebLNProvider } from "@getalby/sdk/webln"; try { const nwc = await NostrWebLNProvider.fromAuthorizationUrl( "https://my.albyhub.com/apps/new", { name: "My app name", }, ); } catch (e) { console.error(e); } await nwc.enable(); let response; try { response = await nwc.sendPayment(invoice); // if success then the response.preimage will be only console.info(`payment successful, the preimage is ${response.preimage}`); } catch (e) { console.error(e.error || e); } ``` -------------------------------- ### NostrWebLNProvider Defaults Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Initializes NostrWebLNProvider with default settings, connecting to Alby's relay and using window.nostr for signing requests. Enables the connection, sends a payment, and provides the preimage upon success. The WebSocket connection can be closed manually. ```js import { NostrWebLNProvider } from "@getalby/sdk/webln"; const nwc = new NostrWebLNProvider(); // use defaults (connects to Alby's relay, will use window.nostr to sign the request) await nwc.enable(); // connect to the relay const response = await nwc.sendPayment(invoice); console.log(response.preimage); nwc.close(); // close the websocket connection ``` -------------------------------- ### Making Payments with LNClient Source: https://github.com/getalby/js-sdk/blob/master/docs/lnclient.md Demonstrates how to use the LN class to make payments using lightning invoices or lightning addresses. Supports specifying amounts in SATS, USD, or other fiat currencies, and includes options for metadata like comments and payer data. ```js import { LN, USD, SATS } from "@getalby/sdk/lnclient"; const credentials = "nostr+walletconnect://..."; // the NWC connection credentials await new LN(credentials).pay("lnbc..."); // pay a lightning invoice await new LN(credentials).pay("hello@getalby.com", SATS(21)); // or pay 21 sats to a lightning address await new LN(credentials).pay("hello@getalby.com", USD(1)); // or pay $1 USD to a lightning address await new LN(credentials).pay("hello@getalby.com", new FiatAmount(1, "THB")); // or pay an amount in any currency to a lightning address await new LN(credentials).pay("hello@getalby.com", USD(1), { metadata: { comment: "Example comment", payer_data: { name: "Bob" } }, }); // set a comment for the payment you are making, and that the payment was made by Bob ``` -------------------------------- ### Handling Token Refresh Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md Explains how to manage access token expiration and refresh using the `tokenRefreshed` and `tokenRefreshFailed` events, ensuring continuous API access. ```js const token = loadTokenForUser(); // {access_token: string, refresh_token: string, expires_at: number} const authClient = new auth.OAuth2User({ client_id: process.env.CLIENT_ID, callback: "http://localhost:8080/callback", scopes: [ "invoices:read", "account:read", "balance:read", "invoices:create", "invoices:read", "payments:send", ], token: token, }); // listen to the tokenRefreshed event authClient.on("tokenRefreshed", (tokens) => { // store the tokens in database console.log(tokens); }); // Listen to the tokenRefreshFailed event authClient.on("tokenRefreshFailed", (error) => { // Handle the token refresh failure, for example, log the error or launch OAuth authentication flow console.error("Token refresh failed:", error.message); }); ``` -------------------------------- ### NWAClient Generate Connection URI Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Demonstrates how to generate a Nostr Wallet Auth (NWA) URI using the NWAClient class. This URI can be used by client applications to initiate a connection with a wallet. The `connectionUri` property provides the generated URI. ```js import { NWAClient } from "@getalby/sdk/nwc"; const connectionUri = new NWAClient({ relayUrl, requestMethods: ["get_info"], }).connectionUri; // then allow the user to copy it / display it as a QR code to the user ``` -------------------------------- ### Requesting Payments with LNClient Source: https://github.com/getalby/js-sdk/blob/master/docs/lnclient.md Shows how to request a payment using the LN class. It allows specifying the amount and provides methods to handle payment status, such as onPaid for when a payment is received and onTimeout for when a payment expires. ```js const request = await new LN(credentials).requestPayment(USD(1.0)); // give request.invoice to someone, then act upon it: request .onPaid(giveAccess) // listen for incoming payment and then fire the given method .onTimeout(60, showTimeout); // if they didn't pay within 60 seconds, do something else ``` -------------------------------- ### Decode an Invoice Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md Shows how to decode a Lightning Network invoice using the Alby SDK. It mentions an alternative client-side decoding method using the `js-lightning-tools` package and demonstrates extracting key information like payment hash, amount, and description from the decoded invoice. ```js const decodedInvoice = await client.decodeInvoice(paymentRequest); const {payment_hash, amount, description, ...} = decodedInvoice; ``` -------------------------------- ### Alby OAuth2 API Reference Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md This section outlines the available methods for interacting with the Alby Wallet API via OAuth2. It includes methods for account management, invoice handling, and payment operations. ```APIDOC Alby OAuth2 Wallet API Methods: - accountBalance(): Retrieves the user's account balance. - accountSummary(): Provides a summary of the user's account. - signMessage(message: string): Signs a given message with the user's private key. - accountInformation(): Fetches detailed information about the user's account. - accountValue4Value(): Retrieves value-for-value related account data. - invoices(): Lists all invoices associated with the account. - incomingInvoices(): Lists incoming invoices. - outgoingInvoices(): Lists outgoing invoices. - getInvoice(invoiceId: string): Retrieves a specific invoice by its ID. - createInvoice(data: { amount: number, memo?: string }): Creates a new invoice. - decodeInvoice(invoice: string): Decodes a given invoice string. - keysend(data: { destination: string, amount: number, memo?: string }): Sends a keysend payment. - sendPayment(data: { invoice: string }): Sends a payment for a given invoice. - sendBoostagram(data: { ... }): Sends a boostagram payment. - sendBoostagramToAlbyAccount(data: { ... }): Sends a boostagram payment to an Alby account. - createWebhookEndpoint(data: { ... }): Creates a new webhook endpoint. - deleteWebhookEndpoint(endpointId: string): Deletes a webhook endpoint. ``` -------------------------------- ### NWAClient Parse Wallet Auth URL Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Shows how to parse a Nostr Wallet Auth (NWA) URI using the NWAClient.parseWalletAuthUrl method. This is intended for wallet services to process incoming NWA URIs, extract connection options, and handle the connection process, potentially using the `create_connection` NWC command. ```js import { NWAClient } from "@getalby/sdk/nwc"; const nwaOptions = NWAClient.parseWalletAuthUrl(nwaUrl); // then use `nwaOptions` to display a confirmation page to the user and create a connection. // The implementation of actually creating the connection and showing a confirmation page to the user is wallet-specific. In the example, a connection will be created via the `create_connection` NWC command. ``` -------------------------------- ### NostrWebLNProvider Custom URL Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Initializes NostrWebLNProvider with a custom Nostr Wallet Connect URL, allowing connection to specific relays and using a provided secret. It enables the connection, sends a payment, and logs the preimage. The WebSocket connection can be closed manually. ```js import { NostrWebLNProvider } from "@getalby/sdk/webln"; const nwc = new NostrWebLNProvider({ nostrWalletConnectUrl: "nostr+walletconnect://69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9?relay=wss://nostr.bitcoiner.social&secret=c60320b3ecb6c15557510d1518ef41194e9f9337c82621ddef3f979f668bfebd", }); // use defaults await nwc.enable(); // connect to the relay const response = await nwc.sendPayment(invoice); console.log(response.preimage); nwc.close(); // close the websocket connection ``` -------------------------------- ### Send Multiple Boostagrams Source: https://github.com/getalby/js-sdk/blob/master/docs/oauth.md Illustrates how to send multiple boostagrams in a single API call by passing an array of boostagram objects to the `sendBoostagram` method. The response structure, indicating success or failure for each individual boostagram, is also shown. ```js const response = await client.sendBoostagram([ boostagram1, boostagram2, boostagram3, ]); console.log(response.keysends); ``` ```json { "keysends": [ { "keysend": { "amount": 10, "fee": 0, "destination": "xx", "payment_preimage": "xx", "payment_hash": "xx" } }, { "keysend": { "amount": 10, "fee": 0, "destination": "xxx", "payment_preimage": "xxx", "payment_hash": "xxx" } } ] } ``` -------------------------------- ### NostrWebLNProvider Generate NWC URL Source: https://github.com/getalby/js-sdk/blob/master/docs/nwc.md Generates a new Nostr Wallet Connect URL using a locally generated secret via the `fromAuthorizationUrl` helper, which opens a popup to initiate the connection flow. The promise resolves once the NWC app returns. The connect URL with the secret can be retrieved using `getNostrWalletConnectUrl(true)`. ```js // use the `fromAuthorizationUrl` helper which opens a popup to initiate the connection flow. // the promise resolves once the NWC app returned. const nwc = await webln.NostrWebLNProvider.fromAuthorizationUrl( "https://my.albyhub.com/apps/new", { name: "My app name", }, ); // ... enable and send a payment // if you want to get the connect url with the secret: // const nostrWalletConnectUrl nwc.getNostrWalletConnectUrl(true) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.