@0xobelisk/client 0.4.7 → 1.2.0-pre.100

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