chore: remove superfluous .then
[crowdnode.js/.git] / bin / crowdnode.js
1 #!/usr/bin/env node
2 "use strict";
3 /*jshint maxcomplexity:25 */
4
5 require("dotenv").config({ path: ".env" });
6 require("dotenv").config({ path: ".env.secret" });
7
8 let pkg = require("../package.json");
9
10 let Fs = require("fs").promises;
11
12 let CrowdNode = require("../lib/crowdnode.js");
13 let Dash = require("../lib/dash.js");
14 let Insight = require("../lib/insight.js");
15 let Qr = require("../lib/qr.js");
16 let Ws = require("../lib/ws.js");
17
18 let Dashcore = require("@dashevo/dashcore-lib");
19
20 const DUFFS = 100000000;
21 let qrWidth = 2 + 67 + 2;
22 // Sign Up Fees:
23 //   0.00236608 // required for signup
24 //   0.00002000 // TX fee estimate
25 //   0.00238608 // minimum recommended amount
26 // Target:
27 //   0.01000000
28 let signupOnly = CrowdNode.requests.signupForApi + CrowdNode.requests.offset;
29 let acceptOnly = CrowdNode.requests.acceptTerms + CrowdNode.requests.offset;
30 let signupFees = signupOnly + acceptOnly;
31 let feeEstimate = 500;
32 let signupTotal = signupFees + 2 * feeEstimate;
33
34 function showQr(signupAddr, duffs = 0) {
35   let signupUri = `dash://${signupAddr}`;
36   if (duffs) {
37     signupUri += `?amount=${duffs}`;
38   }
39
40   let signupQr = Qr.ascii(signupUri, { indent: 4 });
41   let addrPad = Math.ceil((qrWidth - signupUri.length) / 2);
42
43   console.info(signupQr);
44   console.info();
45   console.info(" ".repeat(addrPad) + signupUri);
46 }
47
48 function showVersion() {
49   console.info(`${pkg.name} v${pkg.version} - ${pkg.description}`);
50   console.info();
51 }
52
53 function showHelp() {
54   showVersion();
55
56   console.info("Usage:");
57   console.info("    crowdnode help");
58   console.info("    crowdnode status ./privkey.wif");
59   console.info("    crowdnode signup ./privkey.wif");
60   console.info("    crowdnode accept ./privkey.wif");
61   console.info(
62     "    crowdnode deposit ./privkey.wif [dash-amount] [--no-reserve]",
63   );
64   console.info(
65     "    crowdnode withdrawal ./privkey.wif <percent> # 1.0-100.0 (steps by 0.1)",
66   );
67   console.info("");
68
69   console.info("Helpful Extras:");
70   console.info("    crowdnode generate [./privkey.wif]");
71   console.info("    crowdnode balance ./privkey.wif");
72   console.info(
73     "    crowdnode transfer ./source.wif <key-file-or-pub-addr> [dash-amount]",
74   );
75   console.info("");
76
77   console.info("CrowdNode HTTP RPC:");
78   console.info("    crowdnode http FundsOpen <addr>");
79   console.info("    crowdnode http VotingOpen <addr>");
80   console.info("    crowdnode http GetFunds <addr>");
81   console.info("    crowdnode http GetFundsFrom <addr> <seconds-since-epoch>");
82   console.info("    crowdnode http GetBalance <addr>");
83   console.info("    crowdnode http GetMessages <addr>");
84   console.info("    crowdnode http IsAddressInUse <addr>");
85   // TODO create signature rather than requiring it
86   console.info("    crowdnode http SetEmail ./privkey.wif <email> <signature>");
87   console.info("    crowdnode http Vote ./privkey.wif <gobject-hash> ");
88   console.info("        <Yes|No|Abstain|Delegate|DoNothing> <signature>");
89   console.info(
90     "    crowdnode http SetReferral ./privkey.wif <referral-id> <signature>",
91   );
92   console.info("");
93 }
94
95 function removeItem(arr, item) {
96   let index = arr.indexOf(item);
97   if (index >= 0) {
98     return arr.splice(index, 1)[0];
99   }
100   return null;
101 }
102
103 async function main() {
104   // Usage:
105   //    crowdnode <subcommand> [flags] <privkey> [options]
106   // Example:
107   //    crowdnode withdrawal ./Xxxxpubaddr.wif 100.0
108
109   let args = process.argv.slice(2);
110
111   // flags
112   let forceConfirm = removeItem(args, "--unconfirmed");
113   let noReserve = removeItem(args, "--no-reserve");
114
115   let subcommand = args.shift();
116
117   if (!subcommand || ["--help", "-h", "help"].includes(subcommand)) {
118     showHelp();
119     process.exit(0);
120     return;
121   }
122
123   if (["--version", "-V", "version"].includes(subcommand)) {
124     showVersion();
125     process.exit(0);
126     return;
127   }
128
129   if ("generate" === subcommand) {
130     await generate(args.shift());
131     return;
132   }
133
134   let insightBaseUrl =
135     process.env.INSIGHT_BASE_URL || "https://insight.dash.org";
136   let insightApi = Insight.create({ baseUrl: insightBaseUrl });
137   let dashApi = Dash.create({ insightApi: insightApi });
138
139   process.stdout.write("Checking CrowdNode API... ");
140   await CrowdNode.init({
141     baseUrl: "https://app.crowdnode.io",
142     insightBaseUrl,
143     insightApi: insightApi,
144   });
145   console.info(`hotwallet is ${CrowdNode.main.hotwallet}`);
146
147   let rpc = "";
148   if ("http" === subcommand) {
149     rpc = args.shift();
150     let keyfile = args.shift();
151     let pub = await wifFileToAddr(keyfile);
152
153     // ex: http <rpc>(<pub>, ...)
154     args.unshift(pub);
155     let hasRpc = rpc in CrowdNode.http;
156     if (!hasRpc) {
157       console.error(`Unrecognized rpc command ${rpc}`);
158       console.error();
159       showHelp();
160       process.exit(1);
161     }
162     let result = await CrowdNode.http[rpc].apply(null, args);
163     if ("string" === typeof result) {
164       console.info(result);
165     } else {
166       console.info(JSON.stringify(result, null, 2));
167     }
168     return;
169   }
170
171   let keyfile = args.shift();
172   let privKey;
173   if (keyfile) {
174     privKey = await Fs.readFile(keyfile, "utf8");
175     privKey = privKey.trim();
176   } else {
177     privKey = process.env.PRIVATE_KEY;
178   }
179   if (!privKey) {
180     // TODO generate private key?
181     console.error();
182     console.error(
183       `Error: you must provide either the WIF key file path or PRIVATE_KEY in .env`,
184     );
185     console.error();
186     process.exit(1);
187   }
188
189   let pk = new Dashcore.PrivateKey(privKey);
190   let pub = pk.toPublicKey().toAddress().toString();
191
192   // deposit if balance is over 100,000 (0.00100000)
193   process.stdout.write("Checking balance... ");
194   let balanceInfo = await dashApi.getInstantBalance(pub);
195   let balanceDash = toDash(balanceInfo.balanceSat);
196   console.info(`${balanceInfo.balanceSat} (Đ${balanceDash})`);
197   /*
198   let balanceInfo = await insightApi.getBalance(pub);
199   if (balanceInfo.unconfirmedBalanceSat || balanceInfo.unconfirmedAppearances) {
200     if (!forceConfirm) {
201       console.error(
202         `Error: This address has pending transactions. Please try again in 1-2 minutes or use --unconfirmed.`,
203       );
204       console.error(balanceInfo);
205       if ("status" !== subcommand) {
206         process.exit(1);
207         return;
208       }
209     }
210   }
211   */
212
213   let state = {
214     balanceInfo: balanceInfo,
215     dashApi: dashApi,
216     forceConfirm: forceConfirm,
217     hotwallet: CrowdNode.main.hotwallet,
218     insightBaseUrl: insightBaseUrl,
219     insightApi: insightApi,
220     noReserve: noReserve,
221     privKey: privKey,
222     pub: pub,
223
224     // status
225     status: {
226       signup: 0,
227       accept: 0,
228       deposit: 0,
229     },
230     signup: "❌",
231     accept: "❌",
232     deposit: "❌",
233   };
234
235   if ("balance" === subcommand) {
236     await balance(args, state);
237     process.exit(0);
238     return;
239   }
240
241   // helper for debugging
242   if ("transfer" === subcommand) {
243     await transfer(args, state);
244     return;
245   }
246
247   state.status = await CrowdNode.status(pub, state.hotwallet);
248   if (state.status?.signup) {
249     state.signup = "✅";
250   }
251   if (state.status?.accept) {
252     state.accept = "✅";
253   }
254   if (state.status?.deposit) {
255     state.deposit = "✅";
256   }
257
258   if ("status" === subcommand) {
259     await status(args, state);
260     return;
261   }
262
263   if ("signup" === subcommand) {
264     await signup(args, state);
265     return;
266   }
267
268   if ("accept" === subcommand) {
269     await accept(args, state);
270     return;
271   }
272
273   if ("deposit" === subcommand) {
274     await deposit(args, state);
275     return;
276   }
277
278   if ("withdrawal" === subcommand) {
279     await withdrawal(args, state);
280     return;
281   }
282
283   console.error(`Unrecognized subcommand ${subcommand}`);
284   console.error();
285   showHelp();
286   process.exit(1);
287 }
288
289 // Subcommands
290
291 async function generate(name) {
292   let pk = new Dashcore.PrivateKey();
293
294   let pub = pk.toAddress().toString();
295   let wif = pk.toWIF();
296
297   let filepath = `./${pub}.wif`;
298   let note = "";
299   if (name) {
300     filepath = name;
301     note = `\n(for pubkey address ${pub})`;
302   }
303
304   let testDash = 0.01;
305   let testDuff = toDuff(testDash);
306
307   let err = await Fs.access(filepath).catch(Object);
308   if (!err) {
309     // TODO show QR anyway
310     //wif = await Fs.readFile(filepath, 'utf8')
311     //showQr(pub, testDuff);
312     console.info(`'${filepath}' already exists (will not overwrite)`);
313     process.exit(0);
314     return;
315   }
316
317   await Fs.writeFile(filepath, wif, "utf8");
318   console.info(``);
319   console.info(
320     `Use the QR Code below to load a test deposit of Đ${testDash} onto your staking key.`,
321   );
322   console.info(``);
323   showQr(pub, testDuff);
324   console.info(``);
325   console.info(
326     `Use the QR Code above to load a test deposit of Đ${testDash} onto your staking key.`,
327   );
328   console.info(``);
329   console.info(`Generated ${filepath} ${note}`);
330   process.exit(0);
331 }
332
333 async function balance(args, state) {
334   console.info(state.balanceInfo);
335   process.exit(0);
336   return;
337 }
338
339 // ex: node ./bin/crowdnode.js transfer ./priv.wif 'pub' 0.01
340 async function transfer(args, state) {
341   let newAddr = await wifFileToAddr(process.argv[4]);
342   let dashAmount = parseFloat(process.argv[5] || 0);
343   let duffAmount = Math.round(dashAmount * DUFFS);
344   let tx;
345   if (duffAmount) {
346     tx = await state.dashApi.createPayment(state.privKey, newAddr, duffAmount);
347   } else {
348     tx = await state.dashApi.createBalanceTransfer(state.privKey, newAddr);
349   }
350   if (duffAmount) {
351     let dashAmountStr = toDash(duffAmount);
352     console.info(
353       `Transferring ${duffAmount} (Đ${dashAmountStr}) to ${newAddr}...`,
354     );
355   } else {
356     console.info(`Transferring balance to ${newAddr}...`);
357   }
358   await state.insightApi.instantSend(tx);
359   console.info(`Queued...`);
360   setTimeout(function () {
361     // TODO take a cleaner approach
362     // (waitForVout needs a reasonable timeout)
363     console.error(`Error: Transfer did not complete.`);
364     if (state.forceConfirm) {
365       console.error(`(using --unconfirmed may lead to rejected double spends)`);
366     }
367     process.exit(1);
368   }, 30 * 1000);
369   await Ws.waitForVout(state.insightBaseUrl, newAddr, 0);
370   console.info(`Accepted!`);
371   process.exit(0);
372   return;
373 }
374
375 async function status(args, state) {
376   console.info();
377   console.info(`API Actions Complete for ${state.pub}:`);
378   console.info(`    ${state.signup} SignUpForApi`);
379   console.info(`    ${state.accept} AcceptTerms`);
380   console.info(`    ${state.deposit} DepositReceived`);
381   console.info();
382   let pk = new Dashcore.PrivateKey(state.privKey);
383   let pub = pk.toPublicKey().toAddress().toString();
384   let crowdNodeBalance = await CrowdNode.http.GetBalance(pub);
385   let crowdNodeDash = toDash(crowdNodeBalance.TotalBalance);
386   console.info(
387     `CrowdNode Stake: ${crowdNodeBalance.TotalBalance} (Đ${crowdNodeDash})`,
388   );
389   console.info();
390   process.exit(0);
391   return;
392 }
393
394 async function signup(args, state) {
395   if (state.status?.signup) {
396     console.info(
397       `${state.pub} is already signed up. Here's the account status:`,
398     );
399     console.info(`    ${state.signup} SignUpForApi`);
400     console.info(`    ${state.accept} AcceptTerms`);
401     console.info(`    ${state.deposit} DepositReceived`);
402     process.exit(0);
403     return;
404   }
405
406   let hasEnough = state.balanceInfo.balanceSat > signupOnly + feeEstimate;
407   if (!hasEnough) {
408     await collectSignupFees(state.insightBaseUrl, state.pub);
409   }
410   console.info("Requesting account...");
411   await CrowdNode.signup(state.privKey, state.hotwallet);
412   state.signup = "✅";
413   console.info(`    ${state.signup} SignUpForApi`);
414   console.info(`    ${state.accept} AcceptTerms`);
415   process.exit(0);
416   return;
417 }
418
419 async function accept(args, state) {
420   if (state.status?.accept) {
421     console.info(
422       `${state.pub} is already signed up. Here's the account status:`,
423     );
424     console.info(`    ${state.signup} SignUpForApi`);
425     console.info(`    ${state.accept} AcceptTerms`);
426     console.info(`    ${state.deposit} DepositReceived`);
427     process.exit(0);
428     return;
429   }
430   let hasEnough = state.balanceInfo.balanceSat > acceptOnly + feeEstimate;
431   if (!hasEnough) {
432     await collectSignupFees(state.insightBaseUrl, state.pub);
433   }
434   console.info("Accepting terms...");
435   await CrowdNode.accept(state.privKey, state.hotwallet);
436   state.accept = "✅";
437   console.info(`    ${state.signup} SignUpForApi`);
438   console.info(`    ${state.accept} AcceptTerms`);
439   console.info(`    ${state.deposit} DepositReceived`);
440   process.exit(0);
441   return;
442 }
443
444 async function deposit(args, state) {
445   if (!state.status?.accept) {
446     console.error(`no account for address ${state.pub}`);
447     process.exit(1);
448     return;
449   }
450
451   // this would allow for at least 2 withdrawals costing (21000 + 1000)
452   let reserve = 50000;
453   let reserveDash = toDash(reserve);
454   if (!state.noReserve) {
455     console.info(
456       `reserving ${reserve} (Đ${reserveDash}) for withdrawals (--no-reserve to disable)`,
457     );
458   } else {
459     reserve = 0;
460   }
461
462   // TODO if unconfirmed, check utxos instead
463
464   // deposit what the user asks, or all that we have,
465   // or all that the user deposits - but at least 2x the reserve
466   let desiredAmountDash = parseFloat(args.shift() || 0);
467   let desiredAmountDuff = Math.round(desiredAmountDash * DUFFS);
468   let effectiveAmount = desiredAmountDuff;
469   if (!effectiveAmount) {
470     effectiveAmount = state.balanceInfo.balanceSat - reserve;
471   }
472   let needed = Math.max(reserve * 2, effectiveAmount + reserve);
473
474   if (state.balanceInfo.balanceSat < needed) {
475     let ask = 0;
476     if (desiredAmountDuff) {
477       ask = desiredAmountDuff + reserve + -state.balanceInfo.balanceSat;
478     }
479     await collectDeposit(state.insightBaseUrl, state.pub, ask);
480     state.balanceInfo = await state.dashApi.getInstantBalance(state.pub);
481     if (state.balanceInfo.balanceSat < needed) {
482       let balanceDash = toDash(state.balanceInfo.balanceSat);
483       console.error(
484         `Balance is still too small: ${state.balanceInfo.balanceSat} (Đ${balanceDash})`,
485       );
486       process.exit(1);
487       return;
488     }
489   }
490   if (!desiredAmountDuff) {
491     effectiveAmount = state.balanceInfo.balanceSat - reserve;
492   }
493
494   let effectiveDash = toDash(effectiveAmount);
495   console.info(
496     `Initiating deposit of ${effectiveAmount} (Đ${effectiveDash})...`,
497   );
498   await CrowdNode.deposit(state.privKey, state.hotwallet, effectiveAmount);
499   state.deposit = "✅";
500   console.info(`    ${state.deposit} DepositReceived`);
501   process.exit(0);
502   return;
503 }
504
505 async function withdrawal(args, state) {
506   if (!state.status?.accept) {
507     console.error(`no account for address ${state.pub}`);
508     process.exit(1);
509     return;
510   }
511
512   let percentStr = args.shift() || "100.0";
513   // pass: .1 0.1, 1, 1.0, 10, 10.0, 100, 100.0
514   // fail: 1000, 10.00
515   if (!/^1?\d?\d?(\.\d)?$/.test(percentStr)) {
516     console.error("Error: withdrawal percent must be between 0.1 and 100.0");
517     process.exit(1);
518   }
519   let percent = parseFloat(percentStr);
520
521   let permil = Math.round(percent * 10);
522   if (permil <= 0 || permil > 1000) {
523     console.error("Error: withdrawal percent must be between 0.1 and 100.0");
524     process.exit(1);
525   }
526
527   let realPercentStr = (permil / 10).toFixed(1);
528   console.info(`Initiating withdrawal of ${realPercentStr}...`);
529
530   let paid = await CrowdNode.withdrawal(state.privKey, state.hotwallet, permil);
531   //let paidFloat = (paid.satoshis / DUFFS).toFixed(8);
532   //let paidInt = paid.satoshis.toString().padStart(9, "0");
533   console.info(`API Response: ${paid.api}`);
534   process.exit(0);
535   return;
536 }
537
538 /*
539 async function stake(args, state) {
540   // TODO
541   return;
542 }
543 */
544
545 // Helpers
546
547 async function wifFileToAddr(keyfile) {
548   let privKey = keyfile;
549
550   let err = await Fs.access(keyfile).catch(Object);
551   if (!err) {
552     privKey = await Fs.readFile(keyfile, "utf8");
553     privKey = privKey.trim();
554   }
555
556   if (34 === privKey.length) {
557     // actually payment addr
558     return privKey;
559   }
560
561   if (52 === privKey.length) {
562     let pk = new Dashcore.PrivateKey(privKey);
563     let pub = pk.toPublicKey().toAddress().toString();
564     return pub;
565   }
566
567   throw new Error("bad file path or address");
568 }
569
570 async function collectSignupFees(insightBaseUrl, pub) {
571   showQr(pub);
572
573   let signupTotalDash = toDash(signupTotal);
574   let signupMsg = `Please send >= ${signupTotal} (Đ${signupTotalDash}) to Sign Up to CrowdNode`;
575   let msgPad = Math.ceil((qrWidth - signupMsg.length) / 2);
576   let subMsg = "(plus whatever you'd like to deposit)";
577   let subMsgPad = Math.ceil((qrWidth - subMsg.length) / 2);
578
579   console.info();
580   console.info(" ".repeat(msgPad) + signupMsg);
581   console.info(" ".repeat(subMsgPad) + subMsg);
582   console.info();
583
584   console.info("");
585   console.info("(waiting...)");
586   console.info("");
587   let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
588   console.info(`Received ${payment.satoshis}`);
589 }
590
591 async function collectDeposit(insightBaseUrl, pub, duffAmount) {
592   showQr(pub, duffAmount);
593
594   let depositMsg = `Please send what you wish to deposit to ${pub}`;
595   if (duffAmount) {
596     let depositDash = toDash(duffAmount);
597     depositMsg = `Please deposit ${duffAmount} (Đ${depositDash}) to ${pub}`;
598   }
599
600   let msgPad = Math.ceil((qrWidth - depositMsg.length) / 2);
601   msgPad = Math.max(0, msgPad);
602
603   console.info();
604   console.info(" ".repeat(msgPad) + depositMsg);
605   console.info();
606
607   console.info("");
608   console.info("(waiting...)");
609   console.info("");
610   let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
611   console.info(`Received ${payment.satoshis}`);
612 }
613
614 function toDash(duffs) {
615   return (duffs / DUFFS).toFixed(8);
616 }
617
618 function toDuff(dash) {
619   return Math.round(parseFloat(dash) * DUFFS);
620 }
621
622 // Run
623
624 main().catch(function (err) {
625   console.error("Fail:");
626   console.error(err.stack || err);
627   process.exit(1);
628 });