generated from actions/javascript-action
-
Notifications
You must be signed in to change notification settings - Fork 1
/
nostr.js
76 lines (69 loc) · 1.95 KB
/
nostr.js
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
66
67
68
69
70
71
72
73
74
75
76
require('websocket-polyfill');
const { nip19, getPublicKey, getEventHash, signEvent, SimplePool } = require('nostr-tools');
const { setTimeout } = require('node:timers/promises');
/**
* @param {string} privateKey
* @param {number} kind
* @param {string} content
*/
module.exports.createEvent = (privateKey, kind, content) => {
if (privateKey.startsWith('nsec')) {
privateKey = nip19.decode(privateKey).data;
}
const tags = [];
const createdAt = Math.round(Date.now() / 1000);
let event = {
created_at: createdAt,
kind,
tags,
content,
pubkey: getPublicKey(privateKey),
};
event.id = getEventHash(event);
event.sig = signEvent(event, privateKey);
console.log('[event]', event);
return event;
};
/**
* @param {string[]} relays
* @param {Event} event
*/
module.exports.publishEvent = (relays, event) => {
console.log('[publish]', relays, event);
return new Promise((resolve, reject) => {
const pool = new SimplePool();
const publishedRelays = [];
const failedRelays = [];
const close = () => {
console.log('[close]');
pool.close(relays);
if (publishedRelays.length > 0) {
resolve();
} else {
reject();
}
}
const closeIfCompleted = () => {
console.log('[ok | failed]', relays.length, publishedRelays.length, failedRelays.length);
if (relays.length === publishedRelays.length + failedRelays.length) {
close()
}
};
setTimeout(() => {
console.warn('[timeout]', relays, publishedRelays, failedRelays);
close();
}, 5000);
const start = Date.now();
const pub = pool.publish(relays, event);
pub.on('ok', relay => {
console.info('[ok]', relay, `${Date.now() - start}ms`);
publishedRelays.push(relay);
closeIfCompleted();
});
pub.on('failed', relay => {
console.warn('[failed]', relay, `${Date.now() - start}ms`);
failedRelays.push(relay);
closeIfCompleted();
});
});
};