summaryrefslogtreecommitdiff
path: root/gui/src/logic/nostr.ts
blob: 3112f4b7b47315c20c664abed2d865e49a5ee27b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
// import { generateSecretKey, getPublicKey } from "nostr-tools/pure";
import * as nip19 from "nostr-tools/nip19";
import type { Event } from "@/types/nostr";

export function generateNevent(event: Event) {
  const evp: nip19.EventPointer = {
    id: event.id,
    author: event.pubkey,
    kind: event.kind,
  };
  const nev = nip19.neventEncode(evp);
  return nev;
}

export function generateNpub(pubkey: string) {
  const npub = nip19.npubEncode(pubkey);
  return npub;
}
export function generateNprofile(pubkey: string) {
  const prof = { pubkey };
  const nprofile = nip19.nprofileEncode(prof);
  return nprofile;
}
export function decodeNostrKey(key: string): string | null {
  try {
    const { type, data } = nip19.decode(key);
    if (type === "nevent") return data.id;
    else if (type === "nprofile") return data.pubkey;
    else if (type === "naddr") return data.pubkey;
    else if (type === "npub") return data;
    else if (type === "nsec") return uint8ArrayToHexString(data);
    else if (type === "note") return data;
    else return null;
  } catch (e) {
    try {
      // TODO do we want this for something
      nip19.npubEncode(key);
      return key;
    } catch (e2) {
      console.error(e2, "not valid nostr key");
      return null;
    }
  }
}
function uint8ArrayToHexString(uint8Array: Uint8Array) {
  return Array.from(uint8Array)
    .map((byte) => byte.toString(16).padStart(2, "0"))
    .join("");
}

// let pk = getPublicKey(generateSecretKey())
// let npub = nip19.npubEncode(pk)
// let { type, data } = nip19.decode(npub)
// assert(type === 'npub')
// assert(data === pk)

// let pk = getPublicKey(generateSecretKey())
// let relays = ['wss://relay.nostr.example.mydomain.example.com', 'wss://nostr.banana.com']
// let nprofile = nip19.nprofileEncode({ pubkey: pk, relays })
// let { type, data } = nip19.decode(nprofile)
// assert(type === 'nprofile')
// assert(data.pubkey === pk)
// assert(data.relays.length === 2)
//
// nevent1qqsp3faj5jy9fpc6779rcs9kdccc0mxwlv2pnhymwqtjmletn72u5echttguv;