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 console.info(`${balanceInfo.balanceSat} (Đ${balanceInfo.balance})`);
197 let balanceInfo = await insightApi.getBalance(pub);
198 if (balanceInfo.unconfirmedBalanceSat || balanceInfo.unconfirmedAppearances) {
201 `Error: This address has pending transactions. Please try again in 1-2 minutes or use --unconfirmed.`,
203 console.error(balanceInfo);
204 if ("status" !== subcommand) {
213 balanceInfo: balanceInfo,
215 forceConfirm: forceConfirm,
216 hotwallet: CrowdNode.main.hotwallet,
217 insightBaseUrl: insightBaseUrl,
218 insightApi: insightApi,
219 noReserve: noReserve,
234 if ("balance" === subcommand) {
235 await balance(args, state);
240 // helper for debugging
241 if ("transfer" === subcommand) {
242 await transfer(args, state);
246 state.status = await CrowdNode.status(pub, state.hotwallet);
247 if (state.status?.signup) {
250 if (state.status?.accept) {
253 if (state.status?.deposit) {
257 if ("status" === subcommand) {
258 await status(args, state);
262 if ("signup" === subcommand) {
263 await signup(args, state);
267 if ("accept" === subcommand) {
268 await accept(args, state);
272 if ("deposit" === subcommand) {
273 await deposit(args, state);
277 if ("withdrawal" === subcommand) {
278 await withdrawal(args, state);
282 console.error(`Unrecognized subcommand ${subcommand}`);
290 async function generate(name) {
291 let pk = new Dashcore.PrivateKey();
293 let pub = pk.toAddress().toString();
294 let wif = pk.toWIF();
296 let filepath = `./${pub}.wif`;
300 note = `\n(for pubkey address ${pub})`;
303 let err = await Fs.access(filepath).catch(Object);
305 // TODO show QR anyway
306 //wif = await Fs.readFile(filepath, 'utf8')
308 console.info(`'${filepath}' already exists (will not overwrite)`);
313 await Fs.writeFile(filepath, wif, "utf8").then(function () {
316 `Use the QR Code below to load a test deposit of Đ0.01 onto your staking key.`,
322 `Use the QR Code above to load a test deposit of Đ0.01 onto your staking key.`,
325 console.info(`Generated ${filepath} ${note}`);
330 async function balance(args, state) {
331 console.info(state.balanceInfo);
336 // ex: node ./bin/crowdnode.js transfer ./priv.wif 'pub' 0.01
337 async function transfer(args, state) {
338 let newAddr = await wifFileToAddr(process.argv[4]);
339 let dashAmount = parseFloat(process.argv[5] || 0);
340 let duffAmount = Math.round(dashAmount * DUFFS);
343 tx = await state.dashApi.createPayment(state.privKey, newAddr, duffAmount);
345 tx = await state.dashApi.createBalanceTransfer(state.privKey, newAddr);
349 `Transferring ${duffAmount} (Đ${dashAmount}) to ${newAddr}...`,
352 console.info(`Transferring balance to ${newAddr}...`);
354 await state.insightApi.instantSend(tx);
355 console.info(`Queued...`);
356 setTimeout(function () {
357 // TODO take a cleaner approach
358 // (waitForVout needs a reasonable timeout)
359 console.error(`Error: Transfer did not complete.`);
360 if (state.forceConfirm) {
361 console.error(`(using --unconfirmed may lead to rejected double spends)`);
365 await Ws.waitForVout(state.insightBaseUrl, newAddr, 0);
366 console.info(`Accepted!`);
371 async function status(args, state) {
373 console.info(`API Actions Complete for ${state.pub}:`);
374 console.info(` ${state.signup} SignUpForApi`);
375 console.info(` ${state.accept} AcceptTerms`);
376 console.info(` ${state.deposit} DepositReceived`);
382 async function signup(args, state) {
383 if (state.status?.signup) {
385 `${state.pub} is already signed up. Here's the account status:`,
387 console.info(` ${state.signup} SignUpForApi`);
388 console.info(` ${state.accept} AcceptTerms`);
389 console.info(` ${state.deposit} DepositReceived`);
394 let hasEnough = state.balanceInfo.balanceSat > signupOnly + feeEstimate;
396 await collectSignupFees(state.insightBaseUrl, state.pub);
398 console.info("Requesting account...");
399 await CrowdNode.signup(state.privKey, state.hotwallet);
401 console.info(` ${state.signup} SignUpForApi`);
402 console.info(` ${state.accept} AcceptTerms`);
407 async function accept(args, state) {
408 if (state.status?.accept) {
410 `${state.pub} is already signed up. Here's the account status:`,
412 console.info(` ${state.signup} SignUpForApi`);
413 console.info(` ${state.accept} AcceptTerms`);
414 console.info(` ${state.deposit} DepositReceived`);
418 let hasEnough = state.balanceInfo.balanceSat > acceptOnly + feeEstimate;
420 await collectSignupFees(state.insightBaseUrl, state.pub);
422 console.info("Accepting terms...");
423 await CrowdNode.accept(state.privKey, state.hotwallet);
425 console.info(` ${state.signup} SignUpForApi`);
426 console.info(` ${state.accept} AcceptTerms`);
427 console.info(` ${state.deposit} DepositReceived`);
432 async function deposit(args, state) {
433 if (!state.status?.accept) {
434 console.error(`no account for address ${state.pub}`);
439 // this would allow for at least 2 withdrawals costing (21000 + 1000)
441 let reserveDash = toDash(reserve);
442 if (!state.noReserve) {
444 `reserving ${reserve} (Đ${reserveDash}) for withdrawals (--no-reserve to disable)`,
450 // TODO if unconfirmed, check utxos instead
452 // deposit what the user asks, or all that we have,
453 // or all that the user deposits - but at least 2x the reserve
454 let desiredAmountDash = parseFloat(args.shift() || 0);
455 let desiredAmountDuff = Math.round(desiredAmountDash * DUFFS);
456 let effectiveAmount = desiredAmountDuff;
457 if (!effectiveAmount) {
458 effectiveAmount = state.balanceInfo.balanceSat - reserve;
460 let needed = Math.max(reserve * 2, effectiveAmount + reserve);
462 if (state.balanceInfo.balanceSat < needed) {
464 if (desiredAmountDuff) {
465 ask = desiredAmountDuff + reserve + -state.balanceInfo.balanceSat;
467 await collectDeposit(state.insightBaseUrl, state.pub, ask);
468 state.balanceInfo = await state.dashApi.getInstantBalance(state.pub);
469 if (state.balanceInfo.balanceSat < needed) {
470 let balanceDash = toDash(state.balanceInfo.balanceSat);
472 `Balance is still too small: ${state.balanceInfo.balanceSat} (Đ${balanceDash})`,
478 if (!desiredAmountDuff) {
479 effectiveAmount = state.balanceInfo.balanceSat - reserve;
483 `(holding ${reserve} (Đ${reserveDash}) in reserve for API calls)`,
485 let effectiveDash = toDash(effectiveAmount);
487 `Initiating deposit of ${effectiveAmount} (Đ${effectiveDash})...`,
489 await CrowdNode.deposit(state.privKey, state.hotwallet, effectiveAmount);
491 console.info(` ${state.deposit} DepositReceived`);
496 async function withdrawal(args, state) {
497 if (!state.status?.accept) {
498 console.error(`no account for address ${state.pub}`);
503 let percentStr = args.shift() || "100.0";
504 // pass: .1 0.1, 1, 1.0, 10, 10.0, 100, 100.0
506 if (!/^1?\d?\d?(\.\d)?$/.test(percentStr)) {
507 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
510 let percent = parseFloat(percentStr);
512 let permil = Math.round(percent * 10);
513 if (permil <= 0 || permil > 1000) {
514 console.error("Error: withdrawal percent must be between 0.1 and 100.0");
518 let realPercentStr = (permil / 10).toFixed(1);
519 console.info(`Initiating withdrawal of ${realPercentStr}...`);
521 let paid = await CrowdNode.withdrawal(state.privKey, state.hotwallet, permil);
522 //let paidFloat = (paid.satoshis / DUFFS).toFixed(8);
523 //let paidInt = paid.satoshis.toString().padStart(9, "0");
524 console.info(`API Response: ${paid.api}`);
530 async function stake(args, state) {
538 async function wifFileToAddr(keyfile) {
539 let privKey = keyfile;
541 let err = await Fs.access(keyfile).catch(Object);
543 privKey = await Fs.readFile(keyfile, "utf8");
544 privKey = privKey.trim();
547 if (34 === privKey.length) {
548 // actually payment addr
552 if (52 === privKey.length) {
553 let pk = new Dashcore.PrivateKey(privKey);
554 let pub = pk.toPublicKey().toAddress().toString();
558 throw new Error("bad file path or address");
561 async function collectSignupFees(insightBaseUrl, pub) {
564 let signupTotalDash = (signupTotal / DUFFS).toFixed(8);
565 let signupMsg = `Please send >= ${signupTotal} (Đ${signupTotalDash}) to Sign Up to CrowdNode`;
566 let msgPad = Math.ceil((qrWidth - signupMsg.length) / 2);
567 let subMsg = "(plus whatever you'd like to deposit)";
568 let subMsgPad = Math.ceil((qrWidth - subMsg.length) / 2);
571 console.info(" ".repeat(msgPad) + signupMsg);
572 console.info(" ".repeat(subMsgPad) + subMsg);
576 console.info("(waiting...)");
578 let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
579 console.info(`Received ${payment.satoshis}`);
582 async function collectDeposit(insightBaseUrl, pub, duffAmount) {
583 showQr(pub, duffAmount);
585 let depositMsg = `Please send what you wish to deposit to ${pub}`;
587 let depositDash = toDash(duffAmount);
588 depositMsg = `Please deposit ${duffAmount} (Đ${depositDash}) to ${pub}`;
591 let msgPad = Math.ceil((qrWidth - depositMsg.length) / 2);
592 msgPad = Math.max(0, msgPad);
595 console.info(" ".repeat(msgPad) + depositMsg);
599 console.info("(waiting...)");
601 let payment = await Ws.waitForVout(insightBaseUrl, pub, 0);
602 console.info(`Received ${payment.satoshis}`);
605 function toDash(duffs) {
606 return (duffs / DUFFS).toFixed(8);
611 main().catch(function (err) {
612 console.error("Fail:");
613 console.error(err.stack || err);