// 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'));
})();