@easysui/sdk 0.1.1 → 0.2.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.
package/dist/index.mjs CHANGED
@@ -7,6 +7,7 @@ import { decodeSuiPrivateKey } from '@mysten/sui/cryptography';
7
7
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
8
8
  import { Secp256k1Keypair } from '@mysten/sui/keypairs/secp256k1';
9
9
  import { Secp256r1Keypair } from '@mysten/sui/keypairs/secp256r1';
10
+ import { SUI_CLOCK_OBJECT_ID, fromHex, fromBase64, toBase64, deriveObjectID, toHex } from '@mysten/sui/utils';
10
11
  import { Transaction, coinWithBalance } from '@mysten/sui/transactions';
11
12
  import { bcs } from '@mysten/sui/bcs';
12
13
  import { execSync } from 'child_process';
@@ -32,20 +33,26 @@ function getKeypair(privkey) {
32
33
 
33
34
  // src/config/static.ts
34
35
  var STATIC_CONFIGS = {
36
+ localnet: {
37
+ CHAIN_ID: "d07607dc"
38
+ },
39
+ devnet: {
40
+ CHAIN_ID: "4c78adac"
41
+ },
35
42
  testnet: {
43
+ CHAIN_ID: "4c78adac",
36
44
  USDC_PACKAGE_ID: "0xa1ec7fc00a6f40db9693ad1415d0c193ad3906494428cf252621037bd7117e29"
37
45
  },
38
46
  mainnet: {
47
+ CHAIN_ID: "35834a8a",
39
48
  USDC_PACKAGE_ID: "0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7"
40
49
  }
41
50
  };
42
-
43
- // src/config/config.ts
44
- dotenv.config({ path: path.resolve(process.cwd(), ".env") });
51
+ dotenv.config({ path: path.resolve(process.cwd(), ".env"), quiet: true });
45
52
  var DENY_LIST_ID = "0x403";
46
- var CLOCK_ID = "0x6";
53
+ var CLOCK_ID = SUI_CLOCK_OBJECT_ID;
47
54
  var COIN_REGISTRY = "0x000000000000000000000000000000000000000000000000000000000000000c";
48
- var ADMIN_KEYPAIR = getKeypair(process.env.ADMIN_PRIVATE_KEY);
55
+ var ADMIN_KEYPAIR = process.env.ADMIN_PRIVATE_KEY ? getKeypair(process.env.ADMIN_PRIVATE_KEY) : void 0;
49
56
  var Config = class _Config {
50
57
  static instance = null;
51
58
  static getInstance() {
@@ -55,7 +62,7 @@ var Config = class _Config {
55
62
  return this.instance;
56
63
  }
57
64
  get env() {
58
- let env = process.env.NODE_ENV;
65
+ let env = process.env.NETWORK;
59
66
  if (!["mainnet", "testnet", "devnet", "localnet"].includes(env || "")) {
60
67
  env = "localnet";
61
68
  }
@@ -71,7 +78,7 @@ var Config = class _Config {
71
78
  static get vars() {
72
79
  const instance = this.getInstance();
73
80
  const NETWORK = instance.env;
74
- dotenv.config({ path: path.resolve(process.cwd(), `.env.${NETWORK}`), override: true });
81
+ dotenv.config({ path: path.resolve(process.cwd(), `.env.${NETWORK}`), override: true, quiet: true });
75
82
  const envVars = {
76
83
  NETWORK,
77
84
  RPC: getFullnodeUrl(NETWORK),
@@ -135,6 +142,22 @@ function analyze_cost(ptb, resp) {
135
142
  columns.push(gasSpent);
136
143
  fs3.appendFileSync(COST_ANALYSIS_FILE, columns.join(",") + "\n");
137
144
  }
145
+ function toFormatType(type, bytes) {
146
+ switch (type) {
147
+ case 2 /* base64 */:
148
+ return toBase64(bytes);
149
+ case 1 /* hex */:
150
+ return toHex(bytes);
151
+ default:
152
+ throw "The FORMAT_TYPES must be one of hex or base64";
153
+ }
154
+ }
155
+ function isHex(str) {
156
+ return /^[0-9a-fA-F]+$/.test(str) && str.length % 2 === 0;
157
+ }
158
+ function hexToBase64(hex) {
159
+ return toBase64(fromHex(hex));
160
+ }
138
161
 
139
162
  // src/utils/sui_client.ts
140
163
  var MoveType = /* @__PURE__ */ ((MoveType2) => {
@@ -146,12 +169,19 @@ var MoveType = /* @__PURE__ */ ((MoveType2) => {
146
169
  MoveType2[MoveType2["u256"] = 6] = "u256";
147
170
  MoveType2[MoveType2["bool"] = 7] = "bool";
148
171
  MoveType2[MoveType2["string"] = 8] = "string";
149
- MoveType2[MoveType2["object"] = 9] = "object";
150
- MoveType2[MoveType2["address"] = 10] = "address";
151
- MoveType2[MoveType2["address_opt"] = 11] = "address_opt";
152
- MoveType2[MoveType2["vec_address"] = 12] = "vec_address";
172
+ MoveType2[MoveType2["string_opt"] = 9] = "string_opt";
173
+ MoveType2[MoveType2["object"] = 10] = "object";
174
+ MoveType2[MoveType2["address"] = 11] = "address";
175
+ MoveType2[MoveType2["address_opt"] = 12] = "address_opt";
176
+ MoveType2[MoveType2["vec_address"] = 13] = "vec_address";
177
+ MoveType2[MoveType2["vec_u64"] = 14] = "vec_u64";
153
178
  return MoveType2;
154
179
  })(MoveType || {});
180
+ var txOptions = {
181
+ showEffects: true,
182
+ showObjectChanges: true,
183
+ showBalanceChanges: true
184
+ };
155
185
  var SuiClient = class _SuiClient {
156
186
  static instance = null;
157
187
  client;
@@ -167,26 +197,21 @@ var SuiClient = class _SuiClient {
167
197
  static get client() {
168
198
  return this.getInstance().client;
169
199
  }
170
- static async signAndExecute(ptb, signer, errorHandler = (e) => e) {
171
- try {
172
- const resp = await _SuiClient.client.signAndExecuteTransaction({
173
- transaction: ptb,
174
- signer,
175
- options: {
176
- showEffects: true,
177
- showObjectChanges: true,
178
- showBalanceChanges: true
179
- }
180
- });
181
- await _SuiClient.client.waitForTransaction({ digest: resp.digest });
182
- if (resp.effects?.status.status !== "success") {
183
- throw new Error(JSON.stringify(resp));
184
- }
185
- analyze_cost(ptb, resp);
186
- return resp;
187
- } catch (e) {
188
- throw new Error(errorHandler(e));
200
+ static async waitForTransaction(ptb, resp) {
201
+ await _SuiClient.client.waitForTransaction({ digest: resp.digest });
202
+ if (resp.effects?.status.status !== "success") {
203
+ throw new Error(JSON.stringify(resp));
189
204
  }
205
+ analyze_cost(ptb, resp);
206
+ return resp;
207
+ }
208
+ static async signAndExecute(ptb, signer) {
209
+ const resp = await _SuiClient.client.signAndExecuteTransaction({
210
+ transaction: ptb,
211
+ signer,
212
+ options: txOptions
213
+ });
214
+ return _SuiClient.waitForTransaction(ptb, resp);
190
215
  }
191
216
  static toMoveArg(ptb, value, type) {
192
217
  if (typeof value === "object" && !Array.isArray(value)) {
@@ -195,7 +220,7 @@ var SuiClient = class _SuiClient {
195
220
  if (!type) {
196
221
  if (typeof value === "string") {
197
222
  if (value.startsWith("0x")) {
198
- type = 9 /* object */;
223
+ type = 10 /* object */;
199
224
  } else {
200
225
  type = 8 /* string */;
201
226
  }
@@ -214,10 +239,12 @@ var SuiClient = class _SuiClient {
214
239
  [6 /* u256 */]: (v) => ptb.pure.u256(v),
215
240
  [7 /* bool */]: (v) => ptb.pure.bool(v),
216
241
  [8 /* string */]: (v) => ptb.pure.string(v),
217
- [9 /* object */]: (v) => ptb.object(v),
218
- [10 /* address */]: (v) => ptb.pure.address(v),
219
- [11 /* address_opt */]: (v) => ptb.pure.option("address", v),
220
- [12 /* vec_address */]: (v) => ptb.pure.vector("address", v)
242
+ [9 /* string_opt */]: (v) => ptb.pure.option("string", v),
243
+ [10 /* object */]: (v) => ptb.object(v),
244
+ [11 /* address */]: (v) => ptb.pure.address(v),
245
+ [12 /* address_opt */]: (v) => ptb.pure.option("address", v),
246
+ [13 /* vec_address */]: (v) => ptb.pure.vector("address", v),
247
+ [14 /* vec_u64 */]: (v) => ptb.pure.vector("u64", v)
221
248
  };
222
249
  return factory[type](value);
223
250
  }
@@ -227,20 +254,73 @@ var SuiClient = class _SuiClient {
227
254
  typeArgs = [],
228
255
  args = [],
229
256
  argTypes = [],
230
- errorHandler = (e) => e,
231
257
  ptb,
232
258
  withTransfer = false
233
259
  }) {
260
+ ptb = this.getPTB(target, typeArgs, args, argTypes, signer.toSuiAddress(), withTransfer, ptb);
261
+ return _SuiClient.signAndExecute(ptb, signer);
262
+ }
263
+ static async getMoveCallBytes({
264
+ signer,
265
+ target,
266
+ typeArgs = [],
267
+ args = [],
268
+ argTypes = [],
269
+ ptb,
270
+ withTransfer = false,
271
+ gasOwner,
272
+ format = 1 /* hex */
273
+ }) {
274
+ ptb = this.getPTB(target, typeArgs, args, argTypes, signer, withTransfer, ptb);
275
+ return await this.getMoveCallBytesFromPTB(ptb, signer, gasOwner, format);
276
+ }
277
+ static async getMoveCallBytesFromPTB(ptb, signer, gasOwner, format = 1 /* hex */) {
278
+ ptb.setSender(signer);
279
+ gasOwner ??= signer;
280
+ ptb.setGasOwner(gasOwner || signer);
281
+ const bytes = await ptb.build({ client: _SuiClient.client, onlyTransactionKind: false });
282
+ return toFormatType(format, bytes);
283
+ }
284
+ static toBytes(bytes) {
285
+ if (typeof bytes === "string") {
286
+ return isHex(bytes) ? fromHex(bytes) : fromBase64(bytes);
287
+ }
288
+ return bytes;
289
+ }
290
+ static async getSignature(signatureOrKeypair, bytes) {
291
+ if (typeof signatureOrKeypair !== "string") {
292
+ const signature = await signatureOrKeypair.signTransaction(bytes);
293
+ return signature.signature;
294
+ }
295
+ return isHex(signatureOrKeypair) ? hexToBase64(signatureOrKeypair) : signatureOrKeypair;
296
+ }
297
+ static async executeMoveCallBytes(bytes, senderSignature, gasOwnerSignature) {
298
+ const transactionBlock = this.toBytes(bytes);
299
+ senderSignature = await this.getSignature(senderSignature, transactionBlock);
300
+ const signature = [senderSignature];
301
+ if (gasOwnerSignature) {
302
+ gasOwnerSignature = await this.getSignature(gasOwnerSignature, transactionBlock);
303
+ signature.push(gasOwnerSignature);
304
+ }
305
+ const resp = await _SuiClient.client.executeTransactionBlock({
306
+ transactionBlock: toBase64(transactionBlock),
307
+ signature,
308
+ options: txOptions
309
+ });
310
+ const ptb = Transaction.from(toBase64(transactionBlock));
311
+ return _SuiClient.waitForTransaction(ptb, resp);
312
+ }
313
+ static getPTB(target, typeArgs = [], args = [], argTypes = [], signer, withTransfer = false, ptb) {
234
314
  ptb = ptb || new Transaction();
235
315
  const obj = ptb.moveCall({
236
316
  target,
237
317
  typeArguments: typeArgs,
238
318
  arguments: args.map((arg, i) => _SuiClient.toMoveArg(ptb, arg, argTypes[i]))
239
319
  });
240
- if (withTransfer) {
241
- ptb.transferObjects([obj], signer.toSuiAddress());
320
+ if (withTransfer && signer) {
321
+ ptb.transferObjects([obj], signer);
242
322
  }
243
- return _SuiClient.signAndExecute(ptb, signer, errorHandler);
323
+ return ptb;
244
324
  }
245
325
  static async public_transfer(objects, from, to) {
246
326
  const tx = new Transaction();
@@ -273,10 +353,22 @@ var SuiClient = class _SuiClient {
273
353
  const bytes = Uint8Array.from(value);
274
354
  return "0x" + Buffer.from(bytes).toString("hex");
275
355
  }
356
+ static async devInspectString(ptb, sender) {
357
+ const value = await this.devInspectRaw(ptb, sender);
358
+ if (!value) {
359
+ return "";
360
+ }
361
+ return bcs.string().parse(new Uint8Array(value));
362
+ }
276
363
  static async getObject(id) {
277
364
  return _SuiClient.client.getObject({
278
365
  id,
279
- options: { showContent: true }
366
+ options: {
367
+ showContent: true,
368
+ showType: true,
369
+ showDisplay: true,
370
+ showBcs: true
371
+ }
280
372
  });
281
373
  }
282
374
  static async getObjectsByType(owner, type) {
@@ -321,7 +413,7 @@ var Coin = class {
321
413
  target: `0x2::coin::mint`,
322
414
  typeArgs: [this.coinType],
323
415
  args: [treasuryId, amount],
324
- argTypes: [9 /* object */, 4 /* u64 */],
416
+ argTypes: [10 /* object */, 4 /* u64 */],
325
417
  withTransfer: true
326
418
  });
327
419
  }
@@ -336,7 +428,7 @@ var Coin = class {
336
428
  target: `0x2::coin_registry::finalize_registration`,
337
429
  typeArgs: [this.coinType],
338
430
  args: [COIN_REGISTRY, currencyId],
339
- argTypes: [9 /* object */, 9 /* object */]
431
+ argTypes: [10 /* object */, 10 /* object */]
340
432
  });
341
433
  }
342
434
  static async send(amount, from, to) {
@@ -370,7 +462,7 @@ var USDC = class extends Coin {
370
462
  target: `${Config.vars.USDC_PACKAGE_ID}::treasury::configure_new_controller`,
371
463
  typeArgs: [this.coinType],
372
464
  args: [Config.vars.USDC_TREASURY_CAP, admin.toSuiAddress(), admin.toSuiAddress()],
373
- argTypes: [9 /* object */, 10 /* address */, 10 /* address */]
465
+ argTypes: [10 /* object */, 11 /* address */, 11 /* address */]
374
466
  });
375
467
  mintCapId = await getMintCapFromChain();
376
468
  }
@@ -383,7 +475,7 @@ var USDC = class extends Coin {
383
475
  target: `${Config.vars.USDC_PACKAGE_ID}::treasury::configure_minter`,
384
476
  typeArgs: [this.coinType],
385
477
  args: [Config.vars.USDC_TREASURY_CAP, DENY_LIST_ID, amount],
386
- argTypes: [9 /* object */, 9 /* object */, 4 /* u64 */]
478
+ argTypes: [10 /* object */, 10 /* object */, 4 /* u64 */]
387
479
  });
388
480
  await SuiClient.moveCall({
389
481
  signer: admin,
@@ -391,11 +483,11 @@ var USDC = class extends Coin {
391
483
  typeArgs: [this.coinType],
392
484
  args: [Config.vars.USDC_TREASURY_CAP, mintCapId, DENY_LIST_ID, amount, receiver],
393
485
  argTypes: [
394
- 9 /* object */,
395
- 9 /* object */,
396
- 9 /* object */,
486
+ 10 /* object */,
487
+ 10 /* object */,
488
+ 10 /* object */,
397
489
  4 /* u64 */,
398
- 10 /* address */
490
+ 11 /* address */
399
491
  ]
400
492
  });
401
493
  }
@@ -458,53 +550,41 @@ var PublishSingleton = class _PublishSingleton {
458
550
  false
459
551
  );
460
552
  }
461
- static getPublishTx(packagePath, sender) {
462
- const transaction = new Transaction();
553
+ static getPublishCmd(packagePath, sender, inBytes = false) {
554
+ const network = Config.vars.NETWORK;
463
555
  if (!fs3__default.existsSync(packagePath)) {
464
556
  throw new Error(`Package doesn't exist under: ${packagePath}`);
465
557
  }
466
558
  if (fs3__default.existsSync(`${packagePath}/Move.lock`)) {
467
559
  fs3__default.unlinkSync(`${packagePath}/Move.lock`);
468
560
  }
561
+ if (fs3__default.existsSync(`Pub.${network}.toml`)) {
562
+ fs3__default.unlinkSync(`Pub.${network}.toml`);
563
+ }
469
564
  fs3__default.rmSync(`${packagePath}/build`, { recursive: true, force: true });
470
- let buildCommand = `sui move build --dump-bytecode-as-base64 --path ${packagePath}`;
471
- const network = Config.vars.NETWORK;
565
+ const isEphemeralChain = network !== "mainnet" && network !== "testnet";
566
+ const publishCmd = isEphemeralChain ? `test-publish --build-env testnet` : "publish";
567
+ let buildCommand = `sui client ${publishCmd} ${packagePath}`;
472
568
  if (network === "localnet" || network === "devnet") {
473
569
  buildCommand += " --with-unpublished-dependencies";
474
570
  }
475
- const { modules, dependencies } = JSON.parse(execSync(buildCommand, { encoding: "utf-8" }));
476
- const upgradeCap = transaction.publish({
477
- modules,
478
- dependencies
479
- });
480
- transaction.transferObjects([upgradeCap], sender);
481
- return transaction;
571
+ buildCommand += inBytes ? " --serialize-unsigned-transaction" : " --json";
572
+ return buildCommand;
482
573
  }
483
574
  static async getPublishBytes(signer, packagePath) {
484
575
  signer ??= ADMIN_KEYPAIR.toSuiAddress();
485
576
  const _packagePath = this.getPackagePath(packagePath);
486
- const transaction = this.getPublishTx(_packagePath, signer);
487
- const client = new SuiClient$1({ url: Config.vars.RPC });
488
- const txBytes = await transaction.build({ client, onlyTransactionKind: true });
489
- return Buffer.from(txBytes).toString("base64");
577
+ const cmd = this.getPublishCmd(_packagePath, signer, true);
578
+ return execSync(cmd, { encoding: "utf-8" }).trim();
490
579
  }
491
580
  static async publishPackage(signer, packagePath) {
492
- const transaction = this.getPublishTx(packagePath, signer.toSuiAddress());
493
- const client = new SuiClient$1({ url: Config.vars.RPC });
494
- const resp = await client.signAndExecuteTransaction({
495
- transaction,
496
- signer,
497
- options: {
498
- showObjectChanges: true,
499
- showEffects: true
500
- }
501
- });
502
- if (resp.effects?.status.status !== "success") {
503
- throw new Error(`Failure during publish transaction:
504
- ${JSON.stringify(resp, null, 2)}`);
581
+ const cmd = this.getPublishCmd(packagePath, signer.toSuiAddress());
582
+ const res = execSync(cmd, { encoding: "utf-8" });
583
+ const match = res.match(/\{[\s\S]*\}/);
584
+ if (!match) {
585
+ throw new Error(`No JSON found in the publish command output: ${res}`);
505
586
  }
506
- await client.waitForTransaction({ digest: resp.digest });
507
- return resp;
587
+ return JSON.parse(match[0]);
508
588
  }
509
589
  static findPublishedPackage(resp) {
510
590
  return resp.objectChanges?.find(
@@ -519,9 +599,9 @@ ${JSON.stringify(resp, null, 2)}`);
519
599
  };
520
600
 
521
601
  // src/utils/deploy.ts
522
- async function deploy(ConfigClass = Config) {
602
+ async function deploy(ConfigClass = Config, packagePath) {
523
603
  const vars = ConfigClass.vars;
524
- await PublishSingleton.publish();
604
+ await PublishSingleton.publish(ADMIN_KEYPAIR, packagePath);
525
605
  const newConfig = {
526
606
  ...vars,
527
607
  PACKAGE_ID: PublishSingleton.packageId,
@@ -579,7 +659,16 @@ async function waitForNextEpoch(timeoutMs = 5 * 60 * 1e3, pollIntervalMs = 2e3)
579
659
  await sleep(pollIntervalMs);
580
660
  }
581
661
  }
662
+ function deriveObjectId(parentId, module, key, packageId, type, serializedBcs) {
663
+ serializedBcs ??= bcs.struct(key, { dummy_value: bcs.bool() }).serialize({ dummy_value: false });
664
+ const keyU8 = serializedBcs.toBytes();
665
+ let typeTag = `${packageId}::${module}::${key}`;
666
+ if (type) {
667
+ typeTag += `<${type}>`;
668
+ }
669
+ return deriveObjectID(parentId, typeTag, keyU8);
670
+ }
582
671
 
583
- export { ADMIN_KEYPAIR, CLOCK_ID, Coin, Config, DENY_LIST_ID, MoveType, PublishSingleton, STATIC_CONFIGS, SuiClient, USDC, analyze_cost, createFundedWallet, createWallet, deploy, getDeployBytes, getKeypair, sleep, waitForNextEpoch };
672
+ export { ADMIN_KEYPAIR, CLOCK_ID, Coin, Config, DENY_LIST_ID, MoveType, PublishSingleton, STATIC_CONFIGS, SuiClient, USDC, analyze_cost, createFundedWallet, createWallet, deploy, deriveObjectId, getDeployBytes, getKeypair, sleep, waitForNextEpoch };
584
673
  //# sourceMappingURL=index.mjs.map
585
674
  //# sourceMappingURL=index.mjs.map