@0xobelisk/sui-client 0.4.9

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.
Files changed (47) hide show
  1. package/LICENSE +92 -0
  2. package/README.md +284 -0
  3. package/dist/index.d.ts +9 -0
  4. package/dist/index.js +1311 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/index.mjs +1292 -0
  7. package/dist/index.mjs.map +1 -0
  8. package/dist/libs/suiAccountManager/crypto.d.ts +1 -0
  9. package/dist/libs/suiAccountManager/index.d.ts +35 -0
  10. package/dist/libs/suiAccountManager/keypair.d.ts +21 -0
  11. package/dist/libs/suiAccountManager/util.d.ts +29 -0
  12. package/dist/libs/suiContractFactory/index.d.ts +20 -0
  13. package/dist/libs/suiContractFactory/types.d.ts +49 -0
  14. package/dist/libs/suiInteractor/defaultConfig.d.ts +10 -0
  15. package/dist/libs/suiInteractor/index.d.ts +2 -0
  16. package/dist/libs/suiInteractor/suiInteractor.d.ts +204 -0
  17. package/dist/libs/suiInteractor/util.d.ts +1 -0
  18. package/dist/libs/suiModel/index.d.ts +2 -0
  19. package/dist/libs/suiModel/suiOwnedObject.d.ts +24 -0
  20. package/dist/libs/suiModel/suiSharedObject.d.ts +12 -0
  21. package/dist/libs/suiTxBuilder/index.d.ts +544 -0
  22. package/dist/libs/suiTxBuilder/util.d.ts +76 -0
  23. package/dist/metadata/index.d.ts +34 -0
  24. package/dist/obelisk.d.ts +2568 -0
  25. package/dist/types/index.d.ts +141 -0
  26. package/dist/utils/index.d.ts +3 -0
  27. package/package.json +149 -0
  28. package/src/index.ts +9 -0
  29. package/src/libs/suiAccountManager/crypto.ts +7 -0
  30. package/src/libs/suiAccountManager/index.ts +72 -0
  31. package/src/libs/suiAccountManager/keypair.ts +38 -0
  32. package/src/libs/suiAccountManager/util.ts +70 -0
  33. package/src/libs/suiContractFactory/index.ts +120 -0
  34. package/src/libs/suiContractFactory/types.ts +61 -0
  35. package/src/libs/suiInteractor/defaultConfig.ts +32 -0
  36. package/src/libs/suiInteractor/index.ts +2 -0
  37. package/src/libs/suiInteractor/suiInteractor.ts +302 -0
  38. package/src/libs/suiInteractor/util.ts +2 -0
  39. package/src/libs/suiModel/index.ts +2 -0
  40. package/src/libs/suiModel/suiOwnedObject.ts +62 -0
  41. package/src/libs/suiModel/suiSharedObject.ts +33 -0
  42. package/src/libs/suiTxBuilder/index.ts +245 -0
  43. package/src/libs/suiTxBuilder/util.ts +84 -0
  44. package/src/metadata/index.ts +22 -0
  45. package/src/obelisk.ts +636 -0
  46. package/src/types/index.ts +211 -0
  47. package/src/utils/index.ts +23 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,1292 @@
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
+ import { BCS as BCS2, getSuiMoveConfig as getSuiMoveConfig2 } 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 typeArguments the type arguments of the move call, such as `['0x2::sui::SUI']`
290
+ */
291
+ moveCall(target, args = [], typeArguments = []) {
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
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: string[]) {
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) as ObjectFieldType;
573
+ // const index = objectFields.name;
574
+ // const key = objectFields.value;
575
+ // return {
576
+ // objectId,
577
+ // index,
578
+ // key,
579
+ // };
580
+ // });
581
+ // return parsedObjects as EntityData[];
582
+ // } catch (err) {
583
+ // await delay(2000);
584
+ // console.warn(
585
+ // `Failed to get EntitiesObjects with fullnode ${provider.connection.fullnode}: ${err}`
586
+ // );
587
+ // }
588
+ // }
589
+ // throw new Error('Failed to get EntitiesObjects 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 DynamicFieldObject with fullnode ${provider.connection.fullnode}: ${err}`
599
+ );
600
+ }
601
+ }
602
+ throw new Error("Failed to get DynamicFieldObject 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 DynamicFields with fullnode ${provider.connection.fullnode}: ${err}`
612
+ );
613
+ }
614
+ }
615
+ throw new Error("Failed to get DynamicFields 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 OwnedObjects with fullnode ${provider.connection.fullnode}: ${err}`
625
+ );
626
+ }
627
+ }
628
+ throw new Error("Failed to get OwnedObjects 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 NormalizedMoveModules with fullnode ${provider.connection.fullnode}: ${err}`
640
+ );
641
+ }
642
+ }
643
+ throw new Error("Failed to get NormalizedMoveModules 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, typeArguments, isRaw) => {
841
+ const result = await fn(tx, params, typeArguments, isRaw);
842
+ return result;
843
+ }
844
+ );
845
+ }
846
+ function createTx(meta, fn) {
847
+ return withMeta(
848
+ meta,
849
+ async (tx, params, typeArguments, isRaw) => {
850
+ return await fn(tx, params, typeArguments, isRaw);
851
+ }
852
+ );
853
+ }
854
+ var _query, _tx, _exec, _read;
855
+ var Obelisk = class {
856
+ /**
857
+ * Support the following ways to init the ObeliskClient:
858
+ * 1. mnemonics
859
+ * 2. secretKey (base64 or hex)
860
+ * If none of them is provided, will generate a random mnemonics with 24 words.
861
+ *
862
+ * @param mnemonics, 12 or 24 mnemonics words, separated by space
863
+ * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
864
+ * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
865
+ * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type
866
+ * @param packageId
867
+ */
868
+ constructor({
869
+ mnemonics,
870
+ secretKey,
871
+ networkType,
872
+ fullnodeUrls,
873
+ packageId,
874
+ metadata
875
+ } = {}) {
876
+ __privateAdd(this, _query, {});
877
+ __privateAdd(this, _tx, {});
878
+ __privateAdd(this, _exec, async (meta, tx, params, typeArguments, isRaw) => {
879
+ tx.moveCall({
880
+ target: `${this.contractFactory.packageId}::${meta.moduleName}::${meta.funcName}`,
881
+ arguments: params,
882
+ typeArguments
883
+ });
884
+ if (isRaw === true) {
885
+ return tx;
886
+ }
887
+ return await this.signAndSendTxn(tx);
888
+ });
889
+ __privateAdd(this, _read, async (meta, tx, params, typeArguments, isRaw) => {
890
+ tx.moveCall({
891
+ target: `${this.contractFactory.packageId}::${meta.moduleName}::${meta.funcName}`,
892
+ arguments: params,
893
+ typeArguments
894
+ });
895
+ if (isRaw === true) {
896
+ return tx;
897
+ }
898
+ return await this.inspectTxn(tx);
899
+ });
900
+ this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
901
+ fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
902
+ this.suiInteractor = new SuiInteractor(fullnodeUrls, networkType);
903
+ this.packageId = packageId;
904
+ if (metadata !== void 0) {
905
+ this.metadata = metadata;
906
+ Object.values(metadata).forEach((value) => {
907
+ const data = value;
908
+ const moduleName = data.name;
909
+ Object.entries(data.exposedFunctions).forEach(([funcName, value2]) => {
910
+ const meta = value2;
911
+ meta.moduleName = moduleName;
912
+ meta.funcName = funcName;
913
+ if (isUndefined(__privateGet(this, _query)[moduleName])) {
914
+ __privateGet(this, _query)[moduleName] = {};
915
+ }
916
+ if (isUndefined(__privateGet(this, _query)[moduleName][funcName])) {
917
+ __privateGet(this, _query)[moduleName][funcName] = createQuery(
918
+ meta,
919
+ (tx, p, typeArguments, isRaw) => __privateGet(this, _read).call(this, meta, tx, p, typeArguments, isRaw)
920
+ );
921
+ }
922
+ if (isUndefined(__privateGet(this, _tx)[moduleName])) {
923
+ __privateGet(this, _tx)[moduleName] = {};
924
+ }
925
+ if (isUndefined(__privateGet(this, _tx)[moduleName][funcName])) {
926
+ __privateGet(this, _tx)[moduleName][funcName] = createTx(
927
+ meta,
928
+ (tx, p, typeArguments, isRaw) => __privateGet(this, _exec).call(this, meta, tx, p, typeArguments, isRaw)
929
+ );
930
+ }
931
+ });
932
+ });
933
+ }
934
+ this.contractFactory = new SuiContractFactory({
935
+ packageId,
936
+ metadata
937
+ });
938
+ }
939
+ get query() {
940
+ return __privateGet(this, _query);
941
+ }
942
+ get tx() {
943
+ return __privateGet(this, _tx);
944
+ }
945
+ /**
946
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner.
947
+ * else:
948
+ * it will generate signer from the mnemonic with the given derivePathParams.
949
+ * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
950
+ */
951
+ getSigner(derivePathParams) {
952
+ const keyPair = this.accountManager.getKeyPair(derivePathParams);
953
+ return new RawSigner(keyPair, this.suiInteractor.currentProvider);
954
+ }
955
+ /**
956
+ * @description Switch the current account with the given derivePathParams
957
+ * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
958
+ */
959
+ switchAccount(derivePathParams) {
960
+ this.accountManager.switchAccount(derivePathParams);
961
+ }
962
+ /**
963
+ * @description Get the address of the account for the given derivePathParams
964
+ * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
965
+ */
966
+ getAddress(derivePathParams) {
967
+ return this.accountManager.getAddress(derivePathParams);
968
+ }
969
+ currentAddress() {
970
+ return this.accountManager.currentAddress;
971
+ }
972
+ provider() {
973
+ return this.suiInteractor.currentProvider;
974
+ }
975
+ getPackageId() {
976
+ return this.contractFactory.packageId;
977
+ }
978
+ getMetadata() {
979
+ return this.contractFactory.metadata;
980
+ }
981
+ /**
982
+ * Request some SUI from faucet
983
+ * @Returns {Promise<boolean>}, true if the request is successful, false otherwise.
984
+ */
985
+ async requestFaucet(address, network) {
986
+ return this.suiInteractor.requestFaucet(address, network);
987
+ }
988
+ async getBalance(coinType, derivePathParams) {
989
+ const owner = this.accountManager.getAddress(derivePathParams);
990
+ return this.suiInteractor.currentProvider.getBalance({ owner, coinType });
991
+ }
992
+ async getObject(objectId) {
993
+ return this.suiInteractor.getObject(objectId);
994
+ }
995
+ async getObjects(objectIds) {
996
+ return this.suiInteractor.getObjects(objectIds);
997
+ }
998
+ async signTxn(tx, derivePathParams) {
999
+ tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
1000
+ const signer = this.getSigner(derivePathParams);
1001
+ return signer.signTransactionBlock({ transactionBlock: tx });
1002
+ }
1003
+ async signAndSendTxn(tx, derivePathParams) {
1004
+ const { transactionBlockBytes, signature } = await this.signTxn(
1005
+ tx,
1006
+ derivePathParams
1007
+ );
1008
+ return this.suiInteractor.sendTx(transactionBlockBytes, signature);
1009
+ }
1010
+ /**
1011
+ * Transfer the given amount of SUI to the recipient
1012
+ * @param recipient
1013
+ * @param amount
1014
+ * @param derivePathParams
1015
+ */
1016
+ async transferSui(recipient, amount, derivePathParams) {
1017
+ const tx = new SuiTxBlock();
1018
+ tx.transferSui(recipient, amount);
1019
+ return this.signAndSendTxn(tx, derivePathParams);
1020
+ }
1021
+ /**
1022
+ * Transfer to mutliple recipients
1023
+ * @param recipients the recipients addresses
1024
+ * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients
1025
+ * @param derivePathParams
1026
+ */
1027
+ async transferSuiToMany(recipients, amounts, derivePathParams) {
1028
+ const tx = new SuiTxBlock();
1029
+ tx.transferSuiToMany(recipients, amounts);
1030
+ return this.signAndSendTxn(tx, derivePathParams);
1031
+ }
1032
+ /**
1033
+ * Transfer the given amounts of coin to multiple recipients
1034
+ * @param recipients the list of recipient address
1035
+ * @param amounts the amounts to transfer for each recipient
1036
+ * @param coinType any custom coin type but not SUI
1037
+ * @param derivePathParams the derive path params for the current signer
1038
+ */
1039
+ async transferCoinToMany(recipients, amounts, coinType, derivePathParams) {
1040
+ const tx = new SuiTxBlock();
1041
+ const owner = this.accountManager.getAddress(derivePathParams);
1042
+ const totalAmount = amounts.reduce((a, b) => a + b, 0);
1043
+ const coins = await this.suiInteractor.selectCoins(
1044
+ owner,
1045
+ totalAmount,
1046
+ coinType
1047
+ );
1048
+ tx.transferCoinToMany(
1049
+ coins.map((c) => c.objectId),
1050
+ owner,
1051
+ recipients,
1052
+ amounts
1053
+ );
1054
+ return this.signAndSendTxn(tx, derivePathParams);
1055
+ }
1056
+ async transferCoin(recipient, amount, coinType, derivePathParams) {
1057
+ return this.transferCoinToMany(
1058
+ [recipient],
1059
+ [amount],
1060
+ coinType,
1061
+ derivePathParams
1062
+ );
1063
+ }
1064
+ async transferObjects(objects, recipient, derivePathParams) {
1065
+ const tx = new SuiTxBlock();
1066
+ tx.transferObjects(objects, recipient);
1067
+ return this.signAndSendTxn(tx, derivePathParams);
1068
+ }
1069
+ async moveCall(callParams) {
1070
+ const {
1071
+ target,
1072
+ arguments: args = [],
1073
+ typeArguments = [],
1074
+ derivePathParams
1075
+ } = callParams;
1076
+ const tx = new SuiTxBlock();
1077
+ tx.moveCall(target, args, typeArguments);
1078
+ return this.signAndSendTxn(tx, derivePathParams);
1079
+ }
1080
+ /**
1081
+ * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount
1082
+ * @param amount
1083
+ * @param coinType
1084
+ * @param owner
1085
+ */
1086
+ async selectCoinsWithAmount(amount, coinType, owner) {
1087
+ owner = owner || this.accountManager.currentAddress;
1088
+ const coins = await this.suiInteractor.selectCoins(owner, amount, coinType);
1089
+ return coins.map((c) => c.objectId);
1090
+ }
1091
+ /**
1092
+ * stake the given amount of SUI to the validator
1093
+ * @param amount the amount of SUI to stake
1094
+ * @param validatorAddr the validator address
1095
+ * @param derivePathParams the derive path params for the current signer
1096
+ */
1097
+ async stakeSui(amount, validatorAddr, derivePathParams) {
1098
+ const tx = new SuiTxBlock();
1099
+ tx.stakeSui(amount, validatorAddr);
1100
+ return this.signAndSendTxn(tx, derivePathParams);
1101
+ }
1102
+ /**
1103
+ * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction.
1104
+ * Since the transaction is not submitted, its gas cost is not charged.
1105
+ * @param tx the transaction to execute
1106
+ * @param derivePathParams the derive path params
1107
+ * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted.
1108
+ */
1109
+ async inspectTxn(tx, derivePathParams) {
1110
+ tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
1111
+ return this.suiInteractor.currentProvider.devInspectTransactionBlock({
1112
+ transactionBlock: tx,
1113
+ sender: this.getAddress(derivePathParams)
1114
+ });
1115
+ }
1116
+ async getWorld(worldObjectId) {
1117
+ return this.suiInteractor.getObject(worldObjectId);
1118
+ }
1119
+ async listSchemaNames(worldId) {
1120
+ const worldObject = await this.getObject(worldId);
1121
+ const newObjectContent = worldObject.objectFields;
1122
+ return newObjectContent["schemaNames"];
1123
+ }
1124
+ async getEntity(worldId, schemaName, entityId) {
1125
+ const schemaModuleName = `${schemaName}_schema`;
1126
+ const tx = new TransactionBlock3();
1127
+ const params = [tx.pure(worldId)];
1128
+ if (entityId !== void 0) {
1129
+ params.push(tx.pure(entityId));
1130
+ }
1131
+ const getResult = await this.query[schemaModuleName].get(
1132
+ tx,
1133
+ params
1134
+ );
1135
+ const returnValue = [];
1136
+ if (getResult.effects.status.status === "success") {
1137
+ const resultList = getResult.results[0].returnValues;
1138
+ for (const res of resultList) {
1139
+ const bcs = new BCS(getSuiMoveConfig());
1140
+ const value = Uint8Array.from(res[0]);
1141
+ const bcsType = res[1].replace(/0x1::ascii::String/g, "string");
1142
+ const data = bcs.de(bcsType, value);
1143
+ returnValue.push(data);
1144
+ }
1145
+ return returnValue;
1146
+ } else {
1147
+ return void 0;
1148
+ }
1149
+ }
1150
+ async containEntity(worldId, schemaName, entityId) {
1151
+ const schemaModuleName = `${schemaName}_schema`;
1152
+ const tx = new TransactionBlock3();
1153
+ const params = [tx.pure(worldId)];
1154
+ if (entityId !== void 0) {
1155
+ params.push(tx.pure(entityId));
1156
+ }
1157
+ const getResult = await this.query[schemaModuleName].contains(
1158
+ tx,
1159
+ params
1160
+ );
1161
+ if (getResult.effects.status.status === "success") {
1162
+ const res = getResult.results[0].returnValues[0];
1163
+ const bcs = new BCS(getSuiMoveConfig());
1164
+ const value = Uint8Array.from(res[0]);
1165
+ return bcs.de(res[1], value);
1166
+ } else {
1167
+ return void 0;
1168
+ }
1169
+ }
1170
+ // async getEntities(
1171
+ // worldId: string,
1172
+ // schemaName: string,
1173
+ // cursor?: string,
1174
+ // limit?: number
1175
+ // ) {
1176
+ // let schemaModuleName = `${schemaName}_schema`;
1177
+ // const tx = new TransactionBlock();
1178
+ // let params = [tx.pure(worldId)] as SuiTxArgument[];
1179
+ // const tableResult = (await this.query[schemaonentModuleName].entities(
1180
+ // tx,
1181
+ // params
1182
+ // )) as DevInspectResults;
1183
+ // const entities = tableResult.results as SuiReturnValues;
1184
+ // const bcs = new BCS(getSuiMoveConfig());
1185
+ // let value = Uint8Array.from(entities[0].returnValues[0][0]);
1186
+ // let tableId = '0x' + bcs.de('address', value);
1187
+ // let dynamicFields = await this.suiInteractor.getDynamicFields(
1188
+ // tableId,
1189
+ // cursor,
1190
+ // limit
1191
+ // );
1192
+ // let objectIds = dynamicFields.data.map((field) => field.objectId);
1193
+ // let objectDatas = await this.suiInteractor.getEntitiesObjects(objectIds);
1194
+ // return {
1195
+ // data: objectDatas,
1196
+ // nextCursor: dynamicFields.nextCursor,
1197
+ // hasNextPage: dynamicFields.hasNextPage,
1198
+ // };
1199
+ // }
1200
+ async getOwnedObjects(owner, cursor, limit) {
1201
+ const ownedObjects = await this.suiInteractor.getOwnedObjects(
1202
+ owner,
1203
+ cursor,
1204
+ limit
1205
+ );
1206
+ const ownedObjectsRes = [];
1207
+ for (const object of ownedObjects.data) {
1208
+ const objectDetail = await this.getObject(object.data.objectId);
1209
+ if (objectDetail.objectType.split("::")[0] === this.contractFactory.packageId) {
1210
+ ownedObjectsRes.push(objectDetail);
1211
+ }
1212
+ }
1213
+ return ownedObjectsRes;
1214
+ }
1215
+ async entity_key_from_object(objectId) {
1216
+ const checkObjectId = normalizeHexAddress(objectId);
1217
+ if (checkObjectId !== null) {
1218
+ objectId = checkObjectId;
1219
+ return objectId;
1220
+ } else {
1221
+ return void 0;
1222
+ }
1223
+ }
1224
+ async entity_key_from_bytes(bytes) {
1225
+ const hashBytes = keccak256(bytes);
1226
+ const hashU8Array = Array.from(hashBytes);
1227
+ const bcs = new BCS(getSuiMoveConfig());
1228
+ const value = Uint8Array.from(hashU8Array);
1229
+ const data = bcs.de("address", value);
1230
+ return "0x" + data;
1231
+ }
1232
+ async entity_key_from_address_with_seed(objectId, seed) {
1233
+ const checkObjectId = normalizeHexAddress(objectId);
1234
+ if (checkObjectId !== null) {
1235
+ objectId = checkObjectId;
1236
+ const bytes = Buffer.from(objectId.slice(2), "hex");
1237
+ const newBuffer = Buffer.concat([bytes, Buffer.from(seed, "utf-8")]);
1238
+ return this.entity_key_from_bytes(newBuffer);
1239
+ } else {
1240
+ return void 0;
1241
+ }
1242
+ }
1243
+ async entity_key_from_address_with_u256(objectId, x) {
1244
+ const checkObjectId = normalizeHexAddress(objectId);
1245
+ if (checkObjectId !== null) {
1246
+ objectId = checkObjectId;
1247
+ const bcs = new BCS(getSuiMoveConfig());
1248
+ const bytes = Buffer.from(objectId.slice(2), "hex");
1249
+ const numberBytes = bcs.ser("u256", x).toBytes();
1250
+ return this.entity_key_from_bytes(Buffer.concat([bytes, numberBytes]));
1251
+ } else {
1252
+ return void 0;
1253
+ }
1254
+ }
1255
+ async entity_key_from_u256(x) {
1256
+ return numberToAddressHex(x);
1257
+ }
1258
+ async formatData(type, value) {
1259
+ const bcs = new BCS(getSuiMoveConfig());
1260
+ const u8Value = Uint8Array.from(value);
1261
+ return bcs.de(type, u8Value);
1262
+ }
1263
+ };
1264
+ _query = new WeakMap();
1265
+ _tx = new WeakMap();
1266
+ _exec = new WeakMap();
1267
+ _read = new WeakMap();
1268
+
1269
+ // src/metadata/index.ts
1270
+ async function loadMetadata(networkType, packageId) {
1271
+ const fullnodeUrls = [getDefaultConnection(networkType).fullnode];
1272
+ const suiInteractor = new SuiInteractor(fullnodeUrls);
1273
+ if (packageId !== void 0) {
1274
+ const jsonData = await suiInteractor.getNormalizedMoveModulesByPackage(
1275
+ packageId
1276
+ );
1277
+ return jsonData;
1278
+ } else {
1279
+ console.error("please set your package id.");
1280
+ }
1281
+ }
1282
+ export {
1283
+ BCS2 as BCS,
1284
+ Ed25519Keypair3 as Ed25519Keypair,
1285
+ Obelisk,
1286
+ SuiAccountManager,
1287
+ SuiContractFactory,
1288
+ SuiTxBlock,
1289
+ getSuiMoveConfig2 as getSuiMoveConfig,
1290
+ loadMetadata
1291
+ };
1292
+ //# sourceMappingURL=index.mjs.map