3 /*jshint maxcomplexity:25 */
5 require("dotenv").config({ path: ".env" });
6 require("dotenv").config({ path: ".env.secret" });
8 let pkg = require("../package.json");
10 let Fs = require("fs").promises;
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");
18 let Dashcore = require("@dashevo/dashcore-lib");
20 const DUFFS = 100000000;
21 let qrWidth = 2 + 67 + 2;
23 // 0.00236608 // required for signup
24 // 0.00002000 // TX fee estimate
25 // 0.00238608 // minimum recommended amount
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;
34 function showQr(signupAddr, duffs = 0) {
35 let signupUri = `dash://${signupAddr}`;
37 signupUri += `?amount=${duffs}`;
40 let signupQr = Qr.ascii(signupUri, { indent: 4 });
41 let addrPad = Math.ceil((qrWidth - signupUri.length) / 2);
43 console.info(signupQr);
45 console.info(" ".repeat(addrPad) + signupUri);
48 function showVersion() {
49 console.info(`${pkg.name} v${pkg.version} - ${pkg.description}`);
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");
62 " crowdnode deposit ./privkey.wif [dash-amount] [--no-reserve]",
65 " crowdnode withdrawal ./privkey.wif <percent> # 1.0-100.0 (steps by 0.1)",
69 console.info("Helpful Extras:");
70 console.info(" crowdnode generate [./privkey.wif]");
71 console.info(" crowdnode balance ./privkey.wif");
73 " crowdnode transfer ./source.wif <key-file-or-pub-addr> [dash-amount]",
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>");
90 " crowdnode http SetReferral ./privkey.wif <referral-id> <signature>",
95 function removeItem(arr, item) {
96 let index = arr.indexOf(item);
98 return arr.splice(index, 1)[0];
103 async function main() {
105 // crowdnode <subcommand> [flags] <privkey> [options]
107 // crowdnode withdrawal ./Xxxxpubaddr.wif 100.0
109 let args = process.argv.slice(2);
112 let forceConfirm = removeItem(args, "--unconfirmed");
113 let noReserve = removeItem(args, "--no-reserve");
115 let subcommand = args.shift();
117 if (!subcommand || ["--help", "-h", "help"].includes(subcommand)) {
123 if (["--version", "-V", "version"].includes(subcommand)) {
129 if ("generate" === subcommand) {
130 await generate(args.shift());
135 process.env.INSIGHT_BASE_URL || "https://insight.dash.org";
136 let insightApi = Insight.create({ baseUrl: insightBaseUrl });
137 let dashApi = Dash.create({ insightApi: insightApi });
139 process.stdout.write("Checking CrowdNode API... ");
140 await CrowdNode.init({
141 baseUrl: "https://app.crowdnode.io",
143 insightApi: insightApi,
145 console.info(`hotwallet is ${CrowdNode.main.hotwallet}`);
148 if ("http" === subcommand) {
150 let keyfile = args.shift();
151 let pub = await wifFileToAddr(keyfile);
153 // ex: http <rpc>(<pub>, ...)
155 let hasRpc = rpc in CrowdNode.http;
157 console.error(`Unrecognized rpc command ${rpc}`);
162 let result = await CrowdNode.http[rpc].apply(null, args);
163 if ("string" === typeof result) {
164 console.info(result);
166 console.info(JSON.stringify(result, null, 2));
171 let keyfile = args.shift();
174 privKey = await Fs.readFile(keyfile, "utf8");
175 privKey = privKey.trim();
177 privKey = process.env.PRIVATE_KEY;
180 // TODO generate private key?
183 `Error: you must provide either the WIF key file path or PRIVATE_KEY in .env`,
189 let pk = new Dashcore.PrivateKey(privKey);
190 let pub = pk.toPublicKey().toAddress().toString();
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})`);
198 let balanceInfo = await insightApi.getBalance(pub);
199 if (balanceInfo.unconfirmedBalanceSat || balanceInfo.unconfirmedAppearances) {
202 `Error: This address has pending transactions. Please try again in 1-2 minutes or use --unconfirmed.`,
204 console.error(balanceInfo);
205 if ("status" !== subcommand) {
214 balanceInfo: balanceInfo,
216 forceConfirm: forceConfirm,
217 hotwallet: CrowdNode.main.hotwallet,
218 insightBaseUrl: insightBaseUrl,
219 insightApi: insightApi,
220 noReserve: noReserve,
235 if ("balance" === subcommand) {
236 await balance(args, state);
241 // helper for debugging
242 if ("transfer" === subcommand) {
243 await transfer(args, state);
247 state.status = await CrowdNode.status(pub, state.hotwallet);
248 if (state.status?.signup) {
251 if (state.status?.accept) {
254 if (state.status?.deposit) {
258 if ("status" === subcommand) {
259 await status(args, state);
263 if ("signup" === subcommand) {
264 await signup(args, state);
268 if ("accept" === subcommand) {
269 await accept(args, state);
273 if ("deposit" === subcommand) {
274 await deposit(args, state);
278 if ("withdrawal" === subcommand) {
279 await withdrawal(args, state);
283 console.error(`Unrecognized subcommand ${subcommand}`);
291 async function generate(name) {
292 let pk = new Dashcore.PrivateKey();
294 let pub = pk.toAddress().toString();
295 let wif = pk.toWIF();
297 let filepath = `./${pub}.wif`;
301 note = `\n(for pubkey address ${pub})`;
304 let err = await Fs.access(filepath).catch(Object);
306 // TODO show QR anyway
307 //wif = await Fs.readFile(filepath, 'utf8')
309 console.info(`'${filepath}' already exists (will not overwrite)`);
314 await Fs.writeFile(filepath, wif, "utf8").then(function () {
317 `Use the QR Code below to load a test deposit of Đ0.01 onto your staking key.`,
323 `Use the QR Code above to load a test deposit of Đ0.01 onto your staking key.`,
326 console.info(`Generated ${filepath} ${note}`);
331 async function balance(args, state) {
332 console.info(state.balanceInfo);
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);
344 tx = await state.dashApi.createPayment(state.privKey, newAddr, duffAmount);
346 tx = await state.dashApi.createBalanceTransfer(state.privKey, newAddr);
349 let dashAmountStr = toDash(duffAmount);
351 `Transferring ${duffAmount} (Đ${dashAmountStr}) to ${newAddr}...`,
354 console.info(`Transferring balance to ${newAddr}...`);
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)`);
367 await Ws.waitForVout(state.insightBaseUrl, newAddr, 0);
368 console.info(`Accepted!`);
373 async function status(args, state) {
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`);
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);
385 `CrowdNode Stake: ${crowdNodeBalance.TotalBalance} (Đ${crowdNodeDash})`,
392 async function signup(args, state) {
393 if (state.status?.signup) {
395 `${state.pub} is already signed up. Here's the account status:`,
397 console.info(` ${state.signup} SignUpForApi`);
398 console.info(` ${state.accept} AcceptTerms`);
399 console.info(` ${state.deposit} DepositReceived`);
404 let hasEnough = state.balanceInfo.balanceSat > signupOnly + feeEstimate;
406 await collectSignupFees(state.insightBaseUrl, state.pub);
408 console.info("Requesting account...");
409 await CrowdNode.signup(state.privKey, state.hotwallet);
411 console.info(` ${state.signup} SignUpForApi`);
412 console.info(` ${state.accept} AcceptTerms`);
417 async function accept(args, state) {
418 if (state.status?.accept) {
420 `${state.pub} is already signed up. Here's the account status:`,
422 console.info(` ${state.signup} SignUpForApi`);
423 console.info(` ${state.accept} AcceptTerms`);
424 console.info(` ${state.deposit} DepositReceived`);
428 let hasEnough = state.balanceInfo.balanceSat > acceptOnly + feeEstimate;
430 await collectSignupFees(state.insightBaseUrl, state.pub);
432 console.info("Accepting terms...");
433 await CrowdNode.accept(state.privKey, state.hotwallet);
435 console.info(` ${state.signup} SignUpForApi`);
436 console.info(` ${state.accept} AcceptTerms`);
437 console.info(` ${state.deposit} DepositReceived`);
442 async function deposit(args, state) {
443 if (!state.status?.accept) {
444 console.error(`no account for address ${state.pub}`);
449 // this would allow for at least 2 withdrawals costing (21000 + 1000)
451 let reserveDash = toDash(reserve);
452 if (!state.noReserve) {
454 `reserving ${reserve} (Đ${reserveDash}) for withdrawals (--no-reserve to disable)`,
460 // TODO if unconfirmed, check utxos instead
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;
470 let needed = Math.max(reserve * 2, effectiveAmount + reserve);
472 if (state.balanceInfo.balanceSat < needed) {
474 if (desiredAmountDuff) {
475 ask = desiredAmountDuff + reserve + -state.balanceInfo.balanceSat;
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);
482 `Balance is still too small: ${state.balanceInfo.balanceSat} (Đ${balanceDash})`,
488 if (!desiredAmountDuff) {
489 effectiveAmount = state.balanceInfo.balanceSat - reserve;
492 let effectiveDash = toDash(effectiveAmount);
494 `Initiating deposit of ${effectiveAmount} (Đ${effectiveDash})...`,
496 await CrowdNode.deposit(state.privKey, state.hotwallet, effectiveAmount);
498 console.info(` ${state.deposit} DepositReceived`);
503 async function withdrawal(args, state) {
504 if (!state.status?.accept) {
505 console.error(`no account for address ${state.pub}`);
510 let percentStr = args.shift() || "100.0";
511 // pass: .1 0.1, 1, 1.0, 10, 10.0, 100, 100.0
513 if (!/^1?\d?\d?(\.\d)?$/.test(percentStr)) {
514 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
517 let percent = parseFloat(percentStr);
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");
525 let realPercentStr = (permil / 10).toFixed(1);
526 console.info(`Initiating withdrawal of ${realPercentStr}...`);
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}`);
537 async function stake(args, state) {
545 async function wifFileToAddr(keyfile) {
546 let privKey = keyfile;
548 let err = await Fs.access(keyfile).catch(Object);
550 privKey = await Fs.readFile(keyfile, "utf8");
551 privKey = privKey.trim();
554 if (34 === privKey.length) {
555 // actually payment addr
559 if (52 === privKey.length) {
560 let pk = new Dashcore.PrivateKey(privKey);
561 let pub = pk.toPublicKey().toAddress().toString();
565 throw new Error("bad file path or address");
568 async function collectSignupFees(insightBaseUrl, pub) {
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);
578 console.info(" ".repeat(msgPad) + signupMsg);
579 console.info(" ".repeat(subMsgPad) + subMsg);
583 console.info("(waiting...)");
585 let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
586 console.info(`Received ${payment.satoshis}`);
589 async function collectDeposit(insightBaseUrl, pub, duffAmount) {
590 showQr(pub, duffAmount);
592 let depositMsg = `Please send what you wish to deposit to ${pub}`;
594 let depositDash = toDash(duffAmount);
595 depositMsg = `Please deposit ${duffAmount} (Đ${depositDash}) to ${pub}`;
598 let msgPad = Math.ceil((qrWidth - depositMsg.length) / 2);
599 msgPad = Math.max(0, msgPad);
602 console.info(" ".repeat(msgPad) + depositMsg);
606 console.info("(waiting...)");
608 let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
609 console.info(`Received ${payment.satoshis}`);
612 function toDash(duffs) {
613 return (duffs / DUFFS).toFixed(8);
618 main().catch(function (err) {
619 console.error("Fail:");
620 console.error(err.stack || err);