@scallop-io/sui-kit 1.4.3 → 2.0.0

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 (37) hide show
  1. package/README.md +1 -1
  2. package/dist/index.cjs +32 -0
  3. package/dist/index.d.cts +747 -0
  4. package/dist/index.d.ts +745 -6
  5. package/dist/index.js +13 -29
  6. package/package.json +14 -13
  7. package/src/index.ts +10 -6
  8. package/src/libs/multiSig/client.ts +1 -1
  9. package/src/libs/multiSig/index.ts +1 -1
  10. package/src/libs/suiAccountManager/index.ts +7 -4
  11. package/src/libs/suiAccountManager/keypair.ts +1 -1
  12. package/src/libs/suiInteractor/index.ts +7 -1
  13. package/src/libs/suiInteractor/suiInteractor.ts +150 -71
  14. package/src/libs/suiModel/index.ts +2 -2
  15. package/src/libs/suiModel/suiOwnedObject.ts +17 -8
  16. package/src/libs/suiTxBuilder/index.ts +24 -13
  17. package/src/libs/suiTxBuilder/util.ts +40 -5
  18. package/src/suiKit.ts +62 -32
  19. package/src/types/index.ts +17 -3
  20. package/dist/index.mjs +0 -15
  21. package/dist/libs/multiSig/client.d.ts +0 -15
  22. package/dist/libs/multiSig/index.d.ts +0 -1
  23. package/dist/libs/multiSig/publickey.d.ts +0 -2
  24. package/dist/libs/suiAccountManager/crypto.d.ts +0 -1
  25. package/dist/libs/suiAccountManager/index.d.ts +0 -39
  26. package/dist/libs/suiAccountManager/keypair.d.ts +0 -21
  27. package/dist/libs/suiAccountManager/util.d.ts +0 -29
  28. package/dist/libs/suiInteractor/index.d.ts +0 -1
  29. package/dist/libs/suiInteractor/suiInteractor.d.ts +0 -39
  30. package/dist/libs/suiInteractor/util.d.ts +0 -2
  31. package/dist/libs/suiModel/index.d.ts +0 -2
  32. package/dist/libs/suiModel/suiOwnedObject.d.ts +0 -24
  33. package/dist/libs/suiModel/suiSharedObject.d.ts +0 -11
  34. package/dist/libs/suiTxBuilder/index.d.ts +0 -637
  35. package/dist/libs/suiTxBuilder/util.d.ts +0 -43
  36. package/dist/suiKit.d.ts +0 -128
  37. package/dist/types/index.d.ts +0 -76
@@ -6,8 +6,8 @@ import {
6
6
  convertObjArg,
7
7
  convertAmounts,
8
8
  partitionArray,
9
- } from './util';
10
- import type { SuiClient, SuiObjectRef } from '@mysten/sui/client';
9
+ } from './util.js';
10
+ import type { ClientWithCoreApi } from '@mysten/sui/client';
11
11
  import type { Keypair } from '@mysten/sui/cryptography';
12
12
  import type {
13
13
  SuiTxArg,
@@ -15,9 +15,16 @@ import type {
15
15
  SuiObjectArg,
16
16
  SuiVecTxArg,
17
17
  SuiAmountsArg,
18
- } from 'src/types';
18
+ } from '../../types/index.js';
19
19
  import type { bcs } from '@mysten/sui/bcs';
20
20
 
21
+ // Object reference type
22
+ interface SuiObjectRef {
23
+ objectId: string;
24
+ version: number | string;
25
+ digest: string;
26
+ }
27
+
21
28
  export class SuiTxBlock {
22
29
  public txBlock: Transaction;
23
30
 
@@ -31,13 +38,8 @@ export class SuiTxBlock {
31
38
  get gas() {
32
39
  return this.txBlock.gas;
33
40
  }
34
- /** @deprecated Use `getData()` instead. */
35
- get blockData() {
36
- // TODO: need to update this method to use the new blockData method
37
- return this.txBlock.blockData;
38
- }
39
41
 
40
- get getData() {
42
+ getData() {
41
43
  return this.txBlock.getData();
42
44
  }
43
45
 
@@ -95,20 +97,20 @@ export class SuiTxBlock {
95
97
 
96
98
  sign(params: {
97
99
  signer: Keypair;
98
- client?: SuiClient;
100
+ client?: ClientWithCoreApi;
99
101
  onlyTransactionKind?: boolean;
100
102
  }) {
101
103
  return this.txBlock.sign(params);
102
104
  }
103
105
  build(
104
106
  params: {
105
- client?: SuiClient;
107
+ client?: ClientWithCoreApi;
106
108
  onlyTransactionKind?: boolean;
107
109
  } = {}
108
110
  ) {
109
111
  return this.txBlock.build(params);
110
112
  }
111
- getDigest(params: { client?: SuiClient } = {}) {
113
+ getDigest(params: { client?: ClientWithCoreApi } = {}) {
112
114
  return this.txBlock.getDigest(params);
113
115
  }
114
116
  add(...args: Parameters<typeof this.txBlock.add>) {
@@ -195,12 +197,16 @@ export class SuiTxBlock {
195
197
  this.txBlock.gas,
196
198
  convertAmounts(this.txBlock, amounts)
197
199
  );
200
+
198
201
  const recipientObjects = recipients.map((recipient) =>
199
202
  convertAddressArg(this.txBlock, recipient)
200
203
  );
204
+
205
+ // Transfer splitted coins to recipients
201
206
  recipientObjects.forEach((address, index) => {
202
207
  this.txBlock.transferObjects([coins[index]], address);
203
208
  });
209
+
204
210
  return this;
205
211
  }
206
212
 
@@ -253,7 +259,7 @@ export class SuiTxBlock {
253
259
  // require recipients.length === amounts.length
254
260
  if (recipients.length !== amounts.length) {
255
261
  throw new Error(
256
- 'transferSuiToMany: recipients.length !== amounts.length'
262
+ 'transferCoinToMany: recipients.length !== amounts.length'
257
263
  );
258
264
  }
259
265
  const coinObjects = coins.map((coin) => convertObjArg(this.txBlock, coin));
@@ -264,13 +270,18 @@ export class SuiTxBlock {
264
270
  const recipientObjects = recipients.map((recipient) =>
265
271
  convertAddressArg(this.txBlock, recipient)
266
272
  );
273
+
274
+ // Transfer splitted coins to recipients
267
275
  recipientObjects.forEach((address, index) => {
268
276
  this.txBlock.transferObjects([splitedCoins[index]], address);
269
277
  });
278
+
279
+ // Return the remaining coin back to sender
270
280
  this.txBlock.transferObjects(
271
281
  [mergedCoin],
272
282
  convertAddressArg(this.txBlock, sender)
273
283
  );
284
+
274
285
  return this;
275
286
  }
276
287
 
@@ -11,6 +11,7 @@ import type {
11
11
  Transaction,
12
12
  TransactionObjectArgument,
13
13
  } from '@mysten/sui/transactions';
14
+ import type { SuiClientTypes } from '@mysten/sui/client';
14
15
  import type {
15
16
  SuiObjectArg,
16
17
  SuiAddressArg,
@@ -18,8 +19,36 @@ import type {
18
19
  SuiVecTxArg,
19
20
  SuiInputTypes,
20
21
  SuiAmountsArg,
21
- } from 'src/types';
22
- import type { SuiObjectRef } from '@mysten/sui/client';
22
+ } from '../../types/index.js';
23
+
24
+ // Object reference type
25
+ interface SuiObjectRef {
26
+ objectId: string;
27
+ version: number | string;
28
+ digest: string;
29
+ }
30
+
31
+ // Simple types that can be converted to OpenSignatureBody
32
+ const SIMPLE_BCS_TYPES = [
33
+ 'u8',
34
+ 'u16',
35
+ 'u32',
36
+ 'u64',
37
+ 'u128',
38
+ 'u256',
39
+ 'bool',
40
+ 'address',
41
+ ] as const;
42
+
43
+ type SimpleBcsType = (typeof SIMPLE_BCS_TYPES)[number];
44
+
45
+ // Convert simple type string to OpenSignatureBody
46
+ function toOpenSignatureBody(type: string): SuiClientTypes.OpenSignatureBody {
47
+ if (!SIMPLE_BCS_TYPES.includes(type as SimpleBcsType)) {
48
+ throw new Error(`Invalid SimpleBcsType: ${type}`);
49
+ }
50
+ return { $kind: type } as SuiClientTypes.OpenSignatureBody;
51
+ }
23
52
 
24
53
  // TODO: unclear why we need this function and types
25
54
  export const getDefaultSuiInputType = (
@@ -138,13 +167,18 @@ export function makeVecParam(
138
167
  !VECTOR_REGEX.test(type) &&
139
168
  !STRUCT_REGEX.test(type)
140
169
  ) {
141
- const bcsSchema = getPureBcsSchema(type)!;
170
+ // Convert simple type to OpenSignatureBody for BCS schema
171
+ const signatureBody = toOpenSignatureBody(type as SimpleBcsType);
172
+ const bcsSchema = getPureBcsSchema(signatureBody);
173
+ if (!bcsSchema) {
174
+ throw new Error(`Unknown type: ${type}`);
175
+ }
142
176
  return txBlock.pure(bcs.vector(bcsSchema).serialize(args));
143
177
  } else {
144
178
  const elements = args.map((arg) =>
145
179
  convertObjArg(txBlock, arg as SuiObjectArg)
146
180
  );
147
- return txBlock.makeMoveVec({ elements, type });
181
+ return txBlock.makeMoveVec({ elements, type: type as string });
148
182
  }
149
183
  }
150
184
 
@@ -175,7 +209,8 @@ export function convertArgs(
175
209
  return convertAmounts(txBlock, [arg])[0];
176
210
  }
177
211
 
178
- return convertObjArg(txBlock, arg);
212
+ // Cast to SuiObjectArg - at this point it should be an object type
213
+ return convertObjArg(txBlock, arg as unknown as SuiObjectArg);
179
214
  });
180
215
  }
181
216
 
package/src/suiKit.ts CHANGED
@@ -1,18 +1,16 @@
1
1
  /**
2
2
  * @description This file is used to aggregate the tools that used to interact with SUI network.
3
3
  */
4
- import { getFullnodeUrl } from '@mysten/sui/client';
5
4
  import { Transaction } from '@mysten/sui/transactions';
6
- import { SuiAccountManager } from './libs/suiAccountManager';
7
- import { SuiTxBlock } from './libs/suiTxBuilder';
8
- import { SuiInteractor } from './libs/suiInteractor';
9
- import type {
10
- SuiTransactionBlockResponse,
11
- DevInspectResults,
12
- SuiObjectDataOptions,
13
- DryRunTransactionBlockResponse,
14
- } from '@mysten/sui/client';
15
- import type { SuiSharedObject, SuiOwnedObject } from './libs/suiModel';
5
+ import { SuiAccountManager } from './libs/suiAccountManager/index.js';
6
+ import { SuiTxBlock } from './libs/suiTxBuilder/index.js';
7
+ import {
8
+ SuiInteractor,
9
+ getFullnodeUrl,
10
+ type SuiObjectDataOptions,
11
+ type SimulateTransactionResponse,
12
+ } from './libs/suiInteractor/index.js';
13
+ import type { SuiSharedObject, SuiOwnedObject } from './libs/suiModel/index.js';
16
14
  import type {
17
15
  SuiKitParams,
18
16
  DerivePathParams,
@@ -20,7 +18,9 @@ import type {
20
18
  SuiVecTxArg,
21
19
  SuiKitReturnType,
22
20
  SuiObjectArg,
23
- } from './types';
21
+ SuiTransactionBlockResponse,
22
+ } from './types/index.js';
23
+ import { normalizeStructTag, SUI_TYPE_ARG } from '@mysten/sui/utils';
24
24
 
25
25
  /**
26
26
  * @class SuiKit
@@ -46,14 +46,20 @@ export class SuiKit {
46
46
  // Init the account manager
47
47
  this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
48
48
 
49
+ const network = networkType ?? 'mainnet';
50
+
49
51
  let suiInteractorParams;
50
52
  if ('fullnodeUrls' in params) {
51
- suiInteractorParams = { fullnodeUrls: params.fullnodeUrls };
53
+ suiInteractorParams = {
54
+ fullnodeUrls: params.fullnodeUrls,
55
+ network,
56
+ };
52
57
  } else if ('suiClients' in params) {
53
58
  suiInteractorParams = { suiClients: params.suiClients };
54
59
  } else {
55
60
  suiInteractorParams = {
56
- fullnodeUrls: [getFullnodeUrl(networkType ?? 'mainnet')],
61
+ fullnodeUrls: [getFullnodeUrl(network)],
62
+ network,
57
63
  };
58
64
  }
59
65
 
@@ -102,7 +108,11 @@ export class SuiKit {
102
108
 
103
109
  async getBalance(coinType?: string, derivePathParams?: DerivePathParams) {
104
110
  const owner = this.accountManager.getAddress(derivePathParams);
105
- return this.suiInteractor.currentClient.getBalance({ owner, coinType });
111
+ const { balance } = await this.suiInteractor.currentClient.core.getBalance({
112
+ owner,
113
+ coinType,
114
+ });
115
+ return balance;
106
116
  }
107
117
 
108
118
  get client() {
@@ -111,7 +121,8 @@ export class SuiKit {
111
121
 
112
122
  async getObjects(
113
123
  objectIds: string[],
114
- options?: SuiObjectDataOptions & {
124
+ options?: {
125
+ include?: SuiObjectDataOptions;
115
126
  batchSize?: number;
116
127
  switchClientDelay?: number;
117
128
  }
@@ -154,7 +165,7 @@ export class SuiKit {
154
165
  async dryRunTxn(
155
166
  tx: Uint8Array | Transaction | SuiTxBlock,
156
167
  derivePathParams?: DerivePathParams
157
- ): Promise<DryRunTransactionBlockResponse> {
168
+ ): Promise<SimulateTransactionResponse> {
158
169
  if (tx instanceof SuiTxBlock) {
159
170
  tx.setSender(this.getAddress(derivePathParams));
160
171
  }
@@ -262,17 +273,23 @@ export class SuiKit {
262
273
  const tx = new SuiTxBlock();
263
274
  const owner = this.accountManager.getAddress(derivePathParams);
264
275
  const totalAmount = amounts.reduce((a, b) => a + b, 0);
265
- const coins = await this.suiInteractor.selectCoins(
266
- owner,
267
- totalAmount,
268
- coinType
269
- );
270
- tx.transferCoinToMany(
271
- coins.map((c) => c.objectId),
272
- owner,
273
- recipients,
274
- amounts
275
- );
276
+ if (normalizeStructTag(coinType) === normalizeStructTag(SUI_TYPE_ARG)) {
277
+ tx.transferSuiToMany(recipients, amounts);
278
+ } else {
279
+ const coins = await this.suiInteractor.selectCoins(
280
+ owner,
281
+ totalAmount,
282
+ coinType
283
+ );
284
+
285
+ tx.transferCoinToMany(
286
+ coins.map((coin) => ('objectId' in coin ? tx.objectRef(coin) : coin)),
287
+ owner,
288
+ recipients,
289
+ amounts
290
+ );
291
+ }
292
+
276
293
  return sign
277
294
  ? ((await this.signAndSendTxn(
278
295
  tx,
@@ -409,11 +426,24 @@ export class SuiKit {
409
426
  async inspectTxn(
410
427
  tx: Uint8Array | Transaction | SuiTxBlock,
411
428
  derivePathParams?: DerivePathParams
412
- ): Promise<DevInspectResults> {
429
+ ): Promise<SimulateTransactionResponse> {
430
+ if (tx instanceof SuiTxBlock) {
431
+ tx.setSender(this.getAddress(derivePathParams));
432
+ }
413
433
  const txBlock = tx instanceof SuiTxBlock ? tx.txBlock : tx;
414
- return this.suiInteractor.currentClient.devInspectTransactionBlock({
415
- transactionBlock: txBlock,
416
- sender: this.getAddress(derivePathParams),
434
+ const txBytes =
435
+ txBlock instanceof Uint8Array
436
+ ? txBlock
437
+ : await txBlock.build({ client: this.client });
438
+
439
+ return this.suiInteractor.currentClient.core.simulateTransaction({
440
+ transaction: txBytes,
441
+ include: {
442
+ effects: true,
443
+ events: true,
444
+ balanceChanges: true,
445
+ commandResults: true,
446
+ },
417
447
  });
418
448
  }
419
449
  }
@@ -6,8 +6,8 @@ import type {
6
6
  TransactionArgument,
7
7
  } from '@mysten/sui/transactions';
8
8
  import type { SerializedBcs } from '@mysten/bcs';
9
- import { SuiClient, SuiTransactionBlockResponse } from '@mysten/sui/client';
10
- import { SuiTxBlock } from 'src/libs/suiTxBuilder';
9
+ import type { ClientWithCoreApi, SuiClientTypes } from '@mysten/sui/client';
10
+ import { SuiTxBlock } from 'src/libs/suiTxBuilder/index.js';
11
11
 
12
12
  export type SuiKitParams = (AccountManagerParams & {
13
13
  faucetUrl?: string;
@@ -18,9 +18,10 @@ export type SuiKitParams = (AccountManagerParams & {
18
18
  export type SuiInteractorParams =
19
19
  | {
20
20
  fullnodeUrls: string[];
21
+ network?: NetworkType;
21
22
  }
22
23
  | {
23
- suiClients: SuiClient[];
24
+ suiClients: ClientWithCoreApi[];
24
25
  };
25
26
 
26
27
  export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
@@ -113,6 +114,19 @@ export type SuiBasicTypes =
113
114
 
114
115
  export type SuiInputTypes = 'object' | SuiBasicTypes;
115
116
 
117
+ // Transaction result type from SDK v2
118
+ export type SuiTransactionResult<
119
+ Include extends SuiClientTypes.TransactionInclude = {},
120
+ > = SuiClientTypes.TransactionResult<Include>;
121
+
122
+ // Full transaction response with all includes enabled
123
+ export type SuiTransactionBlockResponse = SuiClientTypes.TransactionResult<{
124
+ balanceChanges: true;
125
+ effects: true;
126
+ events: true;
127
+ objectTypes: true;
128
+ }>;
129
+
116
130
  export type SuiKitReturnType<T extends boolean> = T extends true
117
131
  ? SuiTransactionBlockResponse
118
132
  : SuiTxBlock;
package/dist/index.mjs DELETED
@@ -1,15 +0,0 @@
1
- import { SUI_SYSTEM_STATE_OBJECT_ID, isValidSuiAddress, normalizeSuiAddress, isValidSuiObjectId, normalizeSuiObjectId } from '@mysten/sui/utils';
2
- export * from '@mysten/sui/utils';
3
- import { Transaction, Inputs, getPureBcsSchema } from '@mysten/sui/transactions';
4
- export * from '@mysten/sui/transactions';
5
- import { getFullnodeUrl, SuiClient } from '@mysten/sui/client';
6
- import { Ed25519Keypair, Ed25519PublicKey } from '@mysten/sui/keypairs/ed25519';
7
- import { fromHex, fromBase64, SerializedBcs, isSerializedBcs, bcs } from '@mysten/bcs';
8
- import { generateMnemonic } from '@scure/bip39';
9
- import { wordlist } from '@scure/bip39/wordlists/english';
10
- import { SUI_PRIVATE_KEY_PREFIX, decodeSuiPrivateKey } from '@mysten/sui/cryptography';
11
- import { MultiSigPublicKey } from '@mysten/sui/multisig';
12
-
13
- var _=(r={})=>{let{accountIndex:t=0,isExternal:e=!1,addressIndex:i=0}=r;return `m/44'/784'/${t}'/${e?1:0}'/${i}'`},S=(r,t={})=>{let e=_(t);return Ed25519Keypair.deriveKeypair(r,e)};var W=r=>/^0x[0-9a-fA-F]+$|^[0-9a-fA-F]+$/.test(r),Z=r=>/^[a-zA-Z0-9+/]+={0,2}$/g.test(r),B=r=>{if(W(r))return fromHex(r);if(Z(r))return fromBase64(r);throw new Error("The string is not a valid hex or base64 string.")},T=32,Y=64,O=r=>{if(r.length===Y)return r.slice(0,T);if(r.length===T+1&&r[0]===0)return r.slice(1);if(r.length===T)return r;throw new Error("invalid secret key")};var v=(r=24)=>generateMnemonic(wordlist,r===12?128:256);var f=class{constructor({mnemonics:t,secretKey:e}={}){this.mnemonics=t||"",this.secretKey=e||"",!this.mnemonics&&!this.secretKey&&(this.mnemonics=v(24)),this.currentKeyPair=this.secretKey?this.parseSecretKey(this.secretKey):S(this.mnemonics),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress();}parseSecretKey(t){if(t.startsWith(SUI_PRIVATE_KEY_PREFIX)){let{secretKey:e}=decodeSuiPrivateKey(t);return Ed25519Keypair.fromSecretKey(O(e))}return Ed25519Keypair.fromSecretKey(O(B(t)))}getKeyPair(t){return !t||!this.mnemonics?this.currentKeyPair:S(this.mnemonics,t)}getAddress(t){return !t||!this.mnemonics?this.currentAddress:S(this.mnemonics,t).getPublicKey().toSuiAddress()}switchAccount(t){this.mnemonics&&(this.currentKeyPair=S(this.mnemonics,t),this.currentAddress=this.currentKeyPair.getPublicKey().toSuiAddress());}};var nt=r=>{if(typeof r=="string"&&isValidSuiObjectId(r))return "object";if(typeof r=="number"||typeof r=="bigint")return "u64";if(typeof r=="boolean")return "bool"};function E(r){return typeof r=="number"||typeof r=="bigint"||typeof r=="string"&&!isValidSuiAddress(r)&&!isNaN(Number(r))}function st(r){return typeof r=="object"&&"vecType"in r&&"value"in r?!0:!!Array.isArray(r)}function ot(r){return typeof r=="object"&&"digest"in r&&"version"in r&&"objectId"in r}function at(r){return typeof r=="object"&&"objectId"in r&&"initialSharedVersion"in r&&"mutable"in r}function K(r,t,e){if(t.length===0)throw new Error("Transaction builder error: Empty array is not allowed");let i=nt(t[0]),n=/^vector<(.+)>$/,s=/^([^:]+)::([^:]+)::([^<]+)(<(.+)>)?/;if(e=e||i,e==="object"){let o=t.map(c=>typeof c=="string"&&isValidSuiObjectId(c)?r.object(normalizeSuiObjectId(c)):h(r,c));return r.makeMoveVec({elements:o})}else if(typeof e=="string"&&!n.test(e)&&!s.test(e)){let o=getPureBcsSchema(e);return r.pure(bcs.vector(o).serialize(t))}else {let o=t.map(c=>h(r,c));return r.makeMoveVec({elements:o,type:e})}}function y(r,t){return t.map(e=>e instanceof SerializedBcs||isSerializedBcs(e)?r.pure(e):st(e)?"vecType"in e?K(r,e.value,e.vecType):K(r,e):E(e)?d(r,[e])[0]:h(r,e))}function g(r,t){return typeof t=="string"&&isValidSuiAddress(t)?r.pure.address(normalizeSuiAddress(t)):y(r,[t])[0]}function h(r,t){if(typeof t=="string")return r.object(t);if(ot(t))return r.objectRef(t);if(at(t))return r.sharedObjectRef(t);if("Object"in t){if("ImmOrOwnedObject"in t.Object)return r.object(Inputs.ObjectRef(t.Object.ImmOrOwnedObject));if("SharedObject"in t.Object)return r.object(Inputs.SharedObjectRef(t.Object.SharedObject));throw new Error("Invalid argument type")}if(typeof t=="function"||"GasCoin"in t||"Input"in t||"Result"in t||"NestedResult"in t)return t;throw new Error("Invalid argument type")}function d(r,t){return t.map(e=>E(e)?r.pure.u64(e):y(r,[e])[0])}var M=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var u=class{constructor(t){this.txBlock=t?Transaction.from(t):new Transaction;}get gas(){return this.txBlock.gas}get blockData(){return this.txBlock.blockData}get getData(){return this.txBlock.getData()}address(t){return this.txBlock.pure.address(t)}get pure(){return this.txBlock.pure}object(t){return this.txBlock.object(t)}objectRef(t){return this.txBlock.objectRef(t)}sharedObjectRef(t){return this.txBlock.sharedObjectRef(t)}setSender(t){return this.txBlock.setSender(t)}setSenderIfNotSet(t){return this.txBlock.setSenderIfNotSet(t)}setExpiration(t){return this.txBlock.setExpiration(t)}setGasPrice(t){return this.txBlock.setGasPrice(t)}setGasBudget(t){return this.txBlock.setGasBudget(t)}setGasOwner(t){return this.txBlock.setGasOwner(t)}setGasPayment(t){return this.txBlock.setGasPayment(t)}serialize(){return this.txBlock.serialize()}toJSON(){return this.txBlock.toJSON()}sign(t){return this.txBlock.sign(t)}build(t={}){return this.txBlock.build(t)}getDigest(t={}){return this.txBlock.getDigest(t)}add(...t){return this.txBlock.add(...t)}publish({modules:t,dependencies:e}){return this.txBlock.publish({modules:t,dependencies:e})}upgrade(...t){return this.txBlock.upgrade(...t)}makeMoveVec(...t){return this.txBlock.makeMoveVec(...t)}transferObjects(t,e){return this.txBlock.transferObjects(t.map(i=>h(this.txBlock,i)),g(this.txBlock,e))}splitCoins(t,e){let i=this.txBlock.splitCoins(h(this.txBlock,t),d(this.txBlock,e));return e.map((n,s)=>i[s])}mergeCoins(t,e){let i=h(this.txBlock,t),n=e.map(s=>h(this.txBlock,s));return this.txBlock.mergeCoins(i,n)}moveCall(t,e=[],i=[]){let n=/(?<package>[a-zA-Z0-9]+)::(?<module>[a-zA-Z0-9_]+)::(?<function>[a-zA-Z0-9_]+)/;if(t.match(n)===null)throw new Error("Invalid target format. Expected `${string}::${string}::${string}`");let o=y(this.txBlock,e);return this.txBlock.moveCall({target:t,arguments:o,typeArguments:i})}transferSuiToMany(t,e){if(t.length!==e.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let i=this.txBlock.splitCoins(this.txBlock.gas,d(this.txBlock,e));return t.map(s=>g(this.txBlock,s)).forEach((s,o)=>{this.txBlock.transferObjects([i[o]],s);}),this}transferSui(t,e){return this.transferSuiToMany([t],[e])}takeAmountFromCoins(t,e){let{splitedCoins:i,mergedCoin:n}=this.splitMultiCoins(t,d(this.txBlock,[e]));return [i,n]}splitSUIFromGas(t){return this.txBlock.splitCoins(this.txBlock.gas,d(this.txBlock,t))}splitMultiCoins(t,e){if(t.length===0)throw new Error("takeAmountFromCoins: coins array is empty");let i=M(t.slice(1),511),n=h(this.txBlock,t[0]);for(let o of i){let c=o.map(l=>h(this.txBlock,l));this.txBlock.mergeCoins(n,c);}return {splitedCoins:this.txBlock.splitCoins(n,d(this.txBlock,e)),mergedCoin:n}}transferCoinToMany(t,e,i,n){if(i.length!==n.length)throw new Error("transferSuiToMany: recipients.length !== amounts.length");let s=t.map(a=>h(this.txBlock,a)),{splitedCoins:o,mergedCoin:c}=this.splitMultiCoins(s,d(this.txBlock,n));return i.map(a=>g(this.txBlock,a)).forEach((a,m)=>{this.txBlock.transferObjects([o[m]],a);}),this.txBlock.transferObjects([c],g(this.txBlock,e)),this}transferCoin(t,e,i,n){return this.transferCoinToMany(t,e,[i],[n])}stakeSui(t,e){let[i]=this.txBlock.splitCoins(this.txBlock.gas,d(this.txBlock,[t]));return this.txBlock.moveCall({target:"0x3::sui_system::request_add_stake",arguments:y(this.txBlock,[this.txBlock.object(SUI_SYSTEM_STATE_OBJECT_ID),i,g(this.txBlock,e)])})}};var A=class{constructor(t){this.objectId=t.objectId,this.version=t.version,this.digest=t.digest;}isFullObject(){return !!this.version&&!!this.digest}asCallArg(){return !this.version||!this.digest?this.objectId:{$kind:"Object",Object:{$kind:"ImmOrOwnedObject",ImmOrOwnedObject:{objectId:this.objectId,version:this.version,digest:this.digest}}}}updateFromTxResponse(t){let e=t.objectChanges;if(!e)throw new Error("Bad transaction response!");for(let i of e)if(i.type==="mutated"&&i.objectId===this.objectId){this.digest=i.digest,this.version=i.version;return}throw new Error("Could not find object in transaction response!")}};var x=class{constructor(t){this.objectId=t.objectId,this.initialSharedVersion=t.initialSharedVersion;}asCallArg(t=!1){return this.initialSharedVersion?{$kind:"Object",Object:{$kind:"SharedObject",SharedObject:{objectId:this.objectId,initialSharedVersion:this.initialSharedVersion,mutable:t}}}:this.objectId}};var P=r=>new Promise(t=>setTimeout(t,r)),U=(r,t)=>{let e=[];for(let i=0;i<r.length;i+=t)e.push(r.slice(i,i+t));return e};var b=class{constructor(t){this.clients=[];this.fullNodes=[];"fullnodeUrls"in t?(this.fullNodes=t.fullnodeUrls??[getFullnodeUrl("mainnet")],this.clients=this.fullNodes.map(e=>new SuiClient({url:e}))):"suiClients"in t&&t.suiClients?this.clients=t.suiClients:this.clients=[new SuiClient({url:getFullnodeUrl("mainnet")})],this.currentClient=this.clients[0];}switchToNextClient(){let t=this.clients.indexOf(this.currentClient);this.currentClient=this.clients[(t+1)%this.clients.length];}switchFullNodes(t){if(t.length===0)throw new Error("fullNodes cannot be empty");this.fullNodes=t,this.clients=t.map(e=>new SuiClient({url:e})),this.currentClient=this.clients[0];}get currentFullNode(){if(this.fullNodes.length===0)throw new Error("No full nodes available");let t=this.clients.indexOf(this.currentClient);if(t===-1)throw new Error("Current client not found");return this.fullNodes[t]}async sendTx(t,e){let i={showEvents:!0,showEffects:!0,showRawEffects:!0,showObjectChanges:!0,showBalanceChanges:!0};for(let n in this.clients)try{return await this.clients[n].executeTransactionBlock({transactionBlock:t,signature:e,options:i})}catch(s){console.warn(`Failed to send transaction with fullnode ${this.fullNodes[n]}: ${s}`),await P(2e3);}throw new Error("Failed to send transaction with all fullnodes")}async dryRunTx(t){for(let e in this.clients)try{return await this.clients[e].dryRunTransactionBlock({transactionBlock:t})}catch(i){console.warn(`Failed to dry run transaction with fullnode ${this.fullNodes[e]}: ${i}`),await P(2e3);}throw new Error("Failed to dry run transaction with all fullnodes")}async getObjects(t,e){let i=e??{showContent:!0,showDisplay:!0,showType:!0,showOwner:!0},n=U(t,Math.max(e?.batchSize??50,50)),s=[],o=null;for(let c of n){for(let l in this.clients)try{let m=(await this.clients[l].multiGetObjects({ids:c,options:i})).map(p=>p.data).filter(p=>p!=null);s.push(...m),o=null;break}catch(a){o=a instanceof Error?a:new Error(String(a)),await P(e?.switchClientDelay??2e3),console.warn(`Failed to get objects with fullnode ${this.fullNodes[l]}: ${a}`);}if(o)throw new Error(`Failed to get objects with all fullnodes: ${o}`)}return s}async getObject(t,e){return (await this.getObjects([t],e))[0]}async updateObjects(t){let e=t.map(n=>n.objectId),i=await this.getObjects(e);for(let n of i){let s=t.find(o=>o.objectId===n?.objectId);s instanceof x?n.owner&&typeof n.owner=="object"&&"Shared"in n.owner?s.initialSharedVersion=n.owner.Shared.initial_shared_version:s.initialSharedVersion=void 0:s instanceof A&&(s.version=n?.version,s.digest=n?.digest);}}async selectCoins(t,e,i="0x2::SUI::SUI"){let n=[],s=0,o=!0,c=null;for(;o&&s<e;){let l=await this.currentClient.getCoins({owner:t,coinType:i,cursor:c});l.data.sort((a,m)=>parseInt(m.balance)-parseInt(a.balance));for(let a of l.data)if(n.push({objectId:a.coinObjectId,digest:a.digest,version:a.version,balance:a.balance}),s=s+parseInt(a.balance),s>=e)break;c=l.nextCursor,o=l.hasNextPage;}if(!n.length)throw new Error("No valid coins found for the transaction.");return n}};var k=class{constructor(t){let{mnemonics:e,secretKey:i,networkType:n}=t;this.accountManager=new f({mnemonics:e,secretKey:i});let s;"fullnodeUrls"in t?s={fullnodeUrls:t.fullnodeUrls}:"suiClients"in t?s={suiClients:t.suiClients}:s={fullnodeUrls:[getFullnodeUrl(n??"mainnet")]},this.suiInteractor=new b(s);}createTxBlock(){let t=new u;return t.setSender(this.accountManager.currentAddress),t}getKeypair(t){return this.accountManager.getKeyPair(t)}switchAccount(t){this.accountManager.switchAccount(t);}getAddress(t){return this.accountManager.getAddress(t)}get currentAddress(){return this.accountManager.currentAddress}async getBalance(t,e){let i=this.accountManager.getAddress(e);return this.suiInteractor.currentClient.getBalance({owner:i,coinType:t})}get client(){return this.suiInteractor.currentClient}async getObjects(t,e){return this.suiInteractor.getObjects(t,e)}async updateObjects(t){return this.suiInteractor.updateObjects(t)}async signTxn(t,e){t instanceof u&&t.setSender(this.getAddress(e));let i=t instanceof u?t.txBlock:t,n=i instanceof Uint8Array?i:await i.build({client:this.client});return await this.getKeypair(e).signTransaction(n)}async signAndSendTxn(t,e){let{bytes:i,signature:n}=await this.signTxn(t,e);return this.suiInteractor.sendTx(i,n)}async dryRunTxn(t,e){t instanceof u&&t.setSender(this.getAddress(e));let i=t instanceof u?t.txBlock:t,n=i instanceof Uint8Array?i:await i.build({client:this.client});return this.suiInteractor.dryRunTx(n)}async transferSui(t,e,i=!0,n){let s=new u;return s.transferSui(t,e),i?await this.signAndSendTxn(s,n):s}async transferSuiToMany(t,e,i=!0,n){let s=new u;return s.transferSuiToMany(t,e),i?await this.signAndSendTxn(s,n):s}async transferCoinToMany(t,e,i,n=!0,s){let o=new u,c=this.accountManager.getAddress(s),l=e.reduce((m,p)=>m+p,0),a=await this.suiInteractor.selectCoins(c,l,i);return o.transferCoinToMany(a.map(m=>m.objectId),c,t,e),n?await this.signAndSendTxn(o,s):o}async transferCoin(t,e,i,n=!0,s){return this.transferCoinToMany([t],[e],i,n,s)}async transferObjects(t,e,i=!0,n){let s=new u;return s.transferObjects(t,e),i?await this.signAndSendTxn(s,n):s}async moveCall(t){let{target:e,arguments:i=[],typeArguments:n=[],derivePathParams:s}=t,o=new u;return o.moveCall(e,i,n),this.signAndSendTxn(o,s)}async selectCoinsWithAmount(t,e,i){return i=i||this.accountManager.currentAddress,await this.suiInteractor.selectCoins(i,t,e)}async stakeSui(t,e,i=!0,n){let s=new u;return s.stakeSui(t,e),i?await this.signAndSendTxn(s,n):s}async inspectTxn(t,e){let i=t instanceof u?t.txBlock:t;return this.suiInteractor.currentClient.devInspectTransactionBlock({transactionBlock:i,sender:this.getAddress(e)})}};function N(r){let t=fromBase64(r);if(t.length!==32&&t.length!==33)throw "invalid pubkey length";return t=t.length===33?t.slice(1):t,new Ed25519PublicKey(t)}var j=class r{constructor(t,e){this.pksWeightPairs=t,this.threshold=e,this.multiSigPublicKey=MultiSigPublicKey.fromPublicKeys({threshold:this.threshold,publicKeys:this.pksWeightPairs});}static fromRawEd25519PublicKeys(t,e,i){let n=t.map((s,o)=>({publicKey:N(s),weight:e[o]}));return new r(n,i)}multiSigAddress(){return this.multiSigPublicKey.toSuiAddress()}combinePartialSigs(t){return this.multiSigPublicKey.combinePartialSignatures(t)}};
14
-
15
- export { j as MultiSigClient, f as SuiAccountManager, b as SuiInteractor, k as SuiKit, u as SuiTxBlock };
@@ -1,15 +0,0 @@
1
- import { MultiSigPublicKey } from '@mysten/sui/multisig';
2
- import type { PublicKey } from '@mysten/sui/cryptography';
3
- export type PublicKeyWeightPair = {
4
- publicKey: PublicKey;
5
- weight: number;
6
- };
7
- export declare class MultiSigClient {
8
- readonly pksWeightPairs: PublicKeyWeightPair[];
9
- readonly threshold: number;
10
- readonly multiSigPublicKey: MultiSigPublicKey;
11
- constructor(pks: PublicKeyWeightPair[], threshold: number);
12
- static fromRawEd25519PublicKeys(rawPublicKeys: string[], weights: number[], threshold: number): MultiSigClient;
13
- multiSigAddress(): string;
14
- combinePartialSigs(sigs: string[]): string;
15
- }
@@ -1 +0,0 @@
1
- export { MultiSigClient } from './client';
@@ -1,2 +0,0 @@
1
- import { PublicKey } from '@mysten/sui/cryptography';
2
- export declare function ed25519PublicKeyFromBase64(rawPubkey: string): PublicKey;
@@ -1 +0,0 @@
1
- export declare const generateMnemonic: (numberOfWords?: 12 | 24) => string;
@@ -1,39 +0,0 @@
1
- import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
2
- import type { AccountManagerParams, DerivePathParams } from 'src/types';
3
- export declare class SuiAccountManager {
4
- private mnemonics;
5
- private secretKey;
6
- currentKeyPair: Ed25519Keypair;
7
- currentAddress: string;
8
- /**
9
- * Support the following ways to init the SuiToolkit:
10
- * 1. mnemonics
11
- * 2. secretKey (base64 or hex)
12
- * If none of them is provided, will generate a random mnemonics with 24 words.
13
- *
14
- * @param mnemonics, 12 or 24 mnemonics words, separated by space
15
- * @param secretKey, base64 or hex string or Bech32 string, when mnemonics is provided, secretKey will be ignored
16
- */
17
- constructor({ mnemonics, secretKey }?: AccountManagerParams);
18
- /**
19
- * Check if the secretKey starts with bench32 format
20
- */
21
- parseSecretKey(secretKey: string): Ed25519Keypair;
22
- /**
23
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentKeyPair.
24
- * else:
25
- * it will generate keyPair from the mnemonic with the given derivePathParams.
26
- */
27
- getKeyPair(derivePathParams?: DerivePathParams): Ed25519Keypair;
28
- /**
29
- * if derivePathParams is not provided or mnemonics is empty, it will return the currentAddress.
30
- * else:
31
- * it will generate address from the mnemonic with the given derivePathParams.
32
- */
33
- getAddress(derivePathParams?: DerivePathParams): string;
34
- /**
35
- * Switch the current account with the given derivePathParams.
36
- * This is only useful when the mnemonics is provided. For secretKey mode, it will always use the same account.
37
- */
38
- switchAccount(derivePathParams: DerivePathParams): void;
39
- }
@@ -1,21 +0,0 @@
1
- import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
2
- import type { DerivePathParams } from 'src/types';
3
- /**
4
- * @description Get ed25519 derive path for SUI
5
- * @param derivePathParams
6
- */
7
- export declare const getDerivePathForSUI: (derivePathParams?: DerivePathParams) => string;
8
- /**
9
- * the format is m/44'/784'/accountIndex'/${isExternal ? 1 : 0}'/addressIndex'
10
- *
11
- * accountIndex is the index of the account, default is 0.
12
- *
13
- * isExternal is the type of the address, default is false. Usually, the external address is used to receive coins. The internal address is used to change coins.
14
- *
15
- * addressIndex is the index of the address, default is 0. It's used to generate multiple addresses for one account.
16
- *
17
- * @description Get keypair from mnemonics and derive path
18
- * @param mnemonics
19
- * @param derivePathParams
20
- */
21
- export declare const getKeyPair: (mnemonics: string, derivePathParams?: DerivePathParams) => Ed25519Keypair;
@@ -1,29 +0,0 @@
1
- /**
2
- * @description This regular expression matches any string that contains only hexadecimal digits (0-9, A-F, a-f).
3
- * @param str
4
- */
5
- export declare const isHex: (str: string) => boolean;
6
- /**
7
- * @description This regular expression matches any string that contains only base64 digits (0-9, A-Z, a-z, +, /, =).
8
- * Note that the "=" signs at the end are optional padding characters that may be present in some base64 encoded strings.
9
- * @param str
10
- */
11
- export declare const isBase64: (str: string) => boolean;
12
- /**
13
- * Use fromHex or fromBase64 from @mysten/bcs directly instead.
14
- * @description Convert a hex or base64 string to Uint8Array
15
- */
16
- export declare const hexOrBase64ToUint8Array: (str: string) => Uint8Array;
17
- /**
18
- * normalize a private key
19
- * A private key is a 32-byte array.
20
- * But there are two different formats for private keys:
21
- * 1. A 32-byte array
22
- * 2. A 64-byte array with the first 32 bytes being the private key and the last 32 bytes being the public key
23
- * 3. A 33-byte array with the first byte being 0x00 (sui.keystore key is a Base64 string with scheme flag 0x00 at the beginning)
24
- */
25
- export declare const normalizePrivateKey: (key: Uint8Array) => Uint8Array;
26
- /**
27
- * @deprecated Please use fromHex and fromBase64 from '@mysten/bcs' directly.
28
- */
29
- export { fromHex, fromBase64 } from '@mysten/bcs';
@@ -1 +0,0 @@
1
- export { SuiInteractor } from './suiInteractor';
@@ -1,39 +0,0 @@
1
- import { SuiInteractorParams } from 'src/types';
2
- import { SuiOwnedObject, SuiSharedObject } from '../suiModel';
3
- import { type SuiTransactionBlockResponse, type SuiObjectDataOptions, type SuiObjectData, type DryRunTransactionBlockResponse, SuiClient } from '@mysten/sui/client';
4
- /**
5
- * Encapsulates all functions that interact with the sui sdk
6
- */
7
- export declare class SuiInteractor {
8
- private clients;
9
- currentClient: SuiClient;
10
- private fullNodes;
11
- constructor(params: Partial<SuiInteractorParams>);
12
- switchToNextClient(): void;
13
- switchFullNodes(fullNodes: string[]): void;
14
- get currentFullNode(): string;
15
- sendTx(transactionBlock: Uint8Array | string, signature: string | string[]): Promise<SuiTransactionBlockResponse>;
16
- dryRunTx(transactionBlock: Uint8Array): Promise<DryRunTransactionBlockResponse>;
17
- getObjects(ids: string[], options?: SuiObjectDataOptions & {
18
- batchSize?: number;
19
- switchClientDelay?: number;
20
- }): Promise<SuiObjectData[]>;
21
- getObject(id: string, options?: SuiObjectDataOptions): Promise<SuiObjectData>;
22
- /**
23
- * @description Update objects in a batch
24
- * @param suiObjects
25
- */
26
- updateObjects(suiObjects: (SuiOwnedObject | SuiSharedObject)[]): Promise<void>;
27
- /**
28
- * @description Select coins that add up to the given amount.
29
- * @param addr the address of the owner
30
- * @param amount the amount that is needed for the coin
31
- * @param coinType the coin type, default is '0x2::SUI::SUI'
32
- */
33
- selectCoins(addr: string, amount: number, coinType?: string): Promise<{
34
- objectId: string;
35
- digest: string;
36
- version: string;
37
- balance: string;
38
- }[]>;
39
- }
@@ -1,2 +0,0 @@
1
- export declare const delay: (ms: number) => Promise<unknown>;
2
- export declare const batch: <T>(arr: T[], size: number) => T[][];
@@ -1,2 +0,0 @@
1
- export { SuiOwnedObject } from './suiOwnedObject';
2
- export { SuiSharedObject } from './suiSharedObject';
@@ -1,24 +0,0 @@
1
- import type { SuiTransactionBlockResponse } from '@mysten/sui/client';
2
- import type { CallArg } from '@mysten/sui/transactions';
3
- export declare class SuiOwnedObject {
4
- readonly objectId: string;
5
- version?: string;
6
- digest?: string;
7
- constructor(param: {
8
- objectId: string;
9
- version?: string;
10
- digest?: string;
11
- });
12
- /**
13
- * Check if the object is fully initialized.
14
- * So that when it's used as an input, it won't be necessary to fetch from fullnode again.
15
- * Which can save time when sending transactions.
16
- */
17
- isFullObject(): boolean;
18
- asCallArg(): CallArg | string;
19
- /**
20
- * Update object version & digest based on the transaction response.
21
- * @param txResponse
22
- */
23
- updateFromTxResponse(txResponse: SuiTransactionBlockResponse): void;
24
- }
@@ -1,11 +0,0 @@
1
- import type { CallArg } from '@mysten/sui/transactions';
2
- export declare class SuiSharedObject {
3
- readonly objectId: string;
4
- initialSharedVersion?: string;
5
- constructor(param: {
6
- objectId: string;
7
- initialSharedVersion?: string;
8
- mutable?: boolean;
9
- });
10
- asCallArg(mutable?: boolean): CallArg | string;
11
- }