↔️Code examples: Creating Requests
Prerequisites
yarn add node-fetch
yarn add nostr-toolsgo get github.com/nbd-wtf/go-nostr
go get github.com/nbd-wtf/go-nostr/nip04Code 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&[email protected]";
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
Was this helpful?

