@bolt-liquidity-hq/sui-client 0.1.0-beta.42 → 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.
package/dist/index.cjs CHANGED
@@ -59,7 +59,7 @@ module.exports = __toCommonJS(index_exports);
59
59
 
60
60
  // src/lib/client.ts
61
61
  var import_core15 = require("@bolt-liquidity-hq/core");
62
- var import_client = require("@mysten/sui/client");
62
+ var import_grpc = require("@mysten/sui/grpc");
63
63
  var import_utils11 = require("@mysten/sui/utils");
64
64
  var import_axios = __toESM(require("axios"), 1);
65
65
 
@@ -261,16 +261,12 @@ var POOL_MODULE = "pool";
261
261
  // src/lib/helpers/bcs-parse.ts
262
262
  var import_core = require("@bolt-liquidity-hq/core");
263
263
  var import_bcs = require("@mysten/bcs");
264
- var extractBytes = (result, resultIndex = 0, returnValueIndex = 0) => {
265
- const returnValues = result.results?.[resultIndex]?.returnValues;
266
- if (!returnValues || !returnValues[returnValueIndex]) {
267
- return null;
268
- }
269
- const [bytes] = returnValues[returnValueIndex];
270
- return new Uint8Array(bytes);
264
+ var extractBytes = (commandResults, resultIndex = 0, returnValueIndex = 0) => {
265
+ const returnValues = commandResults[resultIndex]?.returnValues;
266
+ return returnValues?.[returnValueIndex]?.bcs ?? null;
271
267
  };
272
- var parseDevInspectResult = (result, bcsType, resultIndex = 0, returnValueIndex = 0) => {
273
- const bytes = extractBytes(result, resultIndex, returnValueIndex);
268
+ var parseDevInspectResult = (commandResults, bcsType, resultIndex = 0, returnValueIndex = 0) => {
269
+ const bytes = extractBytes(commandResults, resultIndex, returnValueIndex);
274
270
  if (!bytes) {
275
271
  throw new import_core.InvalidObjectError("When trying to parse result, no bytes found", {
276
272
  bcsType,
@@ -281,9 +277,9 @@ var parseDevInspectResult = (result, bcsType, resultIndex = 0, returnValueIndex
281
277
  try {
282
278
  return bcsType.parse(bytes);
283
279
  } catch (error) {
284
- throw new import_core.ParseError("DevInspectResult", "from bcs to a typescript type", {
280
+ throw new import_core.ParseError("CommandResult", "from bcs to a typescript type", {
285
281
  error,
286
- result,
282
+ commandResults,
287
283
  bcsType,
288
284
  resultIndex,
289
285
  returnValueIndex
@@ -298,7 +294,7 @@ var CoinManager = class {
298
294
  /**
299
295
  * Creates a new CoinManager instance.
300
296
  *
301
- * @param client - The SuiClient instance for blockchain interactions
297
+ * @param client - The Sui client (core API) for blockchain interactions
302
298
  * @param defaultOwner - Optional default owner address for coin operations.
303
299
  * If not provided, owner must be specified in each method call.
304
300
  *
@@ -343,7 +339,7 @@ var CoinManager = class {
343
339
  *
344
340
  * // Display coin details
345
341
  * suiCoins.forEach(coin => {
346
- * console.log(`Coin ID: ${coin.coinObjectId}`);
342
+ * console.log(`Coin ID: ${coin.objectId}`);
347
343
  * console.log(`Balance: ${coin.balance}`);
348
344
  * });
349
345
  * ```
@@ -353,13 +349,13 @@ var CoinManager = class {
353
349
  const allCoins = [];
354
350
  let cursor;
355
351
  do {
356
- const response = await this.client.getCoins({
352
+ const response = await this.client.core.listCoins({
357
353
  owner: ownerAddress,
358
354
  coinType,
359
355
  cursor
360
356
  });
361
- allCoins.push(...response.data);
362
- cursor = response.hasNextPage ? response.nextCursor : void 0;
357
+ allCoins.push(...response.objects);
358
+ cursor = response.hasNextPage ? response.cursor : void 0;
363
359
  } while (cursor);
364
360
  return allCoins;
365
361
  }
@@ -425,11 +421,11 @@ var CoinManager = class {
425
421
  */
426
422
  async getTotalBalance(coinType, owner) {
427
423
  const ownerAddress = this.getOwnerAddress(owner);
428
- const balance = await this.client.getBalance({
424
+ const { balance } = await this.client.core.getBalance({
429
425
  owner: ownerAddress,
430
426
  coinType
431
427
  });
432
- return balance.totalBalance;
428
+ return balance.coinBalance;
433
429
  }
434
430
  /**
435
431
  * Asserts that the owner has sufficient balance for a transaction.
@@ -531,7 +527,7 @@ var CoinManager = class {
531
527
  async selectCoins(coinType, amount, options = {}, owner) {
532
528
  const ownerAddress = this.getOwnerAddress(owner);
533
529
  const coins = await this.getAllCoins(coinType, owner);
534
- const availableCoins = options.excludeIds ? coins.filter((c) => !options.excludeIds?.includes(c.coinObjectId)) : coins;
530
+ const availableCoins = options.excludeIds ? coins.filter((c) => !options.excludeIds?.includes(c.objectId)) : coins;
535
531
  if (availableCoins.length === 0) {
536
532
  throw new import_core2.InsufficientFundsError(amount, "0", {
537
533
  availableCoins,
@@ -673,14 +669,14 @@ var CoinManager = class {
673
669
  });
674
670
  }
675
671
  if (selection.coins.length === 1 && !selection.requiresSplit) {
676
- return tx.object(selection.coins[0].coinObjectId);
672
+ return tx.object(selection.coins[0].objectId);
677
673
  }
678
674
  if (selection.coins.length === 1 && selection.requiresSplit) {
679
- const [split] = tx.splitCoins(tx.object(selection.coins[0].coinObjectId), [amount]);
675
+ const [split] = tx.splitCoins(tx.object(selection.coins[0].objectId), [amount]);
680
676
  return split;
681
677
  }
682
- const primaryCoin = tx.object(selection.coins[0].coinObjectId);
683
- const mergeCoins = selection.coins.slice(1).map((c) => tx.object(c.coinObjectId));
678
+ const primaryCoin = tx.object(selection.coins[0].objectId);
679
+ const mergeCoins = selection.coins.slice(1).map((c) => tx.object(c.objectId));
684
680
  tx.mergeCoins(primaryCoin, mergeCoins);
685
681
  if (selection.requiresSplit) {
686
682
  const [split] = tx.splitCoins(primaryCoin, [amount]);
@@ -704,13 +700,15 @@ var queryDevInspect = async (suiClient, target, args, typeArguments, senderAddre
704
700
  arguments: txArgs,
705
701
  typeArguments
706
702
  });
703
+ tx.setSender(senderAddress ?? ZERO_ADDRESS);
707
704
  try {
708
- const result = await suiClient.devInspectTransactionBlock({
709
- transactionBlock: tx,
710
- sender: senderAddress ?? ZERO_ADDRESS
705
+ const result = await suiClient.core.simulateTransaction({
706
+ transaction: tx,
707
+ checksEnabled: false,
708
+ include: { commandResults: true }
711
709
  });
712
- if (result.effects.status.status === "success") {
713
- return result;
710
+ if (result.$kind === "Transaction" && result.Transaction.status.success) {
711
+ return result.commandResults;
714
712
  } else {
715
713
  throw new import_core3.TransactionFailedError("N/A", "Failed to query smart contract", { result });
716
714
  }
@@ -729,6 +727,12 @@ var import_bcs2 = require("@mysten/bcs");
729
727
  var import_transactions2 = require("@mysten/sui/transactions");
730
728
  var import_utils5 = require("@mysten/sui/utils");
731
729
  var import_bignumber = require("bignumber.js");
730
+ var TX_INCLUDE = {
731
+ effects: true,
732
+ events: true,
733
+ balanceChanges: true
734
+ };
735
+ var unwrapTransaction = (result) => result.$kind === "Transaction" ? result.Transaction : result.FailedTransaction;
732
736
  var buildSwapTxArgs = async (client, swapParams, signer) => {
733
737
  const { assetIn, amountIn, assetOut, minimumAmountOut, receiver, swapType = "buy" } = swapParams;
734
738
  const pool = client.routerClient.getPool(assetIn, assetOut, swapType);
@@ -758,7 +762,7 @@ var buildSwapTxArgs = async (client, swapParams, signer) => {
758
762
  tx
759
763
  };
760
764
  };
761
- var signAndExecuteTx = async (suiClient, signer, target, args, typeArguments, transaction, options) => {
765
+ var signAndExecuteTx = async (suiClient, signer, target, args, typeArguments, transaction) => {
762
766
  const tx = transaction ?? new import_transactions2.Transaction();
763
767
  const targetString = Array.isArray(target) ? `${target[0]}::${target[1]}::${target[2]}` : target;
764
768
  const txArgs = args?.map(
@@ -770,15 +774,16 @@ var signAndExecuteTx = async (suiClient, signer, target, args, typeArguments, tr
770
774
  typeArguments
771
775
  });
772
776
  if ("toSuiAddress" in signer) {
773
- const result = await suiClient.signAndExecuteTransaction({
777
+ const result = await suiClient.core.signAndExecuteTransaction({
774
778
  signer,
775
779
  transaction: tx,
776
- options
780
+ include: TX_INCLUDE
777
781
  });
778
- if (result.effects?.status.status === "success") {
779
- return result;
782
+ if (result.$kind === "Transaction" && result.Transaction.status.success) {
783
+ return result.Transaction;
780
784
  } else {
781
- throw new import_core4.TransactionFailedError(result.digest, result.effects?.status.error, { result });
785
+ const failedTx = unwrapTransaction(result);
786
+ throw new import_core4.TransactionFailedError(failedTx.digest, failedTx.status.error?.message, { result });
782
787
  }
783
788
  } else {
784
789
  const result = await signer.signAndExecuteTransaction({
@@ -787,14 +792,15 @@ var signAndExecuteTx = async (suiClient, signer, target, args, typeArguments, tr
787
792
  if (!result.digest) {
788
793
  throw new import_core4.TransactionFailedError("not found");
789
794
  }
790
- const fullTx = await suiClient.waitForTransaction({
795
+ const fullTx = await suiClient.core.waitForTransaction({
791
796
  digest: result.digest,
792
- options
797
+ include: TX_INCLUDE
793
798
  });
794
- if (fullTx.effects?.status.status !== "success") {
795
- throw new import_core4.TransactionFailedError(result.digest, fullTx.effects?.status.error, { result });
799
+ if (fullTx.$kind !== "Transaction" || !fullTx.Transaction.status.success) {
800
+ const failedTx = unwrapTransaction(fullTx);
801
+ throw new import_core4.TransactionFailedError(result.digest, failedTx.status.error?.message, { result });
796
802
  }
797
- return fullTx;
803
+ return fullTx.Transaction;
798
804
  }
799
805
  };
800
806
  var estimateTxGasPrice = async (suiClient, senderAddress, target, args, typeArguments, transaction, gasAdjustment = import_core4.DEFAULT_GAS_ADJUSTMENT) => {
@@ -811,22 +817,24 @@ var estimateTxGasPrice = async (suiClient, senderAddress, target, args, typeArgu
811
817
  tx.setSender(senderAddress);
812
818
  try {
813
819
  const transactionBytes = await tx.build({ client: suiClient });
814
- const dryRunResult = await suiClient.dryRunTransactionBlock({
815
- transactionBlock: transactionBytes
820
+ const dryRunResult = await suiClient.core.simulateTransaction({
821
+ transaction: transactionBytes,
822
+ include: { effects: true }
816
823
  });
817
- if (dryRunResult.effects.status.status !== "success") {
824
+ const simulatedTx = unwrapTransaction(dryRunResult);
825
+ if (!simulatedTx.status.success) {
818
826
  throw new import_core4.UnexpectedError(
819
- `Dry run failed: ${dryRunResult.effects.status.error}`,
827
+ `Transaction simulation failed: ${simulatedTx.status.error?.message}`,
820
828
  "Failed to estimate gas",
821
829
  {
822
830
  target: targetString,
823
831
  args,
824
832
  typeArguments,
825
- error: dryRunResult.effects.status.error
833
+ error: simulatedTx.status.error
826
834
  }
827
835
  );
828
836
  }
829
- const gasUsed = dryRunResult.effects.gasUsed;
837
+ const gasUsed = simulatedTx.effects.gasUsed;
830
838
  const totalGasCost = (0, import_bignumber.BigNumber)(gasUsed.computationCost).plus(gasUsed.storageCost).minus(gasUsed.storageRebate);
831
839
  const adjustedGasCost = totalGasCost.times(gasAdjustment);
832
840
  return {
@@ -1094,49 +1102,53 @@ var import_core6 = require("@bolt-liquidity-hq/core");
1094
1102
  var import_utils8 = require("@mysten/sui/utils");
1095
1103
  var import_bignumber3 = require("bignumber.js");
1096
1104
  var getPrices = async (client) => {
1097
- const oracleObject = await client.suiClient.getObject({
1098
- id: client.contracts.oracle,
1099
- options: { showContent: true }
1100
- });
1101
- if (!oracleObject.data?.content || oracleObject.data.content.dataType !== "moveObject") {
1105
+ let oracleJson;
1106
+ try {
1107
+ const { object } = await client.suiClient.core.getObject({
1108
+ objectId: client.contracts.oracle,
1109
+ include: { json: true }
1110
+ });
1111
+ oracleJson = object.json;
1112
+ } catch {
1102
1113
  throw new import_core6.NotFoundError("Oracle object");
1103
1114
  }
1104
- const pricesTableId = oracleObject.data.content.fields?.prices?.fields?.id?.id;
1105
- if (!pricesTableId) {
1115
+ const pricesTable = oracleJson?.["prices"];
1116
+ const pricesTableId = pricesTable?.id;
1117
+ if (typeof pricesTableId !== "string") {
1106
1118
  throw new import_core6.NotFoundError("Prices table in the Oracle contract");
1107
1119
  }
1108
1120
  const prices = [];
1109
1121
  let cursor = null;
1110
1122
  while (true) {
1111
- const dynamicFields = await client.suiClient.getDynamicFields({
1123
+ const dynamicFields = await client.suiClient.core.listDynamicFields({
1112
1124
  parentId: pricesTableId,
1113
1125
  cursor,
1114
1126
  limit: 50
1115
1127
  // Max limit per request
1116
1128
  });
1117
- const fieldPromises = dynamicFields.data.map(
1118
- (field) => client.suiClient.getDynamicFieldObject({
1129
+ const fieldPromises = dynamicFields.dynamicFields.map(
1130
+ (field) => client.suiClient.core.getDynamicField({
1119
1131
  parentId: pricesTableId,
1120
1132
  name: field.name
1121
1133
  })
1122
1134
  );
1123
- const fieldObjects = await Promise.all(fieldPromises);
1124
- fieldObjects.forEach((obj, index) => {
1125
- if (obj.data?.content?.dataType === "moveObject") {
1126
- const fields = obj.data.content.fields?.value?.fields?.price?.fields;
1127
- const pairKey = dynamicFields.data[index]?.name?.value;
1128
- if (fields && pairKey) {
1129
- prices.push({
1130
- baseDenom: (0, import_utils8.normalizeStructTag)(pairKey.base.name),
1131
- quoteDenom: (0, import_utils8.normalizeStructTag)(pairKey.quote.name),
1132
- price: (0, import_bignumber3.BigNumber)(fields.price).shiftedBy(-18).toFixed(),
1133
- expiryTime: (0, import_bignumber3.BigNumber)(fields.expiry).times(1e6).toFixed()
1134
- });
1135
- }
1135
+ const fieldValues = await Promise.all(fieldPromises);
1136
+ fieldValues.forEach(({ dynamicField }, index) => {
1137
+ const nameBcs = dynamicFields.dynamicFields[index]?.name.bcs;
1138
+ if (!nameBcs) {
1139
+ return;
1136
1140
  }
1141
+ const pairKey = RawPairStruct.parse(nameBcs);
1142
+ const priceData = PriceDataStruct.parse(dynamicField.value.bcs);
1143
+ prices.push({
1144
+ baseDenom: (0, import_utils8.normalizeStructTag)(pairKey.base.name),
1145
+ quoteDenom: (0, import_utils8.normalizeStructTag)(pairKey.quote.name),
1146
+ price: (0, import_bignumber3.BigNumber)(priceData.price.price).shiftedBy(-18).toFixed(),
1147
+ expiryTime: (0, import_bignumber3.BigNumber)(priceData.price.expiry).times(1e6).toFixed()
1148
+ });
1137
1149
  });
1138
1150
  if (!dynamicFields.hasNextPage) break;
1139
- cursor = dynamicFields.nextCursor;
1151
+ cursor = dynamicFields.cursor;
1140
1152
  }
1141
1153
  return prices;
1142
1154
  };
@@ -1359,13 +1371,12 @@ var swapExactIn = async (client, swapParams, signer) => {
1359
1371
  swapArgs.target,
1360
1372
  swapArgs.args,
1361
1373
  swapArgs.typeArguments,
1362
- swapArgs.tx,
1363
- { showEffects: true, showEvents: true, showBalanceChanges: true }
1374
+ swapArgs.tx
1364
1375
  );
1365
1376
  return {
1366
1377
  txOutput,
1367
1378
  txHash: txOutput.digest,
1368
- amountOut: txOutput.events?.at(0)?.parsedJson?.["amount_out"] ?? "0",
1379
+ amountOut: txOutput.events.at(0)?.json?.["amount_out"] ?? "0",
1369
1380
  assetOut: swapParams.assetOut
1370
1381
  };
1371
1382
  };
@@ -1395,7 +1406,7 @@ var BoltSuiClient = class extends import_core15.BaseClient {
1395
1406
  * @param config.customOverride.nativeTokenDenom - (Optional) Custom native token denomination (e.g., "SUI")
1396
1407
  * @param config.customOverride.assetsConfig - (Optional) Custom asset configurations indexed by denom
1397
1408
  * @param config.signer - (Optional) Pre-existing Signer for transaction signing
1398
- * @param config.suiClient - (Optional) Pre-existing SuiClient to use for blockchain queries
1409
+ * @param config.suiClient - (Optional) Pre-existing Sui client to use for blockchain queries.
1399
1410
  *
1400
1411
  * @throws {InvalidObjectError} Thrown when required configuration fields are missing
1401
1412
  *
@@ -1495,7 +1506,7 @@ var BoltSuiClient = class extends import_core15.BaseClient {
1495
1506
  */
1496
1507
  __publicField(this, "signer");
1497
1508
  /**
1498
- * Instance of the Sui client to interact with the blockchain
1509
+ * Instance of the Sui client to interact with the blockchain.
1499
1510
  */
1500
1511
  __publicField(this, "suiClient");
1501
1512
  /**
@@ -1513,7 +1524,10 @@ var BoltSuiClient = class extends import_core15.BaseClient {
1513
1524
  this.packageId = packageId;
1514
1525
  this.poolGlobalConfigId = poolGlobalConfigId;
1515
1526
  this.signer = signer;
1516
- this.suiClient = suiClient ?? new import_client.SuiClient({ url: chainConfig.rpcEndpoint });
1527
+ this.suiClient = suiClient ?? new import_grpc.SuiGrpcClient({
1528
+ network: environment,
1529
+ baseUrl: chainConfig.rpcEndpoint
1530
+ });
1517
1531
  this.routerClient = new RouterClient(pools);
1518
1532
  this.configFileUrl = isEnvironmentMainnet ? void 0 : TestnetConfigUrl;
1519
1533
  }
@@ -1654,12 +1668,12 @@ var BoltSuiClient = class extends import_core15.BaseClient {
1654
1668
  * console.log(`Transaction digest: ${result.txHash}`);
1655
1669
  * console.log(`Received: ${result.amountOut} ${result.assetOut}`);
1656
1670
  * console.log(`Gas cost: ${result.txOutput.effects.gasUsed.computationCost}`);
1657
- * console.log(`Status: ${result.txOutput.effects.status.status}`);
1671
+ * console.log(`Success: ${result.txOutput.status.success}`);
1658
1672
  * ```
1659
1673
  *
1660
1674
  * @remarks
1661
- * This implementation returns a SuiTransactionBlockResponse as the transaction output,
1662
- * which includes details like gas costs, transaction effects, object changes, and events.
1675
+ * This implementation returns a SuiTransactionResponse as the transaction output,
1676
+ * which includes details like gas costs, transaction effects, balance changes, and events.
1663
1677
  */
1664
1678
  async swap(params, signer) {
1665
1679
  await this.loadConfigFromUrl();