@t2000/sdk 0.56.2 → 1.0.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.js CHANGED
@@ -6,7 +6,7 @@ import { SuiJsonRpcClient, getJsonRpcFullnodeUrl } from '@mysten/sui/jsonRpc';
6
6
  import { normalizeSuiAddress, isValidSuiAddress, normalizeStructTag } from '@mysten/sui/utils';
7
7
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
8
8
  import { decodeSuiPrivateKey } from '@mysten/sui/cryptography';
9
- import { createHash, randomBytes, createCipheriv, createDecipheriv, scryptSync } from 'crypto';
9
+ import { randomBytes, createCipheriv, createDecipheriv, scryptSync } from 'crypto';
10
10
  import { access, mkdir, writeFile, readFile } from 'fs/promises';
11
11
  import { join as join$1, dirname, resolve } from 'path';
12
12
  import { homedir } from 'os';
@@ -809,9 +809,6 @@ var MIST_PER_SUI = 1000000000n;
809
809
  var SUI_DECIMALS = 9;
810
810
  var USDC_DECIMALS = 6;
811
811
  var BPS_DENOMINATOR = 10000n;
812
- var AUTO_TOPUP_THRESHOLD = 50000000n;
813
- var GAS_RESERVE_TARGET = 150000000n;
814
- var AUTO_TOPUP_MIN_USDC = 2000000n;
815
812
  var SAVE_FEE_BPS = 10n;
816
813
  var BORROW_FEE_BPS = 5n;
817
814
  var CLOCK_ID = "0x6";
@@ -5122,8 +5119,6 @@ async function refreshOracle(tx, client, address, options) {
5122
5119
  const oracleOpts = {
5123
5120
  ...sdkOptions(client),
5124
5121
  throws: false,
5125
- // Pyth update uses tx.splitCoins(tx.gas, ...) which is incompatible
5126
- // with sponsored transactions where tx.gas belongs to the sponsor.
5127
5122
  updatePythPriceFeeds: !options?.skipPythUpdate
5128
5123
  };
5129
5124
  await mt(tx, address, pools, oracleOpts);
@@ -5314,7 +5309,7 @@ async function buildWithdrawTx(client, address, amount, options = {}) {
5314
5309
  }
5315
5310
  const tx = new Transaction();
5316
5311
  tx.setSender(address);
5317
- await refreshOracle(tx, client, address, { skipPythUpdate: options.sponsored });
5312
+ await refreshOracle(tx, client, address, { skipPythUpdate: options.skipPythUpdate });
5318
5313
  try {
5319
5314
  const coin = await Qe(tx, assetInfo.type, rawAmount, sdkOptions(client));
5320
5315
  tx.transferObjects([coin], address);
@@ -5326,7 +5321,6 @@ async function buildWithdrawTx(client, address, amount, options = {}) {
5326
5321
  }
5327
5322
  async function addWithdrawToTx(tx, client, address, amount, options = {}) {
5328
5323
  const asset = options.asset ?? "USDC";
5329
- const sponsored = options.sponsored ?? true;
5330
5324
  const assetInfo = resolveAssetInfo(asset);
5331
5325
  const posResult = await getPositions(client, address);
5332
5326
  const supply = posResult.positions.find(
@@ -5344,7 +5338,7 @@ async function addWithdrawToTx(tx, client, address, amount, options = {}) {
5344
5338
  });
5345
5339
  return { coin, effectiveAmount: 0 };
5346
5340
  }
5347
- await refreshOracle(tx, client, address, { skipPythUpdate: sponsored });
5341
+ await refreshOracle(tx, client, address, { skipPythUpdate: options.skipPythUpdate });
5348
5342
  try {
5349
5343
  const coin = await Qe(tx, assetInfo.type, rawAmount, sdkOptions(client));
5350
5344
  return { coin, effectiveAmount };
@@ -5368,9 +5362,8 @@ async function addSaveToTx(tx, _client, _address, coin, options = {}) {
5368
5362
  }
5369
5363
  async function addRepayToTx(tx, client, address, coin, options = {}) {
5370
5364
  const asset = options.asset ?? "USDC";
5371
- const sponsored = options.sponsored ?? true;
5372
5365
  const assetInfo = resolveAssetInfo(asset);
5373
- await refreshOracle(tx, client, address, { skipPythUpdate: sponsored });
5366
+ await refreshOracle(tx, client, address, { skipPythUpdate: options.skipPythUpdate });
5374
5367
  try {
5375
5368
  await xe(tx, assetInfo.type, coin, { env: "prod" });
5376
5369
  } catch (err) {
@@ -5387,7 +5380,7 @@ async function buildBorrowTx(client, address, amount, options = {}) {
5387
5380
  const rawAmount = Number(stableToRaw(amount, assetInfo.decimals));
5388
5381
  const tx = new Transaction();
5389
5382
  tx.setSender(address);
5390
- await refreshOracle(tx, client, address, { skipPythUpdate: options.sponsored });
5383
+ await refreshOracle(tx, client, address, { skipPythUpdate: options.skipPythUpdate });
5391
5384
  try {
5392
5385
  const borrowedCoin = await Xe(tx, assetInfo.type, rawAmount, sdkOptions(client));
5393
5386
  if (options.collectFee) {
@@ -5419,8 +5412,8 @@ async function buildRepayTx(client, address, amount, options = {}) {
5419
5412
  const rawAmount = Math.min(rawRequested, Number(totalBalance));
5420
5413
  const [repayCoin] = tx.splitCoins(coinObj, [rawAmount]);
5421
5414
  await refreshOracle(tx, client, address, {
5422
- skipPythUpdate: options.sponsored,
5423
- skipOracle: options.skipOracle
5415
+ skipOracle: options.skipOracle,
5416
+ skipPythUpdate: options.skipPythUpdate
5424
5417
  });
5425
5418
  try {
5426
5419
  await xe(tx, assetInfo.type, repayCoin, {
@@ -5734,7 +5727,10 @@ var NaviAdapter = class {
5734
5727
  }
5735
5728
  async buildWithdrawTx(address, amount, asset, options) {
5736
5729
  const normalized = normalizeAsset(asset);
5737
- const result = await buildWithdrawTx(this.client, address, amount, { asset: normalized, sponsored: options?.sponsored });
5730
+ const result = await buildWithdrawTx(this.client, address, amount, {
5731
+ asset: normalized,
5732
+ skipPythUpdate: options?.skipPythUpdate
5733
+ });
5738
5734
  return { tx: result.tx, effectiveAmount: result.effectiveAmount };
5739
5735
  }
5740
5736
  async buildBorrowTx(address, amount, asset, options) {
@@ -5746,8 +5742,8 @@ var NaviAdapter = class {
5746
5742
  const normalized = normalizeAsset(asset);
5747
5743
  const tx = await buildRepayTx(this.client, address, amount, {
5748
5744
  asset: normalized,
5749
- sponsored: options?.sponsored,
5750
- skipOracle: options?.skipOracle
5745
+ skipOracle: options?.skipOracle,
5746
+ skipPythUpdate: options?.skipPythUpdate
5751
5747
  });
5752
5748
  return { tx };
5753
5749
  }
@@ -5757,17 +5753,23 @@ var NaviAdapter = class {
5757
5753
  async maxBorrow(address, _asset) {
5758
5754
  return maxBorrowAmount(this.client, address);
5759
5755
  }
5760
- async addWithdrawToTx(tx, address, amount, asset) {
5756
+ async addWithdrawToTx(tx, address, amount, asset, options) {
5761
5757
  const normalized = normalizeAsset(asset);
5762
- return addWithdrawToTx(tx, this.client, address, amount, { asset: normalized });
5758
+ return addWithdrawToTx(tx, this.client, address, amount, {
5759
+ asset: normalized,
5760
+ skipPythUpdate: options?.skipPythUpdate
5761
+ });
5763
5762
  }
5764
5763
  async addSaveToTx(tx, address, coin, asset, options) {
5765
5764
  const normalized = normalizeAsset(asset);
5766
5765
  return addSaveToTx(tx, this.client, address, coin, { ...options, asset: normalized });
5767
5766
  }
5768
- async addRepayToTx(tx, address, coin, asset) {
5767
+ async addRepayToTx(tx, address, coin, asset, options) {
5769
5768
  const normalized = normalizeAsset(asset);
5770
- return addRepayToTx(tx, this.client, address, coin, { asset: normalized });
5769
+ return addRepayToTx(tx, this.client, address, coin, {
5770
+ asset: normalized,
5771
+ skipPythUpdate: options?.skipPythUpdate
5772
+ });
5771
5773
  }
5772
5774
  async getPendingRewards(address) {
5773
5775
  return getPendingRewards(this.client, address);
@@ -5776,339 +5778,6 @@ var NaviAdapter = class {
5776
5778
  return addClaimRewardsToTx(tx, this.client, address);
5777
5779
  }
5778
5780
  };
5779
- function hasLeadingZeroBits(hash, bits) {
5780
- const fullBytes = Math.floor(bits / 8);
5781
- const remainingBits = bits % 8;
5782
- for (let i = 0; i < fullBytes; i++) {
5783
- if (hash[i] !== 0) return false;
5784
- }
5785
- if (remainingBits > 0) {
5786
- const mask = 255 << 8 - remainingBits;
5787
- if ((hash[fullBytes] & mask) !== 0) return false;
5788
- }
5789
- return true;
5790
- }
5791
- function solveHashcash(challenge) {
5792
- const bits = parseInt(challenge.split(":")[1], 10);
5793
- let counter = 0;
5794
- while (true) {
5795
- const stamp = `${challenge}${counter.toString(16)}`;
5796
- const hash = createHash("sha256").update(stamp).digest();
5797
- if (hasLeadingZeroBits(hash, bits)) return stamp;
5798
- counter++;
5799
- }
5800
- }
5801
-
5802
- // src/gas/manager.ts
5803
- init_errors();
5804
-
5805
- // src/gas/autoTopUp.ts
5806
- async function shouldAutoTopUp(client, address) {
5807
- const [suiBalance, usdcBalance] = await Promise.all([
5808
- client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.SUI.type }),
5809
- client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.USDC.type })
5810
- ]);
5811
- const suiRaw = BigInt(suiBalance.totalBalance);
5812
- const usdcRaw = BigInt(usdcBalance.totalBalance);
5813
- if (suiRaw < GAS_RESERVE_TARGET && usdcRaw >= AUTO_TOPUP_MIN_USDC) {
5814
- return false;
5815
- }
5816
- return false;
5817
- }
5818
- async function executeAutoTopUp(_client, _signer) {
5819
- return { success: false, tx: "", usdcSpent: 0, suiReceived: 0 };
5820
- }
5821
-
5822
- // src/gas/gasStation.ts
5823
- init_errors();
5824
-
5825
- // src/utils/base64.ts
5826
- function toBase642(bytes) {
5827
- let binary = "";
5828
- for (const byte of bytes) binary += String.fromCharCode(byte);
5829
- return btoa(binary);
5830
- }
5831
- function fromBase642(b64) {
5832
- const binary = atob(b64);
5833
- const bytes = new Uint8Array(binary.length);
5834
- for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
5835
- return bytes;
5836
- }
5837
-
5838
- // src/gas/gasStation.ts
5839
- async function requestGasSponsorship(txJson, sender, type, txBcsBytes) {
5840
- const payload = { sender, type };
5841
- if (txBcsBytes) {
5842
- payload.txBcsBytes = txBcsBytes;
5843
- } else {
5844
- payload.txJson = txJson;
5845
- payload.txBytes = toBase642(new TextEncoder().encode(txJson));
5846
- }
5847
- const res = await fetch(`${API_BASE_URL}/api/gas`, {
5848
- method: "POST",
5849
- headers: { "Content-Type": "application/json" },
5850
- body: JSON.stringify(payload)
5851
- });
5852
- const data = await res.json();
5853
- if (!res.ok) {
5854
- const errorCode = data.error;
5855
- if (errorCode === "CIRCUIT_BREAKER" || errorCode === "POOL_DEPLETED" || errorCode === "PRICE_STALE") {
5856
- throw new T2000Error(
5857
- "GAS_STATION_UNAVAILABLE",
5858
- data.message ?? "Gas station temporarily unavailable",
5859
- { retryAfter: data.retryAfter, reason: errorCode },
5860
- true
5861
- );
5862
- }
5863
- if (errorCode === "GAS_FEE_EXCEEDED") {
5864
- throw new T2000Error(
5865
- "GAS_FEE_EXCEEDED",
5866
- data.message ?? "Gas fee exceeds ceiling",
5867
- { retryAfter: data.retryAfter },
5868
- true
5869
- );
5870
- }
5871
- throw new T2000Error(
5872
- "GAS_STATION_UNAVAILABLE",
5873
- data.message ?? "Gas sponsorship request failed",
5874
- { reason: errorCode },
5875
- true
5876
- );
5877
- }
5878
- return data;
5879
- }
5880
- async function reportGasUsage(sender, txDigest, gasCostSui, usdcCharged, type) {
5881
- try {
5882
- await fetch(`${API_BASE_URL}/api/gas/report`, {
5883
- method: "POST",
5884
- headers: { "Content-Type": "application/json" },
5885
- body: JSON.stringify({ sender, txDigest, gasCostSui, usdcCharged, type })
5886
- });
5887
- } catch {
5888
- }
5889
- }
5890
- async function getGasStatus(address) {
5891
- const url = new URL(`${API_BASE_URL}/api/gas/status`);
5892
- if (address) url.searchParams.set("address", address);
5893
- const res = await fetch(url.toString());
5894
- if (!res.ok) {
5895
- throw new T2000Error("GAS_STATION_UNAVAILABLE", "Failed to fetch gas status", void 0, true);
5896
- }
5897
- return await res.json();
5898
- }
5899
-
5900
- // src/gas/manager.ts
5901
- function extractGasCost(effects) {
5902
- if (!effects?.gasUsed) return 0;
5903
- return (Number(effects.gasUsed.computationCost) + Number(effects.gasUsed.storageCost) - Number(effects.gasUsed.storageRebate)) / 1e9;
5904
- }
5905
- async function getSuiBalance(client, address) {
5906
- const bal = await client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.SUI.type });
5907
- return BigInt(bal.totalBalance);
5908
- }
5909
- async function assertTxSuccess(effects, digest) {
5910
- const eff = effects;
5911
- if (eff?.status?.status === "failure") {
5912
- const errMsg = eff.status.error ?? "unknown on-chain error";
5913
- if (isMoveAbort(errMsg)) {
5914
- throw new T2000Error("TRANSACTION_FAILED", parseMoveAbortMessage(errMsg));
5915
- }
5916
- throw new T2000Error("TRANSACTION_FAILED", `Transaction ${digest} failed on-chain: ${errMsg}`);
5917
- }
5918
- }
5919
- async function trySelfFunded(client, signer, tx) {
5920
- const address = signer.getAddress();
5921
- const suiBalance = await getSuiBalance(client, address);
5922
- if (suiBalance < AUTO_TOPUP_THRESHOLD) return null;
5923
- tx.setSender(address);
5924
- const builtBytes = await tx.build({ client });
5925
- const { signature } = await signer.signTransaction(builtBytes);
5926
- const result = await client.executeTransactionBlock({
5927
- transactionBlock: toBase642(builtBytes),
5928
- signature: [signature],
5929
- options: { showEffects: true, showBalanceChanges: true }
5930
- });
5931
- await client.waitForTransaction({ digest: result.digest });
5932
- await assertTxSuccess(result.effects, result.digest);
5933
- return {
5934
- digest: result.digest,
5935
- effects: result.effects,
5936
- balanceChanges: result.balanceChanges,
5937
- gasMethod: "self-funded",
5938
- gasCostSui: extractGasCost(result.effects),
5939
- preTxSuiMist: suiBalance
5940
- };
5941
- }
5942
- async function tryAutoTopUpThenSelfFund(client, signer, buildTx) {
5943
- const address = signer.getAddress();
5944
- const canTopUp = await shouldAutoTopUp(client, address);
5945
- if (!canTopUp) return null;
5946
- await executeAutoTopUp();
5947
- const tx = await buildTx();
5948
- tx.setSender(address);
5949
- const suiAfterTopUp = await getSuiBalance(client, address);
5950
- const builtBytes = await tx.build({ client });
5951
- const { signature } = await signer.signTransaction(builtBytes);
5952
- const result = await client.executeTransactionBlock({
5953
- transactionBlock: toBase642(builtBytes),
5954
- signature: [signature],
5955
- options: { showEffects: true, showBalanceChanges: true }
5956
- });
5957
- await client.waitForTransaction({ digest: result.digest });
5958
- await assertTxSuccess(result.effects, result.digest);
5959
- return {
5960
- digest: result.digest,
5961
- effects: result.effects,
5962
- balanceChanges: result.balanceChanges,
5963
- gasMethod: "auto-topup",
5964
- gasCostSui: extractGasCost(result.effects),
5965
- preTxSuiMist: suiAfterTopUp
5966
- };
5967
- }
5968
- async function trySponsored(client, signer, tx) {
5969
- const address = signer.getAddress();
5970
- const suiBalance = await getSuiBalance(client, address);
5971
- tx.setSender(address);
5972
- let txJson;
5973
- let txBcsBase64;
5974
- try {
5975
- txJson = tx.serialize();
5976
- } catch {
5977
- const bcsBytes = await tx.build({ client });
5978
- txBcsBase64 = toBase642(bcsBytes);
5979
- }
5980
- const sponsoredResult = await requestGasSponsorship(txJson ?? "", address, void 0, txBcsBase64);
5981
- const sponsoredTxBytes = fromBase642(sponsoredResult.txBytes);
5982
- const { signature: agentSig } = await signer.signTransaction(sponsoredTxBytes);
5983
- const result = await client.executeTransactionBlock({
5984
- transactionBlock: sponsoredResult.txBytes,
5985
- signature: [agentSig, sponsoredResult.sponsorSignature],
5986
- options: { showEffects: true, showBalanceChanges: true }
5987
- });
5988
- await client.waitForTransaction({ digest: result.digest });
5989
- await assertTxSuccess(result.effects, result.digest);
5990
- const gasCost = extractGasCost(result.effects);
5991
- reportGasUsage(address, result.digest, gasCost, 0, sponsoredResult.type);
5992
- return {
5993
- digest: result.digest,
5994
- effects: result.effects,
5995
- balanceChanges: result.balanceChanges,
5996
- gasMethod: "sponsored",
5997
- gasCostSui: gasCost,
5998
- preTxSuiMist: suiBalance
5999
- };
6000
- }
6001
- async function waitForIndexer(client, digest) {
6002
- for (let i = 0; i < 3; i++) {
6003
- try {
6004
- await client.getTransactionBlock({ digest, options: { showObjectChanges: true } });
6005
- return;
6006
- } catch {
6007
- await new Promise((r) => setTimeout(r, 500));
6008
- }
6009
- }
6010
- }
6011
- async function executeWithGas(client, signer, buildTx, options) {
6012
- if (options?.enforcer && options?.metadata) {
6013
- options.enforcer.check(options.metadata);
6014
- }
6015
- const result = await resolveGas(client, signer, buildTx);
6016
- try {
6017
- if (result.preTxSuiMist !== void 0) {
6018
- const gasCostMist = result.gasMethod === "sponsored" ? 0n : BigInt(Math.round(result.gasCostSui * 1e9));
6019
- const estimatedRemaining = result.preTxSuiMist - gasCostMist;
6020
- if (estimatedRemaining < GAS_RESERVE_TARGET) {
6021
- const address = signer.getAddress();
6022
- const usdcBal = await client.getBalance({
6023
- owner: address,
6024
- coinType: SUPPORTED_ASSETS.USDC.type
6025
- });
6026
- if (BigInt(usdcBal.totalBalance) >= AUTO_TOPUP_MIN_USDC) {
6027
- await executeAutoTopUp(client, signer);
6028
- }
6029
- }
6030
- }
6031
- } catch {
6032
- }
6033
- return result;
6034
- }
6035
- var GAS_RESOLUTION_CODES = /* @__PURE__ */ new Set([
6036
- "INSUFFICIENT_GAS",
6037
- "GAS_STATION_UNAVAILABLE",
6038
- "GAS_FEE_EXCEEDED",
6039
- "AUTO_TOPUP_FAILED",
6040
- "SPONSOR_UNAVAILABLE"
6041
- ]);
6042
- function isBuildError(err) {
6043
- return err instanceof T2000Error && !GAS_RESOLUTION_CODES.has(err.code);
6044
- }
6045
- async function resolveGas(client, signer, buildTx) {
6046
- const errors = [];
6047
- let lastBuildError;
6048
- try {
6049
- const tx = await buildTx();
6050
- const result = await trySelfFunded(client, signer, tx);
6051
- if (result) {
6052
- await waitForIndexer(client, result.digest);
6053
- return result;
6054
- }
6055
- errors.push("self-funded: SUI below threshold");
6056
- } catch (err) {
6057
- if (err instanceof T2000Error && err.code === "TRANSACTION_FAILED") throw err;
6058
- const msg = err instanceof Error ? err.message : String(err);
6059
- if (isMoveAbort(msg)) {
6060
- throw new T2000Error("TRANSACTION_FAILED", parseMoveAbortMessage(msg));
6061
- }
6062
- if (isBuildError(err)) lastBuildError = err;
6063
- errors.push(`self-funded: ${msg}`);
6064
- }
6065
- try {
6066
- const result = await tryAutoTopUpThenSelfFund(client, signer, buildTx);
6067
- if (result) {
6068
- await waitForIndexer(client, result.digest);
6069
- return result;
6070
- }
6071
- errors.push("auto-topup: not eligible (low USDC or sufficient SUI)");
6072
- } catch (err) {
6073
- if (err instanceof T2000Error && err.code === "TRANSACTION_FAILED") throw err;
6074
- errors.push(`auto-topup: ${err instanceof Error ? err.message : String(err)}`);
6075
- }
6076
- try {
6077
- const tx = await buildTx();
6078
- const result = await trySelfFunded(client, signer, tx);
6079
- if (result) {
6080
- await waitForIndexer(client, result.digest);
6081
- return result;
6082
- }
6083
- } catch (err) {
6084
- if (err instanceof T2000Error && err.code === "TRANSACTION_FAILED") throw err;
6085
- const msg = err instanceof Error ? err.message : String(err);
6086
- if (isMoveAbort(msg)) {
6087
- throw new T2000Error("TRANSACTION_FAILED", parseMoveAbortMessage(msg));
6088
- }
6089
- if (isBuildError(err)) lastBuildError = err;
6090
- errors.push(`self-funded-retry: ${msg}`);
6091
- }
6092
- try {
6093
- const tx = await buildTx();
6094
- const result = await trySponsored(client, signer, tx);
6095
- if (result) {
6096
- await waitForIndexer(client, result.digest);
6097
- return result;
6098
- }
6099
- errors.push("sponsored: returned null");
6100
- } catch (err) {
6101
- if (err instanceof T2000Error && err.code === "TRANSACTION_FAILED") throw err;
6102
- if (isBuildError(err)) lastBuildError = err;
6103
- errors.push(`sponsored: ${err instanceof Error ? err.message : String(err)}`);
6104
- }
6105
- if (lastBuildError) throw lastBuildError;
6106
- throw new T2000Error(
6107
- "INSUFFICIENT_GAS",
6108
- `No SUI for gas and sponsorship unavailable. Fund your wallet with SUI or USDC. [${errors.join(" | ")}]`,
6109
- { reason: "all_gas_methods_exhausted", errors }
6110
- );
6111
- }
6112
5781
 
6113
5782
  // src/t2000.ts
6114
5783
  init_errors();
@@ -6353,6 +6022,25 @@ var ContactManager = class {
6353
6022
  }
6354
6023
  };
6355
6024
  var DEFAULT_CONFIG_DIR = join$1(homedir(), ".t2000");
6025
+ async function executeTx(client, signer, buildTx) {
6026
+ const tx = await buildTx();
6027
+ tx.setSender(signer.getAddress());
6028
+ const txBytes = await tx.build({ client });
6029
+ const { signature } = await signer.signTransaction(txBytes);
6030
+ const result = await client.executeTransactionBlock({
6031
+ transactionBlock: txBytes,
6032
+ signature,
6033
+ options: { showEffects: true }
6034
+ });
6035
+ await client.waitForTransaction({ digest: result.digest });
6036
+ const gasUsed = result.effects?.gasUsed;
6037
+ let gasCostSui = 0;
6038
+ if (gasUsed) {
6039
+ const total = BigInt(gasUsed.computationCost) + BigInt(gasUsed.storageCost) - BigInt(gasUsed.storageRebate);
6040
+ gasCostSui = Number(total) / 1e9;
6041
+ }
6042
+ return { digest: result.digest, gasCostSui, effects: result.effects ?? void 0 };
6043
+ }
6356
6044
  var T2000 = class _T2000 extends EventEmitter {
6357
6045
  _signer;
6358
6046
  _keypair;
@@ -6387,16 +6075,9 @@ var T2000 = class _T2000 extends EventEmitter {
6387
6075
  return registry;
6388
6076
  }
6389
6077
  static async create(options = {}) {
6390
- const { keyPath, pin, passphrase, network = DEFAULT_NETWORK, rpcUrl, sponsored, name } = options;
6078
+ const { keyPath, pin, passphrase, rpcUrl } = options;
6391
6079
  const secret = pin ?? passphrase;
6392
6080
  const client = getSuiClient(rpcUrl);
6393
- if (sponsored) {
6394
- const keypair2 = generateKeypair();
6395
- if (secret) {
6396
- await saveKey(keypair2, secret, keyPath);
6397
- }
6398
- return new _T2000(keypair2, client, void 0, DEFAULT_CONFIG_DIR);
6399
- }
6400
6081
  const exists = await walletExists(keyPath);
6401
6082
  if (!exists) {
6402
6083
  throw new T2000Error(
@@ -6422,15 +6103,7 @@ var T2000 = class _T2000 extends EventEmitter {
6422
6103
  const client = getSuiClient();
6423
6104
  const agent = new _T2000(keypair, client, void 0, DEFAULT_CONFIG_DIR);
6424
6105
  const address = agent.address();
6425
- let sponsored = false;
6426
- if (options.sponsored !== false) {
6427
- try {
6428
- await callSponsorApi(address, options.name);
6429
- sponsored = true;
6430
- } catch {
6431
- }
6432
- }
6433
- return { agent, address, sponsored };
6106
+ return { agent, address };
6434
6107
  }
6435
6108
  // -- Gas --
6436
6109
  /** SuiJsonRpcClient used by this agent — exposed for integrations. */
@@ -6463,7 +6136,7 @@ var T2000 = class _T2000 extends EventEmitter {
6463
6136
  client,
6464
6137
  signer: { toSuiAddress: () => signerAddress },
6465
6138
  execute: async (tx) => {
6466
- const result = await executeWithGas(client, signer, () => tx);
6139
+ const result = await executeTx(client, signer, () => tx);
6467
6140
  return { digest: result.digest, effects: result.effects };
6468
6141
  }
6469
6142
  })]
@@ -6501,7 +6174,7 @@ var T2000 = class _T2000 extends EventEmitter {
6501
6174
  const { buildStakeVSuiTx: buildStakeVSuiTx2, getVoloStats: getVoloStats2 } = await Promise.resolve().then(() => (init_volo(), volo_exports));
6502
6175
  const amountMist = BigInt(Math.floor(params.amount * Number(MIST_PER_SUI)));
6503
6176
  const stats = await getVoloStats2();
6504
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6177
+ const gasResult = await executeTx(this.client, this._signer, async () => {
6505
6178
  return buildStakeVSuiTx2(this.client, this._address, amountMist);
6506
6179
  });
6507
6180
  const vSuiReceived = params.amount / stats.exchangeRate;
@@ -6511,8 +6184,7 @@ var T2000 = class _T2000 extends EventEmitter {
6511
6184
  amountSui: params.amount,
6512
6185
  vSuiReceived,
6513
6186
  apy: stats.apy,
6514
- gasCost: gasResult.gasCostSui,
6515
- gasMethod: gasResult.gasMethod
6187
+ gasCost: gasResult.gasCostSui
6516
6188
  };
6517
6189
  }
6518
6190
  async unstakeVSui(params) {
@@ -6529,7 +6201,7 @@ var T2000 = class _T2000 extends EventEmitter {
6529
6201
  vSuiAmount = params.amount;
6530
6202
  }
6531
6203
  const stats = await getVoloStats2();
6532
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6204
+ const gasResult = await executeTx(this.client, this._signer, async () => {
6533
6205
  return buildUnstakeVSuiTx2(this.client, this._address, amountMist);
6534
6206
  });
6535
6207
  const suiReceived = vSuiAmount * stats.exchangeRate;
@@ -6538,8 +6210,7 @@ var T2000 = class _T2000 extends EventEmitter {
6538
6210
  tx: gasResult.digest,
6539
6211
  vSuiAmount,
6540
6212
  suiReceived,
6541
- gasCost: gasResult.gasCostSui,
6542
- gasMethod: gasResult.gasMethod
6213
+ gasCost: gasResult.gasCostSui
6543
6214
  };
6544
6215
  }
6545
6216
  // -- Swap --
@@ -6573,7 +6244,7 @@ var T2000 = class _T2000 extends EventEmitter {
6573
6244
  preBalRaw = BigInt(preBal.totalBalance);
6574
6245
  } catch {
6575
6246
  }
6576
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6247
+ const gasResult = await executeTx(this.client, this._signer, async () => {
6577
6248
  const tx = new Transaction();
6578
6249
  tx.setSender(this._address);
6579
6250
  let inputCoin;
@@ -6642,8 +6313,7 @@ var T2000 = class _T2000 extends EventEmitter {
6642
6313
  toAmount,
6643
6314
  priceImpact: route.priceImpact,
6644
6315
  route: routeDesc,
6645
- gasCost: gasResult.gasCostSui,
6646
- gasMethod: gasResult.gasMethod
6316
+ gasCost: gasResult.gasCostSui
6647
6317
  };
6648
6318
  }
6649
6319
  async swapQuote(params) {
@@ -6690,11 +6360,10 @@ var T2000 = class _T2000 extends EventEmitter {
6690
6360
  const resolved = this.contacts.resolve(params.to);
6691
6361
  const sendAmount = params.amount;
6692
6362
  const sendTo = resolved.address;
6693
- const gasResult = await executeWithGas(
6363
+ const gasResult = await executeTx(
6694
6364
  this.client,
6695
6365
  this._signer,
6696
- () => buildSendTx({ client: this.client, address: this._address, to: sendTo, amount: sendAmount, asset }),
6697
- { metadata: { operation: "send", amount: sendAmount }, enforcer: this.enforcer }
6366
+ () => buildSendTx({ client: this.client, address: this._address, to: sendTo, amount: sendAmount, asset })
6698
6367
  );
6699
6368
  this.enforcer.recordUsage(sendAmount);
6700
6369
  const balance = await this.balance();
@@ -6707,7 +6376,6 @@ var T2000 = class _T2000 extends EventEmitter {
6707
6376
  contactName: resolved.contactName,
6708
6377
  gasCost: gasResult.gasCostSui,
6709
6378
  gasCostUnit: "SUI",
6710
- gasMethod: gasResult.gasMethod,
6711
6379
  balance
6712
6380
  };
6713
6381
  }
@@ -6840,7 +6508,7 @@ var T2000 = class _T2000 extends EventEmitter {
6840
6508
  const saveAmount = amount;
6841
6509
  const adapter = await this.resolveLending(params.protocol, asset, "save");
6842
6510
  const canPTB = !!adapter.addSaveToTx;
6843
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6511
+ const gasResult = await executeTx(this.client, this._signer, async () => {
6844
6512
  if (canPTB) {
6845
6513
  const tx2 = new Transaction();
6846
6514
  tx2.setSender(this._address);
@@ -6878,7 +6546,6 @@ var T2000 = class _T2000 extends EventEmitter {
6878
6546
  apy: rates.saveApy,
6879
6547
  fee: fee.amount,
6880
6548
  gasCost: gasResult.gasCostSui,
6881
- gasMethod: gasResult.gasMethod,
6882
6549
  savingsBalance
6883
6550
  };
6884
6551
  }
@@ -6937,7 +6604,7 @@ var T2000 = class _T2000 extends EventEmitter {
6937
6604
  }
6938
6605
  const withdrawAmount = amount;
6939
6606
  let finalAmount = withdrawAmount;
6940
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6607
+ const gasResult = await executeTx(this.client, this._signer, async () => {
6941
6608
  if (adapter.addWithdrawToTx) {
6942
6609
  const tx = new Transaction();
6943
6610
  tx.setSender(this._address);
@@ -6956,8 +6623,7 @@ var T2000 = class _T2000 extends EventEmitter {
6956
6623
  tx: gasResult.digest,
6957
6624
  amount: finalAmount,
6958
6625
  asset: target.asset,
6959
- gasCost: gasResult.gasCostSui,
6960
- gasMethod: gasResult.gasMethod
6626
+ gasCost: gasResult.gasCostSui
6961
6627
  };
6962
6628
  }
6963
6629
  async withdrawAllProtocols() {
@@ -6994,7 +6660,7 @@ var T2000 = class _T2000 extends EventEmitter {
6994
6660
  }
6995
6661
  let totalReceived = 0;
6996
6662
  const canPTB = entries.every((e) => e.adapter.addWithdrawToTx);
6997
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6663
+ const gasResult = await executeTx(this.client, this._signer, async () => {
6998
6664
  if (canPTB) {
6999
6665
  const tx = new Transaction();
7000
6666
  tx.setSender(this._address);
@@ -7025,8 +6691,7 @@ var T2000 = class _T2000 extends EventEmitter {
7025
6691
  success: true,
7026
6692
  tx: gasResult.digest,
7027
6693
  amount: totalReceived,
7028
- gasCost: gasResult.gasCostSui,
7029
- gasMethod: gasResult.gasMethod
6694
+ gasCost: gasResult.gasCostSui
7030
6695
  };
7031
6696
  }
7032
6697
  /**
@@ -7144,7 +6809,7 @@ var T2000 = class _T2000 extends EventEmitter {
7144
6809
  }
7145
6810
  const fee = calculateFee("borrow", params.amount);
7146
6811
  const borrowAmount = params.amount;
7147
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6812
+ const gasResult = await executeTx(this.client, this._signer, async () => {
7148
6813
  const { tx } = await adapter.buildBorrowTx(this._address, borrowAmount, asset, { collectFee: true });
7149
6814
  return tx;
7150
6815
  });
@@ -7158,8 +6823,7 @@ var T2000 = class _T2000 extends EventEmitter {
7158
6823
  asset,
7159
6824
  fee: fee.amount,
7160
6825
  healthFactor: hf.healthFactor,
7161
- gasCost: gasResult.gasCostSui,
7162
- gasMethod: gasResult.gasMethod
6826
+ gasCost: gasResult.gasCostSui
7163
6827
  };
7164
6828
  }
7165
6829
  async repay(params) {
@@ -7188,7 +6852,7 @@ var T2000 = class _T2000 extends EventEmitter {
7188
6852
  if (!adapter) throw new T2000Error("PROTOCOL_UNAVAILABLE", `Protocol ${target.protocolId} not found`);
7189
6853
  const repayAmount = Math.min(params.amount, target.amount);
7190
6854
  const targetAssetInfo = SUPPORTED_ASSETS[target.asset] ?? SUPPORTED_ASSETS.USDC;
7191
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6855
+ const gasResult = await executeTx(this.client, this._signer, async () => {
7192
6856
  if (adapter.addRepayToTx) {
7193
6857
  const tx2 = new Transaction();
7194
6858
  tx2.setSender(this._address);
@@ -7211,8 +6875,7 @@ var T2000 = class _T2000 extends EventEmitter {
7211
6875
  amount: repayAmount,
7212
6876
  asset: target.asset,
7213
6877
  remainingDebt: hf.borrowed,
7214
- gasCost: gasResult.gasCostSui,
7215
- gasMethod: gasResult.gasMethod
6878
+ gasCost: gasResult.gasCostSui
7216
6879
  };
7217
6880
  }
7218
6881
  async _repayAllBorrows(borrows) {
@@ -7224,7 +6887,7 @@ var T2000 = class _T2000 extends EventEmitter {
7224
6887
  }
7225
6888
  const canPTB = entries.every((e) => e.adapter.addRepayToTx);
7226
6889
  let totalRepaid = 0;
7227
- const gasResult = await executeWithGas(this.client, this._signer, async () => {
6890
+ const gasResult = await executeTx(this.client, this._signer, async () => {
7228
6891
  if (canPTB) {
7229
6892
  const tx = new Transaction();
7230
6893
  tx.setSender(this._address);
@@ -7265,8 +6928,7 @@ var T2000 = class _T2000 extends EventEmitter {
7265
6928
  amount: totalRepaid,
7266
6929
  asset: dominantAsset,
7267
6930
  remainingDebt: hf.borrowed,
7268
- gasCost: gasResult.gasCostSui,
7269
- gasMethod: gasResult.gasMethod
6931
+ gasCost: gasResult.gasCostSui
7270
6932
  };
7271
6933
  }
7272
6934
  async maxBorrow() {
@@ -7299,7 +6961,7 @@ var T2000 = class _T2000 extends EventEmitter {
7299
6961
  this.enforcer.assertNotLocked();
7300
6962
  const adapters = this.registry.listLending().filter((a) => a.addClaimRewardsToTx);
7301
6963
  if (adapters.length === 0) {
7302
- return { success: true, tx: "", rewards: [], totalValueUsd: 0, gasCost: 0, gasMethod: "none" };
6964
+ return { success: true, tx: "", rewards: [], totalValueUsd: 0, gasCost: 0 };
7303
6965
  }
7304
6966
  const tx = new Transaction();
7305
6967
  tx.setSender(this._address);
@@ -7312,9 +6974,9 @@ var T2000 = class _T2000 extends EventEmitter {
7312
6974
  }
7313
6975
  }
7314
6976
  if (allRewards.length === 0) {
7315
- return { success: true, tx: "", rewards: [], totalValueUsd: 0, gasCost: 0, gasMethod: "none" };
6977
+ return { success: true, tx: "", rewards: [], totalValueUsd: 0, gasCost: 0 };
7316
6978
  }
7317
- const claimResult = await executeWithGas(this.client, this._signer, async () => tx);
6979
+ const claimResult = await executeTx(this.client, this._signer, async () => tx);
7318
6980
  await this.client.waitForTransaction({ digest: claimResult.digest });
7319
6981
  const totalValueUsd = allRewards.reduce((s, r) => s + r.estimatedValueUsd, 0);
7320
6982
  return {
@@ -7322,8 +6984,7 @@ var T2000 = class _T2000 extends EventEmitter {
7322
6984
  tx: claimResult.digest,
7323
6985
  rewards: allRewards,
7324
6986
  totalValueUsd,
7325
- gasCost: claimResult.gasCostSui,
7326
- gasMethod: claimResult.gasMethod
6987
+ gasCost: claimResult.gasCostSui
7327
6988
  };
7328
6989
  }
7329
6990
  /**
@@ -7395,7 +7056,7 @@ var T2000 = class _T2000 extends EventEmitter {
7395
7056
  byAmountIn: true
7396
7057
  });
7397
7058
  if (!route || route.insufficientLiquidity) continue;
7398
- const swapResult = await executeWithGas(this.client, this._signer, async () => {
7059
+ const swapResult = await executeTx(this.client, this._signer, async () => {
7399
7060
  const tx = new Transaction();
7400
7061
  tx.setSender(this._address);
7401
7062
  const freshCoins = await this._fetchCoins(reward.coinType);
@@ -7426,7 +7087,7 @@ var T2000 = class _T2000 extends EventEmitter {
7426
7087
  if (gainedRaw > 0n) {
7427
7088
  try {
7428
7089
  const adapter = await this.resolveLending(void 0, "USDC", "save");
7429
- const depositResult = await executeWithGas(this.client, this._signer, async () => {
7090
+ const depositResult = await executeTx(this.client, this._signer, async () => {
7430
7091
  const tx = new Transaction();
7431
7092
  tx.setSender(this._address);
7432
7093
  const coins = await this._fetchCoins(USDC_TYPE2);
@@ -7557,29 +7218,6 @@ var T2000 = class _T2000 extends EventEmitter {
7557
7218
  this.emit("balanceChange", { asset, previous: 0, current: 0, cause, tx });
7558
7219
  }
7559
7220
  };
7560
- async function callSponsorApi(address, name) {
7561
- const res = await fetch(`${API_BASE_URL}/api/sponsor`, {
7562
- method: "POST",
7563
- headers: { "Content-Type": "application/json" },
7564
- body: JSON.stringify({ address, name })
7565
- });
7566
- if (res.status === 429) {
7567
- const data = await res.json();
7568
- if (data.challenge) {
7569
- const proof = solveHashcash(data.challenge);
7570
- const retry = await fetch(`${API_BASE_URL}/api/sponsor`, {
7571
- method: "POST",
7572
- headers: { "Content-Type": "application/json" },
7573
- body: JSON.stringify({ address, name, proof })
7574
- });
7575
- if (!retry.ok) throw new T2000Error("SPONSOR_RATE_LIMITED", "Sponsor rate limited");
7576
- return;
7577
- }
7578
- }
7579
- if (!res.ok) {
7580
- throw new T2000Error("SPONSOR_FAILED", "Sponsor API unavailable");
7581
- }
7582
- }
7583
7221
 
7584
7222
  // src/index.ts
7585
7223
  init_errors();
@@ -7766,6 +7404,6 @@ init_volo();
7766
7404
  (*! scure-base - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
7767
7405
  */
7768
7406
 
7769
- export { ALL_NAVI_ASSETS, BORROW_FEE_BPS, BPS_DENOMINATOR, CETUS_USDC_SUI_POOL, CLOCK_ID, COIN_REGISTRY, ContactManager, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, ETH_TYPE, GAS_RESERVE_MIN, HF_CRITICAL_THRESHOLD, HF_WARN_THRESHOLD, IKA_TYPE, KNOWN_TARGETS, KeypairSigner, LABEL_PATTERNS, LOFI_TYPE, MANIFEST_TYPE, MIST_PER_SUI, NAVX_TYPE, NaviAdapter, OPERATION_ASSETS, OUTBOUND_OPS, OVERLAY_FEE_RATE, ProtocolRegistry, SAVE_FEE_BPS, STABLE_ASSETS, SUI_DECIMALS, SUI_TYPE, SUPPORTED_ASSETS, SafeguardEnforcer, SafeguardError, T2000, T2000Error, TOKEN_MAP, USDC_DECIMALS, USDC_TYPE, USDE_TYPE, USDSUI_TYPE, USDT_TYPE, VOLO_METADATA, VOLO_PKG, VOLO_POOL, VSUI_TYPE, WAL_TYPE, WBTC_TYPE, ZkLoginSigner, addCollectFeeToTx, allDescriptors, assertAllowedAsset, buildStakeVSuiTx, buildSwapTx, buildUnstakeVSuiTx, calculateFee, classifyAction, classifyLabel, classifyTransaction, executeAutoTopUp, executeWithGas, exportPrivateKey, extractTransferDetails, extractTxCommands, extractTxSender, fallbackLabel, findSwapRoute, formatAssetAmount, formatSui, formatUsd, generateKeypair, getAddress, getDecimals, getDecimalsForCoinType, getFinancialSummary, getGasStatus, getPendingRewards, getRates, getSwapQuote, getTier, getVoloStats, isAllowedAsset, isSupported, isTier1, isTier2, keypairFromPrivateKey, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, naviDescriptor, normalizeCoinType, parseSuiRpcTx, queryHistory, queryTransaction, rawToStable, rawToUsdc, refineLendingLabel, resolveSymbol, resolveTokenType, saveKey, shouldAutoTopUp, simulateTransaction, solveHashcash, stableToRaw, suiToMist, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, walletExists };
7407
+ export { ALL_NAVI_ASSETS, BORROW_FEE_BPS, BPS_DENOMINATOR, CETUS_USDC_SUI_POOL, CLOCK_ID, COIN_REGISTRY, ContactManager, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, ETH_TYPE, GAS_RESERVE_MIN, HF_CRITICAL_THRESHOLD, HF_WARN_THRESHOLD, IKA_TYPE, KNOWN_TARGETS, KeypairSigner, LABEL_PATTERNS, LOFI_TYPE, MANIFEST_TYPE, MIST_PER_SUI, NAVX_TYPE, NaviAdapter, OPERATION_ASSETS, OUTBOUND_OPS, OVERLAY_FEE_RATE, ProtocolRegistry, SAVE_FEE_BPS, STABLE_ASSETS, SUI_DECIMALS, SUI_TYPE, SUPPORTED_ASSETS, SafeguardEnforcer, SafeguardError, T2000, T2000Error, TOKEN_MAP, USDC_DECIMALS, USDC_TYPE, USDE_TYPE, USDSUI_TYPE, USDT_TYPE, VOLO_METADATA, VOLO_PKG, VOLO_POOL, VSUI_TYPE, WAL_TYPE, WBTC_TYPE, ZkLoginSigner, addCollectFeeToTx, allDescriptors, assertAllowedAsset, buildStakeVSuiTx, buildSwapTx, buildUnstakeVSuiTx, calculateFee, classifyAction, classifyLabel, classifyTransaction, exportPrivateKey, extractTransferDetails, extractTxCommands, extractTxSender, fallbackLabel, findSwapRoute, formatAssetAmount, formatSui, formatUsd, generateKeypair, getAddress, getDecimals, getDecimalsForCoinType, getFinancialSummary, getPendingRewards, getRates, getSwapQuote, getTier, getVoloStats, isAllowedAsset, isSupported, isTier1, isTier2, keypairFromPrivateKey, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, naviDescriptor, normalizeCoinType, parseSuiRpcTx, queryHistory, queryTransaction, rawToStable, rawToUsdc, refineLendingLabel, resolveSymbol, resolveTokenType, saveKey, simulateTransaction, stableToRaw, suiToMist, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, walletExists };
7770
7408
  //# sourceMappingURL=index.js.map
7771
7409
  //# sourceMappingURL=index.js.map