@0xobelisk/client 0.0.1

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 (38) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1 -0
  3. package/dist/index.d.ts +6 -0
  4. package/dist/index.js +757 -0
  5. package/dist/index.js.map +1 -0
  6. package/dist/index.mjs +755 -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/types.d.ts +9 -0
  12. package/dist/libs/suiAccountManager/util.d.ts +29 -0
  13. package/dist/libs/suiRpcProvider/defaultChainConfigs.d.ts +8 -0
  14. package/dist/libs/suiRpcProvider/faucet.d.ts +8 -0
  15. package/dist/libs/suiRpcProvider/index.d.ts +40 -0
  16. package/dist/libs/suiRpcProvider/types.d.ts +14 -0
  17. package/dist/libs/suiTxBuilder/index.d.ts +544 -0
  18. package/dist/libs/suiTxBuilder/types.d.ts +12 -0
  19. package/dist/libs/suiTxBuilder/util.d.ts +76 -0
  20. package/dist/obelisk.d.ts +2857 -0
  21. package/dist/test/tsconfig.tsbuildinfo +1 -0
  22. package/dist/types/index.d.ts +11 -0
  23. package/package.json +152 -0
  24. package/src/index.ts +10 -0
  25. package/src/libs/suiAccountManager/crypto.ts +7 -0
  26. package/src/libs/suiAccountManager/index.ts +72 -0
  27. package/src/libs/suiAccountManager/keypair.ts +38 -0
  28. package/src/libs/suiAccountManager/types.ts +10 -0
  29. package/src/libs/suiAccountManager/util.ts +70 -0
  30. package/src/libs/suiRpcProvider/defaultChainConfigs.ts +30 -0
  31. package/src/libs/suiRpcProvider/faucet.ts +57 -0
  32. package/src/libs/suiRpcProvider/index.ts +114 -0
  33. package/src/libs/suiRpcProvider/types.ts +17 -0
  34. package/src/libs/suiTxBuilder/index.ts +245 -0
  35. package/src/libs/suiTxBuilder/types.ts +32 -0
  36. package/src/libs/suiTxBuilder/util.ts +84 -0
  37. package/src/obelisk.ts +297 -0
  38. package/src/types/index.ts +17 -0
package/dist/index.mjs ADDED
@@ -0,0 +1,755 @@
1
+ // src/index.ts
2
+ import {
3
+ TransactionBlock as TransactionBlock4,
4
+ SUI_CLOCK_OBJECT_ID,
5
+ SUI_SYSTEM_STATE_OBJECT_ID as SUI_SYSTEM_STATE_OBJECT_ID2
6
+ } from "@mysten/sui.js";
7
+
8
+ // src/obelisk.ts
9
+ import {
10
+ RawSigner,
11
+ TransactionBlock as TransactionBlock3
12
+ } from "@mysten/sui.js";
13
+
14
+ // src/libs/suiAccountManager/index.ts
15
+ import { Ed25519Keypair as Ed25519Keypair2 } from "@mysten/sui.js";
16
+
17
+ // src/libs/suiAccountManager/keypair.ts
18
+ import { Ed25519Keypair } from "@mysten/sui.js";
19
+ var getDerivePathForSUI = (derivePathParams = {}) => {
20
+ const {
21
+ accountIndex = 0,
22
+ isExternal = false,
23
+ addressIndex = 0
24
+ } = derivePathParams;
25
+ return `m/44'/784'/${accountIndex}'/${isExternal ? 1 : 0}'/${addressIndex}'`;
26
+ };
27
+ var getKeyPair = (mnemonics, derivePathParams = {}) => {
28
+ const derivePath = getDerivePathForSUI(derivePathParams);
29
+ return Ed25519Keypair.deriveKeypair(mnemonics, derivePath);
30
+ };
31
+
32
+ // src/libs/suiAccountManager/util.ts
33
+ import { fromB64 } from "@mysten/sui.js";
34
+ var isHex = (str) => /^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(str);
35
+ var isBase64 = (str) => /^[a-zA-Z0-9+/]+={0,2}$/g.test(str);
36
+ var fromHEX = (hexStr) => {
37
+ if (!hexStr) {
38
+ throw new Error("cannot parse empty string to Uint8Array");
39
+ }
40
+ const intArr = hexStr.replace("0x", "").match(/.{1,2}/g)?.map((byte) => parseInt(byte, 16));
41
+ if (!intArr || intArr.length === 0) {
42
+ throw new Error(`Unable to parse HEX: ${hexStr}`);
43
+ }
44
+ return Uint8Array.from(intArr);
45
+ };
46
+ var hexOrBase64ToUint8Array = (str) => {
47
+ if (isHex(str)) {
48
+ return fromHEX(str);
49
+ } else if (isBase64(str)) {
50
+ return fromB64(str);
51
+ } else {
52
+ throw new Error("The string is not a valid hex or base64 string.");
53
+ }
54
+ };
55
+ var PRIVATE_KEY_SIZE = 32;
56
+ var LEGACY_PRIVATE_KEY_SIZE = 64;
57
+ var normalizePrivateKey = (key) => {
58
+ if (key.length === LEGACY_PRIVATE_KEY_SIZE) {
59
+ key = key.slice(0, PRIVATE_KEY_SIZE);
60
+ } else if (key.length === PRIVATE_KEY_SIZE + 1 && key[0] === 0) {
61
+ return key.slice(1);
62
+ } else if (key.length === PRIVATE_KEY_SIZE) {
63
+ return key;
64
+ }
65
+ throw new Error("invalid secret key");
66
+ };
67
+
68
+ // src/libs/suiAccountManager/crypto.ts
69
+ import { generateMnemonic as genMnemonic } from "@scure/bip39";
70
+ import { wordlist } from "@scure/bip39/wordlists/english";
71
+ var generateMnemonic = (numberOfWords = 24) => {
72
+ const strength = numberOfWords === 12 ? 128 : 256;
73
+ return genMnemonic(wordlist, strength);
74
+ };
75
+
76
+ // src/libs/suiAccountManager/index.ts
77
+ var SuiAccountManager = class {
78
+ /**
79
+ * Support the following ways to init the SuiToolkit:
80
+ * 1. mnemonics
81
+ * 2. secretKey (base64 or hex)
82
+ * If none of them is provided, will generate a random mnemonics with 24 words.
83
+ *
84
+ * @param mnemonics, 12 or 24 mnemonics words, separated by space
85
+ * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
86
+ */
87
+ constructor({ mnemonics, secretKey } = {}) {
88
+ this.mnemonics = mnemonics || "";
89
+ this.secretKey = secretKey || "";
90
+ if (!this.mnemonics && !this.secretKey) {
91
+ this.mnemonics = generateMnemonic(24);
92
+ }
93
+ this.currentKeyPair = this.secretKey ? Ed25519Keypair2.fromSecretKey(
94
+ normalizePrivateKey(hexOrBase64ToUint8Array(this.secretKey))
95
+ ) : getKeyPair(this.mnemonics);
96
+ this.currentAddress = this.currentKeyPair.getPublicKey().toSuiAddress();
97
+ }
98
+ /**
99
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.
100
+ * else:
101
+ * it will generate keyPair from the mnemonic with the given derivePathParams.
102
+ */
103
+ getKeyPair(derivePathParams) {
104
+ if (!derivePathParams || !this.mnemonics)
105
+ return this.currentKeyPair;
106
+ return getKeyPair(this.mnemonics, derivePathParams);
107
+ }
108
+ /**
109
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentAddress.
110
+ * else:
111
+ * it will generate address from the mnemonic with the given derivePathParams.
112
+ */
113
+ getAddress(derivePathParams) {
114
+ if (!derivePathParams || !this.mnemonics)
115
+ return this.currentAddress;
116
+ return getKeyPair(this.mnemonics, derivePathParams).getPublicKey().toSuiAddress();
117
+ }
118
+ /**
119
+ * Switch the current account with the given derivePathParams.
120
+ * This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.
121
+ */
122
+ switchAccount(derivePathParams) {
123
+ if (this.mnemonics) {
124
+ this.currentKeyPair = getKeyPair(this.mnemonics, derivePathParams);
125
+ this.currentAddress = this.currentKeyPair.getPublicKey().toSuiAddress();
126
+ }
127
+ }
128
+ };
129
+
130
+ // src/libs/suiRpcProvider/index.ts
131
+ import {
132
+ Connection,
133
+ JsonRpcProvider as JsonRpcProvider2,
134
+ getObjectType,
135
+ getObjectId,
136
+ getObjectFields,
137
+ getObjectDisplay,
138
+ getObjectVersion
139
+ } from "@mysten/sui.js";
140
+
141
+ // src/libs/suiRpcProvider/faucet.ts
142
+ import {
143
+ FaucetRateLimitError,
144
+ assert,
145
+ FaucetResponse
146
+ } from "@mysten/sui.js";
147
+ import { retry } from "ts-retry-promise";
148
+ var requestFaucet = async (address, provider) => {
149
+ console.log("\nRequesting SUI from faucet for address: ", address);
150
+ const headers = {
151
+ authority: "faucet.testnet.sui.io",
152
+ method: "POST",
153
+ path: "/gas",
154
+ scheme: "https",
155
+ accept: "*/*",
156
+ "accept-encoding": "gzip, deflate, br",
157
+ "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7",
158
+ "content-length": "105",
159
+ "content-type": "application/json",
160
+ origin: "chrome-extension://opcgpfmipidbgpenhmajoajpbobppdil",
161
+ cookie: '_ga=GA1.1.2092533979.1664032306; sui_io_cookie={"level":["necessary","analytics"],"revision":0,"data":null,"rfc_cookie":false}; _ga_YKP53WJMB0=GS1.1.1680531285.31.0.1680531334.11.0.0; _ga_0GW4F97GFL=GS1.1.1680826187.125.0.1680826187.60.0.0; __cf_bm=6rPjXUwuzUPy4yDlZuXgDj0v7xLPpUd5z0CFGCoN_YI-1680867579-0-AZMhU7/mKUUbUlOa27LmfW6eIFkBkXsPKqYgWjpjWpj2XzDckgUsRu/pxSRGfvXCspn3w7Df+uO1MR/b+XikJU0=; _cfuvid=zjwCXMmu19KBIVo_L9Qbq4TqFXJpophG3.EvFTxqdf4-1680867579342-0-604800000',
162
+ "sec-ch-ua": '"Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"',
163
+ "sec-ch-ua-mobile": "?0",
164
+ "sec-ch-ua-platform": "macOS",
165
+ "sec-fetch-dest": "empty",
166
+ "sec-fetch-mode": "cors",
167
+ "sec-fetch-site": "none",
168
+ "user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36"
169
+ };
170
+ const resp = await retry(
171
+ () => provider.requestSuiFromFaucet(address, headers),
172
+ {
173
+ backoff: "EXPONENTIAL",
174
+ // overall timeout in 60 seconds
175
+ timeout: 1e3 * 60,
176
+ // skip retry if we hit the rate-limit error
177
+ retryIf: (error) => !(error instanceof FaucetRateLimitError),
178
+ logger: (msg) => console.warn(`Retry requesting faucet: ${msg}`)
179
+ }
180
+ );
181
+ assert(resp, FaucetResponse, "Request faucet failed\n");
182
+ console.log("Request faucet success\n");
183
+ };
184
+
185
+ // src/libs/suiRpcProvider/defaultChainConfigs.ts
186
+ import {
187
+ localnetConnection,
188
+ devnetConnection,
189
+ testnetConnection,
190
+ mainnetConnection
191
+ } from "@mysten/sui.js";
192
+ var getDefaultNetworkParams = (networkType = "devnet") => {
193
+ switch (networkType) {
194
+ case "localnet":
195
+ return localnetConnection;
196
+ case "devnet":
197
+ return devnetConnection;
198
+ case "testnet":
199
+ return testnetConnection;
200
+ case "mainnet":
201
+ return mainnetConnection;
202
+ default:
203
+ return devnetConnection;
204
+ }
205
+ };
206
+
207
+ // src/libs/suiRpcProvider/index.ts
208
+ var SuiRpcProvider = class {
209
+ /**
210
+ *
211
+ * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
212
+ * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type
213
+ * @param faucetUrl, the faucet url, default is the preconfig faucet url for the given network type
214
+ */
215
+ constructor({
216
+ fullnodeUrl,
217
+ faucetUrl,
218
+ networkType
219
+ } = {}) {
220
+ const defaultNetworkParams = getDefaultNetworkParams(
221
+ networkType || "devnet"
222
+ );
223
+ this.fullnodeUrl = fullnodeUrl || defaultNetworkParams.fullnode;
224
+ this.faucetUrl = faucetUrl || defaultNetworkParams.faucet;
225
+ const connection = new Connection({
226
+ fullnode: this.fullnodeUrl,
227
+ faucet: this.faucetUrl
228
+ });
229
+ this.provider = new JsonRpcProvider2(connection);
230
+ }
231
+ /**
232
+ * Request some SUI from faucet
233
+ * @Returns {Promise<boolean>}, true if the request is successful, false otherwise.
234
+ */
235
+ async requestFaucet(addr) {
236
+ return requestFaucet(addr, this.provider);
237
+ }
238
+ async getBalance(addr, coinType) {
239
+ return this.provider.getBalance({ owner: addr, coinType });
240
+ }
241
+ async getObjects(ids) {
242
+ const options = { showContent: true, showDisplay: true, showType: true };
243
+ const objects = await this.provider.multiGetObjects({ ids, options });
244
+ const parsedObjects = objects.map((object) => {
245
+ const objectId = getObjectId(object);
246
+ const objectType = getObjectType(object);
247
+ const objectVersion = getObjectVersion(object);
248
+ const objectFields = getObjectFields(object);
249
+ const objectDisplay = getObjectDisplay(object);
250
+ return {
251
+ objectId,
252
+ objectType,
253
+ objectVersion,
254
+ objectFields,
255
+ objectDisplay
256
+ };
257
+ });
258
+ return parsedObjects;
259
+ }
260
+ /**
261
+ * @description Select coins that add up to the given amount.
262
+ * @param addr the address of the owner
263
+ * @param amount the amount that is needed for the coin
264
+ * @param coinType the coin type, default is '0x2::SUI::SUI'
265
+ */
266
+ async selectCoins(addr, amount, coinType = "0x2::SUI::SUI") {
267
+ const coins = await this.provider.getCoins({ owner: addr, coinType });
268
+ const selectedCoins = [];
269
+ let totalAmount = 0;
270
+ coins.data.sort((a, b) => parseInt(b.balance) - parseInt(a.balance));
271
+ for (const coinData of coins.data) {
272
+ selectedCoins.push({
273
+ objectId: coinData.coinObjectId,
274
+ digest: coinData.digest,
275
+ version: coinData.version
276
+ });
277
+ totalAmount = totalAmount + parseInt(coinData.balance);
278
+ if (totalAmount >= amount) {
279
+ break;
280
+ }
281
+ }
282
+ if (!selectedCoins.length) {
283
+ throw new Error("No valid coins found for the transaction.");
284
+ }
285
+ return selectedCoins;
286
+ }
287
+ };
288
+
289
+ // src/libs/suiTxBuilder/index.ts
290
+ import {
291
+ TransactionBlock as TransactionBlock2,
292
+ SUI_SYSTEM_STATE_OBJECT_ID
293
+ } from "@mysten/sui.js";
294
+
295
+ // src/libs/suiTxBuilder/util.ts
296
+ import {
297
+ normalizeSuiObjectId
298
+ } from "@mysten/sui.js";
299
+ var getDefaultSuiInputType = (value) => {
300
+ if (typeof value === "string" && value.startsWith("0x")) {
301
+ return "object";
302
+ } else if (typeof value === "number" || typeof value === "bigint") {
303
+ return "u64";
304
+ } else if (typeof value === "boolean") {
305
+ return "bool";
306
+ } else {
307
+ return "object";
308
+ }
309
+ };
310
+ function makeVecParam(txBlock, args, type) {
311
+ if (args.length === 0)
312
+ throw new Error("Transaction builder error: Empty array is not allowed");
313
+ const defaultSuiType = getDefaultSuiInputType(args[0]);
314
+ if (type === "object" || !type && defaultSuiType === "object") {
315
+ const objects = args.map(
316
+ (arg) => typeof arg === "string" ? txBlock.object(normalizeSuiObjectId(arg)) : arg
317
+ );
318
+ return txBlock.makeMoveVec({ objects });
319
+ } else {
320
+ const vecType = type || defaultSuiType;
321
+ return txBlock.pure(args, `vector<${vecType}>`);
322
+ }
323
+ }
324
+ function isMoveVecArg(arg) {
325
+ const isFullMoveVecArg = arg && arg.value && Array.isArray(arg.value) && arg.vecType;
326
+ const isSimpleMoveVecArg = Array.isArray(arg);
327
+ return isFullMoveVecArg || isSimpleMoveVecArg;
328
+ }
329
+ function convertArgs(txBlock, args) {
330
+ return args.map((arg) => {
331
+ if (typeof arg === "string" && arg.startsWith("0x")) {
332
+ return txBlock.object(normalizeSuiObjectId(arg));
333
+ } else if (isMoveVecArg(arg)) {
334
+ const vecType = arg.vecType || void 0;
335
+ return vecType ? makeVecParam(txBlock, arg.value, vecType) : makeVecParam(txBlock, arg);
336
+ } else if (typeof arg !== "object") {
337
+ return txBlock.pure(arg);
338
+ } else {
339
+ return arg;
340
+ }
341
+ });
342
+ }
343
+
344
+ // src/libs/suiTxBuilder/index.ts
345
+ var SuiTxBlock = class {
346
+ constructor(transaction) {
347
+ this.txBlock = new TransactionBlock2(transaction);
348
+ }
349
+ //======== override methods of TransactionBlock ============
350
+ address(value) {
351
+ return this.txBlock.pure(value, "address");
352
+ }
353
+ pure(value, type) {
354
+ return this.txBlock.pure(value, type);
355
+ }
356
+ object(value) {
357
+ return this.txBlock.object(value);
358
+ }
359
+ objectRef(ref) {
360
+ return this.txBlock.objectRef(ref);
361
+ }
362
+ sharedObjectRef(ref) {
363
+ return this.txBlock.sharedObjectRef(ref);
364
+ }
365
+ setSender(sender) {
366
+ return this.txBlock.setSender(sender);
367
+ }
368
+ setSenderIfNotSet(sender) {
369
+ return this.txBlock.setSenderIfNotSet(sender);
370
+ }
371
+ setExpiration(expiration) {
372
+ return this.txBlock.setExpiration(expiration);
373
+ }
374
+ setGasPrice(price) {
375
+ return this.txBlock.setGasPrice(price);
376
+ }
377
+ setGasBudget(budget) {
378
+ return this.txBlock.setGasBudget(budget);
379
+ }
380
+ setGasOwner(owner) {
381
+ return this.txBlock.setGasOwner(owner);
382
+ }
383
+ setGasPayment(payments) {
384
+ return this.txBlock.setGasPayment(payments);
385
+ }
386
+ add(transaction) {
387
+ return this.txBlock.add(transaction);
388
+ }
389
+ serialize() {
390
+ return this.txBlock.serialize();
391
+ }
392
+ build(params = {}) {
393
+ return this.txBlock.build(params);
394
+ }
395
+ getDigest({ provider } = {}) {
396
+ return this.txBlock.getDigest({ provider });
397
+ }
398
+ get gas() {
399
+ return this.txBlock.gas;
400
+ }
401
+ get blockData() {
402
+ return this.txBlock.blockData;
403
+ }
404
+ transferObjects(objects, recipient) {
405
+ const tx = this.txBlock;
406
+ tx.transferObjects(convertArgs(this.txBlock, objects), tx.pure(recipient));
407
+ return this;
408
+ }
409
+ splitCoins(coin, amounts) {
410
+ const tx = this.txBlock;
411
+ const coinObject = convertArgs(this.txBlock, [coin])[0];
412
+ const res = tx.splitCoins(
413
+ coinObject,
414
+ amounts.map((m) => tx.pure(m))
415
+ );
416
+ return amounts.map((_, i) => res[i]);
417
+ }
418
+ mergeCoins(destination, sources) {
419
+ const destinationObject = convertArgs(this.txBlock, [destination])[0];
420
+ const sourceObjects = convertArgs(this.txBlock, sources);
421
+ return this.txBlock.mergeCoins(destinationObject, sourceObjects);
422
+ }
423
+ publish(...args) {
424
+ return this.txBlock.publish(...args);
425
+ }
426
+ upgrade(...args) {
427
+ return this.txBlock.upgrade(...args);
428
+ }
429
+ makeMoveVec(...args) {
430
+ return this.txBlock.makeMoveVec(...args);
431
+ }
432
+ /**
433
+ * @description Move call
434
+ * @param target `${string}::${string}::${string}`, e.g. `0x3::sui_system::request_add_stake`
435
+ * @param args the arguments of the move call, such as `['0x1', '0x2']`
436
+ * @param typeArgs the type arguments of the move call, such as `['0x2::sui::SUI']`
437
+ */
438
+ moveCall(target, args = [], typeArgs = []) {
439
+ const regex = /(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;
440
+ const match = target.match(regex);
441
+ if (match === null)
442
+ throw new Error(
443
+ "Invalid target format. Expected `${string}::${string}::${string}`"
444
+ );
445
+ const convertedArgs = convertArgs(this.txBlock, args);
446
+ const tx = this.txBlock;
447
+ return tx.moveCall({
448
+ target,
449
+ arguments: convertedArgs,
450
+ typeArguments: typeArgs
451
+ });
452
+ }
453
+ //======== enhance methods ============
454
+ transferSuiToMany(recipients, amounts) {
455
+ if (recipients.length !== amounts.length) {
456
+ throw new Error(
457
+ "transferSuiToMany: recipients.length !== amounts.length"
458
+ );
459
+ }
460
+ const tx = this.txBlock;
461
+ const coins = tx.splitCoins(
462
+ tx.gas,
463
+ amounts.map((amount) => tx.pure(amount))
464
+ );
465
+ recipients.forEach((recipient, index) => {
466
+ tx.transferObjects([coins[index]], tx.pure(recipient));
467
+ });
468
+ return this;
469
+ }
470
+ transferSui(recipient, amount) {
471
+ return this.transferSuiToMany([recipient], [amount]);
472
+ }
473
+ takeAmountFromCoins(coins, amount) {
474
+ const tx = this.txBlock;
475
+ const coinObjects = convertArgs(this.txBlock, coins);
476
+ const mergedCoin = coinObjects[0];
477
+ if (coins.length > 1) {
478
+ tx.mergeCoins(mergedCoin, coinObjects.slice(1));
479
+ }
480
+ const [sendCoin] = tx.splitCoins(mergedCoin, [tx.pure(amount)]);
481
+ return [sendCoin, mergedCoin];
482
+ }
483
+ splitSUIFromGas(amounts) {
484
+ const tx = this.txBlock;
485
+ return tx.splitCoins(
486
+ tx.gas,
487
+ amounts.map((m) => tx.pure(m))
488
+ );
489
+ }
490
+ splitMultiCoins(coins, amounts) {
491
+ const tx = this.txBlock;
492
+ const coinObjects = convertArgs(this.txBlock, coins);
493
+ const mergedCoin = coinObjects[0];
494
+ if (coins.length > 1) {
495
+ tx.mergeCoins(mergedCoin, coinObjects.slice(1));
496
+ }
497
+ const splitedCoins = tx.splitCoins(
498
+ mergedCoin,
499
+ amounts.map((m) => tx.pure(m))
500
+ );
501
+ return { splitedCoins, mergedCoin };
502
+ }
503
+ transferCoinToMany(inputCoins, sender, recipients, amounts) {
504
+ if (recipients.length !== amounts.length) {
505
+ throw new Error(
506
+ "transferSuiToMany: recipients.length !== amounts.length"
507
+ );
508
+ }
509
+ const tx = this.txBlock;
510
+ const { splitedCoins, mergedCoin } = this.splitMultiCoins(
511
+ inputCoins,
512
+ amounts
513
+ );
514
+ recipients.forEach((recipient, index) => {
515
+ tx.transferObjects([splitedCoins[index]], tx.pure(recipient));
516
+ });
517
+ tx.transferObjects([mergedCoin], tx.pure(sender));
518
+ return this;
519
+ }
520
+ transferCoin(inputCoins, sender, recipient, amount) {
521
+ return this.transferCoinToMany(inputCoins, sender, [recipient], [amount]);
522
+ }
523
+ stakeSui(amount, validatorAddr) {
524
+ const tx = this.txBlock;
525
+ const [stakeCoin] = tx.splitCoins(tx.gas, [tx.pure(amount)]);
526
+ tx.moveCall({
527
+ target: "0x3::sui_system::request_add_stake",
528
+ arguments: [
529
+ tx.object(SUI_SYSTEM_STATE_OBJECT_ID),
530
+ stakeCoin,
531
+ tx.pure(validatorAddr)
532
+ ]
533
+ });
534
+ return tx;
535
+ }
536
+ };
537
+
538
+ // src/obelisk.ts
539
+ var Obelisk = class {
540
+ /**
541
+ * Support the following ways to init the SuiToolkit:
542
+ * 1. mnemonics
543
+ * 2. secretKey (base64 or hex)
544
+ * If none of them is provided, will generate a random mnemonics with 24 words.
545
+ *
546
+ * @param mnemonics, 12 or 24 mnemonics words, separated by space
547
+ * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
548
+ * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
549
+ * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type
550
+ * @param faucetUrl, the faucet url, default is the preconfig faucet url for the given network type
551
+ */
552
+ constructor({
553
+ mnemonics,
554
+ secretKey,
555
+ networkType,
556
+ fullnodeUrl,
557
+ faucetUrl
558
+ } = {}) {
559
+ this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
560
+ this.rpcProvider = new SuiRpcProvider({
561
+ fullnodeUrl,
562
+ faucetUrl,
563
+ networkType
564
+ });
565
+ }
566
+ /**
567
+ * if derivePathParams is not provided or mnemonics is empty, it will return the currentSigner.
568
+ * else:
569
+ * it will generate signer from the mnemonic with the given derivePathParams.
570
+ * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
571
+ */
572
+ getSigner(derivePathParams) {
573
+ const keyPair = this.accountManager.getKeyPair(derivePathParams);
574
+ return new RawSigner(keyPair, this.rpcProvider.provider);
575
+ }
576
+ /**
577
+ * @description Switch the current account with the given derivePathParams
578
+ * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
579
+ */
580
+ switchAccount(derivePathParams) {
581
+ this.accountManager.switchAccount(derivePathParams);
582
+ }
583
+ /**
584
+ * @description Get the address of the account for the given derivePathParams
585
+ * @param derivePathParams, such as { accountIndex: 2, isExternal: false, addressIndex: 10 }, comply with the BIP44 standard
586
+ */
587
+ getAddress(derivePathParams) {
588
+ return this.accountManager.getAddress(derivePathParams);
589
+ }
590
+ currentAddress() {
591
+ return this.accountManager.currentAddress;
592
+ }
593
+ provider() {
594
+ return this.rpcProvider.provider;
595
+ }
596
+ /**
597
+ * Request some SUI from faucet
598
+ * @Returns {Promise<boolean>}, true if the request is successful, false otherwise.
599
+ */
600
+ async requestFaucet(derivePathParams) {
601
+ const addr = this.accountManager.getAddress(derivePathParams);
602
+ return this.rpcProvider.requestFaucet(addr);
603
+ }
604
+ async getBalance(coinType, derivePathParams) {
605
+ const owner = this.accountManager.getAddress(derivePathParams);
606
+ return this.rpcProvider.getBalance(owner, coinType);
607
+ }
608
+ async getObjects(objectIds) {
609
+ return this.rpcProvider.getObjects(objectIds);
610
+ }
611
+ async signTxn(tx, derivePathParams) {
612
+ tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
613
+ const signer = this.getSigner(derivePathParams);
614
+ return signer.signTransactionBlock({ transactionBlock: tx });
615
+ }
616
+ async signAndSendTxn(tx, derivePathParams) {
617
+ tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
618
+ const signer = this.getSigner(derivePathParams);
619
+ return signer.signAndExecuteTransactionBlock({
620
+ transactionBlock: tx,
621
+ options: {
622
+ showEffects: true,
623
+ showEvents: true,
624
+ showObjectChanges: true
625
+ }
626
+ });
627
+ }
628
+ /**
629
+ * Transfer the given amount of SUI to the recipient
630
+ * @param recipient
631
+ * @param amount
632
+ * @param derivePathParams
633
+ */
634
+ async transferSui(recipient, amount, derivePathParams) {
635
+ const tx = new SuiTxBlock();
636
+ tx.transferSui(recipient, amount);
637
+ return this.signAndSendTxn(tx, derivePathParams);
638
+ }
639
+ /**
640
+ * Transfer to mutliple recipients
641
+ * @param recipients the recipients addresses
642
+ * @param amounts the amounts of SUI to transfer to each recipient, the length of amounts should be the same as the length of recipients
643
+ * @param derivePathParams
644
+ */
645
+ async transferSuiToMany(recipients, amounts, derivePathParams) {
646
+ const tx = new SuiTxBlock();
647
+ tx.transferSuiToMany(recipients, amounts);
648
+ return this.signAndSendTxn(tx, derivePathParams);
649
+ }
650
+ /**
651
+ * Transfer the given amounts of coin to multiple recipients
652
+ * @param recipients the list of recipient address
653
+ * @param amounts the amounts to transfer for each recipient
654
+ * @param coinType any custom coin type but not SUI
655
+ * @param derivePathParams the derive path params for the current signer
656
+ */
657
+ async transferCoinToMany(recipients, amounts, coinType, derivePathParams) {
658
+ const tx = new SuiTxBlock();
659
+ const owner = this.accountManager.getAddress(derivePathParams);
660
+ const totalAmount = amounts.reduce((a, b) => a + b, 0);
661
+ const coins = await this.rpcProvider.selectCoins(
662
+ owner,
663
+ totalAmount,
664
+ coinType
665
+ );
666
+ tx.transferCoinToMany(
667
+ coins.map((c) => c.objectId),
668
+ owner,
669
+ recipients,
670
+ amounts
671
+ );
672
+ return this.signAndSendTxn(tx, derivePathParams);
673
+ }
674
+ async transferCoin(recipient, amount, coinType, derivePathParams) {
675
+ return this.transferCoinToMany(
676
+ [recipient],
677
+ [amount],
678
+ coinType,
679
+ derivePathParams
680
+ );
681
+ }
682
+ async transferObjects(objects, recipient, derivePathParams) {
683
+ const tx = new SuiTxBlock();
684
+ tx.transferObjects(objects, recipient);
685
+ return this.signAndSendTxn(tx, derivePathParams);
686
+ }
687
+ async moveCall(callParams) {
688
+ const {
689
+ target,
690
+ arguments: args = [],
691
+ typeArguments = [],
692
+ derivePathParams
693
+ } = callParams;
694
+ const tx = new SuiTxBlock();
695
+ tx.moveCall(target, args, typeArguments);
696
+ return this.signAndSendTxn(tx, derivePathParams);
697
+ }
698
+ /**
699
+ * Select coins with the given amount and coin type, the total amount is greater than or equal to the given amount
700
+ * @param amount
701
+ * @param coinType
702
+ * @param owner
703
+ */
704
+ async selectCoinsWithAmount(amount, coinType, owner) {
705
+ owner = owner || this.accountManager.currentAddress;
706
+ const coins = await this.rpcProvider.selectCoins(owner, amount, coinType);
707
+ return coins.map((c) => c.objectId);
708
+ }
709
+ /**
710
+ * stake the given amount of SUI to the validator
711
+ * @param amount the amount of SUI to stake
712
+ * @param validatorAddr the validator address
713
+ * @param derivePathParams the derive path params for the current signer
714
+ */
715
+ async stakeSui(amount, validatorAddr, derivePathParams) {
716
+ const tx = new SuiTxBlock();
717
+ tx.stakeSui(amount, validatorAddr);
718
+ return this.signAndSendTxn(tx, derivePathParams);
719
+ }
720
+ /**
721
+ * Execute the transaction with on-chain data but without really submitting. Useful for querying the effects of a transaction.
722
+ * Since the transaction is not submitted, its gas cost is not charged.
723
+ * @param tx the transaction to execute
724
+ * @param derivePathParams the derive path params
725
+ * @returns the effects and events of the transaction, such as object changes, gas cost, event emitted.
726
+ */
727
+ async inspectTxn(tx, derivePathParams) {
728
+ tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
729
+ return this.rpcProvider.provider.devInspectTransactionBlock({
730
+ transactionBlock: tx,
731
+ sender: this.getAddress(derivePathParams)
732
+ });
733
+ }
734
+ async call(world_id, system_name, counter, derivePathParams) {
735
+ const tx = new TransactionBlock3();
736
+ tx.moveCall({
737
+ target: `${world_id}::system::${system_name}`,
738
+ arguments: [
739
+ // txb.pure(manager),
740
+ tx.pure(counter)
741
+ ]
742
+ });
743
+ return this.signAndSendTxn(tx, derivePathParams);
744
+ }
745
+ };
746
+ export {
747
+ Obelisk,
748
+ SUI_CLOCK_OBJECT_ID,
749
+ SUI_SYSTEM_STATE_OBJECT_ID2 as SUI_SYSTEM_STATE_OBJECT_ID,
750
+ SuiAccountManager,
751
+ SuiRpcProvider,
752
+ SuiTxBlock,
753
+ TransactionBlock4 as TransactionBlock
754
+ };
755
+ //# sourceMappingURL=index.mjs.map