forked from MystenLabs/sui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
815 lines (674 loc) · 21.4 KB
/
index.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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
// Copyright (c) Mysten Labs, Inc.
// SPDX-License-Identifier: Apache-2.0
/* eslint-disable eqeqeq */
/**
* Implements a `kiosk-cli`. To view available commands, run:
* ```sh
* $ node index.js help
* ```
*
* Alternatively, via the `pnpm`:
* ```sh
* pnpm cli help
* ```
*
* This package allows for:
* - Creating a Kiosk;
* - Placing items into the Kiosk;
* - Listing items in the Kiosk for sale;
* - Purchasing items from the Kiosk;
* - Taking items from the Kiosk;
* - Locking items in the Kiosk;
* - Delisting items from the Kiosk;
* - Viewing the inventory of the sender;
* - Viewing the contents of a Kiosk;
*/
import {
formatAddress,
isValidSuiAddress,
isValidSuiObjectId,
MIST_PER_SUI,
} from '@mysten/sui.js/utils';
import { bcs } from '@mysten/sui.js/bcs';
import { program } from 'commander';
import { KIOSK_LISTING, KioskClient, KioskTransaction, Network } from '@mysten/kiosk';
import { SuiClient, getFullnodeUrl } from '@mysten/sui.js/client';
import { Ed25519Keypair } from '@mysten/sui.js/keypairs/ed25519';
import { TransactionBlock } from '@mysten/sui.js/transactions';
/**
* List of known types for shorthand search in the `search` command.
*/
const KNOWN_TYPES = {
suifren:
'0x80d7de9c4a56194087e0ba0bf59492aa8e6a5ee881606226930827085ddf2332::suifrens::SuiFren<0x80d7de9c4a56194087e0ba0bf59492aa8e6a5ee881606226930827085ddf2332::capy::Capy>',
};
/** JsonRpcProvider for the Testnet */
const client = new SuiClient({ url: getFullnodeUrl('testnet') });
const kioskClient = new KioskClient({
client,
network: Network.TESTNET,
});
/**
* Create the signer instance from the mnemonic.
*/
const keypair = (function (mnemonic) {
if (!mnemonic) {
console.log('Requires MNEMONIC; set with `export MNEMONIC="..."`');
process.exit(1);
}
return Ed25519Keypair.deriveKeypair(process.env.MNEMONIC);
})(process.env.MNEMONIC);
program
.name('kiosk-cli')
.description(
'Simple CLI to interact with Kiosk smart contracts. \nRequires MNEMONIC environment variable.',
)
.version('0.0.1');
program
.command('new')
.description('create and share a Kiosk; send OwnerCap to sender')
.action(newKiosk);
program
.command('inventory')
.description('view the inventory of the sender')
.option('-a, --address <address>', "Fetch another user's inventory")
.option('--cursor', 'Fetch inventory starting from this cursor')
.option('--only-display', 'Only show items that have Display')
.option('-f, --filter <type>', 'Filter by type')
.action(showInventory);
program
.command('contents')
.description('list all Items and Listings in the Kiosk owned by the sender')
.option('--id <id>', 'The ID of the Kiosk to look up')
.option('--address <address>', 'The address of the Kiosk owner')
.action(showKioskContents);
program
.command('place')
.description("place an item from the sender's inventory into the Kiosk")
.argument('<item ID>', 'The ID of the item to place')
.action(placeItem);
program
.command('lock')
.description('lock an item in the user Kiosk (requires TransferPolicy)')
.argument('<item ID>', 'The ID of the item to place')
.action(lockItem);
program
.command('take')
.description('Take an item from the Kiosk and transfer to sender or to <address>')
.argument('<item ID>', 'The ID of the item to take')
.option('-a, --address <address>')
.action(takeItem);
program
.command('list')
.description('list an item in the Kiosk for the specified amount of SUI')
.argument('<item ID>', 'The ID of the item to list')
.argument('<amount MIST>', 'The amount of SUI to list the item for')
.action(listItem);
program
.command('delist')
.description('delist an item from the Kiosk')
.argument('<item ID>', 'The ID of the item to delist')
.action(delistItem);
program
.command('purchase')
.description('purchase an item from the specified Kiosk')
.argument('<item ID>', 'The ID of the item to purchase')
.option(
'--kiosk <ID>',
'The ID of the Kiosk to purchase from (speeds up purchase by skipping search)',
)
.action(purchaseItem);
program
.command('search')
.description('search open listings in Kiosks')
.argument('<type>', 'The type of the item to search for. \nAvailable aliases: "suifren", "test"')
.action(searchType);
program
.command('policy')
.description('search for a TransferPolicy for the specified type')
.argument('<type>', 'The type of the item to search for. \nAvailable aliases: "suifren", "test"')
.action(searchPolicy);
program
.command('withdraw')
.description('Withdraw all profits from the Kiosk to the Kiosk Owner')
.action(withdrawAll);
program
.command('publisher')
.description('View the Publisher objects owned by the user')
.action(showPublisher);
program.parse(process.argv);
/**
* Command: `new`
* Description: creates and shares a Kiosk
*/
async function newKiosk() {
const sender = keypair.getPublicKey().toSuiAddress();
const kioskCap = await findKioskCap().catch(() => null);
if (kioskCap !== null) {
throw new Error(`Kiosk already exists for ${sender}`);
}
const txb = new TransactionBlock();
new KioskTransaction({ transactionBlock: txb, kioskClient })
.create()
.shareAndTransferCap(sender)
.finalize();
return sendTx(txb);
}
/**
* Command: `inventory`
* Description: view the inventory of the sender (or a specified address)
*/
async function showInventory({ address, onlyDisplay, cursor, filter }) {
const owner = address || keypair.getPublicKey().toSuiAddress();
if (!isValidSuiAddress(owner)) {
throw new Error(`Invalid SUI address: "${owner}"`);
}
const options = {
owner,
cursor,
options: {
showType: true,
showDisplay: true,
},
};
if (filter) {
options.filter = { StructType: KNOWN_TYPES[filter] || filter };
}
const { data, nextCursor, hasNextPage } = await client.getOwnedObjects(options);
if (hasNextPage) {
console.log('Showing first page of results. Use `--cursor` to get the next page.');
console.log('Next cursor: %s', nextCursor);
}
const list = data
.filter(({ data, error }) => !error && data)
.sort((a, b) => a.data.type.localeCompare(b.data.type))
.map(({ data }) => ({
objectId: data.objectId,
type: formatType(data.type),
hasDisplay: !!data.display.data,
}));
console.log('- Owner %s', owner);
if (onlyDisplay) {
console.table(list.filter(({ hasDisplay }) => hasDisplay));
} else {
console.table(list);
}
}
/**
* Command: `contents`
* Description: Show the contents of the Kiosk owned by the sender (or the
* specified address) or directly by the specified Kiosk ID
*/
async function showKioskContents({ id, address }) {
let kioskId = null;
if (id) {
if (!isValidSuiObjectId(id)) {
throw new Error(`Invalid Kiosk ID: "${id}"`);
}
kioskId = id;
} else {
const sender = address || keypair.getPublicKey().toSuiAddress();
if (!isValidSuiAddress(sender)) {
throw new Error(`Invalid SUI address: "${sender}"`);
}
const kioskCap = await findKioskCap(sender).catch(() => null);
if (kioskCap == null) {
throw new Error(`No Kiosk found for ${sender}`);
}
kioskId = kioskCap.kioskId;
}
const {
items,
kiosk,
// data: { items, kiosk },
hasNextPage,
nextCursor,
} = await kioskClient.getKiosk({
id: kioskId,
options: {
withListingPrices: true,
withKioskFields: true,
},
});
if (hasNextPage) {
console.log('Next cursor: %s', nextCursor);
}
console.log('Description');
console.log('- Kiosk ID: %s', kioskId);
console.log('- Profits: %s', kiosk.profits);
console.log('- UID Exposed: %s', kiosk.allowExtensions);
console.log('- Item Count: %s', kiosk.itemCount);
const tabledItems = items
.map((item) => ({
objectId: item.objectId,
type: formatType(item.type),
isLocked: item.isLocked,
listed: !!item.listing,
isPublic: (item.listing && !item.listing.isExclusive) || false,
'price (SUI)': item.listing ? formatAmount(item.listing.price) : 'N/A',
}))
.sort((a, b) => a.listed - b.listed);
console.table(tabledItems);
}
/**
* Command: `place`
* Description: Place an item into the Kiosk owned by the sender
*/
async function placeItem(itemId) {
const kioskCap = await findKioskCap().catch(() => null);
const owner = keypair.getPublicKey().toSuiAddress();
if (kioskCap === null) {
throw new Error('No Kiosk found for sender; use `new` to create one');
}
if (!isValidSuiObjectId(itemId)) {
throw new Error('Invalid Item ID: "%s"', itemId);
}
const item = await client.getObject({
id: itemId,
options: { showType: true, showOwner: true },
});
if ('error' in item || !item.data) {
throw new Error(`Item ${itemId} not found; error: ` + item.error);
}
if (!('AddressOwner' in item.data.owner) || item.data.owner.AddressOwner !== owner) {
throw new Error(`Item ${itemId} is not owned by ${owner}; use \`inventory\` to see your items`);
}
const txb = new TransactionBlock();
const itemArg = txb.objectRef({ ...item.data });
new KioskTransaction({ txb, kioskClient, cap: kioskCap })
.place({
type: item.data.type,
item: itemArg,
})
.finalize();
return sendTx(txb);
}
/**
* Command: `lock`
* Description: Lock an item in the Kiosk owned by the sender (requires TransferPolicy)
*/
async function lockItem(itemId) {
const cap = await findKioskCap().catch(() => null);
const owner = keypair.getPublicKey().toSuiAddress();
if (cap === null) {
throw new Error('No Kiosk found for sender; use `new` to create one');
}
if (!isValidSuiObjectId(itemId)) {
throw new Error('Invalid Item ID: "%s"', itemId);
}
const item = await client.getObject({
id: itemId,
options: { showType: true, showOwner: true },
});
if ('error' in item || !item.data) {
throw new Error(`Item ${itemId} not found; error: ` + item.error);
}
if (!('AddressOwner' in item.data.owner) || item.data.owner.AddressOwner !== owner) {
throw new Error(`Item ${itemId} is not owned by ${owner}; use \`inventory\` to see your items`);
}
const [policy] = await kioskClient.getTransferPolicies({ type: item.data.type });
if (!policy) {
throw new Error(`Item ${itemId} with type ${item.data.type} does not have a TransferPolicy`);
}
const txb = new TransactionBlock();
const itemArg = txb.objectRef({ ...item.data });
new KioskTransaction({ txb, kioskClient, cap })
.lock({
itemType: item.data.type,
itemId: itemArg,
policy: policy.id,
})
.finalize();
return sendTx(txb);
}
/**
* Command: `take`
* Description: Take an item from the Kiosk and transfer to sender (or to
* --address <address>)
*/
async function takeItem(itemId, { address }) {
const cap = await findKioskCap().catch(() => null);
const receiver = address || keypair.getPublicKey().toSuiAddress();
if (!isValidSuiAddress(receiver)) {
throw new Error('Invalid receiver address: "%s"', receiver);
}
if (!isValidSuiObjectId(itemId)) {
throw new Error('Invalid Item ID: "%s"', itemId);
}
if (cap === null) {
throw new Error('No Kiosk found for sender; use `new` to create one');
}
const item = await client.getObject({ id: itemId, options: { showType: true } });
if ('error' in item || !item.data) {
throw new Error(`Item ${itemId} not found; error: ` + item.error);
}
const txb = new TransactionBlock();
new KioskTransaction({ txb, kioskClient, cap })
.transfer({
itemType: item.data.type,
itemId,
address: receiver,
})
.finalize();
return sendTx(txb);
}
/**
* Command: `list`
* Description: Lists an item in the Kiosk for the specified amount of SUI
*/
async function listItem(itemId, price) {
const cap = await findKioskCap().catch(() => null);
if (cap === null) {
throw new Error('No Kiosk found for sender; use `new` to create one');
}
if (!isValidSuiObjectId(itemId)) {
throw new Error('Invalid Item ID: "%s"', itemId);
}
const item = await client.getObject({ id: itemId, options: { showType: true } });
if ('error' in item || !item.data) {
throw new Error(`Item ${itemId} not found; error: ` + item.error);
}
const txb = new TransactionBlock();
new KioskTransaction({ txb, kioskClient, cap })
.list({
itemType: item.data.type,
itemId,
price,
})
.finalize();
return sendTx(txb);
}
/**
* Command: `delist`
* Description: Delists an active listing in the Kiosk
*/
async function delistItem(itemId) {
const cap = await findKioskCap().catch(() => null);
if (cap === null) {
throw new Error('No Kiosk found for sender; use `new` to create one');
}
if (!isValidSuiObjectId(itemId)) {
throw new Error('Invalid Item ID: "%s"', itemId);
}
const item = await client.getObject({ id: itemId, options: { showType: true } });
if ('error' in item || !item.data) {
throw new Error(`Item ${itemId} not found; error: ` + item.error);
}
const txb = new TransactionBlock();
new KioskTransaction({ txb, kioskClient, cap })
.delist({
itemType: item.data.type,
itemId,
})
.finalize();
return sendTx(txb);
}
/**
* Command: `purchase`
* Description: Purchases an item from the specified Kiosk
*
* TODO:
* - add destination "kiosk" or "user" (kiosk by default)
*/
async function purchaseItem(itemId, opts) {
const { kiosk: inputKioskId } = opts;
if (inputKioskId && !isValidSuiObjectId(inputKioskId)) {
throw new Error('Invalid Kiosk ID: "%s"', inputKioskId);
}
if (!isValidSuiObjectId(itemId)) {
throw new Error('Invalid Item ID: "%s"', itemId);
}
let kioskId = inputKioskId;
const itemInfo = await client.getObject({
id: itemId,
options: { showType: true, showOwner: true },
});
if ('error' in itemInfo || !itemInfo.data) {
throw new Error(`Item ${itemId} not found; ${itemInfo.error}`);
}
if (!('ObjectOwner' in itemInfo.data.owner)) {
throw new Error(`Item ${itemId} is not owned by an object`);
}
if (!kioskId) {
const itemKeyId = itemInfo.data.owner.ObjectOwner;
const itemKey = await client.getObject({ id: itemKeyId, options: { showOwner: true } });
if ('error' in itemKey || !itemKey.data) {
throw new Error(`Dynamic Field ${itemId} key not found; ${itemKey.error}`);
}
if (!('ObjectOwner' in itemKey.data.owner)) {
throw new Error(`Dynamic Field ${itemId} key is not owned by an object`);
}
kioskId = itemKey.data.owner.ObjectOwner;
}
const [kiosk, listing] = await Promise.all([
client.getObject({ id: kioskId, options: { showOwner: true } }),
client.getDynamicFieldObject({
parentId: kioskId,
name: { type: KIOSK_LISTING, value: { id: itemId, is_exclusive: false } },
}),
]);
if ('error' in listing || !listing.data) {
throw new Error(`Item ${itemId} not listed in Kiosk ${kioskId}`);
}
if ('error' in kiosk || !kiosk.data) {
throw new Error(`Kiosk ${kioskId} not found`);
}
if ('error' in itemInfo || !itemInfo.data) {
throw new Error(`Item ${itemId} not found`);
}
const price = listing.data.content.fields.value;
const txb = new TransactionBlock();
const fromKioskArg = txb.object(kiosk.data.objectId);
const cap = await findKioskCap().catch(() => null);
if (cap === null) {
throw new Error(
'No Kiosk found for sender; use `new` to create one; cannot place item to Kiosk',
);
}
const kioskTx = new KioskTransaction({ txb, kioskClient, cap });
(
await kioskTx.purchaseAndResolve({
itemType: itemInfo.data.type,
itemId: itemInfo.data.objectId,
price,
sellerKiosk: fromKioskArg,
})
).finalize();
return sendTx(txb);
}
/**
* Command: `search`
* Description: Searches for items of the specified type
*/
async function searchType(type) {
// use known types if available;
type = KNOWN_TYPES[type] || type;
const [{ data: listed }, { data: delisted }, { data: purchased }] = await Promise.all([
client.queryEvents({
query: { MoveEventType: `0x2::kiosk::ItemListed<${type}>` },
limit: 1000,
}),
client.queryEvents({
query: { MoveEventType: `0x2::kiosk::ItemDelisted<${type}>` },
limit: 1000,
}),
client.queryEvents({
query: { MoveEventType: `0x2::kiosk::ItemPurchased<${type}>` },
limit: 1000,
}),
]);
const listings = listed
.filter((e) => {
const { id: itemId } = e.parsedJson;
const timestamp = e.timestampMs;
return !delisted.some((item) => itemId == item.parsedJson.id && timestamp < item.timestampMs);
})
.filter((e) => {
const { id: itemId } = e.parsedJson;
const timestamp = e.timestampMs;
return !purchased.some(
(item) => itemId == item.parsedJson.id && timestamp < item.timestampMs,
);
});
console.log('- Type:', type);
console.table(
listings.map((e) => ({
objectId: e.parsedJson.id,
kiosk: formatAddress(e.parsedJson.kiosk),
price: e.parsedJson.price,
})),
);
}
async function searchPolicy(type) {
// use known types if available;
type = KNOWN_TYPES[type] || type;
const policies = await kioskClient.getTransferPolicies({ type });
if (policies.length === 0) {
console.log(`No transfer policy found for type ${type}`);
process.exit(0);
}
console.log('- Type: %s', formatType(type));
console.table(
policies.map((policy) => ({
id: policy.id,
owner: 'Shared' in policy.owner ? 'Shared' : 'Owned',
rules: policy.rules.map((rule) => rule.split('::').slice(1).join('::')),
balance: policy.balance,
})),
);
}
/**
* Command: `withdraw`
* Description: Withdraws funds from the Kiosk and send them to sender.
*/
async function withdrawAll() {
const sender = keypair.getPublicKey().toSuiAddress();
const cap = await findKioskCap(sender).catch(() => null);
if (cap === null) {
throw new Error('No Kiosk found for sender; use `new` to create one');
}
const txb = new TransactionBlock();
new KioskTransaction({ txb, kioskClient, cap }).withdraw(sender).finalize();
return sendTx(txb);
}
/**
* Command: `publisher`
* Description: Shows the Publisher objects of the current user.
*/
async function showPublisher() {
const sender = keypair.getPublicKey().toSuiAddress();
const result = await client.getOwnedObjects({
owner: sender,
filter: { StructType: '0x2::package::Publisher' },
options: { showBcs: true },
});
if ('error' in result || !result.data) {
throw new Error(`Error fetching Publisher result: ${result.error}`);
}
if (result.data && result.data.length === 0) {
return console.log('No Publisher objects found for sender');
}
console.table(
result.data.map((o) =>
bcs.de(
{
id: 'address',
package: 'string',
module_name: 'string',
},
o.data.bcs.bcsBytes,
'base64',
),
),
);
}
/**
* Find the KioskOwnerCap at the sender address,
* and sets it on the kioskClient instance.
*/
async function findKioskCap(address) {
const sender = address || keypair.getPublicKey().toSuiAddress();
if (!isValidSuiAddress(sender)) {
throw new Error(`Invalid address "${sender}"`);
}
const { kioskOwnerCaps } = await kioskClient.getOwnedKiosks({ address: sender });
if (kioskOwnerCaps.length === 0) {
throw new Error(`No Kiosk found for "${sender}"`);
}
return kioskOwnerCaps[0];
}
/**
* Send the transaction and print the `object changes: created` result.
* If there are errors, print them.
*/
async function sendTx(txb) {
return client
.signAndExecuteTransactionBlock({
signer: keypair,
transactionBlock: txb,
options: {
showEffects: true,
showObjectChanges: true,
},
})
.then((result) => {
if ('errors' in result) {
console.error('Errors found: %s', result.errors);
} else {
console.table(
result.objectChanges.map((change) => ({
objectId: change.objectId,
type: change.type,
sender: formatAddress(change.sender),
objectType: formatType(change.objectType),
})),
);
}
let gas = result.effects.gasUsed;
let total = BigInt(gas.computationCost) + BigInt(gas.storageCost) - BigInt(gas.storageRebate);
console.log('Computation cost: %s', gas.computationCost);
console.log('Storage cost: %s', gas.storageCost);
console.log('Storage rebate: %s', gas.storageRebate);
console.log('NonRefundable Storage Fee: %s', gas.nonRefundableStorageFee);
console.log(
'Total Gas: %s SUI (%s MIST)',
formatAmount(total),
total.toString(),
);
});
}
/**
* Shortens the type (currently, a little messy).
*/
function formatType(type) {
let knownIdx = Object.values(KNOWN_TYPES).indexOf(type);
if (knownIdx !== -1) {
return Object.keys(KNOWN_TYPES)[knownIdx];
}
type = type.replace('0x2', '2');
while (type.includes('0x')) {
let pos = type.indexOf('0x');
let addr = formatAddress(type.slice(pos, pos + 66)).replace('0x', '');
type = type.replace(type.slice(pos, pos + 66), addr);
}
return '0x' + type;
}
/**
* Formats the MIST into SUI.
*/
function formatAmount(amount) {
if (!amount) {
return null;
}
if (amount <= MIST_PER_SUI) {
return Number(amount) / Number(MIST_PER_SUI);
}
let len = amount.toString().length;
let lhs = amount.toString().slice(0, len - 9);
let rhs = amount.toString().slice(-9);
return Number(`${lhs}.${rhs}`);
}
process.on('uncaughtException', (err) => {
console.error(err);
process.exit(1);
});