aboutsummaryrefslogtreecommitdiffstats
path: root/extension/src/provider.js
blob: d662212bfd187dbdfe7237de4c123ea42e64b46f (plain) (blame)
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
// Runs in the page itself: window.nostr (NIP-07) and window.webln. Every call
// is a message to the content script, which hands it to the extension; the
// key and the wallet connection never enter the page.
(() => {
  if (window.nostr && window.nostr._coinos) return;
  const pending = new Map();
  let n = 0;
  window.addEventListener('message', (e) => {
    if (e.source !== window || !e.data || e.data.__coinos !== 'res') return;
    const p = pending.get(e.data.id);
    if (!p) return;
    pending.delete(e.data.id);
    if (e.data.error) p.reject(new Error(e.data.error));
    else p.resolve(e.data.result);
  });
  const call = (method, params) => new Promise((resolve, reject) => {
    const id = `${Date.now().toString(36)}-${++n}-${Math.random().toString(36).slice(2)}`;
    pending.set(id, { resolve, reject });
    window.postMessage({ __coinos: 'req', id, method, params }, '*');
  });

  window.nostr = {
    _coinos: true,
    getPublicKey: () => call('nostr.getPublicKey'),
    signEvent: (event) => call('nostr.signEvent', { event }),
    getRelays: () => call('nostr.getRelays'),
    nip04: {
      encrypt: (pubkey, plaintext) => call('nostr.nip04.encrypt', { pubkey, plaintext }),
      decrypt: (pubkey, ciphertext) => call('nostr.nip04.decrypt', { pubkey, ciphertext }),
    },
    nip44: {
      encrypt: (pubkey, plaintext) => call('nostr.nip44.encrypt', { pubkey, plaintext }),
      decrypt: (pubkey, ciphertext) => call('nostr.nip44.decrypt', { pubkey, ciphertext }),
    },
  };

  const unsupported = (what) => () => Promise.reject(new Error(`${what} is not supported by the Coinos extension`));
  window.webln = {
    _coinos: true,
    enabled: false,
    isEnabled: () => Promise.resolve(window.webln.enabled),
    enable: async () => { const r = await call('webln.enable'); window.webln.enabled = true; return r; },
    getInfo: () => call('webln.getInfo'),
    sendPayment: (paymentRequest) => call('webln.sendPayment', { paymentRequest }),
    makeInvoice: (args) => call('webln.makeInvoice', { args }),
    getBalance: () => call('webln.getBalance'),
    keysend: unsupported('keysend'),
    signMessage: unsupported('signMessage'),
    verifyMessage: unsupported('verifyMessage'),
    lnurl: unsupported('lnurl'),
  };
  window.dispatchEvent(new Event('webln:ready'));
})();