@0xobelisk/client 0.3.2 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs DELETED
@@ -1,1263 +0,0 @@
1
- var __accessCheck = (obj, member, msg) => {
2
- if (!member.has(obj))
3
- throw TypeError("Cannot " + msg);
4
- };
5
- var __privateGet = (obj, member, getter) => {
6
- __accessCheck(obj, member, "read from private field");
7
- return getter ? getter.call(obj) : member.get(obj);
8
- };
9
- var __privateAdd = (obj, member, value) => {
10
- if (member.has(obj))
11
- throw TypeError("Cannot add the same private member more than once");
12
- member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
13
- };
14
-
15
- // src/index.ts
16
- export * from "@mysten/sui.js";
17
- import { Ed25519Keypair as Ed25519Keypair3 } from "@mysten/sui.js/keypairs/ed25519";
18
- export * from "@mysten/bcs";
19
-
20
- // src/obelisk.ts
21
- import {
22
- RawSigner,
23
- TransactionBlock as TransactionBlock3
24
- } from "@mysten/sui.js";
25
-
26
- // src/libs/suiAccountManager/index.ts
27
- import { Ed25519Keypair as Ed25519Keypair2 } from "@mysten/sui.js";
28
-
29
- // src/libs/suiAccountManager/keypair.ts
30
- import { Ed25519Keypair } from "@mysten/sui.js";
31
- var getDerivePathForSUI = (derivePathParams = {}) => {
32
- const {
33
- accountIndex = 0,
34
- isExternal = false,
35
- addressIndex = 0
36
- } = derivePathParams;
37
- return `m/44'/784'/${accountIndex}'/${isExternal ? 1 : 0}'/${addressIndex}'`;
38
- };
39
- var getKeyPair = (mnemonics, derivePathParams = {}) => {
40
- const derivePath = getDerivePathForSUI(derivePathParams);
41
- return Ed25519Keypair.deriveKeypair(mnemonics, derivePath);
42
- };
43
-
44
- // src/libs/suiAccountManager/util.ts
45
- import { fromB64 as fromB642 } from "@mysten/sui.js";
46
- var isHex = (str) => /^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(str);
47
- var isBase64 = (str) => /^[a-zA-Z0-9+/]+={0,2}$/g.test(str);
48
- var fromHEX = (hexStr) => {
49
- if (!hexStr) {
50
- throw new Error("cannot parse empty string to Uint8Array");
51
- }
52
- const intArr = hexStr.replace("0x", "").match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16));
53
- if (!intArr || intArr.length === 0) {
54
- throw new Error(`Unable to parse HEX: ${hexStr}`);
55
- }
56
- return Uint8Array.from(intArr);
57
- };
58
- var hexOrBase64ToUint8Array = (str) => {
59
- if (isHex(str)) {
60
- return fromHEX(str);
61
- } else if (isBase64(str)) {
62
- return fromB642(str);
63
- } else {
64
- throw new Error("The string is not a valid hex or base64 string.");
65
- }
66
- };
67
- var PRIVATE_KEY_SIZE = 32;
68
- var LEGACY_PRIVATE_KEY_SIZE = 64;
69
- var normalizePrivateKey = (key) => {
70
- if (key.length === LEGACY_PRIVATE_KEY_SIZE) {
71
- key = key.slice(0, PRIVATE_KEY_SIZE);
72
- } else if (key.length === PRIVATE_KEY_SIZE + 1 && key[0] === 0) {
73
- return key.slice(1);
74
- } else if (key.length === PRIVATE_KEY_SIZE) {
75
- return key;
76
- }
77
- throw new Error("invalid secret key");
78
- };
79
-
80
- // src/libs/suiAccountManager/crypto.ts
81
- import { generateMnemonic as genMnemonic } from "@scure/bip39";
82
- import { wordlist } from "@scure/bip39/wordlists/english";
83
- var generateMnemonic = (numberOfWords = 24) => {
84
- const strength = numberOfWords === 12 ? 128 : 256;
85
- return genMnemonic(wordlist, strength);
86
- };
87
-
88
- // src/libs/suiAccountManager/index.ts
89
- var SuiAccountManager = class {
90
- /**
91
- * Support the following ways to init the SuiToolkit:
92
- * 1. mnemonics
93
- * 2. secretKey (base64 or hex)
94
- * If none of them is provided, will generate a random mnemonics with 24 words.
95
- *
96
- * @param mnemonics, 12 or 24 mnemonics words, separated by space
97
- * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
98
- */
99
- constructor({ mnemonics, secretKey } = {}) {
100
- this.mnemonics = mnemonics || "";
101
- this.secretKey = secretKey || "";
102
- if (!this.mnemonics && !this.secretKey) {
103
- this.mnemonics = generateMnemonic(24);
104
- }
105
- this.currentKeyPair = this.secretKey ? Ed25519Keypair2.fromSecretKey(
106
- normalizePrivateKey(hexOrBase64ToUint8Array(this.secretKey))
107
- ) : getKeyPair(this.mnemonics);
108
- this.currentAddress = this.currentKeyPair.getPublicKey().toSuiAddress();
109
- }
110
- /**
111
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.
112
- * else:
113
- * it will generate keyPair from the mnemonic with the given derivePathParams.
114
- */
115
- getKeyPair(derivePathParams) {
116
- if (!derivePathParams || !this.mnemonics)
117
- return this.currentKeyPair;
118
- return getKeyPair(this.mnemonics, derivePathParams);
119
- }
120
- /**
121
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentAddress.
122
- * else:
123
- * it will generate address from the mnemonic with the given derivePathParams.
124
- */
125
- getAddress(derivePathParams) {
126
- if (!derivePathParams || !this.mnemonics)
127
- return this.currentAddress;
128
- return getKeyPair(this.mnemonics, derivePathParams).getPublicKey().toSuiAddress();
129
- }
130
- /**
131
- * Switch the current account with the given derivePathParams.
132
- * This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.
133
- */
134
- switchAccount(derivePathParams) {
135
- if (this.mnemonics) {
136
- this.currentKeyPair = getKeyPair(this.mnemonics, derivePathParams);
137
- this.currentAddress = this.currentKeyPair.getPublicKey().toSuiAddress();
138
- }
139
- }
140
- };
141
-
142
- // src/libs/suiTxBuilder/index.ts
143
- import {
144
- TransactionBlock as TransactionBlock2,
145
- SUI_SYSTEM_STATE_OBJECT_ID
146
- } from "@mysten/sui.js";
147
-
148
- // src/libs/suiTxBuilder/util.ts
149
- import {
150
- normalizeSuiObjectId
151
- } from "@mysten/sui.js";
152
- var getDefaultSuiInputType = (value) => {
153
- if (typeof value === "string" && value.startsWith("0x")) {
154
- return "object";
155
- } else if (typeof value === "number" || typeof value === "bigint") {
156
- return "u64";
157
- } else if (typeof value === "boolean") {
158
- return "bool";
159
- } else {
160
- return "object";
161
- }
162
- };
163
- function makeVecParam(txBlock, args, type) {
164
- if (args.length === 0)
165
- throw new Error("Transaction builder error: Empty array is not allowed");
166
- const defaultSuiType = getDefaultSuiInputType(args[0]);
167
- if (type === "object" || !type && defaultSuiType === "object") {
168
- const objects = args.map(
169
- (arg) => typeof arg === "string" ? txBlock.object(normalizeSuiObjectId(arg)) : arg
170
- );
171
- return txBlock.makeMoveVec({ objects });
172
- } else {
173
- const vecType = type || defaultSuiType;
174
- return txBlock.pure(args, `vector<${vecType}>`);
175
- }
176
- }
177
- function isMoveVecArg(arg) {
178
- const isFullMoveVecArg = arg && arg.value && Array.isArray(arg.value) && arg.vecType;
179
- const isSimpleMoveVecArg = Array.isArray(arg);
180
- return isFullMoveVecArg || isSimpleMoveVecArg;
181
- }
182
- function convertArgs(txBlock, args) {
183
- return args.map((arg) => {
184
- if (typeof arg === "string" && arg.startsWith("0x")) {
185
- return txBlock.object(normalizeSuiObjectId(arg));
186
- } else if (isMoveVecArg(arg)) {
187
- const vecType = arg.vecType || void 0;
188
- return vecType ? makeVecParam(txBlock, arg.value, vecType) : makeVecParam(txBlock, arg);
189
- } else if (typeof arg !== "object") {
190
- return txBlock.pure(arg);
191
- } else {
192
- return arg;
193
- }
194
- });
195
- }
196
-
197
- // src/libs/suiTxBuilder/index.ts
198
- var SuiTxBlock = class {
199
- constructor(transaction) {
200
- this.txBlock = new TransactionBlock2(transaction);
201
- }
202
- //======== override methods of TransactionBlock ============
203
- address(value) {
204
- return this.txBlock.pure(value, "address");
205
- }
206
- pure(value, type) {
207
- return this.txBlock.pure(value, type);
208
- }
209
- object(value) {
210
- return this.txBlock.object(value);
211
- }
212
- objectRef(ref) {
213
- return this.txBlock.objectRef(ref);
214
- }
215
- sharedObjectRef(ref) {
216
- return this.txBlock.sharedObjectRef(ref);
217
- }
218
- setSender(sender) {
219
- return this.txBlock.setSender(sender);
220
- }
221
- setSenderIfNotSet(sender) {
222
- return this.txBlock.setSenderIfNotSet(sender);
223
- }
224
- setExpiration(expiration) {
225
- return this.txBlock.setExpiration(expiration);
226
- }
227
- setGasPrice(price) {
228
- return this.txBlock.setGasPrice(price);
229
- }
230
- setGasBudget(budget) {
231
- return this.txBlock.setGasBudget(budget);
232
- }
233
- setGasOwner(owner) {
234
- return this.txBlock.setGasOwner(owner);
235
- }
236
- setGasPayment(payments) {
237
- return this.txBlock.setGasPayment(payments);
238
- }
239
- add(transaction) {
240
- return this.txBlock.add(transaction);
241
- }
242
- serialize() {
243
- return this.txBlock.serialize();
244
- }
245
- build(params = {}) {
246
- return this.txBlock.build(params);
247
- }
248
- getDigest({ provider } = {}) {
249
- return this.txBlock.getDigest({ provider });
250
- }
251
- get gas() {
252
- return this.txBlock.gas;
253
- }
254
- get blockData() {
255
- return this.txBlock.blockData;
256
- }
257
- transferObjects(objects, recipient) {
258
- const tx = this.txBlock;
259
- tx.transferObjects(convertArgs(this.txBlock, objects), tx.pure(recipient));
260
- return this;
261
- }
262
- splitCoins(coin, amounts) {
263
- const tx = this.txBlock;
264
- const coinObject = convertArgs(this.txBlock, [coin])[0];
265
- const res = tx.splitCoins(
266
- coinObject,
267
- amounts.map((m) => tx.pure(m))
268
- );
269
- return amounts.map((_, i) => res[i]);
270
- }
271
- mergeCoins(destination, sources) {
272
- const destinationObject = convertArgs(this.txBlock, [destination])[0];
273
- const sourceObjects = convertArgs(this.txBlock, sources);
274
- return this.txBlock.mergeCoins(destinationObject, sourceObjects);
275
- }
276
- publish(...args) {
277
- return this.txBlock.publish(...args);
278
- }
279
- upgrade(...args) {
280
- return this.txBlock.upgrade(...args);
281
- }
282
- makeMoveVec(...args) {
283
- return this.txBlock.makeMoveVec(...args);
284
- }
285
- /**
286
- * @description Move call
287
- * @param target `${string}::${string}::${string}`, e.g. `0x3::sui_system::request_add_stake`
288
- * @param args the arguments of the move call, such as `['0x1', '0x2']`
289
- * @param typeArgs the type arguments of the move call, such as `['0x2::sui::SUI']`
290
- */
291
- moveCall(target, args = [], typeArgs = []) {
292
- const regex = /(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;
293
- const match = target.match(regex);
294
- if (match === null)
295
- throw new Error(
296
- "Invalid target format. Expected `${string}::${string}::${string}`"
297
- );
298
- const convertedArgs = convertArgs(this.txBlock, args);
299
- const tx = this.txBlock;
300
- return tx.moveCall({
301
- target,
302
- arguments: convertedArgs,
303
- typeArguments: typeArgs
304
- });
305
- }
306
- //======== enhance methods ============
307
- transferSuiToMany(recipients, amounts) {
308
- if (recipients.length !== amounts.length) {
309
- throw new Error(
310
- "transferSuiToMany: recipients.length !== amounts.length"
311
- );
312
- }
313
- const tx = this.txBlock;
314
- const coins = tx.splitCoins(
315
- tx.gas,
316
- amounts.map((amount) => tx.pure(amount))
317
- );
318
- recipients.forEach((recipient, index) => {
319
- tx.transferObjects([coins[index]], tx.pure(recipient));
320
- });
321
- return this;
322
- }
323
- transferSui(recipient, amount) {
324
- return this.transferSuiToMany([recipient], [amount]);
325
- }
326
- takeAmountFromCoins(coins, amount) {
327
- const tx = this.txBlock;
328
- const coinObjects = convertArgs(this.txBlock, coins);
329
- const mergedCoin = coinObjects[0];
330
- if (coins.length > 1) {
331
- tx.mergeCoins(mergedCoin, coinObjects.slice(1));
332
- }
333
- const [sendCoin] = tx.splitCoins(mergedCoin, [tx.pure(amount)]);
334
- return [sendCoin, mergedCoin];
335
- }
336
- splitSUIFromGas(amounts) {
337
- const tx = this.txBlock;
338
- return tx.splitCoins(
339
- tx.gas,
340
- amounts.map((m) => tx.pure(m))
341
- );
342
- }
343
- splitMultiCoins(coins, amounts) {
344
- const tx = this.txBlock;
345
- const coinObjects = convertArgs(this.txBlock, coins);
346
- const mergedCoin = coinObjects[0];
347
- if (coins.length > 1) {
348
- tx.mergeCoins(mergedCoin, coinObjects.slice(1));
349
- }
350
- const splitedCoins = tx.splitCoins(
351
- mergedCoin,
352
- amounts.map((m) => tx.pure(m))
353
- );
354
- return { splitedCoins, mergedCoin };
355
- }
356
- transferCoinToMany(inputCoins, sender, recipients, amounts) {
357
- if (recipients.length !== amounts.length) {
358
- throw new Error(
359
- "transferSuiToMany: recipients.length !== amounts.length"
360
- );
361
- }
362
- const tx = this.txBlock;
363
- const { splitedCoins, mergedCoin } = this.splitMultiCoins(
364
- inputCoins,
365
- amounts
366
- );
367
- recipients.forEach((recipient, index) => {
368
- tx.transferObjects([splitedCoins[index]], tx.pure(recipient));
369
- });
370
- tx.transferObjects([mergedCoin], tx.pure(sender));
371
- return this;
372
- }
373
- transferCoin(inputCoins, sender, recipient, amount) {
374
- return this.transferCoinToMany(inputCoins, sender, [recipient], [amount]);
375
- }
376
- stakeSui(amount, validatorAddr) {
377
- const tx = this.txBlock;
378
- const [stakeCoin] = tx.splitCoins(tx.gas, [tx.pure(amount)]);
379
- tx.moveCall({
380
- target: "0x3::sui_system::request_add_stake",
381
- arguments: [
382
- tx.object(SUI_SYSTEM_STATE_OBJECT_ID),
383
- stakeCoin,
384
- tx.pure(validatorAddr)
385
- ]
386
- });
387
- return tx;
388
- }
389
- };
390
-
391
- // src/libs/suiInteractor/suiInteractor.ts
392
- import {
393
- JsonRpcProvider as JsonRpcProvider2,
394
- Connection,
395
- getObjectDisplay,
396
- getObjectFields,
397
- getObjectId,
398
- getObjectType,
399
- getObjectVersion,
400
- getSharedObjectInitialVersion
401
- } from "@mysten/sui.js";
402
- import { requestSuiFromFaucetV0, getFaucetHost } from "@mysten/sui.js/faucet";
403
-
404
- // src/libs/suiModel/suiOwnedObject.ts
405
- import {
406
- getObjectChanges
407
- } from "@mysten/sui.js";
408
- var SuiOwnedObject = class {
409
- constructor(param) {
410
- this.objectId = param.objectId;
411
- this.version = param.version;
412
- this.digest = param.digest;
413
- }
414
- /**
415
- * Check if the object is fully initialized.
416
- * So that when it's used as an input, it won't be necessary to fetch from fullnode again.
417
- * Which can save time when sending transactions.
418
- */
419
- isFullObject() {
420
- return !!this.version && !!this.digest;
421
- }
422
- asCallArg() {
423
- if (!this.version || !this.digest) {
424
- return this.objectId;
425
- }
426
- return {
427
- Object: {
428
- ImmOrOwned: {
429
- objectId: this.objectId,
430
- version: this.version,
431
- digest: this.digest
432
- }
433
- }
434
- };
435
- }
436
- /**
437
- * Update object version & digest based on the transaction response.
438
- * @param txResponse
439
- */
440
- updateFromTxResponse(txResponse) {
441
- const changes = getObjectChanges(txResponse);
442
- if (!changes) {
443
- throw new Error("Bad transaction response!");
444
- }
445
- for (const change of changes) {
446
- if (change.type === "mutated" && change.objectId === this.objectId) {
447
- this.digest = change.digest;
448
- this.version = change.version;
449
- return;
450
- }
451
- }
452
- throw new Error("Could not find object in transaction response!");
453
- }
454
- };
455
-
456
- // src/libs/suiModel/suiSharedObject.ts
457
- var SuiSharedObject = class {
458
- constructor(param) {
459
- this.objectId = param.objectId;
460
- this.initialSharedVersion = param.initialSharedVersion;
461
- }
462
- asCallArg(mutable = false) {
463
- if (!this.initialSharedVersion) {
464
- return this.objectId;
465
- }
466
- return {
467
- Object: {
468
- Shared: {
469
- objectId: this.objectId,
470
- initialSharedVersion: this.initialSharedVersion,
471
- mutable
472
- }
473
- }
474
- };
475
- }
476
- };
477
-
478
- // src/libs/suiInteractor/util.ts
479
- var delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
480
-
481
- // src/libs/suiInteractor/suiInteractor.ts
482
- var SuiInteractor = class {
483
- constructor(fullNodeUrls, network) {
484
- if (fullNodeUrls.length === 0)
485
- throw new Error("fullNodeUrls must not be empty");
486
- this.providers = fullNodeUrls.map(
487
- (url) => new JsonRpcProvider2(new Connection({ fullnode: url }))
488
- );
489
- this.currentProvider = this.providers[0];
490
- this.network = network;
491
- }
492
- switchToNextProvider() {
493
- const currentProviderIdx = this.providers.indexOf(this.currentProvider);
494
- this.currentProvider = this.providers[(currentProviderIdx + 1) % this.providers.length];
495
- }
496
- async sendTx(transactionBlock, signature) {
497
- const txResOptions = {
498
- showEvents: true,
499
- showEffects: true,
500
- showObjectChanges: true,
501
- showBalanceChanges: true
502
- };
503
- for (const provider of this.providers) {
504
- try {
505
- const res = await provider.executeTransactionBlock({
506
- transactionBlock,
507
- signature,
508
- options: txResOptions
509
- });
510
- return res;
511
- } catch (err) {
512
- console.warn(
513
- `Failed to send transaction with fullnode ${provider.connection.fullnode}: ${err}`
514
- );
515
- await delay(2e3);
516
- }
517
- }
518
- throw new Error("Failed to send transaction with all fullnodes");
519
- }
520
- async getObjects(ids) {
521
- const options = {
522
- showContent: true,
523
- showDisplay: true,
524
- showType: true,
525
- showOwner: true
526
- };
527
- for (const provider of this.providers) {
528
- try {
529
- const objects = await provider.multiGetObjects({ ids, options });
530
- const parsedObjects = objects.map((object) => {
531
- const objectId = getObjectId(object);
532
- const objectType = getObjectType(object);
533
- const objectVersion = getObjectVersion(object);
534
- const objectDigest = object.data ? object.data.digest : void 0;
535
- const initialSharedVersion = getSharedObjectInitialVersion(object);
536
- const objectFields = getObjectFields(object);
537
- const objectDisplay = getObjectDisplay(object);
538
- return {
539
- objectId,
540
- objectType,
541
- objectVersion,
542
- objectDigest,
543
- objectFields,
544
- objectDisplay,
545
- initialSharedVersion
546
- };
547
- });
548
- return parsedObjects;
549
- } catch (err) {
550
- await delay(2e3);
551
- console.warn(
552
- `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
553
- );
554
- }
555
- }
556
- throw new Error("Failed to get objects with all fullnodes");
557
- }
558
- async getObject(id) {
559
- const objects = await this.getObjects([id]);
560
- return objects[0];
561
- }
562
- async getEntitiesObjects(ids) {
563
- const options = {
564
- showContent: true,
565
- showType: true
566
- };
567
- for (const provider of this.providers) {
568
- try {
569
- const objects = await provider.multiGetObjects({ ids, options });
570
- const parsedObjects = objects.map((object) => {
571
- const objectId = getObjectId(object);
572
- const objectFields = getObjectFields(object);
573
- const index = objectFields.name;
574
- const key = objectFields.value;
575
- return {
576
- objectId,
577
- index,
578
- key
579
- };
580
- });
581
- return parsedObjects;
582
- } catch (err) {
583
- await delay(2e3);
584
- console.warn(
585
- `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
586
- );
587
- }
588
- }
589
- throw new Error("Failed to get objects with all fullnodes");
590
- }
591
- async getDynamicFieldObject(parentId, name) {
592
- for (const provider of this.providers) {
593
- try {
594
- return provider.getDynamicFieldObject({ parentId, name });
595
- } catch (err) {
596
- await delay(2e3);
597
- console.warn(
598
- `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
599
- );
600
- }
601
- }
602
- throw new Error("Failed to get objects with all fullnodes");
603
- }
604
- async getDynamicFields(parentId, cursor, limit) {
605
- for (const provider of this.providers) {
606
- try {
607
- return provider.getDynamicFields({ parentId, cursor, limit });
608
- } catch (err) {
609
- await delay(2e3);
610
- console.warn(
611
- `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
612
- );
613
- }
614
- }
615
- throw new Error("Failed to get objects with all fullnodes");
616
- }
617
- async getOwnedObjects(owner, cursor, limit) {
618
- for (const provider of this.providers) {
619
- try {
620
- return await provider.getOwnedObjects({ owner, cursor, limit });
621
- } catch (err) {
622
- await delay(2e3);
623
- console.warn(
624
- `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
625
- );
626
- }
627
- }
628
- throw new Error("Failed to get objects with all fullnodes");
629
- }
630
- async getNormalizedMoveModulesByPackage(packageId) {
631
- for (const provider of this.providers) {
632
- try {
633
- return provider.getNormalizedMoveModulesByPackage({
634
- package: packageId
635
- });
636
- } catch (err) {
637
- await delay(2e3);
638
- console.warn(
639
- `Failed to get objects with fullnode ${provider.connection.fullnode}: ${err}`
640
- );
641
- }
642
- }
643
- throw new Error("Failed to get objects with all fullnodes");
644
- }
645
- /**
646
- * @description Update objects in a batch
647
- * @param suiObjects
648
- */
649
- async updateObjects(suiObjects) {
650
- const objectIds = suiObjects.map((obj) => obj.objectId);
651
- const objects = await this.getObjects(objectIds);
652
- for (const object of objects) {
653
- const suiObject = suiObjects.find(
654
- (obj) => obj.objectId === object.objectId
655
- );
656
- if (suiObject instanceof SuiSharedObject) {
657
- suiObject.initialSharedVersion = object.initialSharedVersion;
658
- } else if (suiObject instanceof SuiOwnedObject) {
659
- suiObject.version = object.objectVersion;
660
- suiObject.digest = object.objectDigest;
661
- }
662
- }
663
- }
664
- /**
665
- * @description Select coins that add up to the given amount.
666
- * @param addr the address of the owner
667
- * @param amount the amount that is needed for the coin
668
- * @param coinType the coin type, default is '0x2::SUI::SUI'
669
- */
670
- async selectCoins(addr, amount, coinType = "0x2::SUI::SUI") {
671
- const selectedCoins = [];
672
- let totalAmount = 0;
673
- let hasNext = true, nextCursor = null;
674
- while (hasNext && totalAmount < amount) {
675
- const coins = await this.currentProvider.getCoins({
676
- owner: addr,
677
- coinType,
678
- cursor: nextCursor
679
- });
680
- coins.data.sort((a, b) => parseInt(b.balance) - parseInt(a.balance));
681
- for (const coinData of coins.data) {
682
- selectedCoins.push({
683
- objectId: coinData.coinObjectId,
684
- digest: coinData.digest,
685
- version: coinData.version
686
- });
687
- totalAmount = totalAmount + parseInt(coinData.balance);
688
- if (totalAmount >= amount) {
689
- break;
690
- }
691
- }
692
- nextCursor = coins.nextCursor;
693
- hasNext = coins.hasNextPage;
694
- }
695
- if (!selectedCoins.length) {
696
- throw new Error("No valid coins found for the transaction.");
697
- }
698
- return selectedCoins;
699
- }
700
- async requestFaucet(address, network) {
701
- await requestSuiFromFaucetV0({
702
- host: getFaucetHost(network),
703
- recipient: address
704
- });
705
- }
706
- };
707
-
708
- // src/libs/suiInteractor/defaultConfig.ts
709
- import {
710
- localnetConnection,
711
- devnetConnection,
712
- testnetConnection,
713
- mainnetConnection
714
- } from "@mysten/sui.js";
715
- var defaultGasBudget = 10 ** 8;
716
- var getDefaultConnection = (networkType = "devnet") => {
717
- switch (networkType) {
718
- case "localnet":
719
- return localnetConnection;
720
- case "devnet":
721
- return devnetConnection;
722
- case "testnet":
723
- return testnetConnection;
724
- case "mainnet":
725
- return mainnetConnection;
726
- default:
727
- return devnetConnection;
728
- }
729
- };
730
-
731
- // src/libs/suiContractFactory/index.ts
732
- var SuiContractFactory = class {
733
- // readonly #query: MapMessageQuery<ApiTypes> = {};
734
- // readonly #tx: MapMessageTx<ApiTypes> = {};
735
- /**
736
- * Support the following ways to init the SuiToolkit:
737
- * 1. mnemonics
738
- * 2. secretKey (base64 or hex)
739
- * If none of them is provided, will generate a random mnemonics with 24 words.
740
- *
741
- * @param mnemonics, 12 or 24 mnemonics words, separated by space
742
- * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
743
- */
744
- constructor({ packageId, metadata } = {}) {
745
- this.packageId = packageId || "";
746
- this.metadata = metadata || void 0;
747
- }
748
- getFuncByModuleName(moduleName) {
749
- Object.values(this.metadata).forEach(
750
- (value) => {
751
- const data = value;
752
- console.log(`moudle name: ${data.name}`);
753
- Object.entries(data.exposedFunctions).forEach(([key, value2]) => {
754
- console.log(` func name: ${key}`);
755
- Object.values(value2.parameters).forEach((values) => {
756
- });
757
- });
758
- }
759
- );
760
- }
761
- getAllFunc() {
762
- Object.values(this.metadata).forEach(
763
- (value) => {
764
- const data = value;
765
- console.log(`moudle name: ${data.name}`);
766
- Object.entries(data.exposedFunctions).forEach(([key, value2]) => {
767
- console.log(` func name: ${key}`);
768
- console.log(` ${value2.parameters.length}`);
769
- Object.values(value2.parameters).forEach((values) => {
770
- console.log(` args: ${values}`);
771
- });
772
- });
773
- }
774
- );
775
- }
776
- getAllModule() {
777
- Object.values(this.metadata).forEach(
778
- (value, index) => {
779
- const data = value;
780
- console.log(`${index}. ${data.name}`);
781
- }
782
- );
783
- }
784
- // async call(arguments: ({
785
- // kind: "Input";
786
- // index: number;
787
- // type?: "object" | "pure" | undefined;
788
- // value?: any;
789
- // } | {
790
- // kind: "GasCoin";
791
- // } | {
792
- // kind: "Result";
793
- // index: number;
794
- // } | {
795
- // kind: "NestedResult";
796
- // index: number;
797
- // resultIndex: number;
798
- // })[], derivePathParams?: DerivePathParams) {
799
- // const tx = new TransactionBlock();
800
- // tx.moveCall({
801
- // target: `${this.packageId}::${}::${}`,
802
- // arguments,
803
- // })
804
- // return ;
805
- // }
806
- };
807
-
808
- // src/utils/index.ts
809
- function normalizeHexAddress(input) {
810
- const hexRegex = /^(0x)?[0-9a-fA-F]{64}$/;
811
- if (hexRegex.test(input)) {
812
- if (input.startsWith("0x")) {
813
- return input;
814
- } else {
815
- return "0x" + input;
816
- }
817
- } else {
818
- return null;
819
- }
820
- }
821
- function numberToAddressHex(num) {
822
- const hex = num.toString(16);
823
- const paddedHex = "0x" + hex.padStart(64, "0");
824
- return paddedHex;
825
- }
826
-
827
- // src/obelisk.ts
828
- import keccak256 from "keccak256";
829
- import { BCS, getSuiMoveConfig } from "@mysten/bcs";
830
- function isUndefined(value) {
831
- return value === void 0;
832
- }
833
- function withMeta(meta, creator) {
834
- creator.meta = meta;
835
- return creator;
836
- }
837
- function createQuery(meta, fn) {
838
- return withMeta(
839
- meta,
840
- async (tx, params, isRaw) => {
841
- const result = await fn(tx, params, isRaw);
842
- return result;
843
- }
844
- );
845
- }
846
- function createTx(meta, fn) {
847
- return withMeta(
848
- meta,
849
- async (tx, params, isRaw) => {
850
- const result = await fn(tx, params, isRaw);
851
- return result;
852
- }
853
- );
854
- }
855
- var _query, _tx, _exec, _read;
856
- var Obelisk = class {
857
- /**
858
- * Support the following ways to init the ObeliskClient:
859
- * 1. mnemonics
860
- * 2. secretKey (base64 or hex)
861
- * If none of them is provided, will generate a random mnemonics with 24 words.
862
- *
863
- * @param mnemonics, 12 or 24 mnemonics words, separated by space
864
- * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
865
- * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
866
- * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type
867
- * @param packageId
868
- */
869
- constructor({
870
- mnemonics,
871
- secretKey,
872
- networkType,
873
- fullnodeUrls,
874
- packageId,
875
- metadata
876
- } = {}) {
877
- __privateAdd(this, _query, {});
878
- __privateAdd(this, _tx, {});
879
- __privateAdd(this, _exec, async (meta, tx, params, isRaw) => {
880
- tx.moveCall({
881
- target: `${this.contractFactory.packageId}::${meta.moudleName}::${meta.funcName}`,
882
- arguments: params
883
- });
884
- if (isRaw === true) {
885
- return tx;
886
- }
887
- return await this.signAndSendTxn(tx);
888
- });
889
- __privateAdd(this, _read, async (meta, tx, params, isRaw) => {
890
- tx.moveCall({
891
- target: `${this.contractFactory.packageId}::${meta.moudleName}::${meta.funcName}`,
892
- arguments: params
893
- });
894
- if (isRaw === true) {
895
- return tx;
896
- }
897
- return await this.inspectTxn(tx);
898
- });
899
- this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
900
- fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
901
- this.suiInteractor = new SuiInteractor(fullnodeUrls, networkType);
902
- this.packageId = packageId;
903
- if (metadata !== void 0) {
904
- this.metadata = metadata;
905
- Object.values(metadata).forEach((value) => {
906
- const data = value;
907
- const moduleName = data.name;
908
- Object.entries(data.exposedFunctions).forEach(([funcName, value2]) => {
909
- const meta = value2;
910
- meta.moudleName = moduleName;
911
- meta.funcName = funcName;
912
- if (isUndefined(__privateGet(this, _query)[moduleName])) {
913
- __privateGet(this, _query)[moduleName] = {};
914
- }
915
- if (isUndefined(__privateGet(this, _query)[moduleName][funcName])) {
916
- __privateGet(this, _query)[moduleName][funcName] = createQuery(
917
- meta,
918
- (tx, p, isRaw) => __privateGet(this, _read).call(this, meta, tx, p, isRaw)
919
- );
920
- }
921
- if (isUndefined(__privateGet(this, _tx)[moduleName])) {
922
- __privateGet(this, _tx)[moduleName] = {};
923
- }
924
- if (isUndefined(__privateGet(this, _tx)[moduleName][funcName])) {
925
- __privateGet(this, _tx)[moduleName][funcName] = createTx(
926
- meta,
927
- (tx, p, isRaw) => __privateGet(this, _exec).call(this, meta, tx, p, isRaw)
928
- );
929
- }
930
- });
931
- });
932
- }
933
- this.contractFactory = new SuiContractFactory({
934
- packageId,
935
- metadata
936
- });
937
- }
938
- get query() {
939
- return __privateGet(this, _query);
940
- }
941
- get tx() {
942
- return __privateGet(this, _tx);
943
- }
944
- /**
945
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner.
946
- * else:
947
- * it will generate signer from the mnemonic with the given derivePathParams.
948
- * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
949
- */
950
- getSigner(derivePathParams) {
951
- const keyPair = this.accountManager.getKeyPair(derivePathParams);
952
- return new RawSigner(keyPair, this.suiInteractor.currentProvider);
953
- }
954
- /**
955
- * @description Switch the current account with the given derivePathParams
956
- * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
957
- */
958
- switchAccount(derivePathParams) {
959
- this.accountManager.switchAccount(derivePathParams);
960
- }
961
- /**
962
- * @description Get the address of the account for the given derivePathParams
963
- * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
964
- */
965
- getAddress(derivePathParams) {
966
- return this.accountManager.getAddress(derivePathParams);
967
- }
968
- currentAddress() {
969
- return this.accountManager.currentAddress;
970
- }
971
- provider() {
972
- return this.suiInteractor.currentProvider;
973
- }
974
- getPackageId() {
975
- return this.contractFactory.packageId;
976
- }
977
- getMetadata() {
978
- return this.contractFactory.metadata;
979
- }
980
- /**
981
- * Request some SUI from faucet
982
- * @Returns {Promise<boolean>}, true if the request is successful, false otherwise.
983
- */
984
- async requestFaucet(address, network) {
985
- return this.suiInteractor.requestFaucet(address, network);
986
- }
987
- async getBalance(coinType, derivePathParams) {
988
- const owner = this.accountManager.getAddress(derivePathParams);
989
- return this.suiInteractor.currentProvider.getBalance({ owner, coinType });
990
- }
991
- async getObject(objectId) {
992
- return this.suiInteractor.getObject(objectId);
993
- }
994
- async getObjects(objectIds) {
995
- return this.suiInteractor.getObjects(objectIds);
996
- }
997
- async signTxn(tx, derivePathParams) {
998
- tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
999
- const signer = this.getSigner(derivePathParams);
1000
- return signer.signTransactionBlock({ transactionBlock: tx });
1001
- }
1002
- async signAndSendTxn(tx, derivePathParams) {
1003
- const { transactionBlockBytes, signature } = await this.signTxn(
1004
- tx,
1005
- derivePathParams
1006
- );
1007
- return this.suiInteractor.sendTx(transactionBlockBytes, signature);
1008
- }
1009
- /**
1010
- * Transfer the given amount of SUI to the recipient
1011
- * @param recipient
1012
- * @param amount
1013
- * @param derivePathParams
1014
- */
1015
- async transferSui(recipient, amount, derivePathParams) {
1016
- const tx = new SuiTxBlock();
1017
- tx.transferSui(recipient, amount);
1018
- return this.signAndSendTxn(tx, derivePathParams);
1019
- }
1020
- /**
1021
- * Transfer to mutliple recipients
1022
- * @param recipients the recipients addresses
1023
- * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients
1024
- * @param derivePathParams
1025
- */
1026
- async transferSuiToMany(recipients, amounts, derivePathParams) {
1027
- const tx = new SuiTxBlock();
1028
- tx.transferSuiToMany(recipients, amounts);
1029
- return this.signAndSendTxn(tx, derivePathParams);
1030
- }
1031
- /**
1032
- * Transfer the given amounts of coin to multiple recipients
1033
- * @param recipients the list of recipient address
1034
- * @param amounts the amounts to transfer for each recipient
1035
- * @param coinType any custom coin type but not SUI
1036
- * @param derivePathParams the derive path params for the current signer
1037
- */
1038
- async transferCoinToMany(recipients, amounts, coinType, derivePathParams) {
1039
- const tx = new SuiTxBlock();
1040
- const owner = this.accountManager.getAddress(derivePathParams);
1041
- const totalAmount = amounts.reduce((a, b) => a + b, 0);
1042
- const coins = await this.suiInteractor.selectCoins(
1043
- owner,
1044
- totalAmount,
1045
- coinType
1046
- );
1047
- tx.transferCoinToMany(
1048
- coins.map((c) => c.objectId),
1049
- owner,
1050
- recipients,
1051
- amounts
1052
- );
1053
- return this.signAndSendTxn(tx, derivePathParams);
1054
- }
1055
- async transferCoin(recipient, amount, coinType, derivePathParams) {
1056
- return this.transferCoinToMany(
1057
- [recipient],
1058
- [amount],
1059
- coinType,
1060
- derivePathParams
1061
- );
1062
- }
1063
- async transferObjects(objects, recipient, derivePathParams) {
1064
- const tx = new SuiTxBlock();
1065
- tx.transferObjects(objects, recipient);
1066
- return this.signAndSendTxn(tx, derivePathParams);
1067
- }
1068
- async moveCall(callParams) {
1069
- const {
1070
- target,
1071
- arguments: args = [],
1072
- typeArguments = [],
1073
- derivePathParams
1074
- } = callParams;
1075
- const tx = new SuiTxBlock();
1076
- tx.moveCall(target, args, typeArguments);
1077
- return this.signAndSendTxn(tx, derivePathParams);
1078
- }
1079
- /**
1080
- * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount
1081
- * @param amount
1082
- * @param coinType
1083
- * @param owner
1084
- */
1085
- async selectCoinsWithAmount(amount, coinType, owner) {
1086
- owner = owner || this.accountManager.currentAddress;
1087
- const coins = await this.suiInteractor.selectCoins(owner, amount, coinType);
1088
- return coins.map((c) => c.objectId);
1089
- }
1090
- /**
1091
- * stake the given amount of SUI to the validator
1092
- * @param amount the amount of SUI to stake
1093
- * @param validatorAddr the validator address
1094
- * @param derivePathParams the derive path params for the current signer
1095
- */
1096
- async stakeSui(amount, validatorAddr, derivePathParams) {
1097
- const tx = new SuiTxBlock();
1098
- tx.stakeSui(amount, validatorAddr);
1099
- return this.signAndSendTxn(tx, derivePathParams);
1100
- }
1101
- /**
1102
- * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction.
1103
- * Since the transaction is not submitted, its gas cost is not charged.
1104
- * @param tx the transaction to execute
1105
- * @param derivePathParams the derive path params
1106
- * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted.
1107
- */
1108
- async inspectTxn(tx, derivePathParams) {
1109
- tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
1110
- return this.suiInteractor.currentProvider.devInspectTransactionBlock({
1111
- transactionBlock: tx,
1112
- sender: this.getAddress(derivePathParams)
1113
- });
1114
- }
1115
- async getWorld(worldObjectId) {
1116
- return this.suiInteractor.getObject(worldObjectId);
1117
- }
1118
- async listSchemaNames(worldId) {
1119
- const worldObject = await this.getObject(worldId);
1120
- const newObjectContent = worldObject.objectFields;
1121
- return newObjectContent["schemaNames"];
1122
- }
1123
- async getEntity(worldId, schemaName, entityId) {
1124
- const schemaMoudleName = `${schemaName}_schema`;
1125
- const tx = new TransactionBlock3();
1126
- const params = [tx.pure(worldId)];
1127
- if (entityId !== void 0) {
1128
- params.push(tx.pure(entityId));
1129
- }
1130
- const getResult = await this.query[schemaMoudleName].get(
1131
- tx,
1132
- params
1133
- );
1134
- const returnValue = [];
1135
- if (getResult.effects.status.status === "success") {
1136
- const resultList = getResult.results[0].returnValues;
1137
- for (const res of resultList) {
1138
- const bcs = new BCS(getSuiMoveConfig());
1139
- const value = Uint8Array.from(res[0]);
1140
- const data = bcs.de(res[1], value);
1141
- returnValue.push(data);
1142
- }
1143
- return returnValue;
1144
- } else {
1145
- return void 0;
1146
- }
1147
- }
1148
- async containEntity(worldId, schemaName, entityId) {
1149
- const schemaMoudleName = `${schemaName}_schema`;
1150
- const tx = new TransactionBlock3();
1151
- const params = [tx.pure(worldId)];
1152
- if (entityId !== void 0) {
1153
- params.push(tx.pure(entityId));
1154
- }
1155
- const getResult = await this.query[schemaMoudleName].contains(
1156
- tx,
1157
- params
1158
- );
1159
- if (getResult.effects.status.status === "success") {
1160
- const res = getResult.results[0].returnValues[0];
1161
- const bcs = new BCS(getSuiMoveConfig());
1162
- const value = Uint8Array.from(res[0]);
1163
- return bcs.de(res[1], value);
1164
- } else {
1165
- return void 0;
1166
- }
1167
- }
1168
- // async getEntities(
1169
- // worldId: string,
1170
- // schemaName: string,
1171
- // cursor?: string,
1172
- // limit?: number
1173
- // ) {
1174
- // let schemaMoudleName = `${schemaName}_schema`;
1175
- // const tx = new TransactionBlock();
1176
- // let params = [tx.pure(worldId)] as SuiTxArgument[];
1177
- // const tableResult = (await this.query[schemaonentMoudleName].entities(
1178
- // tx,
1179
- // params
1180
- // )) as DevInspectResults;
1181
- // const entities = tableResult.results as SuiReturnValues;
1182
- // const bcs = new BCS(getSuiMoveConfig());
1183
- // let value = Uint8Array.from(entities[0].returnValues[0][0]);
1184
- // let tableId = '0x' + bcs.de('address', value);
1185
- // let dynamicFields = await this.suiInteractor.getDynamicFields(
1186
- // tableId,
1187
- // cursor,
1188
- // limit
1189
- // );
1190
- // let objectIds = dynamicFields.data.map((field) => field.objectId);
1191
- // let objectDatas = await this.suiInteractor.getEntitiesObjects(objectIds);
1192
- // return {
1193
- // data: objectDatas,
1194
- // nextCursor: dynamicFields.nextCursor,
1195
- // hasNextPage: dynamicFields.hasNextPage,
1196
- // };
1197
- // }
1198
- async getOwnedObjects(owner, cursor, limit) {
1199
- const ownedObjects = await this.suiInteractor.getOwnedObjects(
1200
- owner,
1201
- cursor,
1202
- limit
1203
- );
1204
- const ownedObjectsRes = [];
1205
- for (const object of ownedObjects.data) {
1206
- const objectDetail = await this.getObject(object.data.objectId);
1207
- if (objectDetail.objectType.split("::")[0] === this.contractFactory.packageId) {
1208
- ownedObjectsRes.push(objectDetail);
1209
- }
1210
- }
1211
- return ownedObjectsRes;
1212
- }
1213
- async entity_key_from_object(objectId) {
1214
- const checkObjectId = normalizeHexAddress(objectId);
1215
- if (checkObjectId !== null) {
1216
- objectId = checkObjectId;
1217
- return objectId;
1218
- } else {
1219
- return void 0;
1220
- }
1221
- }
1222
- async entity_key_from_bytes(bytes) {
1223
- const hashBytes = keccak256(bytes);
1224
- const hashU8Array = Array.from(hashBytes);
1225
- const bcs = new BCS(getSuiMoveConfig());
1226
- const value = Uint8Array.from(hashU8Array);
1227
- const data = bcs.de("address", value);
1228
- return "0x" + data;
1229
- }
1230
- async entity_key_from_u256(x) {
1231
- return numberToAddressHex(x);
1232
- }
1233
- async formatData(type, value) {
1234
- const bcs = new BCS(getSuiMoveConfig());
1235
- const u8Value = Uint8Array.from(value);
1236
- return bcs.de(type, u8Value);
1237
- }
1238
- };
1239
- _query = new WeakMap();
1240
- _tx = new WeakMap();
1241
- _exec = new WeakMap();
1242
- _read = new WeakMap();
1243
-
1244
- // src/metadata/index.ts
1245
- async function getMetadata(networkType, packageId) {
1246
- const fullnodeUrls = [getDefaultConnection(networkType).fullnode];
1247
- const suiInteractor = new SuiInteractor(fullnodeUrls);
1248
- if (packageId !== void 0) {
1249
- const jsonData = await suiInteractor.getNormalizedMoveModulesByPackage(packageId);
1250
- return jsonData;
1251
- } else {
1252
- console.error("please set your package id.");
1253
- }
1254
- }
1255
- export {
1256
- Ed25519Keypair3 as Ed25519Keypair,
1257
- Obelisk,
1258
- SuiAccountManager,
1259
- SuiContractFactory,
1260
- SuiTxBlock,
1261
- getMetadata
1262
- };
1263
- //# sourceMappingURL=index.mjs.map