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})`;
305 let testDuff = toDuff(testDash);
307 let err = await Fs.access(filepath).catch(Object);
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)`);
317 await Fs.writeFile(filepath, wif, "utf8").then(function () {
320 `Use the QR Code below to load a test deposit of Đ${testDash} onto your staking key.`,
323 showQr(pub, testDuff);
326 `Use the QR Code above to load a test deposit of Đ${testDash} onto your staking key.`,
329 console.info(`Generated ${filepath} ${note}`);
334 async function balance(args, state) {
335 console.info(state.balanceInfo);
340 // ex: node ./bin/crowdnode.js transfer ./priv.wif 'pub' 0.01
341 async function transfer(args, state) {
342 let newAddr = await wifFileToAddr(process.argv[4]);
343 let dashAmount = parseFloat(process.argv[5] || 0);
344 let duffAmount = Math.round(dashAmount * DUFFS);
347 tx = await state.dashApi.createPayment(state.privKey, newAddr, duffAmount);
349 tx = await state.dashApi.createBalanceTransfer(state.privKey, newAddr);
352 let dashAmountStr = toDash(duffAmount);
354 `Transferring ${duffAmount} (Đ${dashAmountStr}) to ${newAddr}...`,
357 console.info(`Transferring balance to ${newAddr}...`);
359 await state.insightApi.instantSend(tx);
360 console.info(`Queued...`);
361 setTimeout(function () {
362 // TODO take a cleaner approach
363 // (waitForVout needs a reasonable timeout)
364 console.error(`Error: Transfer did not complete.`);
365 if (state.forceConfirm) {
366 console.error(`(using --unconfirmed may lead to rejected double spends)`);
370 await Ws.waitForVout(state.insightBaseUrl, newAddr, 0);
371 console.info(`Accepted!`);
376 async function status(args, state) {
378 console.info(`API Actions Complete for ${state.pub}:`);
379 console.info(` ${state.signup} SignUpForApi`);
380 console.info(` ${state.accept} AcceptTerms`);
381 console.info(` ${state.deposit} DepositReceived`);
383 let pk = new Dashcore.PrivateKey(state.privKey);
384 let pub = pk.toPublicKey().toAddress().toString();
385 let crowdNodeBalance = await CrowdNode.http.GetBalance(pub);
386 let crowdNodeDash = toDash(crowdNodeBalance.TotalBalance);
388 `CrowdNode Stake: ${crowdNodeBalance.TotalBalance} (Đ${crowdNodeDash})`,
395 async function signup(args, state) {
396 if (state.status?.signup) {
398 `${state.pub} is already signed up. Here's the account status:`,
400 console.info(` ${state.signup} SignUpForApi`);
401 console.info(` ${state.accept} AcceptTerms`);
402 console.info(` ${state.deposit} DepositReceived`);
407 let hasEnough = state.balanceInfo.balanceSat > signupOnly + feeEstimate;
409 await collectSignupFees(state.insightBaseUrl, state.pub);
411 console.info("Requesting account...");
412 await CrowdNode.signup(state.privKey, state.hotwallet);
414 console.info(` ${state.signup} SignUpForApi`);
415 console.info(` ${state.accept} AcceptTerms`);
420 async function accept(args, state) {
421 if (state.status?.accept) {
423 `${state.pub} is already signed up. Here's the account status:`,
425 console.info(` ${state.signup} SignUpForApi`);
426 console.info(` ${state.accept} AcceptTerms`);
427 console.info(` ${state.deposit} DepositReceived`);
431 let hasEnough = state.balanceInfo.balanceSat > acceptOnly + feeEstimate;
433 await collectSignupFees(state.insightBaseUrl, state.pub);
435 console.info("Accepting terms...");
436 await CrowdNode.accept(state.privKey, state.hotwallet);
438 console.info(` ${state.signup} SignUpForApi`);
439 console.info(` ${state.accept} AcceptTerms`);
440 console.info(` ${state.deposit} DepositReceived`);
445 async function deposit(args, state) {
446 if (!state.status?.accept) {
447 console.error(`no account for address ${state.pub}`);
452 // this would allow for at least 2 withdrawals costing (21000 + 1000)
454 let reserveDash = toDash(reserve);
455 if (!state.noReserve) {
457 `reserving ${reserve} (Đ${reserveDash}) for withdrawals (--no-reserve to disable)`,
463 // TODO if unconfirmed, check utxos instead
465 // deposit what the user asks, or all that we have,
466 // or all that the user deposits - but at least 2x the reserve
467 let desiredAmountDash = parseFloat(args.shift() || 0);
468 let desiredAmountDuff = Math.round(desiredAmountDash * DUFFS);
469 let effectiveAmount = desiredAmountDuff;
470 if (!effectiveAmount) {
471 effectiveAmount = state.balanceInfo.balanceSat - reserve;
473 let needed = Math.max(reserve * 2, effectiveAmount + reserve);
475 if (state.balanceInfo.balanceSat < needed) {
477 if (desiredAmountDuff) {
478 ask = desiredAmountDuff + reserve + -state.balanceInfo.balanceSat;
480 await collectDeposit(state.insightBaseUrl, state.pub, ask);
481 state.balanceInfo = await state.dashApi.getInstantBalance(state.pub);
482 if (state.balanceInfo.balanceSat < needed) {
483 let balanceDash = toDash(state.balanceInfo.balanceSat);
485 `Balance is still too small: ${state.balanceInfo.balanceSat} (Đ${balanceDash})`,
491 if (!desiredAmountDuff) {
492 effectiveAmount = state.balanceInfo.balanceSat - reserve;
495 let effectiveDash = toDash(effectiveAmount);
497 `Initiating deposit of ${effectiveAmount} (Đ${effectiveDash})...`,
499 await CrowdNode.deposit(state.privKey, state.hotwallet, effectiveAmount);
501 console.info(` ${state.deposit} DepositReceived`);
506 async function withdrawal(args, state) {
507 if (!state.status?.accept) {
508 console.error(`no account for address ${state.pub}`);
513 let percentStr = args.shift() || "100.0";
514 // pass: .1 0.1, 1, 1.0, 10, 10.0, 100, 100.0
516 if (!/^1?\d?\d?(\.\d)?$/.test(percentStr)) {
517 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
520 let percent = parseFloat(percentStr);
522 let permil = Math.round(percent * 10);
523 if (permil <= 0 || permil > 1000) {
524 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
528 let realPercentStr = (permil / 10).toFixed(1);
529 console.info(`Initiating withdrawal of ${realPercentStr}...`);
531 let paid = await CrowdNode.withdrawal(state.privKey, state.hotwallet, permil);
532 //let paidFloat = (paid.satoshis / DUFFS).toFixed(8);
533 //let paidInt = paid.satoshis.toString().padStart(9, "0");
534 console.info(`API Response: ${paid.api}`);
540 async function stake(args, state) {
548 async function wifFileToAddr(keyfile) {
549 let privKey = keyfile;
551 let err = await Fs.access(keyfile).catch(Object);
553 privKey = await Fs.readFile(keyfile, "utf8");
554 privKey = privKey.trim();
557 if (34 === privKey.length) {
558 // actually payment addr
562 if (52 === privKey.length) {
563 let pk = new Dashcore.PrivateKey(privKey);
564 let pub = pk.toPublicKey().toAddress().toString();
568 throw new Error("bad file path or address");
571 async function collectSignupFees(insightBaseUrl, pub) {
574 let signupTotalDash = toDash(signupTotal);
575 let signupMsg = `Please send >= ${signupTotal} (Đ${signupTotalDash}) to Sign Up to CrowdNode`;
576 let msgPad = Math.ceil((qrWidth - signupMsg.length) / 2);
577 let subMsg = "(plus whatever you'd like to deposit)";
578 let subMsgPad = Math.ceil((qrWidth - subMsg.length) / 2);
581 console.info(" ".repeat(msgPad) + signupMsg);
582 console.info(" ".repeat(subMsgPad) + subMsg);
586 console.info("(waiting...)");
588 let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
589 console.info(`Received ${payment.satoshis}`);
592 async function collectDeposit(insightBaseUrl, pub, duffAmount) {
593 showQr(pub, duffAmount);
595 let depositMsg = `Please send what you wish to deposit to ${pub}`;
597 let depositDash = toDash(duffAmount);
598 depositMsg = `Please deposit ${duffAmount} (Đ${depositDash}) to ${pub}`;
601 let msgPad = Math.ceil((qrWidth - depositMsg.length) / 2);
602 msgPad = Math.max(0, msgPad);
605 console.info(" ".repeat(msgPad) + depositMsg);
609 console.info("(waiting...)");
611 let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
612 console.info(`Received ${payment.satoshis}`);
615 function toDash(duffs) {
616 return (duffs / DUFFS).toFixed(8);
619 function toDuff(dash) {
620 return Math.round(parseFloat(dash) * DUFFS);
625 main().catch(function (err) {
626 console.error("Fail:");
627 console.error(err.stack || err);