-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathmain.js
522 lines (454 loc) · 14.6 KB
/
main.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
const {program} = require('commander');
const pkg = require('../../package.json');
const {transferNameLock} = require('../swapService.js');
const {Context, promptPassphraseGetter} = require('../context.js');
const {createDB, putLockTransfer} = require('../storage.js');
const Table = require('cli-table3');
const {putLockFinalize} = require('../storage.js');
const {finalizeNameLock} = require('../swapService.js');
const {getName} = require('../storage.js');
const {getNames} = require('../storage.js');
const inquirer = require('inquirer');
const fs = require('fs');
const {putAuction} = require('../storage.js');
const {linearReductionStrategy} = require('../auction.js');
const {Auction} = require('../auction.js');
const readline = require('readline');
const {readProofFile} = require('../swapProof.js');
const {writeProofFile} = require('../swapProof.js');
const {putSwapFinalize} = require('../storage.js');
const {finalizeSwap} = require('../swapService.js');
const {formatDate} = require('../conversions.js');
const {putSwapFulfillment} = require('../storage.js');
const {fulfillSwap} = require('../swapService.js');
const {SwapProof} = require('../swapProof.js');
const {Client} = require('bcurl');
program
.version(pkg.version)
.option('-p, --prefix <prefix>', 'Prefix directory to write the database to.', `${process.env.HOME}/.shakedex`)
.option('-n, --network <network>', 'Handshake network to connect to.', 'regtest')
.option('-w, --wallet-id <walletId>', 'Handshake wallet ID.', 'primary')
.option('-a, --api-key <apiKey>', 'Handshake wallet API key.')
.option('--shakedex-web-host <shakedexWebHost>', 'Shakedex web hostname.', 'www.shakedex.com');
program.command('transfer-lock <name>')
.description('Posts a name lock transaction, which when finalized allows the name to be auctioned.')
.action(cliSetup(transferLock));
program.command('finalize-lock <name>')
.description('Finalizes a name lock transaction, which allows the name to be auctioned.')
.action(cliSetup(finalizeLock));
program.command('create-auction <name>')
.description('Creates auction presigns.')
.action(cliSetup(createAuction));
program.command('list-auctions')
.description('Prints all name auctions and their statuses.')
.action(cliSetup(listAuctions));
program.command('fulfill-auction <proposalsPath>')
.description('Fulfills an auction given a set of presigns.')
.action(cliSetup(fulfillAuction));
program.command('finalize-auction <name>')
.description('Finalizes an auction that has been previously fulfilled.')
.action(cliSetup(finalizeAuction));
program.command('list-fulfillments')
.description('Prints the list of auctions that you have attempted to fulfill.')
.action(cliSetup(listFulfillments));
program.parse(process.argv);
function cliSetup(fn) {
return async (...args) => {
try {
setupPrefix();
await fn(...args);
} catch (e) {
console.error('An error occurred. Stack trace:');
console.error(e);
console.error();
console.error(`Please report this as an issue by visiting ${pkg.bugs.url}/new.`);
}
};
}
async function confirm(message) {
const answers = await inquirer.prompt([
{
type: 'confirm',
name: 'confirmed',
message,
},
]);
if (!answers.confirmed) {
die('Cancelled.');
}
}
function setupPrefix() {
const opts = program.opts();
if (fs.existsSync(opts.prefix)) {
return;
}
fs.mkdirSync(opts.prefix);
}
function getContext() {
const opts = program.opts();
return new Context(
opts.network,
opts.walletId,
opts.apiKey,
promptPassphraseGetter(),
);
}
async function transferLock(name) {
await confirm(`Your name ${name} will be transferred to a locking script. ` +
'This can be undone, but requires additional on-chain transactions. Do you wish to continue?');
const db = await createDB(program.opts().prefix);
const context = getContext();
log('Performing locking script transfer.');
const lockTransfer = await transferNameLock(
context,
name,
);
await putLockTransfer(db, lockTransfer);
log(`Name transferred to locking script with transaction hash ${lockTransfer.transferTxHash}.`);
log('Please wait at least 15 minutes for your transaction to be confirmed.');
}
async function finalizeLock(name) {
await confirm(`Your transfer of ${name} to the locking script will be finalized. ` +
'This can be undone, but requires additional on-chain transactions. Do you wish to continue?');
const db = await createDB(program.opts().prefix);
const context = getContext();
const nameObj = await getName(db, name);
if (!nameObj) {
die(`Name ${name} does not exist.`);
}
log('Finalizing locking script transfer.');
const lockFinalize = await finalizeNameLock(
context,
nameObj.transfer,
);
await putLockFinalize(db, lockFinalize);
log(`Name finalized to locking script with transaction hash ${lockFinalize.finalizeTxHash}.`);
log('Please wait at least 15 minutes for your transaction to be confirmed.');
}
async function createAuction(name) {
const db = await createDB(program.opts().prefix);
const shakedexWebHost = program.opts().shakedexWebHost;
const context = getContext();
const nameObj = await getName(db, name);
if (!nameObj) {
die(`Name ${name} does not exist.`);
}
if (!nameObj.finalize) {
die(`Name ${name}'s listing has not been finalized.`);
}
const answers = await inquirer.prompt([
{
type: 'list',
name: 'duration',
message: 'How long should the auction last?',
choices: [
'1 day',
'3 days',
'5 days',
'7 days',
'14 days',
],
},
{
type: 'input',
name: 'startPrice',
message: 'What price would you like to start the auction at? This should be a high price. Expressed in whole HNS.',
validate: (value) => {
const valid = !isNaN(Number(value)) && Number(value) > 0;
if (valid) {
return true;
}
return `Invalid start price.`;
},
},
{
type: 'input',
name: 'endPrice',
message: 'What price would you like to end the auction at? This is the lowest price you will accept for the name. Expressed in whole HNS.',
validate: (value) => {
const valid = !isNaN(Number(value)) && Number(value) > 0;
if (valid) {
return true;
}
return `Invalid end price.`;
},
},
{
type: 'input',
name: 'outPath',
message: 'Where would you like to store your auction presigns?',
},
]);
const durationDays = Number(answers.duration.split(' ')[0]);
const startPrice = Number(answers.startPrice);
const endPrice = Number(answers.endPrice);
if (startPrice < endPrice) {
die('Your start price cannot be less than your end price.');
}
let reductionTimeMS;
switch (durationDays) {
case 1:
reductionTimeMS = 60 * 60 * 1000;
break;
case 3:
reductionTimeMS = 3 * 60 * 60 * 1000;
break;
case 5:
case 7:
case 14:
reductionTimeMS = 24 * 60 * 60 * 1000;
break;
}
let outPath = answers.outPath;
if (answers.outPath[0] === '~') {
outPath = outPath.replace('~', process.env.HOME);
}
const auction = new Auction({
name,
startTime: Date.now(),
endTime: Date.now() + durationDays * 24 * 60 * 60 * 1000,
startPrice: startPrice * 1e6,
endPrice: endPrice * 1e6,
reductionTimeMS,
reductionStrategy: linearReductionStrategy,
});
const proposals = await auction.generateProposals(context, nameObj.finalize);
await writeProofFile(outPath, proposals, context);
const shouldPostAnswer = await inquirer.prompt([{
type: 'confirm',
name: 'shouldPost',
message: `Would you like to publish your auction to Shakedex Web at ${shakedexWebHost}?`,
default: true,
}]);
if (shouldPostAnswer.shouldPost) {
const client = new Client({
host: shakedexWebHost,
ssl: true,
});
const first = proposals[0];
const auction = {
name: first.name,
lockingTxHash: first.lockingTxHash.toString('hex'),
lockingOutputIdx: first.lockingOutputIdx,
publicKey: first.publicKey.toString('hex'),
paymentAddr: first.paymentAddr.toString(context.networkName),
data: proposals.map(p => ({
price: p.price,
lockTime: p.lockTime,
signature: p.signature.toString('hex'),
})),
};
try {
await client.post('api/v1/auctions', {
auction
});
} catch (e) {
log('An error occurred posting your proof to Shakedex Web:')
log(e.message);
log(e.stack);
log(`You can still find your proof in ${outPath}.`)
if (e.json) {
}
}
}
}
async function listAuctions() {
const db = await createDB(program.opts().prefix);
const context = getContext();
const names = await getNames(db);
const table = new Table({
head: [
'Name',
'Status',
'Transfer Broadcast',
'Transfer Confirmed',
'Finalize Broadcast',
'Finalize Confirmed',
'Start Price',
'End Price',
'Current Price',
],
});
for (const name of names) {
if (!name.transfer) {
continue;
}
let status = 'UNKNOWN';
let transferBroadcast = '-';
let transferConfirmed = '-';
let finalizeBroadcast = '-';
let finalizeConfirmed = '-';
let endPrice = '-';
let startPrice = '-';
let currPrice = '-';
if (name.transfer) {
const details = await name.transfer.getConfirmationDetails(context);
transferBroadcast = formatDate(name.transfer.broadcastAt);
if (details.confirmedAt) {
transferConfirmed = formatDate(details.confirmedAt);
status = 'TRANSFER_CONFIRMED_LOCKUP';
if (details.spendable) {
status = 'TRANSFER_CONFIRMED_FINALIZABLE';
}
} else {
status = 'TRANSFER_MEMPOOL';
}
}
if (name.finalize) {
const details = await name.finalize.getConfirmationDetails(context);
finalizeBroadcast = formatDate(name.finalize.broadcastAt);
if (details.confirmedAt) {
finalizeConfirmed = formatDate(details.confirmedAt);
status = 'FINALIZE_CONFIRMED';
} else {
status = 'FINALIZE_MEMPOOL';
}
}
if (name.auction) {
status = 'AUCTION_LIVE';
endPrice = (name.auction.endPrice / 1e6).toFixed(6);
startPrice = (name.auction.startPrice / 1e6).toFixed(6);
currPrice = (name.auction.priceFor(Date.now()) / 1e6).toFixed(6);
}
table.push([
name.name,
status,
transferBroadcast,
transferConfirmed,
finalizeBroadcast,
finalizeConfirmed,
startPrice,
endPrice,
currPrice,
]);
}
console.log(table.toString());
}
async function fulfillAuction(proposalsPath) {
const exists = fs.existsSync(proposalsPath);
if (!exists) {
die(`Proposals file not found.`);
}
const db = await createDB(program.opts().prefix);
const context = getContext();
const proofs = await readProofFile(proposalsPath);
log('Verifying swap proofs.');
for (let i = 0; i < proofs.length; i++) {
const proof = proofs[i];
process.stdout.clearLine();
process.stdout.cursorTo(0);
process.stdout.write(`>> Verified proof ${i + 1}.`);
if (!await proof.verify(context)) {
die(`Swap proof ${i + 1} is invalid - aborting.`);
}
}
process.stdout.clearLine();
process.stdout.cursorTo(0);
log('Calculating best price.');
let bestProof = null;
for (const proof of proofs) {
if (bestProof === null) {
bestProof = proof;
}
if (Date.now() > proof.lockTime && proof.price < bestProof) {
bestProof = proof;
}
}
const table = new Table();
table.push({
'Name': bestProof.name,
}, {
'Price': `${(bestProof.price / 1e6).toFixed(6)} HNS`,
}, {
'Locking Script TX Hash': bestProof.lockingTxHash.toString('hex'),
}, {
'Locking Script Output Index': bestProof.lockingOutputIdx,
}, {
'Payment Address': bestProof.paymentAddr.toString(context.networkName),
});
console.log(table.toString());
const answers = await inquirer.prompt([
{
type: 'confirm',
name: 'confirmed',
message: 'Are you sure you want to fulfill the auction above? This action is not reversible. You are responsible for all blockchain fees.',
},
]);
if (!answers.confirmed) {
die('Cancelled.');
}
const fulfillment = await fulfillSwap(context, bestProof);
await putSwapFulfillment(db, fulfillment);
log(`Fulfilled auction with transaction hash ${fulfillment.fulfillmentTxHash}.`);
log(`Please wait 15 minutes for the blockchain to confirm the transaction.`);
}
async function finalizeAuction(name) {
const db = await createDB(program.opts().prefix);
const context = getContext();
const nameObj = await getName(db, name);
if (!nameObj.swapFulfillment) {
die('This name is not fulfilled.');
}
const finalize = await finalizeSwap(context, nameObj.swapFulfillment);
await putSwapFinalize(db, finalize);
}
async function listFulfillments() {
const db = await createDB(program.opts().prefix);
const context = getContext();
const names = await getNames(db);
const table = new Table({
head: [
'Name',
'Status',
'Price',
'Fulfill Broadcast',
'Fulfill Confirmed',
'Finalize Broadcast',
'Finalize Confirmed',
],
});
for (const name of names) {
if (!name.swapFulfillment) {
continue;
}
let status = 'FULFILL_TRANSFER_MEMPOOL';
const fulfillBroadcastAt = formatDate(name.swapFulfillment.broadcastAt);
let fulfillConfirmedAt = '-';
let finalizeBroadcastAt = '-';
let finalizeConfirmedAt = '-';
const fulfillConfDetails = await name.swapFulfillment.getConfirmationDetails(context);
if (fulfillConfDetails.confirmedAt) {
fulfillConfirmedAt = formatDate(fulfillConfDetails.confirmedAt);
status = 'FULFILL_TRANSFER_LOCKUP';
if (fulfillConfDetails.spendable) {
status = 'FULFILL_TRANSFER_FINALIZABLE';
}
}
if (name.swapFinalize) {
status = 'FULFILL_FINALIZE_MEMPOOL';
finalizeBroadcastAt = formatDate(name.swapFinalize.broadcastAt);
const confDetails = await name.swapFinalize.getConfirmationDetails(context);
if (confDetails.confirmedAt) {
status = 'FULFILL_FINALIZE_CONFIRMED';
finalizeConfirmedAt = formatDate(confDetails.confirmedAt);
}
}
table.push([
name.name,
status,
(name.swapFulfillment.price / 1e6).toFixed(6),
fulfillBroadcastAt,
fulfillConfirmedAt,
finalizeBroadcastAt,
finalizeConfirmedAt,
]);
}
console.log(table.toString());
}
function die(msg) {
console.log(msg);
process.exit(1);
}
function log(msg) {
console.log(`>> ${msg}`);
}