@0xobelisk/client 0.0.8 → 0.1.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 (43) hide show
  1. package/dist/index.d.ts +0 -1
  2. package/dist/index.js +339 -292
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +338 -308
  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 -331
  20. package/dist/types/index.d.ts +48 -6
  21. package/package.json +3 -3
  22. package/src/index.ts +0 -1
  23. package/src/libs/suiAccountManager/index.ts +1 -1
  24. package/src/libs/suiAccountManager/keypair.ts +1 -1
  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 +39 -132
  37. package/src/types/index.ts +92 -10
  38. package/src/utils/index.ts +1 -1
  39. package/src/libs/suiAccountManager/types.ts +0 -10
  40. package/src/libs/suiRpcProvider/faucet.ts +0 -57
  41. package/src/libs/suiRpcProvider/index.ts +0 -150
  42. package/src/libs/suiRpcProvider/types.ts +0 -17
  43. 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,11 +22,10 @@ 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
- const keccak256 = require('keccak256');
25
-
28
+ import keccak256 from "keccak256";
26
29
 
27
30
  export function isUndefined (value?: unknown): value is undefined {
28
31
  return value === undefined;
@@ -60,18 +63,15 @@ function createTx(
60
63
  */
61
64
  export class Obelisk {
62
65
  public accountManager: SuiAccountManager;
63
- public rpcProvider: SuiRpcProvider;
66
+ public suiInteractor: SuiInteractor;
64
67
  public contractFactory: SuiContractFactory;
65
68
  public packageId: string | undefined;
66
- // public needLoad: boolean | undefined;
67
69
  public metadata: SuiMoveNormalizedModules;
68
- public epsId: string;
69
- public componentsId: string;
70
70
 
71
71
  readonly #query: MapMoudleFuncQuery = {};
72
72
  readonly #tx: MapMoudleFuncTx = {};
73
73
  /**
74
- * Support the following ways to init the SuiToolkit:
74
+ * Support the following ways to init the ObeliskClient:
75
75
  * 1. mnemonics
76
76
  * 2. secretKey (base64 or hex)
77
77
  * If none of them is provided, will generate a random mnemonics with 24 words.
@@ -80,29 +80,22 @@ export class Obelisk {
80
80
  * @param secretKey, base64 or hex string, when mnemonics is provided, secretKey will be ignored
81
81
  * @param networkType, 'testnet' | 'mainnet' | 'devnet' | 'localnet', default is 'devnet'
82
82
  * @param fullnodeUrl, the fullnode url, default is the preconfig fullnode url for the given network type
83
- * @param faucetUrl, the faucet url, default is the preconfig faucet url for the given network type
84
83
  * @param packageId
85
84
  */
86
85
  constructor({
87
86
  mnemonics,
88
87
  secretKey,
89
88
  networkType,
90
- fullnodeUrl,
91
- faucetUrl,
89
+ fullnodeUrls,
92
90
  packageId,
93
91
  metadata
94
92
  }: ObeliskParams = {}) {
95
93
  // Init the account manager
96
94
  this.accountManager = new SuiAccountManager({ mnemonics, secretKey });
97
95
  // Init the rpc provider
98
- this.rpcProvider = new SuiRpcProvider({
99
- fullnodeUrl,
100
- faucetUrl,
101
- networkType,
102
- });
96
+ fullnodeUrls = fullnodeUrls || [getDefaultConnection(networkType).fullnode];
97
+ this.suiInteractor = new SuiInteractor(fullnodeUrls, networkType);
103
98
 
104
- this.epsId = "0xf2196f638c3174e18c0e31aa630a02fd516c2c5deec1ded72c0fea864c9f091a"
105
- this.componentsId = "0x3bc407eb543149e42846ade59ac2a3c901584af4339dc1ecd0affd090529545f"
106
99
  this.packageId = packageId;
107
100
  this.metadata = metadata as SuiMoveNormalizedModules;
108
101
  Object.values(metadata as SuiMoveNormalizedModules).forEach(value => {
@@ -135,16 +128,6 @@ export class Obelisk {
135
128
  })
136
129
  }
137
130
 
138
- // async initialize() {
139
- // const metadata = await this.loadData();
140
- // this.metadata = metadata as SuiMoveNormalizedModules;
141
- // this.contractFactory = new SuiContractFactory({
142
- // packageId: this.packageId,
143
- // metadata: this.metadata
144
- // })
145
- // return metadata
146
- // }
147
-
148
131
  public get query (): MapMoudleFuncQuery {
149
132
  return this.#query;
150
133
  }
@@ -185,7 +168,7 @@ export class Obelisk {
185
168
  */
186
169
  getSigner(derivePathParams?: DerivePathParams) {
187
170
  const keyPair = this.accountManager.getKeyPair(derivePathParams);
188
- return new RawSigner(keyPair, this.rpcProvider.provider);
171
+ return new RawSigner(keyPair, this.suiInteractor.currentProvider);
189
172
  }
190
173
 
191
174
  /**
@@ -208,7 +191,7 @@ export class Obelisk {
208
191
  }
209
192
 
210
193
  provider() {
211
- return this.rpcProvider.provider;
194
+ return this.suiInteractor.currentProvider;
212
195
  }
213
196
 
214
197
  getPackageId() {
@@ -222,24 +205,25 @@ export class Obelisk {
222
205
  * Request some SUI from faucet
223
206
  * @Returns {Promise<boolean>}, true if the request is successful, false otherwise.
224
207
  */
225
- async requestFaucet(derivePathParams?: DerivePathParams) {
226
- const addr = this.accountManager.getAddress(derivePathParams);
227
- 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);
228
211
  }
229
212
 
230
213
  async getBalance(coinType?: string, derivePathParams?: DerivePathParams) {
231
214
  const owner = this.accountManager.getAddress(derivePathParams);
232
- return this.rpcProvider.getBalance(owner, coinType);
215
+ return this.suiInteractor.currentProvider.getBalance({ owner, coinType });
233
216
  }
234
217
 
235
218
  async getObject(objectId: string) {
236
- return this.rpcProvider.getObject(objectId);
219
+ return this.suiInteractor.getObject(objectId);
237
220
  }
238
221
 
239
222
  async getObjects(objectIds: string[]) {
240
- return this.rpcProvider.getObjects(objectIds);
223
+ return this.suiInteractor.getObjects(objectIds);
241
224
  }
242
225
 
226
+
243
227
  async signTxn(
244
228
  tx: Uint8Array | TransactionBlock | SuiTxBlock,
245
229
  derivePathParams?: DerivePathParams
@@ -253,16 +237,11 @@ export class Obelisk {
253
237
  tx: Uint8Array | TransactionBlock | SuiTxBlock,
254
238
  derivePathParams?: DerivePathParams
255
239
  ): Promise<SuiTransactionBlockResponse> {
256
- tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
257
- const signer = this.getSigner(derivePathParams);
258
- return signer.signAndExecuteTransactionBlock({
259
- transactionBlock: tx,
260
- options: {
261
- showEffects: true,
262
- showEvents: true,
263
- showObjectChanges: true,
264
- },
265
- });
240
+ const { transactionBlockBytes, signature } = await this.signTxn(
241
+ tx,
242
+ derivePathParams
243
+ );
244
+ return this.suiInteractor.sendTx(transactionBlockBytes, signature);
266
245
  }
267
246
 
268
247
  /**
@@ -313,7 +292,7 @@ export class Obelisk {
313
292
  const tx = new SuiTxBlock();
314
293
  const owner = this.accountManager.getAddress(derivePathParams);
315
294
  const totalAmount = amounts.reduce((a, b) => a + b, 0);
316
- const coins = await this.rpcProvider.selectCoins(
295
+ const coins = await this.suiInteractor.selectCoins(
317
296
  owner,
318
297
  totalAmount,
319
298
  coinType
@@ -380,7 +359,7 @@ export class Obelisk {
380
359
  owner?: string
381
360
  ) {
382
361
  owner = owner || this.accountManager.currentAddress;
383
- const coins = await this.rpcProvider.selectCoins(owner, amount, coinType);
362
+ const coins = await this.suiInteractor.selectCoins(owner, amount, coinType);
384
363
  return coins.map((c) => c.objectId);
385
364
  }
386
365
 
@@ -411,38 +390,21 @@ export class Obelisk {
411
390
  tx: Uint8Array | TransactionBlock | SuiTxBlock,
412
391
  derivePathParams?: DerivePathParams
413
392
  ): Promise<DevInspectResults> {
414
-
415
393
  tx = tx instanceof SuiTxBlock ? tx.txBlock : tx;
416
- return this.rpcProvider.provider.devInspectTransactionBlock({
394
+ return this.suiInteractor.currentProvider.devInspectTransactionBlock({
417
395
  transactionBlock: tx,
418
396
  sender: this.getAddress(derivePathParams),
419
397
  });
420
398
  }
421
399
 
422
400
  async getWorld(worldObjectId: string) {
423
- return this.rpcProvider.getObject(worldObjectId)
424
- }
425
-
426
- async getAllEntities(worldId: string, cursor?: string, limit?: number) {
427
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.entities.fields.id.id;
428
- return await this.rpcProvider.getDynamicFields(parentId, cursor, limit) as DynamicFieldPage;
429
- }
430
-
431
- async getEntity(worldId: string, entityId: string) {
432
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.entities.fields.id.id;
433
-
434
- console.log(parentId)
435
- const name = {
436
- type: "0x2::object::ID",
437
- value: entityId
438
- } as DynamicFieldName
439
- return await this.rpcProvider.getDynamicFieldObject(parentId, name);
401
+ return this.suiInteractor.getObject(worldObjectId)
440
402
  }
441
403
 
442
404
  async getComponents(worldId: string) {
443
- 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;
444
406
 
445
- return await this.rpcProvider.getDynamicFields(parentId);
407
+ return await this.suiInteractor.getDynamicFields(parentId);
446
408
  }
447
409
 
448
410
 
@@ -453,20 +415,19 @@ export class Obelisk {
453
415
 
454
416
  async getComponent(worldId: string, componentId: Buffer) {
455
417
  const componentIdValue: number[] = Array.from(componentId);
456
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.components.fields.id.id;
457
- console.log(parentId)
418
+ const parentId = (await this.suiInteractor.getObject(worldId)).objectFields.components.fields.id.id;
419
+
458
420
  const name = {
459
- // type: "0x2::object::ID",
460
421
  type: "vector<u8>",
461
422
  value: componentIdValue
462
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]
463
424
  } as DynamicFieldName
464
- return await this.rpcProvider.getDynamicFieldObject(parentId, name);
425
+ return await this.suiInteractor.getDynamicFieldObject(parentId, name);
465
426
  }
466
427
 
467
428
  async getOwnedEntities(owner: SuiAddress, cursor?: string, limit?: number) {
468
- const ownedObjects = await this.rpcProvider.getOwnedObjects(owner, cursor, limit)
469
- let ownedEntities: ObjectData[] = [];
429
+ const ownedObjects = await this.suiInteractor.getOwnedObjects(owner, cursor, limit)
430
+ let ownedEntities: ObeliskObjectData[] = [];
470
431
 
471
432
  for (const object of ownedObjects.data) {
472
433
  let objectDetail = await this.getObject(object.data!.objectId);
@@ -478,58 +439,4 @@ export class Obelisk {
478
439
 
479
440
  return ownedEntities;
480
441
  }
481
-
482
- async getTable(worldId: string, entityId: string) {
483
- const parentId = (await this.rpcProvider.getObject(worldId)).objectFields.storages.fields.id.id;
484
-
485
- console.log(parentId)
486
- const name = {
487
- type: "0x2::object::ID",
488
- value: entityId
489
- } as DynamicFieldName
490
- return await this.rpcProvider.getDynamicFieldObject(parentId, name);
491
- }
492
-
493
- async getEntityComponents(worldId: string, entityId: string, cursor?: string, limit?: number) {
494
- const parentContent = (await this.getEntity(worldId, entityId)).data!.content as ComponentContentType;
495
- const parentId = parentContent.fields.value.fields.components.fields.id.id;
496
- return await this.rpcProvider.getDynamicFields(parentId, cursor, limit) as DynamicFieldPage;
497
- }
498
-
499
- async getEntityComponent(entityId: string, componentId: string) {
500
- const parentId = (await this.rpcProvider.getObject(entityId)).objectFields.id.id;
501
-
502
- const name = {
503
- type: "0x2::object::ID",
504
- value: componentId
505
- } as DynamicFieldName
506
- return await this.rpcProvider.getDynamicFieldObject(parentId, name);
507
- }
508
-
509
-
510
- // async loadData() {
511
- // const jsonFileName = `metadata/${this.packageId}.json`;
512
-
513
- // try {
514
- // const data = await fs.promises.readFile(jsonFileName, 'utf-8');
515
- // const jsonData = JSON.parse(data);
516
-
517
- // return jsonData as SuiMoveNormalizedModules;
518
- // } catch (error) {
519
- // if (this.packageId !== undefined) {
520
- // const jsonData = await this.rpcProvider.getNormalizedMoveModulesByPackage(this.packageId);
521
-
522
- // fs.writeFile(jsonFileName, JSON.stringify(jsonData, null, 2), (err) => {
523
- // if (err) {
524
- // console.error('写入文件时出错:', err);
525
- // } else {
526
- // console.log('JSON 数据已保存到文件:', jsonFileName);
527
- // }
528
- // });
529
- // return jsonData as SuiMoveNormalizedModules;
530
- // } else {
531
- // console.error('please set your package id.');
532
- // }
533
- // }
534
- // }
535
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,3 +1,3 @@
1
1
  export function capitalizeFirstLetter(input: string): string {
2
2
  return input.charAt(0).toUpperCase() + input.slice(1);
3
- }
3
+ }
@@ -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
- };