@t2000/sdk 0.8.7 → 0.9.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.d.cts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { EventEmitter } from 'eventemitter3';
2
2
  import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
3
3
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
4
- import { T as T2000Options, S as SendResult, B as BalanceResponse, a as TransactionRecord, D as DepositInfo, L as LendingAdapter, b as SwapAdapter, c as SaveResult, W as WithdrawResult, M as MaxWithdrawResult, d as BorrowResult, R as RepayResult, e as MaxBorrowResult, H as HealthFactorResult, f as SwapResult, P as PositionsResult, g as RatesResult, h as LendingRates, i as RebalanceResult, E as EarningsResult, F as FundStatusResult, j as SentinelAgent, k as SentinelAttackResult, G as GasMethod } from './index-DNjooNFy.cjs';
5
- export { A as AdapterCapability, l as AdapterPositions, m as AdapterTxResult, n as AssetRates, C as CetusAdapter, o as GasReserve, p as HealthInfo, N as NaviAdapter, q as PositionEntry, r as ProtocolDescriptor, s as ProtocolRegistry, t as RebalanceStep, u as SentinelVerdict, v as SuilendAdapter, w as SwapQuote, x as allDescriptors, y as cetusDescriptor, z as getSentinelInfo, I as listSentinels, J as naviDescriptor, K as requestAttack, O as sentinelAttack, Q as sentinelDescriptor, U as settleAttack, V as submitPrompt, X as suilendDescriptor } from './index-DNjooNFy.cjs';
4
+ import { T as T2000Options, S as SendResult, B as BalanceResponse, a as TransactionRecord, D as DepositInfo, L as LendingAdapter, b as SwapAdapter, c as SaveResult, W as WithdrawResult, M as MaxWithdrawResult, d as BorrowResult, R as RepayResult, e as MaxBorrowResult, H as HealthFactorResult, P as PositionsResult, f as RatesResult, g as LendingRates, h as RebalanceResult, E as EarningsResult, F as FundStatusResult, i as SentinelAgent, j as SentinelAttackResult, G as GasMethod } from './index-C7W686z2.cjs';
5
+ export { A as AdapterCapability, k as AdapterPositions, l as AdapterTxResult, m as AssetRates, C as CetusAdapter, n as GasReserve, o as HealthInfo, N as NaviAdapter, p as PositionEntry, q as ProtocolDescriptor, r as ProtocolRegistry, s as RebalanceStep, t as SentinelVerdict, u as SuilendAdapter, v as SwapQuote, w as SwapResult, x as allDescriptors, y as cetusDescriptor, z as getSentinelInfo, I as listSentinels, J as naviDescriptor, K as requestAttack, O as sentinelAttack, Q as sentinelDescriptor, U as settleAttack, V as submitPrompt, X as suilendDescriptor } from './index-C7W686z2.cjs';
6
6
  import { Transaction, TransactionObjectArgument } from '@mysten/sui/transactions';
7
7
 
8
- type T2000ErrorCode = 'INSUFFICIENT_BALANCE' | 'INSUFFICIENT_GAS' | 'INVALID_ADDRESS' | 'INVALID_AMOUNT' | 'WALLET_NOT_FOUND' | 'WALLET_LOCKED' | 'WALLET_EXISTS' | 'SPONSOR_FAILED' | 'SPONSOR_RATE_LIMITED' | 'GAS_STATION_UNAVAILABLE' | 'GAS_FEE_EXCEEDED' | 'SIMULATION_FAILED' | 'TRANSACTION_FAILED' | 'ASSET_NOT_SUPPORTED' | 'SLIPPAGE_EXCEEDED' | 'HEALTH_FACTOR_TOO_LOW' | 'WITHDRAW_WOULD_LIQUIDATE' | 'NO_COLLATERAL' | 'PROTOCOL_PAUSED' | 'PROTOCOL_UNAVAILABLE' | 'RPC_ERROR' | 'RPC_UNREACHABLE' | 'SPONSOR_UNAVAILABLE' | 'AUTO_TOPUP_FAILED' | 'PRICE_EXCEEDS_LIMIT' | 'UNSUPPORTED_NETWORK' | 'PAYMENT_EXPIRED' | 'DUPLICATE_PAYMENT' | 'FACILITATOR_REJECTION' | 'FACILITATOR_TIMEOUT' | 'SENTINEL_API_ERROR' | 'SENTINEL_NOT_FOUND' | 'SENTINEL_TX_FAILED' | 'SENTINEL_TEE_ERROR' | 'UNKNOWN';
8
+ type T2000ErrorCode = 'INSUFFICIENT_BALANCE' | 'INSUFFICIENT_GAS' | 'INVALID_ADDRESS' | 'INVALID_AMOUNT' | 'WALLET_NOT_FOUND' | 'WALLET_LOCKED' | 'WALLET_EXISTS' | 'SPONSOR_FAILED' | 'SPONSOR_RATE_LIMITED' | 'GAS_STATION_UNAVAILABLE' | 'GAS_FEE_EXCEEDED' | 'SIMULATION_FAILED' | 'TRANSACTION_FAILED' | 'ASSET_NOT_SUPPORTED' | 'SWAP_FAILED' | 'SLIPPAGE_EXCEEDED' | 'HEALTH_FACTOR_TOO_LOW' | 'WITHDRAW_WOULD_LIQUIDATE' | 'NO_COLLATERAL' | 'PROTOCOL_PAUSED' | 'PROTOCOL_UNAVAILABLE' | 'RPC_ERROR' | 'RPC_UNREACHABLE' | 'SPONSOR_UNAVAILABLE' | 'AUTO_TOPUP_FAILED' | 'PRICE_EXCEEDS_LIMIT' | 'UNSUPPORTED_NETWORK' | 'PAYMENT_EXPIRED' | 'DUPLICATE_PAYMENT' | 'FACILITATOR_REJECTION' | 'FACILITATOR_TIMEOUT' | 'SENTINEL_API_ERROR' | 'SENTINEL_NOT_FOUND' | 'SENTINEL_TX_FAILED' | 'SENTINEL_TEE_ERROR' | 'UNKNOWN';
9
9
  interface T2000ErrorData {
10
10
  reason?: string;
11
11
  [key: string]: unknown;
@@ -102,48 +102,27 @@ declare class T2000 extends EventEmitter<T2000Events> {
102
102
  registerAdapter(adapter: LendingAdapter | SwapAdapter): Promise<void>;
103
103
  save(params: {
104
104
  amount: number | 'all';
105
- asset?: string;
106
105
  protocol?: string;
107
106
  }): Promise<SaveResult>;
108
107
  withdraw(params: {
109
108
  amount: number | 'all';
110
- asset?: string;
111
109
  protocol?: string;
112
110
  }): Promise<WithdrawResult>;
113
111
  private withdrawAllProtocols;
112
+ private _swapToUsdc;
114
113
  maxWithdraw(): Promise<MaxWithdrawResult>;
115
114
  borrow(params: {
116
115
  amount: number;
117
- asset?: string;
118
116
  protocol?: string;
119
117
  }): Promise<BorrowResult>;
120
118
  repay(params: {
121
119
  amount: number | 'all';
122
- asset?: string;
123
120
  protocol?: string;
124
121
  }): Promise<RepayResult>;
125
122
  maxBorrow(): Promise<MaxBorrowResult>;
126
123
  healthFactor(): Promise<HealthFactorResult>;
127
- swap(params: {
128
- from: string;
129
- to: string;
130
- amount: number;
131
- maxSlippage?: number;
132
- protocol?: string;
133
- }): Promise<SwapResult>;
134
- swapQuote(params: {
135
- from: string;
136
- to: string;
137
- amount: number;
138
- }): Promise<{
139
- expectedOutput: number;
140
- priceImpact: number;
141
- poolPrice: number;
142
- fee: {
143
- amount: number;
144
- rate: number;
145
- };
146
- }>;
124
+ private _swap;
125
+ private _swapQuote;
147
126
  positions(): Promise<PositionsResult>;
148
127
  rates(): Promise<RatesResult>;
149
128
  allRates(asset?: string): Promise<{
@@ -209,8 +188,6 @@ declare const SUPPORTED_ASSETS: {
209
188
  };
210
189
  };
211
190
  type SupportedAsset = keyof typeof SUPPORTED_ASSETS;
212
- type StableAsset = Exclude<SupportedAsset, 'SUI'>;
213
- declare const STABLE_ASSETS: readonly StableAsset[];
214
191
  declare const DEFAULT_NETWORK: "mainnet";
215
192
  declare const SENTINEL: {
216
193
  readonly PACKAGE: "0x88b83f36dafcd5f6dcdcf1d2cb5889b03f61264ab3cee9cae35db7aa940a21b7";
@@ -236,12 +213,6 @@ declare function rawToStable(raw: bigint, decimals: number): number;
236
213
  declare function getDecimals(asset: SupportedAsset): number;
237
214
  declare function formatUsd(amount: number): string;
238
215
  declare function formatSui(amount: number): string;
239
- /**
240
- * Case-insensitive lookup against SUPPORTED_ASSETS keys AND display names.
241
- * 'usde' → 'USDe', 'suiusde' → 'USDe', 'suiusdt' → 'USDT', 'usdsui' → 'USDsui'.
242
- * Returns the original input if not found so downstream validation can reject it.
243
- */
244
- declare function normalizeAsset(input: string): string;
245
216
 
246
217
  declare function generateKeypair(): Ed25519Keypair;
247
218
  declare function keypairFromPrivateKey(privateKey: string): Ed25519Keypair;
@@ -282,11 +253,6 @@ declare function simulateTransaction(client: SuiJsonRpcClient, tx: Transaction,
282
253
  declare function throwIfSimulationFailed(sim: SimulationResult): void;
283
254
 
284
255
  declare function getPoolPrice(client: SuiJsonRpcClient): Promise<number>;
285
- declare function getSwapQuote(client: SuiJsonRpcClient, fromAsset: string, toAsset: string, amount: number): Promise<{
286
- expectedOutput: number;
287
- priceImpact: number;
288
- poolPrice: number;
289
- }>;
290
256
 
291
257
  declare function getRates(client: SuiJsonRpcClient): Promise<RatesResult>;
292
258
 
@@ -329,4 +295,4 @@ interface GasStatusResponse {
329
295
  }
330
296
  declare function getGasStatus(address?: string): Promise<GasStatusResponse>;
331
297
 
332
- export { type AutoTopUpResult, BPS_DENOMINATOR, BalanceResponse, BorrowResult, CLOCK_ID, DEFAULT_NETWORK, DepositInfo, EarningsResult, type FeeOperation, FundStatusResult, type GasExecutionResult, GasMethod, type GasRequestType, type GasSponsorResponse, type GasStatusResponse, HealthFactorResult, LendingAdapter, LendingRates, MIST_PER_SUI, MaxBorrowResult, MaxWithdrawResult, PositionsResult, type ProtocolFeeInfo, RatesResult, RebalanceResult, RepayResult, SENTINEL, STABLE_ASSETS, SUI_DECIMALS, SUPPORTED_ASSETS, SaveResult, SendResult, SentinelAgent, SentinelAttackResult, type SimulationResult, type StableAsset, type SupportedAsset, SwapAdapter, SwapResult, T2000, T2000Error, type T2000ErrorCode, type T2000ErrorData, T2000Options, TransactionRecord, USDC_DECIMALS, WithdrawResult, addCollectFeeToTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, formatSui, formatUsd, generateKeypair, getAddress, getDecimals, getGasStatus, getPoolPrice, getRates, getSwapQuote, keypairFromPrivateKey, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, normalizeAsset, rawToStable, rawToUsdc, saveKey, shouldAutoTopUp, simulateTransaction, solveHashcash, stableToRaw, suiToMist, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, walletExists };
298
+ export { type AutoTopUpResult, BPS_DENOMINATOR, BalanceResponse, BorrowResult, CLOCK_ID, DEFAULT_NETWORK, DepositInfo, EarningsResult, type FeeOperation, FundStatusResult, type GasExecutionResult, GasMethod, type GasRequestType, type GasSponsorResponse, type GasStatusResponse, HealthFactorResult, LendingAdapter, LendingRates, MIST_PER_SUI, MaxBorrowResult, MaxWithdrawResult, PositionsResult, type ProtocolFeeInfo, RatesResult, RebalanceResult, RepayResult, SENTINEL, SUI_DECIMALS, SUPPORTED_ASSETS, SaveResult, SendResult, SentinelAgent, SentinelAttackResult, type SimulationResult, type SupportedAsset, SwapAdapter, T2000, T2000Error, type T2000ErrorCode, type T2000ErrorData, T2000Options, TransactionRecord, USDC_DECIMALS, WithdrawResult, addCollectFeeToTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, formatSui, formatUsd, generateKeypair, getAddress, getDecimals, getGasStatus, getPoolPrice, getRates, keypairFromPrivateKey, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, rawToStable, rawToUsdc, saveKey, shouldAutoTopUp, simulateTransaction, solveHashcash, stableToRaw, suiToMist, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, walletExists };
package/dist/index.d.ts CHANGED
@@ -1,11 +1,11 @@
1
1
  import { EventEmitter } from 'eventemitter3';
2
2
  import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
3
3
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
4
- import { T as T2000Options, S as SendResult, B as BalanceResponse, a as TransactionRecord, D as DepositInfo, L as LendingAdapter, b as SwapAdapter, c as SaveResult, W as WithdrawResult, M as MaxWithdrawResult, d as BorrowResult, R as RepayResult, e as MaxBorrowResult, H as HealthFactorResult, f as SwapResult, P as PositionsResult, g as RatesResult, h as LendingRates, i as RebalanceResult, E as EarningsResult, F as FundStatusResult, j as SentinelAgent, k as SentinelAttackResult, G as GasMethod } from './index-DNjooNFy.js';
5
- export { A as AdapterCapability, l as AdapterPositions, m as AdapterTxResult, n as AssetRates, C as CetusAdapter, o as GasReserve, p as HealthInfo, N as NaviAdapter, q as PositionEntry, r as ProtocolDescriptor, s as ProtocolRegistry, t as RebalanceStep, u as SentinelVerdict, v as SuilendAdapter, w as SwapQuote, x as allDescriptors, y as cetusDescriptor, z as getSentinelInfo, I as listSentinels, J as naviDescriptor, K as requestAttack, O as sentinelAttack, Q as sentinelDescriptor, U as settleAttack, V as submitPrompt, X as suilendDescriptor } from './index-DNjooNFy.js';
4
+ import { T as T2000Options, S as SendResult, B as BalanceResponse, a as TransactionRecord, D as DepositInfo, L as LendingAdapter, b as SwapAdapter, c as SaveResult, W as WithdrawResult, M as MaxWithdrawResult, d as BorrowResult, R as RepayResult, e as MaxBorrowResult, H as HealthFactorResult, P as PositionsResult, f as RatesResult, g as LendingRates, h as RebalanceResult, E as EarningsResult, F as FundStatusResult, i as SentinelAgent, j as SentinelAttackResult, G as GasMethod } from './index-C7W686z2.js';
5
+ export { A as AdapterCapability, k as AdapterPositions, l as AdapterTxResult, m as AssetRates, C as CetusAdapter, n as GasReserve, o as HealthInfo, N as NaviAdapter, p as PositionEntry, q as ProtocolDescriptor, r as ProtocolRegistry, s as RebalanceStep, t as SentinelVerdict, u as SuilendAdapter, v as SwapQuote, w as SwapResult, x as allDescriptors, y as cetusDescriptor, z as getSentinelInfo, I as listSentinels, J as naviDescriptor, K as requestAttack, O as sentinelAttack, Q as sentinelDescriptor, U as settleAttack, V as submitPrompt, X as suilendDescriptor } from './index-C7W686z2.js';
6
6
  import { Transaction, TransactionObjectArgument } from '@mysten/sui/transactions';
7
7
 
8
- type T2000ErrorCode = 'INSUFFICIENT_BALANCE' | 'INSUFFICIENT_GAS' | 'INVALID_ADDRESS' | 'INVALID_AMOUNT' | 'WALLET_NOT_FOUND' | 'WALLET_LOCKED' | 'WALLET_EXISTS' | 'SPONSOR_FAILED' | 'SPONSOR_RATE_LIMITED' | 'GAS_STATION_UNAVAILABLE' | 'GAS_FEE_EXCEEDED' | 'SIMULATION_FAILED' | 'TRANSACTION_FAILED' | 'ASSET_NOT_SUPPORTED' | 'SLIPPAGE_EXCEEDED' | 'HEALTH_FACTOR_TOO_LOW' | 'WITHDRAW_WOULD_LIQUIDATE' | 'NO_COLLATERAL' | 'PROTOCOL_PAUSED' | 'PROTOCOL_UNAVAILABLE' | 'RPC_ERROR' | 'RPC_UNREACHABLE' | 'SPONSOR_UNAVAILABLE' | 'AUTO_TOPUP_FAILED' | 'PRICE_EXCEEDS_LIMIT' | 'UNSUPPORTED_NETWORK' | 'PAYMENT_EXPIRED' | 'DUPLICATE_PAYMENT' | 'FACILITATOR_REJECTION' | 'FACILITATOR_TIMEOUT' | 'SENTINEL_API_ERROR' | 'SENTINEL_NOT_FOUND' | 'SENTINEL_TX_FAILED' | 'SENTINEL_TEE_ERROR' | 'UNKNOWN';
8
+ type T2000ErrorCode = 'INSUFFICIENT_BALANCE' | 'INSUFFICIENT_GAS' | 'INVALID_ADDRESS' | 'INVALID_AMOUNT' | 'WALLET_NOT_FOUND' | 'WALLET_LOCKED' | 'WALLET_EXISTS' | 'SPONSOR_FAILED' | 'SPONSOR_RATE_LIMITED' | 'GAS_STATION_UNAVAILABLE' | 'GAS_FEE_EXCEEDED' | 'SIMULATION_FAILED' | 'TRANSACTION_FAILED' | 'ASSET_NOT_SUPPORTED' | 'SWAP_FAILED' | 'SLIPPAGE_EXCEEDED' | 'HEALTH_FACTOR_TOO_LOW' | 'WITHDRAW_WOULD_LIQUIDATE' | 'NO_COLLATERAL' | 'PROTOCOL_PAUSED' | 'PROTOCOL_UNAVAILABLE' | 'RPC_ERROR' | 'RPC_UNREACHABLE' | 'SPONSOR_UNAVAILABLE' | 'AUTO_TOPUP_FAILED' | 'PRICE_EXCEEDS_LIMIT' | 'UNSUPPORTED_NETWORK' | 'PAYMENT_EXPIRED' | 'DUPLICATE_PAYMENT' | 'FACILITATOR_REJECTION' | 'FACILITATOR_TIMEOUT' | 'SENTINEL_API_ERROR' | 'SENTINEL_NOT_FOUND' | 'SENTINEL_TX_FAILED' | 'SENTINEL_TEE_ERROR' | 'UNKNOWN';
9
9
  interface T2000ErrorData {
10
10
  reason?: string;
11
11
  [key: string]: unknown;
@@ -102,48 +102,27 @@ declare class T2000 extends EventEmitter<T2000Events> {
102
102
  registerAdapter(adapter: LendingAdapter | SwapAdapter): Promise<void>;
103
103
  save(params: {
104
104
  amount: number | 'all';
105
- asset?: string;
106
105
  protocol?: string;
107
106
  }): Promise<SaveResult>;
108
107
  withdraw(params: {
109
108
  amount: number | 'all';
110
- asset?: string;
111
109
  protocol?: string;
112
110
  }): Promise<WithdrawResult>;
113
111
  private withdrawAllProtocols;
112
+ private _swapToUsdc;
114
113
  maxWithdraw(): Promise<MaxWithdrawResult>;
115
114
  borrow(params: {
116
115
  amount: number;
117
- asset?: string;
118
116
  protocol?: string;
119
117
  }): Promise<BorrowResult>;
120
118
  repay(params: {
121
119
  amount: number | 'all';
122
- asset?: string;
123
120
  protocol?: string;
124
121
  }): Promise<RepayResult>;
125
122
  maxBorrow(): Promise<MaxBorrowResult>;
126
123
  healthFactor(): Promise<HealthFactorResult>;
127
- swap(params: {
128
- from: string;
129
- to: string;
130
- amount: number;
131
- maxSlippage?: number;
132
- protocol?: string;
133
- }): Promise<SwapResult>;
134
- swapQuote(params: {
135
- from: string;
136
- to: string;
137
- amount: number;
138
- }): Promise<{
139
- expectedOutput: number;
140
- priceImpact: number;
141
- poolPrice: number;
142
- fee: {
143
- amount: number;
144
- rate: number;
145
- };
146
- }>;
124
+ private _swap;
125
+ private _swapQuote;
147
126
  positions(): Promise<PositionsResult>;
148
127
  rates(): Promise<RatesResult>;
149
128
  allRates(asset?: string): Promise<{
@@ -209,8 +188,6 @@ declare const SUPPORTED_ASSETS: {
209
188
  };
210
189
  };
211
190
  type SupportedAsset = keyof typeof SUPPORTED_ASSETS;
212
- type StableAsset = Exclude<SupportedAsset, 'SUI'>;
213
- declare const STABLE_ASSETS: readonly StableAsset[];
214
191
  declare const DEFAULT_NETWORK: "mainnet";
215
192
  declare const SENTINEL: {
216
193
  readonly PACKAGE: "0x88b83f36dafcd5f6dcdcf1d2cb5889b03f61264ab3cee9cae35db7aa940a21b7";
@@ -236,12 +213,6 @@ declare function rawToStable(raw: bigint, decimals: number): number;
236
213
  declare function getDecimals(asset: SupportedAsset): number;
237
214
  declare function formatUsd(amount: number): string;
238
215
  declare function formatSui(amount: number): string;
239
- /**
240
- * Case-insensitive lookup against SUPPORTED_ASSETS keys AND display names.
241
- * 'usde' → 'USDe', 'suiusde' → 'USDe', 'suiusdt' → 'USDT', 'usdsui' → 'USDsui'.
242
- * Returns the original input if not found so downstream validation can reject it.
243
- */
244
- declare function normalizeAsset(input: string): string;
245
216
 
246
217
  declare function generateKeypair(): Ed25519Keypair;
247
218
  declare function keypairFromPrivateKey(privateKey: string): Ed25519Keypair;
@@ -282,11 +253,6 @@ declare function simulateTransaction(client: SuiJsonRpcClient, tx: Transaction,
282
253
  declare function throwIfSimulationFailed(sim: SimulationResult): void;
283
254
 
284
255
  declare function getPoolPrice(client: SuiJsonRpcClient): Promise<number>;
285
- declare function getSwapQuote(client: SuiJsonRpcClient, fromAsset: string, toAsset: string, amount: number): Promise<{
286
- expectedOutput: number;
287
- priceImpact: number;
288
- poolPrice: number;
289
- }>;
290
256
 
291
257
  declare function getRates(client: SuiJsonRpcClient): Promise<RatesResult>;
292
258
 
@@ -329,4 +295,4 @@ interface GasStatusResponse {
329
295
  }
330
296
  declare function getGasStatus(address?: string): Promise<GasStatusResponse>;
331
297
 
332
- export { type AutoTopUpResult, BPS_DENOMINATOR, BalanceResponse, BorrowResult, CLOCK_ID, DEFAULT_NETWORK, DepositInfo, EarningsResult, type FeeOperation, FundStatusResult, type GasExecutionResult, GasMethod, type GasRequestType, type GasSponsorResponse, type GasStatusResponse, HealthFactorResult, LendingAdapter, LendingRates, MIST_PER_SUI, MaxBorrowResult, MaxWithdrawResult, PositionsResult, type ProtocolFeeInfo, RatesResult, RebalanceResult, RepayResult, SENTINEL, STABLE_ASSETS, SUI_DECIMALS, SUPPORTED_ASSETS, SaveResult, SendResult, SentinelAgent, SentinelAttackResult, type SimulationResult, type StableAsset, type SupportedAsset, SwapAdapter, SwapResult, T2000, T2000Error, type T2000ErrorCode, type T2000ErrorData, T2000Options, TransactionRecord, USDC_DECIMALS, WithdrawResult, addCollectFeeToTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, formatSui, formatUsd, generateKeypair, getAddress, getDecimals, getGasStatus, getPoolPrice, getRates, getSwapQuote, keypairFromPrivateKey, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, normalizeAsset, rawToStable, rawToUsdc, saveKey, shouldAutoTopUp, simulateTransaction, solveHashcash, stableToRaw, suiToMist, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, walletExists };
298
+ export { type AutoTopUpResult, BPS_DENOMINATOR, BalanceResponse, BorrowResult, CLOCK_ID, DEFAULT_NETWORK, DepositInfo, EarningsResult, type FeeOperation, FundStatusResult, type GasExecutionResult, GasMethod, type GasRequestType, type GasSponsorResponse, type GasStatusResponse, HealthFactorResult, LendingAdapter, LendingRates, MIST_PER_SUI, MaxBorrowResult, MaxWithdrawResult, PositionsResult, type ProtocolFeeInfo, RatesResult, RebalanceResult, RepayResult, SENTINEL, SUI_DECIMALS, SUPPORTED_ASSETS, SaveResult, SendResult, SentinelAgent, SentinelAttackResult, type SimulationResult, type SupportedAsset, SwapAdapter, T2000, T2000Error, type T2000ErrorCode, type T2000ErrorData, T2000Options, TransactionRecord, USDC_DECIMALS, WithdrawResult, addCollectFeeToTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, formatSui, formatUsd, generateKeypair, getAddress, getDecimals, getGasStatus, getPoolPrice, getRates, keypairFromPrivateKey, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, rawToStable, rawToUsdc, saveKey, shouldAutoTopUp, simulateTransaction, solveHashcash, stableToRaw, suiToMist, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, walletExists };
package/dist/index.js CHANGED
@@ -1315,24 +1315,6 @@ var ProtocolRegistry = class {
1315
1315
  listSwap() {
1316
1316
  return [...this.swap.values()];
1317
1317
  }
1318
- isSupportedAsset(asset, capability) {
1319
- for (const adapter of this.lending.values()) {
1320
- if (!adapter.supportedAssets.includes(asset)) continue;
1321
- if (capability && !adapter.capabilities.includes(capability)) continue;
1322
- return true;
1323
- }
1324
- return false;
1325
- }
1326
- getSupportedAssets(capability) {
1327
- const assets = /* @__PURE__ */ new Set();
1328
- for (const adapter of this.lending.values()) {
1329
- if (capability && !adapter.capabilities.includes(capability)) continue;
1330
- for (const a of adapter.supportedAssets) {
1331
- assets.add(a);
1332
- }
1333
- }
1334
- return [...assets];
1335
- }
1336
1318
  };
1337
1319
 
1338
1320
  // src/adapters/navi.ts
@@ -2431,43 +2413,34 @@ var T2000 = class _T2000 extends EventEmitter {
2431
2413
  }
2432
2414
  // -- Savings --
2433
2415
  async save(params) {
2434
- const asset = normalizeAsset(params.asset ?? "USDC");
2435
- if (!this.registry.isSupportedAsset(asset, "save")) {
2436
- const supported = this.registry.getSupportedAssets("save").join(", ");
2437
- throw new T2000Error("ASSET_NOT_SUPPORTED", `${asset} is not supported for save. Supported: ${supported}`);
2438
- }
2416
+ const asset = "USDC";
2439
2417
  let amount;
2440
2418
  if (params.amount === "all") {
2441
2419
  const bal = await queryBalance(this.client, this._address);
2442
- const assetBalance = bal.stables[asset] ?? 0;
2443
- const reserve = asset === "USDC" ? 1 : 0;
2444
- amount = assetBalance - reserve;
2420
+ const assetBalance = bal.stables.USDC ?? 0;
2421
+ amount = assetBalance - 1;
2445
2422
  if (amount <= 0) {
2446
- throw new T2000Error("INSUFFICIENT_BALANCE", `Balance too low to save${asset === "USDC" ? " after $1 gas reserve" : ""}`, {
2447
- reason: asset === "USDC" ? "gas_reserve_required" : "zero_balance",
2423
+ throw new T2000Error("INSUFFICIENT_BALANCE", "Balance too low to save after $1 gas reserve", {
2424
+ reason: "gas_reserve_required",
2448
2425
  available: assetBalance
2449
2426
  });
2450
2427
  }
2451
2428
  } else {
2452
2429
  amount = params.amount;
2453
2430
  const bal = await queryBalance(this.client, this._address);
2454
- const assetBalance = bal.stables[asset] ?? 0;
2455
- if (amount > assetBalance) {
2456
- throw new T2000Error("INSUFFICIENT_BALANCE", `Insufficient ${asset}. Available: $${assetBalance.toFixed(2)}, requested: $${amount.toFixed(2)}`);
2431
+ if (amount > (bal.stables.USDC ?? 0)) {
2432
+ throw new T2000Error("INSUFFICIENT_BALANCE", `Insufficient USDC. Available: $${(bal.stables.USDC ?? 0).toFixed(2)}, requested: $${amount.toFixed(2)}`);
2457
2433
  }
2458
2434
  }
2459
- const shouldCollectFee = asset === "USDC";
2460
- const fee = shouldCollectFee ? calculateFee("save", amount) : { amount: 0, rate: 0};
2435
+ const fee = calculateFee("save", amount);
2461
2436
  const saveAmount = amount;
2462
2437
  const adapter = await this.resolveLending(params.protocol, asset, "save");
2463
2438
  const gasResult = await executeWithGas(this.client, this.keypair, async () => {
2464
- const { tx } = await adapter.buildSaveTx(this._address, saveAmount, asset, { collectFee: shouldCollectFee });
2439
+ const { tx } = await adapter.buildSaveTx(this._address, saveAmount, asset, { collectFee: true });
2465
2440
  return tx;
2466
2441
  });
2467
2442
  const rates = await adapter.getRates(asset);
2468
- if (shouldCollectFee) {
2469
- reportFee(this._address, "save", fee.amount, fee.rate, gasResult.digest);
2470
- }
2443
+ reportFee(this._address, "save", fee.amount, fee.rate, gasResult.digest);
2471
2444
  this.emitBalanceChange(asset, saveAmount, "save", gasResult.digest);
2472
2445
  let savingsBalance = saveAmount;
2473
2446
  try {
@@ -2479,7 +2452,6 @@ var T2000 = class _T2000 extends EventEmitter {
2479
2452
  success: true,
2480
2453
  tx: gasResult.digest,
2481
2454
  amount: saveAmount,
2482
- asset,
2483
2455
  apy: rates.saveApy,
2484
2456
  fee: fee.amount,
2485
2457
  gasCost: gasResult.gasCostSui,
@@ -2488,14 +2460,27 @@ var T2000 = class _T2000 extends EventEmitter {
2488
2460
  };
2489
2461
  }
2490
2462
  async withdraw(params) {
2491
- const asset = normalizeAsset(params.asset ?? "USDC");
2492
2463
  if (params.amount === "all" && !params.protocol) {
2493
- return this.withdrawAllProtocols(asset);
2464
+ return this.withdrawAllProtocols();
2494
2465
  }
2495
- const adapter = await this.resolveLending(params.protocol, asset, "withdraw");
2466
+ const allPositions = await this.registry.allPositions(this._address);
2467
+ const supplies = [];
2468
+ for (const pos of allPositions) {
2469
+ if (params.protocol && pos.protocolId !== params.protocol) continue;
2470
+ for (const s of pos.positions.supplies) {
2471
+ if (s.amount > 1e-3) supplies.push({ protocolId: pos.protocolId, asset: s.asset, amount: s.amount, apy: s.apy });
2472
+ }
2473
+ }
2474
+ if (supplies.length === 0) {
2475
+ throw new T2000Error("NO_COLLATERAL", "No savings to withdraw");
2476
+ }
2477
+ supplies.sort((a, b) => a.apy - b.apy);
2478
+ const target = supplies[0];
2479
+ const adapter = this.registry.getLending(target.protocolId);
2480
+ if (!adapter) throw new T2000Error("PROTOCOL_UNAVAILABLE", `Protocol ${target.protocolId} not found`);
2496
2481
  let amount;
2497
2482
  if (params.amount === "all") {
2498
- const maxResult = await adapter.maxWithdraw(this._address, asset);
2483
+ const maxResult = await adapter.maxWithdraw(this._address, target.asset);
2499
2484
  amount = maxResult.maxAmount;
2500
2485
  if (amount <= 0) {
2501
2486
  throw new T2000Error("NO_COLLATERAL", "No savings to withdraw");
@@ -2504,7 +2489,7 @@ var T2000 = class _T2000 extends EventEmitter {
2504
2489
  amount = params.amount;
2505
2490
  const hf = await adapter.getHealth(this._address);
2506
2491
  if (hf.borrowed > 0) {
2507
- const maxResult = await adapter.maxWithdraw(this._address, asset);
2492
+ const maxResult = await adapter.maxWithdraw(this._address, target.asset);
2508
2493
  if (amount > maxResult.maxAmount) {
2509
2494
  throw new T2000Error(
2510
2495
  "WITHDRAW_WOULD_LIQUIDATE",
@@ -2521,20 +2506,37 @@ var T2000 = class _T2000 extends EventEmitter {
2521
2506
  const withdrawAmount = amount;
2522
2507
  let effectiveAmount = withdrawAmount;
2523
2508
  const gasResult = await executeWithGas(this.client, this.keypair, async () => {
2524
- const built = await adapter.buildWithdrawTx(this._address, withdrawAmount, asset);
2509
+ const built = await adapter.buildWithdrawTx(this._address, withdrawAmount, target.asset);
2525
2510
  effectiveAmount = built.effectiveAmount;
2526
2511
  return built.tx;
2527
2512
  });
2528
- this.emitBalanceChange(asset, effectiveAmount, "withdraw", gasResult.digest);
2513
+ let totalGasCost = gasResult.gasCostSui;
2514
+ let finalAmount = effectiveAmount;
2515
+ let lastDigest = gasResult.digest;
2516
+ if (target.asset !== "USDC") {
2517
+ try {
2518
+ const swapResult = await this._swapToUsdc(target.asset, effectiveAmount);
2519
+ finalAmount = swapResult.usdcReceived;
2520
+ lastDigest = swapResult.digest;
2521
+ totalGasCost += swapResult.gasCost;
2522
+ } catch (err) {
2523
+ throw new T2000Error(
2524
+ "SWAP_FAILED",
2525
+ `Withdrew $${effectiveAmount.toFixed(2)} ${target.asset} but swap to USDC failed. Your ${target.asset} is safe in your wallet.`,
2526
+ { withdrawDigest: gasResult.digest, originalError: err instanceof Error ? err.message : String(err) }
2527
+ );
2528
+ }
2529
+ }
2530
+ this.emitBalanceChange("USDC", finalAmount, "withdraw", lastDigest);
2529
2531
  return {
2530
2532
  success: true,
2531
- tx: gasResult.digest,
2532
- amount: effectiveAmount,
2533
- gasCost: gasResult.gasCostSui,
2533
+ tx: lastDigest,
2534
+ amount: finalAmount,
2535
+ gasCost: totalGasCost,
2534
2536
  gasMethod: gasResult.gasMethod
2535
2537
  };
2536
2538
  }
2537
- async withdrawAllProtocols(_asset) {
2539
+ async withdrawAllProtocols() {
2538
2540
  const allPositions = await this.registry.allPositions(this._address);
2539
2541
  const withdrawable = [];
2540
2542
  for (const pos of allPositions) {
@@ -2547,7 +2549,7 @@ var T2000 = class _T2000 extends EventEmitter {
2547
2549
  if (withdrawable.length === 0) {
2548
2550
  throw new T2000Error("NO_COLLATERAL", "No savings to withdraw across any protocol");
2549
2551
  }
2550
- let totalWithdrawn = 0;
2552
+ let totalUsdcReceived = 0;
2551
2553
  let lastDigest = "";
2552
2554
  let totalGasCost = 0;
2553
2555
  let lastGasMethod = "self-funded";
@@ -2562,30 +2564,55 @@ var T2000 = class _T2000 extends EventEmitter {
2562
2564
  effectiveAmount = built.effectiveAmount;
2563
2565
  return built.tx;
2564
2566
  });
2565
- totalWithdrawn += effectiveAmount;
2566
2567
  lastDigest = gasResult.digest;
2567
2568
  totalGasCost += gasResult.gasCostSui;
2568
2569
  lastGasMethod = gasResult.gasMethod;
2569
2570
  this.emitBalanceChange(entry.asset, effectiveAmount, "withdraw", gasResult.digest);
2571
+ if (entry.asset !== "USDC") {
2572
+ try {
2573
+ const swapResult = await this._swapToUsdc(entry.asset, effectiveAmount);
2574
+ totalUsdcReceived += swapResult.usdcReceived;
2575
+ lastDigest = swapResult.digest;
2576
+ totalGasCost += swapResult.gasCost;
2577
+ } catch {
2578
+ totalUsdcReceived += effectiveAmount;
2579
+ }
2580
+ } else {
2581
+ totalUsdcReceived += effectiveAmount;
2582
+ }
2570
2583
  }
2571
- if (totalWithdrawn <= 0) {
2584
+ if (totalUsdcReceived <= 0) {
2572
2585
  throw new T2000Error("NO_COLLATERAL", "No savings to withdraw across any protocol");
2573
2586
  }
2574
2587
  return {
2575
2588
  success: true,
2576
2589
  tx: lastDigest,
2577
- amount: totalWithdrawn,
2590
+ amount: totalUsdcReceived,
2578
2591
  gasCost: totalGasCost,
2579
2592
  gasMethod: lastGasMethod
2580
2593
  };
2581
2594
  }
2595
+ async _swapToUsdc(asset, amount) {
2596
+ const swapAdapter = this.registry.listSwap()[0];
2597
+ if (!swapAdapter) throw new T2000Error("PROTOCOL_UNAVAILABLE", "No swap adapter available");
2598
+ let estimatedOut = 0;
2599
+ let toDecimals = 6;
2600
+ const gasResult = await executeWithGas(this.client, this.keypair, async () => {
2601
+ const built = await swapAdapter.buildSwapTx(this._address, asset, "USDC", amount);
2602
+ estimatedOut = built.estimatedOut;
2603
+ toDecimals = built.toDecimals;
2604
+ return built.tx;
2605
+ });
2606
+ const usdcReceived = estimatedOut / 10 ** toDecimals;
2607
+ return { usdcReceived, digest: gasResult.digest, gasCost: gasResult.gasCostSui };
2608
+ }
2582
2609
  async maxWithdraw() {
2583
2610
  const adapter = await this.resolveLending(void 0, "USDC", "withdraw");
2584
2611
  return adapter.maxWithdraw(this._address, "USDC");
2585
2612
  }
2586
2613
  // -- Borrowing --
2587
2614
  async borrow(params) {
2588
- const asset = normalizeAsset(params.asset ?? "USDC");
2615
+ const asset = "USDC";
2589
2616
  const adapter = await this.resolveLending(params.protocol, asset, "borrow");
2590
2617
  const maxResult = await adapter.maxBorrow(this._address, asset);
2591
2618
  if (maxResult.maxAmount <= 0) {
@@ -2597,17 +2624,14 @@ var T2000 = class _T2000 extends EventEmitter {
2597
2624
  currentHF: maxResult.currentHF
2598
2625
  });
2599
2626
  }
2600
- const shouldCollectFee = asset === "USDC";
2601
- const fee = shouldCollectFee ? calculateFee("borrow", params.amount) : { amount: 0, rate: 0};
2627
+ const fee = calculateFee("borrow", params.amount);
2602
2628
  const borrowAmount = params.amount;
2603
2629
  const gasResult = await executeWithGas(this.client, this.keypair, async () => {
2604
- const { tx } = await adapter.buildBorrowTx(this._address, borrowAmount, asset, { collectFee: shouldCollectFee });
2630
+ const { tx } = await adapter.buildBorrowTx(this._address, borrowAmount, asset, { collectFee: true });
2605
2631
  return tx;
2606
2632
  });
2607
2633
  const hf = await adapter.getHealth(this._address);
2608
- if (shouldCollectFee) {
2609
- reportFee(this._address, "borrow", fee.amount, fee.rate, gasResult.digest);
2610
- }
2634
+ reportFee(this._address, "borrow", fee.amount, fee.rate, gasResult.digest);
2611
2635
  this.emitBalanceChange(asset, borrowAmount, "borrow", gasResult.digest);
2612
2636
  return {
2613
2637
  success: true,
@@ -2620,7 +2644,7 @@ var T2000 = class _T2000 extends EventEmitter {
2620
2644
  };
2621
2645
  }
2622
2646
  async repay(params) {
2623
- const asset = normalizeAsset(params.asset ?? "USDC");
2647
+ const asset = "USDC";
2624
2648
  const adapter = await this.resolveLending(params.protocol, asset, "repay");
2625
2649
  let amount;
2626
2650
  if (params.amount === "all") {
@@ -2662,25 +2686,18 @@ var T2000 = class _T2000 extends EventEmitter {
2662
2686
  }
2663
2687
  return hf;
2664
2688
  }
2665
- // -- Swap --
2666
- async swap(params) {
2667
- const fromAsset = normalizeAsset(params.from);
2668
- const toAsset = normalizeAsset(params.to);
2689
+ // -- Swap (internal — used by rebalance and withdraw auto-swap) --
2690
+ async _swap(params) {
2691
+ const fromAsset = params.from;
2692
+ const toAsset = params.to;
2669
2693
  if (!(fromAsset in SUPPORTED_ASSETS) || !(toAsset in SUPPORTED_ASSETS)) {
2670
2694
  throw new T2000Error("ASSET_NOT_SUPPORTED", `Swap pair ${fromAsset}/${toAsset} is not supported`);
2671
2695
  }
2672
2696
  if (fromAsset === toAsset) {
2673
2697
  throw new T2000Error("INVALID_AMOUNT", "Cannot swap same asset");
2674
2698
  }
2675
- let adapter;
2676
- if (params.protocol) {
2677
- const found = this.registry.getSwap(params.protocol);
2678
- if (!found) throw new T2000Error("ASSET_NOT_SUPPORTED", `Swap adapter '${params.protocol}' not found`);
2679
- adapter = found;
2680
- } else {
2681
- const best = await this.registry.bestSwapQuote(fromAsset, toAsset, params.amount);
2682
- adapter = best.adapter;
2683
- }
2699
+ const best = await this.registry.bestSwapQuote(fromAsset, toAsset, params.amount);
2700
+ const adapter = best.adapter;
2684
2701
  const fee = calculateFee("swap", params.amount);
2685
2702
  const swapAmount = params.amount;
2686
2703
  const slippageBps = params.maxSlippage ? params.maxSlippage * 100 : void 0;
@@ -2723,9 +2740,9 @@ var T2000 = class _T2000 extends EventEmitter {
2723
2740
  gasMethod: gasResult.gasMethod
2724
2741
  };
2725
2742
  }
2726
- async swapQuote(params) {
2727
- const fromAsset = normalizeAsset(params.from);
2728
- const toAsset = normalizeAsset(params.to);
2743
+ async _swapQuote(params) {
2744
+ const fromAsset = params.from;
2745
+ const toAsset = params.to;
2729
2746
  const best = await this.registry.bestSwapQuote(fromAsset, toAsset, params.amount);
2730
2747
  const fee = calculateFee("swap", params.amount);
2731
2748
  return { ...best.quote, fee: { amount: fee.amount, rate: fee.rate } };
@@ -3162,6 +3179,6 @@ var allDescriptors = [
3162
3179
  descriptor
3163
3180
  ];
3164
3181
 
3165
- export { BPS_DENOMINATOR, CLOCK_ID, CetusAdapter, DEFAULT_NETWORK, MIST_PER_SUI, NaviAdapter, ProtocolRegistry, SENTINEL, STABLE_ASSETS, SUI_DECIMALS, SUPPORTED_ASSETS, SuilendAdapter, T2000, T2000Error, USDC_DECIMALS, addCollectFeeToTx, allDescriptors, calculateFee, descriptor3 as cetusDescriptor, executeAutoTopUp, executeWithGas, exportPrivateKey, formatSui, formatUsd, generateKeypair, getAddress, getDecimals, getGasStatus, getPoolPrice, getRates, getSentinelInfo, getSwapQuote, keypairFromPrivateKey, listSentinels, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, descriptor2 as naviDescriptor, normalizeAsset, rawToStable, rawToUsdc, requestAttack, saveKey, attack as sentinelAttack, descriptor as sentinelDescriptor, settleAttack, shouldAutoTopUp, simulateTransaction, solveHashcash, stableToRaw, submitPrompt, suiToMist, descriptor4 as suilendDescriptor, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, walletExists };
3182
+ export { BPS_DENOMINATOR, CLOCK_ID, CetusAdapter, DEFAULT_NETWORK, MIST_PER_SUI, NaviAdapter, ProtocolRegistry, SENTINEL, SUI_DECIMALS, SUPPORTED_ASSETS, SuilendAdapter, T2000, T2000Error, USDC_DECIMALS, addCollectFeeToTx, allDescriptors, calculateFee, descriptor3 as cetusDescriptor, executeAutoTopUp, executeWithGas, exportPrivateKey, formatSui, formatUsd, generateKeypair, getAddress, getDecimals, getGasStatus, getPoolPrice, getRates, getSentinelInfo, keypairFromPrivateKey, listSentinels, loadKey, mapMoveAbortCode, mapWalletError, mistToSui, descriptor2 as naviDescriptor, rawToStable, rawToUsdc, requestAttack, saveKey, attack as sentinelAttack, descriptor as sentinelDescriptor, settleAttack, shouldAutoTopUp, simulateTransaction, solveHashcash, stableToRaw, submitPrompt, suiToMist, descriptor4 as suilendDescriptor, throwIfSimulationFailed, truncateAddress, usdcToRaw, validateAddress, walletExists };
3166
3183
  //# sourceMappingURL=index.js.map
3167
3184
  //# sourceMappingURL=index.js.map