82 lines
2.0 KiB
TypeScript
Raw Normal View History

2021-03-24 17:08:15 +11:00
import readline from 'readline';
2021-03-30 09:24:29 +11:00
import Waku from '../lib/waku';
import { Message } from '../lib/waku_message';
import { TOPIC } from '../lib/waku_relay';
import { delay } from '../test_utils/delay';
(async function () {
const opts = processArguments();
2021-03-24 17:08:15 +11:00
const waku = await Waku.create({ listenAddresses: [opts.listenAddr] });
2021-03-26 12:10:26 +11:00
2021-03-30 09:24:29 +11:00
// TODO: Bubble event to waku, infer topic, decode msg
waku.libp2p.pubsub.on(TOPIC, (event) => {
2021-03-26 12:10:26 +11:00
const msg = Message.fromBinary(event.data);
console.log(msg.utf8Payload());
});
2021-03-24 17:08:15 +11:00
console.log('Waku started');
2021-03-26 12:10:26 +11:00
if (opts.staticNode) {
console.log(`dialing ${opts.staticNode}`);
await waku.dial(opts.staticNode);
}
2021-03-24 17:08:15 +11:00
2021-03-26 12:10:26 +11:00
await new Promise((resolve) =>
waku.libp2p.pubsub.once('gossipsub:heartbeat', resolve)
);
// TODO: identify if it is possible to listen to an event to confirm dial
// finished instead of an arbitrary delay.
await delay(2000);
2021-03-24 17:08:15 +11:00
// TODO: Automatically subscribe
await waku.relay.subscribe();
console.log('Subscribed to waku relay');
2021-03-26 12:10:26 +11:00
await new Promise((resolve) =>
waku.libp2p.pubsub.once('gossipsub:heartbeat', resolve)
);
2021-03-24 17:08:15 +11:00
const rl = readline.createInterface({
input: process.stdin,
2021-03-30 09:24:29 +11:00
output: process.stdout,
2021-03-24 17:08:15 +11:00
});
console.log('Ready to chat!');
rl.prompt();
rl.on('line', async (line) => {
rl.prompt();
const msg = Message.fromUtf8String('(js-chat) ' + line);
await waku.relay.publish(msg);
2021-03-24 17:08:15 +11:00
});
})();
interface Options {
staticNode?: string;
listenAddr: string;
}
function processArguments(): Options {
2021-03-30 09:24:29 +11:00
const passedArgs = process.argv.slice(2);
2021-03-30 09:24:29 +11:00
let opts: Options = { listenAddr: '/ip4/0.0.0.0/tcp/0' };
while (passedArgs.length) {
const arg = passedArgs.shift();
switch (arg) {
case '--staticNode':
opts = Object.assign(opts, { staticNode: passedArgs.shift() });
break;
case '--listenAddr':
opts = Object.assign(opts, { listenAddr: passedArgs.shift() });
break;
default:
console.log(`Unsupported argument: ${arg}`);
2021-03-30 09:24:29 +11:00
process.exit(1);
}
}
return opts;
}