↔ī¸Code examples: Creating Requests

Below is an example demonstrating how to

  1. Create a Request Event (NIP-47)

  2. Sign it using Shared Secret (from Pubkey and Secret in NWC string)

  3. Send it to the API endpoint and receive the Response Event

  4. And finally decrypting the content in the response using the Shared Secret

Prerequisites

Before you begin, ensure you have the necessary packages installed:

yarn add node-fetch
yarn add nostr-tools

You also need a NWC connection string for testing:

  1. Get an Alby Account with this link.

  2. Create your NWC connection string at nwc.getalby.com.

Code Example

import fetch from 'node-fetch'
import { hexToBytes } from '@noble/hashes/utils';
import { nip04, finalizeEvent } from 'nostr-tools'

async function main() {
  const nwcString = "nostr+walletconnect://69effe7b49a6dd5cf525bd0905917a5005ffe480b58eeb8e861418cf3ae760d9?relay=wss://relay.getalby.com/v1&secret=05800d24907112b01a07a745c33de84f565fd1c7938578a120ef7d522e0972d7&lud16=adithya@getalby.com";

  const url = new URL(nwcString);
  const pubkey = url.hostname;
  const secret = url.searchParams.get('secret');

  const jsonStr = JSON.stringify({
    method: "get_balance"
  });

  const payload = await nip04.encrypt(secret, pubkey, jsonStr);

  const event = {
    created_at: Math.floor(Date.now() / 1000),
    kind: 23194, // REQUEST_KIND
    tags: [['p', pubkey]],
    content: payload,
  };

  const postPayload = {
    walletPubkey: pubkey,
    event: finalizeEvent(event, hexToBytes(secret)),
  };

  try {
    const response = await fetch("https://api.getalby.com/nwc/nip47", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(postPayload),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const result = await response.json();
    const content = result.content;

    const decryptedContent = await nip04.decrypt(secret, pubkey, content);
    console.log(decryptedContent);
    // {"result":{"balance":2121212121,"max_amount":100000000,"budget_renewal":"monthly"},"result_type":"get_balance"}


  } catch (error) {
    console.error('Error:', error);
  }
}

main()

Last updated

Logo

Your bitcoin & nostr companion / from 🐝 with 🧡