@0xobelisk/client 0.0.9 → 0.1.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 (42) hide show
  1. package/dist/index.d.ts +2 -1
  2. package/dist/index.js +337 -292
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +345 -303
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/libs/suiAccountManager/index.d.ts +1 -1
  7. package/dist/libs/suiAccountManager/keypair.d.ts +1 -1
  8. package/dist/libs/suiContractFactory/index.d.ts +0 -1
  9. package/dist/libs/suiInteractor/defaultConfig.d.ts +10 -0
  10. package/dist/libs/suiInteractor/index.d.ts +2 -0
  11. package/dist/libs/suiInteractor/suiInteractor.d.ts +204 -0
  12. package/dist/libs/suiInteractor/util.d.ts +1 -0
  13. package/dist/libs/suiModel/index.d.ts +2 -0
  14. package/dist/libs/suiModel/suiOwnedObject.d.ts +24 -0
  15. package/dist/libs/suiModel/suiSharedObject.d.ts +12 -0
  16. package/dist/libs/suiTxBuilder/index.d.ts +2 -2
  17. package/dist/libs/suiTxBuilder/util.d.ts +8 -8
  18. package/dist/metadata/index.d.ts +1 -1
  19. package/dist/obelisk.d.ts +122 -337
  20. package/dist/types/index.d.ts +48 -6
  21. package/package.json +3 -3
  22. package/src/index.ts +2 -1
  23. package/src/libs/suiAccountManager/index.ts +1 -1
  24. package/src/libs/suiAccountManager/keypair.ts +2 -2
  25. package/src/libs/suiContractFactory/index.ts +0 -1
  26. package/src/libs/{suiRpcProvider/defaultChainConfigs.ts → suiInteractor/defaultConfig.ts} +4 -2
  27. package/src/libs/suiInteractor/index.ts +2 -0
  28. package/src/libs/suiInteractor/suiInteractor.ts +269 -0
  29. package/src/libs/suiInteractor/util.ts +2 -0
  30. package/src/libs/suiModel/index.ts +2 -0
  31. package/src/libs/suiModel/suiOwnedObject.ts +62 -0
  32. package/src/libs/suiModel/suiSharedObject.ts +33 -0
  33. package/src/libs/suiTxBuilder/index.ts +1 -1
  34. package/src/libs/suiTxBuilder/util.ts +1 -1
  35. package/src/metadata/index.ts +7 -7
  36. package/src/obelisk.ts +38 -130
  37. package/src/types/index.ts +92 -10
  38. package/src/libs/suiAccountManager/types.ts +0 -10
  39. package/src/libs/suiRpcProvider/faucet.ts +0 -57
  40. package/src/libs/suiRpcProvider/index.ts +0 -150
  41. package/src/libs/suiRpcProvider/types.ts +0 -17
  42. package/src/libs/suiTxBuilder/types.ts +0 -32
package/src/obelisk.ts CHANGED
@@ -1,14 +1,18 @@
1
- import { ObjectData } from './libs/suiRpcProvider/types';
2
1
  import {
3
2
  RawSigner,
4
3
  TransactionBlock,
5
4
  DevInspectResults,
6
5
  SuiTransactionBlockResponse,
7
- SuiMoveNormalizedModules, DynamicFieldPage, DynamicFieldName, SuiAddress,
6
+ SuiMoveNormalizedModules,
7
+ DynamicFieldName,
8
+ SuiAddress
8
9
  } from '@mysten/sui.js';
9
10
  import { SuiAccountManager } from './libs/suiAccountManager';
10
- import { SuiRpcProvider } from './libs/suiRpcProvider';
11
11
  import { SuiTxBlock } from './libs/suiTxBuilder';
12
+ import { SuiInteractor, getDefaultConnection } from './libs/suiInteractor';
13
+ import { SuiSharedObject, SuiOwnedObject } from './libs/suiModel';
14
+
15
+ import { ObeliskObjectData } from 'src/types';
12
16
  import { SuiContractFactory } from './libs/suiContractFactory';
13
17
  import { SuiMoveMoudleValueType, SuiMoveMoudleFuncType } from './libs/suiContractFactory/types';
14
18
  import {
@@ -18,7 +22,7 @@ import {
18
22
  ComponentContentType,
19
23
  SuiTxArgument, ContractQuery,
20
24
  ContractTx, MapMoudleFuncQuery,
21
- MapMoudleFuncTx
25
+ MapMoudleFuncTx, FaucetNetworkType
22
26
  } from './types';
23
27
  import {capitalizeFirstLetter} from "./utils"
24
28
  import keccak256 from "keccak256";
@@ -59,18 +63,15 @@ function createTx(
59
63
  */
60
64
  export class Obelisk {
61
65
  public accountManager: SuiAccountManager;
62
- public rpcProvider: SuiRpcProvider;
66
+ public suiInteractor: SuiInteractor;
63
67
  public contractFactory: SuiContractFactory;
64
68
  public packageId: string | undefined;
65
- // public needLoad: boolean | undefined;
66
69
  public metadata: SuiMoveNormalizedModules;
67
- public epsId: string;
68
- public componentsId: string;
69
70
 
70
71
  readonly #query: MapMoudleFuncQuery = {};
71
72
  readonly #tx: MapMoudleFuncTx = {};
72
73
  /**
73
- * Support the following ways to init the SuiToolkit:
74
+ * Support the following ways to init the ObeliskClient:
74
75
  * 1. mnemonics
75
76
  * 2. secretKey (base64 or hex)
76
77
  * If none of them is provided, will generate a random mnemonics with 24 words.
@@ -79,29 +80,22 @@ export class Obelisk {
79
80
  * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
80
81
  * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
81
82
  * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type
82
- * @param faucetUrl, the faucet url, default is the preconfig faucet url for the given network type
83
83
  * @param packageId
84
84
  */
85
85
  constructor({
86
86
  mnemonics,
87
87
  secretKey,
88
88
  networkType,
89
- fullnodeUrl,
90
- faucetUrl,
89
+ fullnodeUrls,
91
90
  packageId,
92
91
  metadata
93
92
  }: ObeliskParams = {}) {
94
93
  // Init the account manager
95
94
  this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
96
95
  // Init the rpc provider
97
- this.rpcProvider = new SuiRpcProvider({
98
- fullnodeUrl,
99
- faucetUrl,
100
- networkType,
101
- });
96
+ fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
97
+ this.suiInteractor = new SuiInteractor(fullnodeUrls, networkType);
102
98
 
103
- this.epsId = "0xf2196f638c3174e18c0e31aa630a02fd516c2c5deec1ded72c0fea864c9f091a"
104
- this.componentsId = "0x3bc407eb543149e42846ade59ac2a3c901584af4339dc1ecd0affd090529545f"
105
99
  this.packageId = packageId;
106
100
  this.metadata = metadata as SuiMoveNormalizedModules;
107
101
  Object.values(metadata as SuiMoveNormalizedModules).forEach(value => {
@@ -134,16 +128,6 @@ export class Obelisk {
134
128
  })
135
129
  }
136
130
 
137
- // async initialize() {
138
- // const metadata = await this.loadData();
139
- // this.metadata = metadata as SuiMoveNormalizedModules;
140
- // this.contractFactory = new SuiContractFactory({
141
- // packageId: this.packageId,
142
- // metadata: this.metadata
143
- // })
144
- // return metadata
145
- // }
146
-
147
131
  public get query (): MapMoudleFuncQuery {
148
132
  return this.#query;
149
133
  }
@@ -184,7 +168,7 @@ export class Obelisk {
184
168
  */
185
169
  getSigner(derivePathParams?: DerivePathParams) {
186
170
  const keyPair = this.accountManager.getKeyPair(derivePathParams);
187
- return new RawSigner(keyPair, this.rpcProvider.provider);
171
+ return new RawSigner(keyPair, this.suiInteractor.currentProvider);
188
172
  }
189
173
 
190
174
  /**
@@ -207,7 +191,7 @@ export class Obelisk {
207
191
  }
208
192
 
209
193
  provider() {
210
- return this.rpcProvider.provider;
194
+ return this.suiInteractor.currentProvider;
211
195
  }
212
196
 
213
197
  getPackageId() {
@@ -221,24 +205,25 @@ export class Obelisk {
221
205
  * Request some SUI from faucet
222
206
  * @Returns {Promise<boolean>}, true if the request is successful, false otherwise.
223
207
  */
224
- async requestFaucet(derivePathParams?: DerivePathParams) {
225
- const addr = this.accountManager.getAddress(derivePathParams);
226
- return this.rpcProvider.requestFaucet(addr);
208
+ async requestFaucet(address: SuiAddress, network: FaucetNetworkType) {
209
+ // const addr = this.accountManager.getAddress(derivePathParams);
210
+ return this.suiInteractor.requestFaucet(address, network);
227
211
  }
228
212
 
229
213
  async getBalance(coinType?: string, derivePathParams?: DerivePathParams) {
230
214
  const owner = this.accountManager.getAddress(derivePathParams);
231
- return this.rpcProvider.getBalance(owner, coinType);
215
+ return this.suiInteractor.currentProvider.getBalance({ owner, coinType });
232
216
  }
233
217
 
234
218
  async getObject(objectId: string) {
235
- return this.rpcProvider.getObject(objectId);
219
+ return this.suiInteractor.getObject(objectId);
236
220
  }
237
221
 
238
222
  async getObjects(objectIds: string[]) {
239
- return this.rpcProvider.getObjects(objectIds);
223
+ return this.suiInteractor.getObjects(objectIds);
240
224
  }
241
225
 
226
+
242
227
  async signTxn(
243
228
  tx: Uint8Array | TransactionBlock | SuiTxBlock,
244
229
  derivePathParams?: DerivePathParams
@@ -252,16 +237,11 @@ export class Obelisk {
252
237
  tx: Uint8Array | TransactionBlock | SuiTxBlock,
253
238
  derivePathParams?: DerivePathParams
254
239
  ): Promise<SuiTransactionBlockResponse> {
255
- tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
256
- const signer = this.getSigner(derivePathParams);
257
- return signer.signAndExecuteTransactionBlock({
258
- transactionBlock: tx,
259
- options: {
260
- showEffects: true,
261
- showEvents: true,
262
- showObjectChanges: true,
263
- },
264
- });
240
+ const { transactionBlockBytes, signature } = await this.signTxn(
241
+ tx,
242
+ derivePathParams
243
+ );
244
+ return this.suiInteractor.sendTx(transactionBlockBytes, signature);
265
245
  }
266
246
 
267
247
  /**
@@ -312,7 +292,7 @@ export class Obelisk {
312
292
  const tx = new SuiTxBlock();
313
293
  const owner = this.accountManager.getAddress(derivePathParams);
314
294
  const totalAmount = amounts.reduce((a, b) => a + b, 0);
315
- const coins = await this.rpcProvider.selectCoins(
295
+ const coins = await this.suiInteractor.selectCoins(
316
296
  owner,
317
297
  totalAmount,
318
298
  coinType
@@ -379,7 +359,7 @@ export class Obelisk {
379
359
  owner?: string
380
360
  ) {
381
361
  owner = owner || this.accountManager.currentAddress;
382
- const coins = await this.rpcProvider.selectCoins(owner, amount, coinType);
362
+ const coins = await this.suiInteractor.selectCoins(owner, amount, coinType);
383
363
  return coins.map((c) => c.objectId);
384
364
  }
385
365
 
@@ -410,38 +390,21 @@ export class Obelisk {
410
390
  tx: Uint8Array | TransactionBlock | SuiTxBlock,
411
391
  derivePathParams?: DerivePathParams
412
392
  ): Promise<DevInspectResults> {
413
-
414
393
  tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
415
- return this.rpcProvider.provider.devInspectTransactionBlock({
394
+ return this.suiInteractor.currentProvider.devInspectTransactionBlock({
416
395
  transactionBlock: tx,
417
396
  sender: this.getAddress(derivePathParams),
418
397
  });
419
398
  }
420
399
 
421
400
  async getWorld(worldObjectId: string) {
422
- return this.rpcProvider.getObject(worldObjectId)
423
- }
424
-
425
- async getAllEntities(worldId: string, cursor?: string, limit?: number) {
426
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.entities.fields.id.id;
427
- return await this.rpcProvider.getDynamicFields(parentId, cursor, limit) as DynamicFieldPage;
428
- }
429
-
430
- async getEntity(worldId: string, entityId: string) {
431
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.entities.fields.id.id;
432
-
433
- console.log(parentId)
434
- const name = {
435
- type: "0x2::object::ID",
436
- value: entityId
437
- } as DynamicFieldName
438
- return await this.rpcProvider.getDynamicFieldObject(parentId, name);
401
+ return this.suiInteractor.getObject(worldObjectId)
439
402
  }
440
403
 
441
404
  async getComponents(worldId: string) {
442
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.components.fields.id.id;
405
+ const parentId = (await this.suiInteractor.getObject(worldId)).objectFields.components.fields.id.id;
443
406
 
444
- return await this.rpcProvider.getDynamicFields(parentId);
407
+ return await this.suiInteractor.getDynamicFields(parentId);
445
408
  }
446
409
 
447
410
 
@@ -452,20 +415,19 @@ export class Obelisk {
452
415
 
453
416
  async getComponent(worldId: string, componentId: Buffer) {
454
417
  const componentIdValue: number[] = Array.from(componentId);
455
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.components.fields.id.id;
456
- console.log(parentId)
418
+ const parentId = (await this.suiInteractor.getObject(worldId)).objectFields.components.fields.id.id;
419
+
457
420
  const name = {
458
- // type: "0x2::object::ID",
459
421
  type: "vector<u8>",
460
422
  value: componentIdValue
461
423
  // value: [250,208,186,160,39,171,62,206,98,224,138,41,11,217,63,100,248,104,207,64,78,126,43,109,129,68,64,127,236,113,152,132]
462
424
  } as DynamicFieldName
463
- return await this.rpcProvider.getDynamicFieldObject(parentId, name);
425
+ return await this.suiInteractor.getDynamicFieldObject(parentId, name);
464
426
  }
465
427
 
466
428
  async getOwnedEntities(owner: SuiAddress, cursor?: string, limit?: number) {
467
- const ownedObjects = await this.rpcProvider.getOwnedObjects(owner, cursor, limit)
468
- let ownedEntities: ObjectData[] = [];
429
+ const ownedObjects = await this.suiInteractor.getOwnedObjects(owner, cursor, limit)
430
+ let ownedEntities: ObeliskObjectData[] = [];
469
431
 
470
432
  for (const object of ownedObjects.data) {
471
433
  let objectDetail = await this.getObject(object.data!.objectId);
@@ -477,58 +439,4 @@ export class Obelisk {
477
439
 
478
440
  return ownedEntities;
479
441
  }
480
-
481
- async getTable(worldId: string, entityId: string) {
482
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.storages.fields.id.id;
483
-
484
- console.log(parentId)
485
- const name = {
486
- type: "0x2::object::ID",
487
- value: entityId
488
- } as DynamicFieldName
489
- return await this.rpcProvider.getDynamicFieldObject(parentId, name);
490
- }
491
-
492
- async getEntityComponents(worldId: string, entityId: string, cursor?: string, limit?: number) {
493
- const parentContent = (await this.getEntity(worldId, entityId)).data!.content as ComponentContentType;
494
- const parentId = parentContent.fields.value.fields.components.fields.id.id;
495
- return await this.rpcProvider.getDynamicFields(parentId, cursor, limit) as DynamicFieldPage;
496
- }
497
-
498
- async getEntityComponent(entityId: string, componentId: string) {
499
- const parentId = (await this.rpcProvider.getObject(entityId)).objectFields.id.id;
500
-
501
- const name = {
502
- type: "0x2::object::ID",
503
- value: componentId
504
- } as DynamicFieldName
505
- return await this.rpcProvider.getDynamicFieldObject(parentId, name);
506
- }
507
-
508
-
509
- // async loadData() {
510
- // const jsonFileName = `metadata/${this.packageId}.json`;
511
-
512
- // try {
513
- // const data = await fs.promises.readFile(jsonFileName, 'utf-8');
514
- // const jsonData = JSON.parse(data);
515
-
516
- // return jsonData as SuiMoveNormalizedModules;
517
- // } catch (error) {
518
- // if (this.packageId !== undefined) {
519
- // const jsonData = await this.rpcProvider.getNormalizedMoveModulesByPackage(this.packageId);
520
-
521
- // fs.writeFile(jsonFileName, JSON.stringify(jsonData, null, 2), (err) => {
522
- // if (err) {
523
- // console.error('写入文件时出错:', err);
524
- // } else {
525
- // console.log('JSON 数据已保存到文件:', jsonFileName);
526
- // }
527
- // });
528
- // return jsonData as SuiMoveNormalizedModules;
529
- // } else {
530
- // console.error('please set your package id.');
531
- // }
532
- // }
533
- // }
534
442
  }
@@ -1,22 +1,34 @@
1
- import { SuiMoveNormalizedModules, DevInspectResults, SuiTransactionBlockResponse, SuiMoveNormalizedType, TransactionBlock } from "@mysten/sui.js";
1
+ import { Infer } from 'superstruct';
2
+ import {
3
+ DisplayFieldsResponse,
4
+ ObjectCallArg,
5
+ ObjectContentFields,
6
+ SharedObjectRef,
7
+ SuiObjectRef,
8
+ TransactionArgument,
9
+ TransactionBlock,
10
+ SuiTransactionBlockResponse,
11
+ DevInspectResults,
12
+ SuiMoveNormalizedModules
13
+ } from '@mysten/sui.js';
2
14
 
3
- import type { NetworkType as SuiNetworkType } from '../libs/suiRpcProvider/types';
4
15
 
5
- export type { DerivePathParams } from '../libs/suiAccountManager/types';
6
16
  import { SuiMoveMoudleValueType, SuiMoveMoudleFuncType } from '../libs/suiContractFactory/types';
7
17
 
8
- export type {
9
- SuiTxArg,
10
- SuiVecTxArg,
11
- SuiObjectArg,
12
- } from '../libs/suiTxBuilder/types';
13
18
 
14
- export type NetworkType = SuiNetworkType;
19
+ export type ObeliskObjectData = {
20
+ objectId: string;
21
+ objectType: string;
22
+ objectVersion: number;
23
+ objectDisplay: DisplayFieldsResponse;
24
+ objectFields: ObjectContentFields;
25
+ };
26
+
15
27
 
16
28
  export type ObeliskParams = {
17
29
  mnemonics?: string;
18
30
  secretKey?: string;
19
- fullnodeUrl?: string;
31
+ fullnodeUrls?: string[];
20
32
  faucetUrl?: string;
21
33
  networkType?: NetworkType;
22
34
  packageId?: string,
@@ -89,3 +101,73 @@ export type MapMoudleFuncQuery = Record<string, MapMessageQuery>;
89
101
 
90
102
  export type MapMoudleFuncTest = Record<string, Record<string, string>>;
91
103
  export type MapMoudleFuncQueryTest = Record<string, Record<string, string>>;
104
+
105
+
106
+
107
+ export type AccountMangerParams = {
108
+ mnemonics?: string;
109
+ secretKey?: string;
110
+ };
111
+
112
+ export type DerivePathParams = {
113
+ accountIndex?: number;
114
+ isExternal?: boolean;
115
+ addressIndex?: number;
116
+ };
117
+
118
+ export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
119
+ export type FaucetNetworkType = 'testnet' | 'devnet' | 'localnet'
120
+
121
+ export type SuiKitParams = {
122
+ mnemonics?: string;
123
+ secretKey?: string;
124
+ fullnodeUrls?: string[];
125
+ faucetUrl?: string;
126
+ networkType?: NetworkType;
127
+ };
128
+
129
+ export type ObjectData = {
130
+ objectId: string;
131
+ objectType: string;
132
+ objectVersion: number;
133
+ objectDigest: string;
134
+ initialSharedVersion?: number;
135
+ objectDisplay: DisplayFieldsResponse;
136
+ objectFields: ObjectContentFields;
137
+ };
138
+
139
+
140
+
141
+ export type SuiTxArg =
142
+ | Infer<typeof TransactionArgument>
143
+ | Infer<typeof ObjectCallArg>
144
+ | string
145
+ | number
146
+ | bigint
147
+ | boolean;
148
+
149
+ export type SuiObjectArg =
150
+ | SharedObjectRef
151
+ | Infer<typeof SuiObjectRef>
152
+ | string
153
+ | Infer<typeof ObjectCallArg>
154
+ | Infer<typeof TransactionArgument>;
155
+
156
+ export type SuiVecTxArg =
157
+ | { value: SuiTxArg[]; vecType: SuiInputTypes }
158
+ | SuiTxArg[];
159
+
160
+ /**
161
+ * These are the basics types that can be used in the SUI
162
+ */
163
+ export type SuiBasicTypes =
164
+ | 'address'
165
+ | 'bool'
166
+ | 'u8'
167
+ | 'u16'
168
+ | 'u32'
169
+ | 'u64'
170
+ | 'u128'
171
+ | 'u256';
172
+
173
+ export type SuiInputTypes = 'object' | SuiBasicTypes;
@@ -1,10 +0,0 @@
1
- export type AccountMangerParams = {
2
- mnemonics?: string;
3
- secretKey?: string;
4
- };
5
-
6
- export type DerivePathParams = {
7
- accountIndex?: number;
8
- isExternal?: boolean;
9
- addressIndex?: number;
10
- };
@@ -1,57 +0,0 @@
1
- import {
2
- JsonRpcProvider,
3
- FaucetRateLimitError,
4
- assert,
5
- FaucetResponse,
6
- } from '@mysten/sui.js';
7
- import { retry } from 'ts-retry-promise';
8
-
9
- /**
10
- * Request some SUI from faucet
11
- * @param address
12
- * @param provider
13
- * @returns {Promise<boolean>}, return true if the request is successful
14
- */
15
- export const requestFaucet = async (
16
- address: string,
17
- provider: JsonRpcProvider
18
- ) => {
19
- console.log('\nRequesting SUI from faucet for address: ', address);
20
- const headers = {
21
- authority: 'faucet.testnet.sui.io',
22
- method: 'POST',
23
- path: '/gas',
24
- scheme: 'https',
25
- accept: '*/*',
26
- 'accept-encoding': 'gzip, deflate, br',
27
- 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,ja;q=0.7',
28
- 'content-length': '105',
29
- 'content-type': 'application/json',
30
- origin: 'chrome-extension://opcgpfmipidbgpenhmajoajpbobppdil',
31
- cookie:
32
- '_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',
33
- 'sec-ch-ua':
34
- '"Google Chrome";v="111", "Not(A:Brand";v="8", "Chromium";v="111"',
35
- 'sec-ch-ua-mobile': '?0',
36
- 'sec-ch-ua-platform': 'macOS',
37
- 'sec-fetch-dest': 'empty',
38
- 'sec-fetch-mode': 'cors',
39
- 'sec-fetch-site': 'none',
40
- 'user-agent':
41
- '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',
42
- };
43
- // We need to add the following headers to the request, otherwise the request will be rejected by the faucet server
44
- const resp = await retry<FaucetResponse>(
45
- () => provider.requestSuiFromFaucet(address, headers),
46
- {
47
- backoff: 'EXPONENTIAL',
48
- // overall timeout in 60 seconds
49
- timeout: 1000 * 60,
50
- // skip retry if we hit the rate-limit error
51
- retryIf: (error: any) => !(error instanceof FaucetRateLimitError),
52
- logger: (msg) => console.warn(`Retry requesting faucet: ${msg}`),
53
- }
54
- );
55
- assert(resp, FaucetResponse, 'Request faucet failed\n');
56
- console.log('Request faucet success\n');
57
- };
@@ -1,150 +0,0 @@
1
- import {
2
- Connection,
3
- JsonRpcProvider,
4
- getObjectType,
5
- getObjectId,
6
- getObjectFields,
7
- getObjectDisplay,
8
- getObjectVersion,
9
- DynamicFieldName,
10
- SuiAddress
11
- } from '@mysten/sui.js';
12
- import { requestFaucet } from './faucet';
13
- import { getDefaultNetworkParams } from './defaultChainConfigs';
14
- import type { ObjectData, SuiRpcProviderParams } from './types';
15
-
16
- export class SuiRpcProvider {
17
- public fullnodeUrl: string;
18
- public faucetUrl?: string;
19
- public provider: JsonRpcProvider;
20
- /**
21
- *
22
- * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
23
- * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type
24
- * @param faucetUrl, the faucet url, default is the preconfig faucet url for the given network type
25
- */
26
- constructor({
27
- fullnodeUrl,
28
- faucetUrl,
29
- networkType,
30
- }: SuiRpcProviderParams = {}) {
31
- // Get the default fullnode url and faucet url for the given network type, default is 'testnet'
32
- const defaultNetworkParams = getDefaultNetworkParams(
33
- networkType || 'devnet'
34
- );
35
- // Set fullnodeUrl and faucetUrl, if they are not provided, use the default value.
36
- this.fullnodeUrl = fullnodeUrl || defaultNetworkParams.fullnode;
37
- this.faucetUrl = faucetUrl || defaultNetworkParams.faucet;
38
-
39
- // Init the provider
40
- const connection = new Connection({
41
- fullnode: this.fullnodeUrl,
42
- faucet: this.faucetUrl,
43
- });
44
- this.provider = new JsonRpcProvider(connection);
45
- }
46
-
47
- /**
48
- * Request some SUI from faucet
49
- * @Returns {Promise<boolean>}, true if the request is successful, false otherwise.
50
- */
51
- async requestFaucet(addr: string) {
52
- return requestFaucet(addr, this.provider);
53
- }
54
-
55
- async getBalance(addr: string, coinType?: string) {
56
- return this.provider.getBalance({ owner: addr, coinType });
57
- }
58
-
59
-
60
- async getDynamicFieldObject(parentId: string, name: string | DynamicFieldName) {
61
- return this.provider.getDynamicFieldObject({ parentId, name })
62
- }
63
-
64
- async getDynamicFields(parentId: string, cursor?: string, limit?: number) {
65
- return this.provider.getDynamicFields({ parentId, cursor, limit })
66
- }
67
-
68
- async getOwnedObjects(owner: SuiAddress, cursor?: string, limit?: number) {
69
- return await this.provider.getOwnedObjects({ owner, cursor, limit });
70
- }
71
-
72
- async getObject(id: string) {
73
- const options = { showContent: true, showDisplay: true, showType: true };
74
- const object = await this.provider.getObject({ id, options });
75
- const objectId = getObjectId(object);
76
- const objectType = getObjectType(object);
77
- const objectVersion = getObjectVersion(object);
78
- const objectFields = getObjectFields(object);
79
- const objectDisplay = getObjectDisplay(object);
80
- return {
81
- objectId,
82
- objectType,
83
- objectVersion,
84
- objectFields,
85
- objectDisplay,
86
- } as ObjectData;
87
- }
88
-
89
- async getObjects(ids: string[]) {
90
- const options = { showContent: true, showDisplay: true, showType: true };
91
- const objects = await this.provider.multiGetObjects({ ids, options });
92
- const parsedObjects = objects.map((object) => {
93
- const objectId = getObjectId(object);
94
- const objectType = getObjectType(object);
95
- const objectVersion = getObjectVersion(object);
96
- const objectFields = getObjectFields(object);
97
- const objectDisplay = getObjectDisplay(object);
98
- return {
99
- objectId,
100
- objectType,
101
- objectVersion,
102
- objectFields,
103
- objectDisplay,
104
- };
105
- });
106
- return parsedObjects as ObjectData[];
107
- }
108
-
109
- async getNormalizedMoveModulesByPackage(packageId: string) {
110
- return this.provider.getNormalizedMoveModulesByPackage({package: packageId});
111
- }
112
-
113
- /**
114
- * @description Select coins that add up to the given amount.
115
- * @param addr the address of the owner
116
- * @param amount the amount that is needed for the coin
117
- * @param coinType the coin type, default is '0x2::SUI::SUI'
118
- */
119
- async selectCoins(
120
- addr: string,
121
- amount: number,
122
- coinType: string = '0x2::SUI::SUI'
123
- ) {
124
- const coins = await this.provider.getCoins({ owner: addr, coinType });
125
- const selectedCoins: {
126
- objectId: string;
127
- digest: string;
128
- version: string;
129
- }[] = [];
130
- let totalAmount = 0;
131
- // Sort the coins by balance in descending order
132
- coins.data.sort((a, b) => parseInt(b.balance) - parseInt(a.balance));
133
- for (const coinData of coins.data) {
134
- selectedCoins.push({
135
- objectId: coinData.coinObjectId,
136
- digest: coinData.digest,
137
- version: coinData.version,
138
- });
139
- totalAmount = totalAmount + parseInt(coinData.balance);
140
- if (totalAmount >= amount) {
141
- break;
142
- }
143
- }
144
-
145
- if (!selectedCoins.length) {
146
- throw new Error('No valid coins found for the transaction.');
147
- }
148
- return selectedCoins;
149
- }
150
- }
@@ -1,17 +0,0 @@
1
- import { DisplayFieldsResponse, ObjectContentFields } from '@mysten/sui.js';
2
-
3
- export type NetworkType = 'testnet' | 'mainnet' | 'devnet' | 'localnet';
4
-
5
- export type ObjectData = {
6
- objectId: string;
7
- objectType: string;
8
- objectVersion: number;
9
- objectDisplay: DisplayFieldsResponse;
10
- objectFields: ObjectContentFields;
11
- };
12
-
13
- export type SuiRpcProviderParams = {
14
- fullnodeUrl?: string;
15
- faucetUrl?: string;
16
- networkType?: NetworkType;
17
- };