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