feat: make Dash formatting consistent
[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 err = await Fs.access(filepath).catch(Object);
305   if (!err) {
306     // TODO show QR anyway
307     //wif = await Fs.readFile(filepath, 'utf8')
308     //showQr(pub, 0.01);
309     console.info(`'${filepath}' already exists (will not overwrite)`);
310     process.exit(0);
311     return;
312   }
313
314   await Fs.writeFile(filepath, wif, "utf8").then(function () {
315     console.info(``);
316     console.info(
317       `Use the QR Code below to load a test deposit of Đ0.01 onto your staking key.`,
318     );
319     console.info(``);
320     showQr(pub, 0.01);
321     console.info(``);
322     console.info(
323       `Use the QR Code above to load a test deposit of Đ0.01 onto your staking key.`,
324     );
325     console.info(``);
326     console.info(`Generated ${filepath} ${note}`);
327   });
328   process.exit(0);
329 }
330
331 async function balance(args, state) {
332   console.info(state.balanceInfo);
333   process.exit(0);
334   return;
335 }
336
337 // ex: node ./bin/crowdnode.js transfer ./priv.wif 'pub' 0.01
338 async function transfer(args, state) {
339   let newAddr = await wifFileToAddr(process.argv[4]);
340   let dashAmount = parseFloat(process.argv[5] || 0);
341   let duffAmount = Math.round(dashAmount * DUFFS);
342   let tx;
343   if (duffAmount) {
344     tx = await state.dashApi.createPayment(state.privKey, newAddr, duffAmount);
345   } else {
346     tx = await state.dashApi.createBalanceTransfer(state.privKey, newAddr);
347   }
348   if (duffAmount) {
349     let dashAmountStr = toDash(duffAmount);
350     console.info(
351       `Transferring ${duffAmount} (Đ${dashAmountStr}) to ${newAddr}...`,
352     );
353   } else {
354     console.info(`Transferring balance to ${newAddr}...`);
355   }
356   await state.insightApi.instantSend(tx);
357   console.info(`Queued...`);
358   setTimeout(function () {
359     // TODO take a cleaner approach
360     // (waitForVout needs a reasonable timeout)
361     console.error(`Error: Transfer did not complete.`);
362     if (state.forceConfirm) {
363       console.error(`(using --unconfirmed may lead to rejected double spends)`);
364     }
365     process.exit(1);
366   }, 30 * 1000);
367   await Ws.waitForVout(state.insightBaseUrl, newAddr, 0);
368   console.info(`Accepted!`);
369   process.exit(0);
370   return;
371 }
372
373 async function status(args, state) {
374   console.info();
375   console.info(`API Actions Complete for ${state.pub}:`);
376   console.info(`    ${state.signup} SignUpForApi`);
377   console.info(`    ${state.accept} AcceptTerms`);
378   console.info(`    ${state.deposit} DepositReceived`);
379   console.info();
380   let pk = new Dashcore.PrivateKey(state.privKey);
381   let pub = pk.toPublicKey().toAddress().toString();
382   let crowdNodeBalance = await CrowdNode.http.GetBalance(pub);
383   let crowdNodeDash = toDash(crowdNodeBalance.TotalBalance);
384   console.info(
385     `CrowdNode Stake: ${crowdNodeBalance.TotalBalance} (Đ${crowdNodeDash})`,
386   );
387   console.info();
388   process.exit(0);
389   return;
390 }
391
392 async function signup(args, state) {
393   if (state.status?.signup) {
394     console.info(
395       `${state.pub} is already signed up. Here's the account status:`,
396     );
397     console.info(`    ${state.signup} SignUpForApi`);
398     console.info(`    ${state.accept} AcceptTerms`);
399     console.info(`    ${state.deposit} DepositReceived`);
400     process.exit(0);
401     return;
402   }
403
404   let hasEnough = state.balanceInfo.balanceSat > signupOnly + feeEstimate;
405   if (!hasEnough) {
406     await collectSignupFees(state.insightBaseUrl, state.pub);
407   }
408   console.info("Requesting account...");
409   await CrowdNode.signup(state.privKey, state.hotwallet);
410   state.signup = "✅";
411   console.info(`    ${state.signup} SignUpForApi`);
412   console.info(`    ${state.accept} AcceptTerms`);
413   process.exit(0);
414   return;
415 }
416
417 async function accept(args, state) {
418   if (state.status?.accept) {
419     console.info(
420       `${state.pub} is already signed up. Here's the account status:`,
421     );
422     console.info(`    ${state.signup} SignUpForApi`);
423     console.info(`    ${state.accept} AcceptTerms`);
424     console.info(`    ${state.deposit} DepositReceived`);
425     process.exit(0);
426     return;
427   }
428   let hasEnough = state.balanceInfo.balanceSat > acceptOnly + feeEstimate;
429   if (!hasEnough) {
430     await collectSignupFees(state.insightBaseUrl, state.pub);
431   }
432   console.info("Accepting terms...");
433   await CrowdNode.accept(state.privKey, state.hotwallet);
434   state.accept = "✅";
435   console.info(`    ${state.signup} SignUpForApi`);
436   console.info(`    ${state.accept} AcceptTerms`);
437   console.info(`    ${state.deposit} DepositReceived`);
438   process.exit(0);
439   return;
440 }
441
442 async function deposit(args, state) {
443   if (!state.status?.accept) {
444     console.error(`no account for address ${state.pub}`);
445     process.exit(1);
446     return;
447   }
448
449   // this would allow for at least 2 withdrawals costing (21000 + 1000)
450   let reserve = 50000;
451   let reserveDash = toDash(reserve);
452   if (!state.noReserve) {
453     console.info(
454       `reserving ${reserve} (Đ${reserveDash}) for withdrawals (--no-reserve to disable)`,
455     );
456   } else {
457     reserve = 0;
458   }
459
460   // TODO if unconfirmed, check utxos instead
461
462   // deposit what the user asks, or all that we have,
463   // or all that the user deposits - but at least 2x the reserve
464   let desiredAmountDash = parseFloat(args.shift() || 0);
465   let desiredAmountDuff = Math.round(desiredAmountDash * DUFFS);
466   let effectiveAmount = desiredAmountDuff;
467   if (!effectiveAmount) {
468     effectiveAmount = state.balanceInfo.balanceSat - reserve;
469   }
470   let needed = Math.max(reserve * 2, effectiveAmount + reserve);
471
472   if (state.balanceInfo.balanceSat < needed) {
473     let ask = 0;
474     if (desiredAmountDuff) {
475       ask = desiredAmountDuff + reserve + -state.balanceInfo.balanceSat;
476     }
477     await collectDeposit(state.insightBaseUrl, state.pub, ask);
478     state.balanceInfo = await state.dashApi.getInstantBalance(state.pub);
479     if (state.balanceInfo.balanceSat < needed) {
480       let balanceDash = toDash(state.balanceInfo.balanceSat);
481       console.error(
482         `Balance is still too small: ${state.balanceInfo.balanceSat} (Đ${balanceDash})`,
483       );
484       process.exit(1);
485       return;
486     }
487   }
488   if (!desiredAmountDuff) {
489     effectiveAmount = state.balanceInfo.balanceSat - reserve;
490   }
491
492   let effectiveDash = toDash(effectiveAmount);
493   console.info(
494     `Initiating deposit of ${effectiveAmount} (Đ${effectiveDash})...`,
495   );
496   await CrowdNode.deposit(state.privKey, state.hotwallet, effectiveAmount);
497   state.deposit = "✅";
498   console.info(`    ${state.deposit} DepositReceived`);
499   process.exit(0);
500   return;
501 }
502
503 async function withdrawal(args, state) {
504   if (!state.status?.accept) {
505     console.error(`no account for address ${state.pub}`);
506     process.exit(1);
507     return;
508   }
509
510   let percentStr = args.shift() || "100.0";
511   // pass: .1 0.1, 1, 1.0, 10, 10.0, 100, 100.0
512   // fail: 1000, 10.00
513   if (!/^1?\d?\d?(\.\d)?$/.test(percentStr)) {
514     console.error("Error: withdrawal percent must be between 0.1 and 100.0");
515     process.exit(1);
516   }
517   let percent = parseFloat(percentStr);
518
519   let permil = Math.round(percent * 10);
520   if (permil <= 0 || permil > 1000) {
521     console.error("Error: withdrawal percent must be between 0.1 and 100.0");
522     process.exit(1);
523   }
524
525   let realPercentStr = (permil / 10).toFixed(1);
526   console.info(`Initiating withdrawal of ${realPercentStr}...`);
527
528   let paid = await CrowdNode.withdrawal(state.privKey, state.hotwallet, permil);
529   //let paidFloat = (paid.satoshis / DUFFS).toFixed(8);
530   //let paidInt = paid.satoshis.toString().padStart(9, "0");
531   console.info(`API Response: ${paid.api}`);
532   process.exit(0);
533   return;
534 }
535
536 /*
537 async function stake(args, state) {
538   // TODO
539   return;
540 }
541 */
542
543 // Helpers
544
545 async function wifFileToAddr(keyfile) {
546   let privKey = keyfile;
547
548   let err = await Fs.access(keyfile).catch(Object);
549   if (!err) {
550     privKey = await Fs.readFile(keyfile, "utf8");
551     privKey = privKey.trim();
552   }
553
554   if (34 === privKey.length) {
555     // actually payment addr
556     return privKey;
557   }
558
559   if (52 === privKey.length) {
560     let pk = new Dashcore.PrivateKey(privKey);
561     let pub = pk.toPublicKey().toAddress().toString();
562     return pub;
563   }
564
565   throw new Error("bad file path or address");
566 }
567
568 async function collectSignupFees(insightBaseUrl, pub) {
569   showQr(pub);
570
571   let signupTotalDash = toDash(signupTotal);
572   let signupMsg = `Please send >= ${signupTotal} (Đ${signupTotalDash}) to Sign Up to CrowdNode`;
573   let msgPad = Math.ceil((qrWidth - signupMsg.length) / 2);
574   let subMsg = "(plus whatever you'd like to deposit)";
575   let subMsgPad = Math.ceil((qrWidth - subMsg.length) / 2);
576
577   console.info();
578   console.info(" ".repeat(msgPad) + signupMsg);
579   console.info(" ".repeat(subMsgPad) + subMsg);
580   console.info();
581
582   console.info("");
583   console.info("(waiting...)");
584   console.info("");
585   let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
586   console.info(`Received ${payment.satoshis}`);
587 }
588
589 async function collectDeposit(insightBaseUrl, pub, duffAmount) {
590   showQr(pub, duffAmount);
591
592   let depositMsg = `Please send what you wish to deposit to ${pub}`;
593   if (duffAmount) {
594     let depositDash = toDash(duffAmount);
595     depositMsg = `Please deposit ${duffAmount} (Đ${depositDash}) to ${pub}`;
596   }
597
598   let msgPad = Math.ceil((qrWidth - depositMsg.length) / 2);
599   msgPad = Math.max(0, msgPad);
600
601   console.info();
602   console.info(" ".repeat(msgPad) + depositMsg);
603   console.info();
604
605   console.info("");
606   console.info("(waiting...)");
607   console.info("");
608   let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
609   console.info(`Received ${payment.satoshis}`);
610 }
611
612 function toDash(duffs) {
613   return (duffs / DUFFS).toFixed(8);
614 }
615
616 // Run
617
618 main().catch(function (err) {
619   console.error("Fail:");
620   console.error(err.stack || err);
621   process.exit(1);
622 });