@t2000/sdk 0.18.41 → 0.19.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,5 +1,5 @@
1
- import { I as InvestmentTrade, S as StrategyDefinition, A as AutoInvestSchedule, a as AutoInvestStatus, T as T2000Options, b as SendResult, B as BalanceResponse, c as TransactionRecord, D as DepositInfo, L as LendingAdapter, d as SwapAdapter, e as SaveResult, W as WithdrawResult, M as MaxWithdrawResult, f as BorrowResult, R as RepayResult, g as MaxBorrowResult, H as HealthFactorResult, h as SwapResult, i as InvestResult, j as InvestEarnResult, k as InvestRebalanceResult, P as PendingReward, C as ClaimRewardsResult, l as StrategyBuyResult, m as StrategySellResult, n as StrategyRebalanceResult, o as StrategyStatusResult, p as AutoInvestRunResult, q as PortfolioResult, r as InvestmentPosition, s as PositionsResult, t as RatesResult, u as LendingRates, v as RebalanceResult, E as EarningsResult, F as FundStatusResult, w as SentinelAgent, x as SentinelAttackResult, G as GasMethod } from './index-HADTiik7.cjs';
2
- export { y as AdapterCapability, z as AdapterPositions, J as AdapterTxResult, K as AssetRates, N as CetusAdapter, O as GasReserve, Q as HealthInfo, U as InvestRebalanceMove, V as NaviAdapter, X as PerpsAdapter, Y as PerpsPosition, Z as PositionEntry, _ as PositionSide, $ as ProtocolDescriptor, a0 as ProtocolRegistry, a1 as RebalanceStep, a2 as SentinelVerdict, a3 as SuilendAdapter, a4 as SwapQuote, a5 as TradePositionsResult, a6 as TradeResult, a7 as allDescriptors, a8 as cetusDescriptor, a9 as getSentinelInfo, aa as listSentinels, ab as naviDescriptor, ac as requestAttack, ad as sentinelAttack, ae as sentinelDescriptor, af as settleAttack, ag as submitPrompt, ah as suilendDescriptor } from './index-HADTiik7.cjs';
1
+ import { I as InvestmentTrade, S as StrategyDefinition, A as AutoInvestSchedule, a as AutoInvestStatus, T as T2000Options, P as PayOptions, b as PayResult, c as SendResult, B as BalanceResponse, d as TransactionRecord, D as DepositInfo, L as LendingAdapter, e as SwapAdapter, f as SaveResult, W as WithdrawResult, M as MaxWithdrawResult, g as BorrowResult, R as RepayResult, h as MaxBorrowResult, H as HealthFactorResult, i as SwapResult, j as InvestResult, k as InvestEarnResult, l as InvestRebalanceResult, m as PendingReward, C as ClaimRewardsResult, n as StrategyBuyResult, o as StrategySellResult, p as StrategyRebalanceResult, q as StrategyStatusResult, r as AutoInvestRunResult, s as PortfolioResult, t as InvestmentPosition, u as PositionsResult, v as RatesResult, w as LendingRates, x as RebalanceResult, E as EarningsResult, F as FundStatusResult, y as SentinelAgent, z as SentinelAttackResult, G as GasMethod } from './index-D-6pQwzx.cjs';
2
+ export { J as AdapterCapability, K as AdapterPositions, N as AdapterTxResult, O as AssetRates, Q as CetusAdapter, U as GasReserve, V as HealthInfo, X as InvestRebalanceMove, Y as NaviAdapter, Z as PerpsAdapter, _ as PerpsPosition, $ as PositionEntry, a0 as PositionSide, a1 as ProtocolDescriptor, a2 as ProtocolRegistry, a3 as RebalanceStep, a4 as SentinelVerdict, a5 as SuilendAdapter, a6 as SwapQuote, a7 as TradePositionsResult, a8 as TradeResult, a9 as allDescriptors, aa as cetusDescriptor, ab as getSentinelInfo, ac as listSentinels, ad as naviDescriptor, ae as requestAttack, af as sentinelAttack, ag as sentinelDescriptor, ah as settleAttack, ai as submitPrompt, aj as suilendDescriptor } from './index-D-6pQwzx.cjs';
3
3
  import { EventEmitter } from 'eventemitter3';
4
4
  import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
5
5
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
@@ -272,6 +272,7 @@ declare class PortfolioManager {
272
272
  getAllStrategyKeys(): string[];
273
273
  clearStrategy(strategyKey: string): void;
274
274
  hasStrategyPositions(strategyKey: string): boolean;
275
+ closeStrategyPosition(strategyKey: string, asset: string): void;
275
276
  }
276
277
 
277
278
  declare class StrategyManager {
@@ -380,10 +381,11 @@ declare class T2000 extends EventEmitter<T2000Events> {
380
381
  address: string;
381
382
  sponsored: boolean;
382
383
  }>;
383
- /** SuiJsonRpcClient used by this agent — exposed for x402 and other integrations. */
384
+ /** SuiJsonRpcClient used by this agent — exposed for integrations. */
384
385
  get suiClient(): SuiJsonRpcClient;
385
- /** Ed25519Keypair used by this agent — exposed for x402 and other integrations. */
386
+ /** Ed25519Keypair used by this agent — exposed for integrations. */
386
387
  get signer(): Ed25519Keypair;
388
+ pay(options: PayOptions): Promise<PayResult>;
387
389
  address(): string;
388
390
  send(params: {
389
391
  to: string;
@@ -661,4 +663,4 @@ interface GasStatusResponse {
661
663
  }
662
664
  declare function getGasStatus(address?: string): Promise<GasStatusResponse>;
663
665
 
664
- export { AutoInvestManager, AutoInvestRunResult, AutoInvestSchedule, AutoInvestStatus, type AutoTopUpResult, BPS_DENOMINATOR, BalanceResponse, BorrowResult, CLOCK_ID, ClaimRewardsResult, type Contact, ContactManager, type ContactMap, DEFAULT_MAX_LEVERAGE, DEFAULT_MAX_POSITION_SIZE, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, DEFAULT_STRATEGIES, DepositInfo, EarningsResult, type FeeOperation, FundStatusResult, GAS_RESERVE_MIN, type GasExecutionResult, GasMethod, type GasRequestType, type GasSponsorResponse, type GasStatusResponse, HealthFactorResult, INVESTMENT_ASSETS, InvestEarnResult, InvestRebalanceResult, InvestResult, type InvestmentAsset, InvestmentPosition, InvestmentTrade, LendingAdapter, LendingRates, MIST_PER_SUI, MaxBorrowResult, MaxWithdrawResult, OUTBOUND_OPS, PERPS_MARKETS, PendingReward, type PerpsMarket, PortfolioManager, PortfolioResult, PositionsResult, type ProtocolFeeInfo, RatesResult, RebalanceResult, RepayResult, SENTINEL, STABLE_ASSETS, SUI_DECIMALS, SUPPORTED_ASSETS, type SafeguardConfig, SafeguardEnforcer, SafeguardError, type SafeguardErrorDetails, type SafeguardRule, SaveResult, SendResult, SentinelAgent, SentinelAttackResult, type SimulationResult, type StableAsset, StrategyBuyResult, StrategyDefinition, StrategyManager, StrategyRebalanceResult, StrategySellResult, StrategyStatusResult, type SupportedAsset, SwapAdapter, SwapResult, T2000, T2000Error, type T2000ErrorCode, type T2000ErrorData, T2000Options, TransactionRecord, type TxMetadata, USDC_DECIMALS, WithdrawResult, addCollectFeeToTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, formatAssetAmount, 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 };
666
+ export { AutoInvestManager, AutoInvestRunResult, AutoInvestSchedule, AutoInvestStatus, type AutoTopUpResult, BPS_DENOMINATOR, BalanceResponse, BorrowResult, CLOCK_ID, ClaimRewardsResult, type Contact, ContactManager, type ContactMap, DEFAULT_MAX_LEVERAGE, DEFAULT_MAX_POSITION_SIZE, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, DEFAULT_STRATEGIES, DepositInfo, EarningsResult, type FeeOperation, FundStatusResult, GAS_RESERVE_MIN, type GasExecutionResult, GasMethod, type GasRequestType, type GasSponsorResponse, type GasStatusResponse, HealthFactorResult, INVESTMENT_ASSETS, InvestEarnResult, InvestRebalanceResult, InvestResult, type InvestmentAsset, InvestmentPosition, InvestmentTrade, LendingAdapter, LendingRates, MIST_PER_SUI, MaxBorrowResult, MaxWithdrawResult, OUTBOUND_OPS, PERPS_MARKETS, PayOptions, PayResult, PendingReward, type PerpsMarket, PortfolioManager, PortfolioResult, PositionsResult, type ProtocolFeeInfo, RatesResult, RebalanceResult, RepayResult, SENTINEL, STABLE_ASSETS, SUI_DECIMALS, SUPPORTED_ASSETS, type SafeguardConfig, SafeguardEnforcer, SafeguardError, type SafeguardErrorDetails, type SafeguardRule, SaveResult, SendResult, SentinelAgent, SentinelAttackResult, type SimulationResult, type StableAsset, StrategyBuyResult, StrategyDefinition, StrategyManager, StrategyRebalanceResult, StrategySellResult, StrategyStatusResult, type SupportedAsset, SwapAdapter, SwapResult, T2000, T2000Error, type T2000ErrorCode, type T2000ErrorData, T2000Options, TransactionRecord, type TxMetadata, USDC_DECIMALS, WithdrawResult, addCollectFeeToTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, formatAssetAmount, 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,5 +1,5 @@
1
- import { I as InvestmentTrade, S as StrategyDefinition, A as AutoInvestSchedule, a as AutoInvestStatus, T as T2000Options, b as SendResult, B as BalanceResponse, c as TransactionRecord, D as DepositInfo, L as LendingAdapter, d as SwapAdapter, e as SaveResult, W as WithdrawResult, M as MaxWithdrawResult, f as BorrowResult, R as RepayResult, g as MaxBorrowResult, H as HealthFactorResult, h as SwapResult, i as InvestResult, j as InvestEarnResult, k as InvestRebalanceResult, P as PendingReward, C as ClaimRewardsResult, l as StrategyBuyResult, m as StrategySellResult, n as StrategyRebalanceResult, o as StrategyStatusResult, p as AutoInvestRunResult, q as PortfolioResult, r as InvestmentPosition, s as PositionsResult, t as RatesResult, u as LendingRates, v as RebalanceResult, E as EarningsResult, F as FundStatusResult, w as SentinelAgent, x as SentinelAttackResult, G as GasMethod } from './index-HADTiik7.js';
2
- export { y as AdapterCapability, z as AdapterPositions, J as AdapterTxResult, K as AssetRates, N as CetusAdapter, O as GasReserve, Q as HealthInfo, U as InvestRebalanceMove, V as NaviAdapter, X as PerpsAdapter, Y as PerpsPosition, Z as PositionEntry, _ as PositionSide, $ as ProtocolDescriptor, a0 as ProtocolRegistry, a1 as RebalanceStep, a2 as SentinelVerdict, a3 as SuilendAdapter, a4 as SwapQuote, a5 as TradePositionsResult, a6 as TradeResult, a7 as allDescriptors, a8 as cetusDescriptor, a9 as getSentinelInfo, aa as listSentinels, ab as naviDescriptor, ac as requestAttack, ad as sentinelAttack, ae as sentinelDescriptor, af as settleAttack, ag as submitPrompt, ah as suilendDescriptor } from './index-HADTiik7.js';
1
+ import { I as InvestmentTrade, S as StrategyDefinition, A as AutoInvestSchedule, a as AutoInvestStatus, T as T2000Options, P as PayOptions, b as PayResult, c as SendResult, B as BalanceResponse, d as TransactionRecord, D as DepositInfo, L as LendingAdapter, e as SwapAdapter, f as SaveResult, W as WithdrawResult, M as MaxWithdrawResult, g as BorrowResult, R as RepayResult, h as MaxBorrowResult, H as HealthFactorResult, i as SwapResult, j as InvestResult, k as InvestEarnResult, l as InvestRebalanceResult, m as PendingReward, C as ClaimRewardsResult, n as StrategyBuyResult, o as StrategySellResult, p as StrategyRebalanceResult, q as StrategyStatusResult, r as AutoInvestRunResult, s as PortfolioResult, t as InvestmentPosition, u as PositionsResult, v as RatesResult, w as LendingRates, x as RebalanceResult, E as EarningsResult, F as FundStatusResult, y as SentinelAgent, z as SentinelAttackResult, G as GasMethod } from './index-D-6pQwzx.js';
2
+ export { J as AdapterCapability, K as AdapterPositions, N as AdapterTxResult, O as AssetRates, Q as CetusAdapter, U as GasReserve, V as HealthInfo, X as InvestRebalanceMove, Y as NaviAdapter, Z as PerpsAdapter, _ as PerpsPosition, $ as PositionEntry, a0 as PositionSide, a1 as ProtocolDescriptor, a2 as ProtocolRegistry, a3 as RebalanceStep, a4 as SentinelVerdict, a5 as SuilendAdapter, a6 as SwapQuote, a7 as TradePositionsResult, a8 as TradeResult, a9 as allDescriptors, aa as cetusDescriptor, ab as getSentinelInfo, ac as listSentinels, ad as naviDescriptor, ae as requestAttack, af as sentinelAttack, ag as sentinelDescriptor, ah as settleAttack, ai as submitPrompt, aj as suilendDescriptor } from './index-D-6pQwzx.js';
3
3
  import { EventEmitter } from 'eventemitter3';
4
4
  import { SuiJsonRpcClient } from '@mysten/sui/jsonRpc';
5
5
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
@@ -272,6 +272,7 @@ declare class PortfolioManager {
272
272
  getAllStrategyKeys(): string[];
273
273
  clearStrategy(strategyKey: string): void;
274
274
  hasStrategyPositions(strategyKey: string): boolean;
275
+ closeStrategyPosition(strategyKey: string, asset: string): void;
275
276
  }
276
277
 
277
278
  declare class StrategyManager {
@@ -380,10 +381,11 @@ declare class T2000 extends EventEmitter<T2000Events> {
380
381
  address: string;
381
382
  sponsored: boolean;
382
383
  }>;
383
- /** SuiJsonRpcClient used by this agent — exposed for x402 and other integrations. */
384
+ /** SuiJsonRpcClient used by this agent — exposed for integrations. */
384
385
  get suiClient(): SuiJsonRpcClient;
385
- /** Ed25519Keypair used by this agent — exposed for x402 and other integrations. */
386
+ /** Ed25519Keypair used by this agent — exposed for integrations. */
386
387
  get signer(): Ed25519Keypair;
388
+ pay(options: PayOptions): Promise<PayResult>;
387
389
  address(): string;
388
390
  send(params: {
389
391
  to: string;
@@ -661,4 +663,4 @@ interface GasStatusResponse {
661
663
  }
662
664
  declare function getGasStatus(address?: string): Promise<GasStatusResponse>;
663
665
 
664
- export { AutoInvestManager, AutoInvestRunResult, AutoInvestSchedule, AutoInvestStatus, type AutoTopUpResult, BPS_DENOMINATOR, BalanceResponse, BorrowResult, CLOCK_ID, ClaimRewardsResult, type Contact, ContactManager, type ContactMap, DEFAULT_MAX_LEVERAGE, DEFAULT_MAX_POSITION_SIZE, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, DEFAULT_STRATEGIES, DepositInfo, EarningsResult, type FeeOperation, FundStatusResult, GAS_RESERVE_MIN, type GasExecutionResult, GasMethod, type GasRequestType, type GasSponsorResponse, type GasStatusResponse, HealthFactorResult, INVESTMENT_ASSETS, InvestEarnResult, InvestRebalanceResult, InvestResult, type InvestmentAsset, InvestmentPosition, InvestmentTrade, LendingAdapter, LendingRates, MIST_PER_SUI, MaxBorrowResult, MaxWithdrawResult, OUTBOUND_OPS, PERPS_MARKETS, PendingReward, type PerpsMarket, PortfolioManager, PortfolioResult, PositionsResult, type ProtocolFeeInfo, RatesResult, RebalanceResult, RepayResult, SENTINEL, STABLE_ASSETS, SUI_DECIMALS, SUPPORTED_ASSETS, type SafeguardConfig, SafeguardEnforcer, SafeguardError, type SafeguardErrorDetails, type SafeguardRule, SaveResult, SendResult, SentinelAgent, SentinelAttackResult, type SimulationResult, type StableAsset, StrategyBuyResult, StrategyDefinition, StrategyManager, StrategyRebalanceResult, StrategySellResult, StrategyStatusResult, type SupportedAsset, SwapAdapter, SwapResult, T2000, T2000Error, type T2000ErrorCode, type T2000ErrorData, T2000Options, TransactionRecord, type TxMetadata, USDC_DECIMALS, WithdrawResult, addCollectFeeToTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, formatAssetAmount, 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 };
666
+ export { AutoInvestManager, AutoInvestRunResult, AutoInvestSchedule, AutoInvestStatus, type AutoTopUpResult, BPS_DENOMINATOR, BalanceResponse, BorrowResult, CLOCK_ID, ClaimRewardsResult, type Contact, ContactManager, type ContactMap, DEFAULT_MAX_LEVERAGE, DEFAULT_MAX_POSITION_SIZE, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, DEFAULT_STRATEGIES, DepositInfo, EarningsResult, type FeeOperation, FundStatusResult, GAS_RESERVE_MIN, type GasExecutionResult, GasMethod, type GasRequestType, type GasSponsorResponse, type GasStatusResponse, HealthFactorResult, INVESTMENT_ASSETS, InvestEarnResult, InvestRebalanceResult, InvestResult, type InvestmentAsset, InvestmentPosition, InvestmentTrade, LendingAdapter, LendingRates, MIST_PER_SUI, MaxBorrowResult, MaxWithdrawResult, OUTBOUND_OPS, PERPS_MARKETS, PayOptions, PayResult, PendingReward, type PerpsMarket, PortfolioManager, PortfolioResult, PositionsResult, type ProtocolFeeInfo, RatesResult, RebalanceResult, RepayResult, SENTINEL, STABLE_ASSETS, SUI_DECIMALS, SUPPORTED_ASSETS, type SafeguardConfig, SafeguardEnforcer, SafeguardError, type SafeguardErrorDetails, type SafeguardRule, SaveResult, SendResult, SentinelAgent, SentinelAttackResult, type SimulationResult, type StableAsset, StrategyBuyResult, StrategyDefinition, StrategyManager, StrategyRebalanceResult, StrategySellResult, StrategyStatusResult, type SupportedAsset, SwapAdapter, SwapResult, T2000, T2000Error, type T2000ErrorCode, type T2000ErrorData, T2000Options, TransactionRecord, type TxMetadata, USDC_DECIMALS, WithdrawResult, addCollectFeeToTx, calculateFee, executeAutoTopUp, executeWithGas, exportPrivateKey, formatAssetAmount, 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
@@ -56763,6 +56763,19 @@ var PortfolioManager = class {
56763
56763
  if (!bucket) return false;
56764
56764
  return Object.values(bucket).some((p) => p.totalAmount > 0);
56765
56765
  }
56766
+ closeStrategyPosition(strategyKey, asset) {
56767
+ this.load();
56768
+ const bucket = this.data.strategies[strategyKey];
56769
+ if (!bucket?.[asset]) return;
56770
+ bucket[asset].totalAmount = 0;
56771
+ bucket[asset].costBasis = 0;
56772
+ bucket[asset].avgPrice = 0;
56773
+ const hasPositions = Object.values(bucket).some((p) => p.totalAmount > 0);
56774
+ if (!hasPositions) {
56775
+ delete this.data.strategies[strategyKey];
56776
+ }
56777
+ this.save();
56778
+ }
56766
56779
  };
56767
56780
  function emptyData2() {
56768
56781
  return { strategies: {} };
@@ -57088,14 +57101,49 @@ var T2000 = class _T2000 extends EventEmitter {
57088
57101
  return { agent, address, sponsored };
57089
57102
  }
57090
57103
  // -- Gas --
57091
- /** SuiJsonRpcClient used by this agent — exposed for x402 and other integrations. */
57104
+ /** SuiJsonRpcClient used by this agent — exposed for integrations. */
57092
57105
  get suiClient() {
57093
57106
  return this.client;
57094
57107
  }
57095
- /** Ed25519Keypair used by this agent — exposed for x402 and other integrations. */
57108
+ /** Ed25519Keypair used by this agent — exposed for integrations. */
57096
57109
  get signer() {
57097
57110
  return this.keypair;
57098
57111
  }
57112
+ // -- MPP Payments --
57113
+ async pay(options) {
57114
+ this.enforcer.assertNotLocked();
57115
+ this.enforcer.check({ operation: "pay", amount: options.maxPrice ?? 1 });
57116
+ const { Mppx } = await import('mppx/client');
57117
+ const { sui } = await import('@t2000/mpp-sui/client');
57118
+ const mppx = Mppx.create({
57119
+ polyfill: false,
57120
+ methods: [sui({ client: this.client, signer: this.keypair })]
57121
+ });
57122
+ const response = await mppx.fetch(options.url, {
57123
+ method: options.method,
57124
+ headers: options.headers,
57125
+ body: options.body
57126
+ });
57127
+ const contentType = response.headers.get("content-type") ?? "";
57128
+ let body;
57129
+ try {
57130
+ body = contentType.includes("application/json") ? await response.json() : await response.text();
57131
+ } catch {
57132
+ body = null;
57133
+ }
57134
+ const receiptHeader = response.headers.get("x-payment-receipt");
57135
+ const paid = !!receiptHeader;
57136
+ if (paid) {
57137
+ this.enforcer.recordUsage(options.maxPrice ?? 1);
57138
+ }
57139
+ return {
57140
+ status: response.status,
57141
+ body,
57142
+ paid,
57143
+ cost: paid ? options.maxPrice ?? void 0 : void 0,
57144
+ receipt: receiptHeader ? { reference: receiptHeader, timestamp: (/* @__PURE__ */ new Date()).toISOString() } : void 0
57145
+ };
57146
+ }
57099
57147
  // -- Wallet --
57100
57148
  address() {
57101
57149
  return this._address;
@@ -58113,16 +58161,14 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
58113
58161
  if (!(params.asset in INVESTMENT_ASSETS)) {
58114
58162
  throw new T2000Error("ASSET_NOT_SUPPORTED", `${params.asset} is not available for investment`);
58115
58163
  }
58116
- const pos = this.portfolio.getPosition(params.asset);
58117
- if (!pos || pos.totalAmount <= 0) {
58118
- throw new T2000Error("INSUFFICIENT_INVESTMENT", `No ${params.asset} position to sell`);
58119
- }
58120
- const didAutoWithdraw = !!(pos.earning && pos.earningProtocol);
58164
+ let pos = this.portfolio.getPosition(params.asset);
58165
+ const didAutoWithdraw = !!(pos?.earning && pos.earningProtocol);
58121
58166
  if (didAutoWithdraw) {
58122
58167
  const unearnResult = await this.investUnearn({ asset: params.asset });
58123
58168
  if (unearnResult.tx) {
58124
58169
  await this.client.waitForTransaction({ digest: unearnResult.tx, options: { showEffects: true } });
58125
58170
  }
58171
+ pos = this.portfolio.getPosition(params.asset);
58126
58172
  }
58127
58173
  const assetInfo = SUPPORTED_ASSETS[params.asset];
58128
58174
  const gasReserve = params.asset === "SUI" ? GAS_RESERVE_MIN : 0;
@@ -58137,16 +58183,20 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
58137
58183
  await new Promise((r) => setTimeout(r, 1500));
58138
58184
  }
58139
58185
  const maxSellable = Math.max(0, walletAmount - gasReserve);
58186
+ const trackedAmount = pos && pos.totalAmount > 0 ? pos.totalAmount : maxSellable;
58187
+ if (trackedAmount <= 0) {
58188
+ throw new T2000Error("INSUFFICIENT_INVESTMENT", `No ${params.asset} position to sell`);
58189
+ }
58140
58190
  let sellAmountAsset;
58141
58191
  if (params.usdAmount === "all") {
58142
- sellAmountAsset = Math.min(pos.totalAmount, maxSellable);
58192
+ sellAmountAsset = Math.min(trackedAmount, maxSellable);
58143
58193
  } else {
58144
58194
  const swapAdapter = this.registry.listSwap()[0];
58145
58195
  if (!swapAdapter) throw new T2000Error("PROTOCOL_UNAVAILABLE", "No swap adapter available");
58146
58196
  const quote = await swapAdapter.getQuote("USDC", params.asset, 1);
58147
58197
  const assetPrice = 1 / quote.expectedOutput;
58148
58198
  sellAmountAsset = params.usdAmount / assetPrice;
58149
- const maxPosition = params._strategyOnly ? maxSellable : pos.totalAmount;
58199
+ const maxPosition = params._strategyOnly ? maxSellable : trackedAmount;
58150
58200
  sellAmountAsset = Math.min(sellAmountAsset, maxPosition);
58151
58201
  if (sellAmountAsset > maxSellable) {
58152
58202
  throw new T2000Error(
@@ -58181,17 +58231,21 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
58181
58231
  }
58182
58232
  }
58183
58233
  const price = swapResult.toAmount / sellAmountAsset;
58184
- const realizedPnL = this.portfolio.recordSell({
58185
- id: `inv_${Date.now()}`,
58186
- type: "sell",
58187
- asset: params.asset,
58188
- amount: sellAmountAsset,
58189
- price,
58190
- usdValue: swapResult.toAmount,
58191
- fee: swapResult.fee,
58192
- tx: swapResult.tx,
58193
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
58194
- });
58234
+ let realizedPnL = 0;
58235
+ try {
58236
+ realizedPnL = this.portfolio.recordSell({
58237
+ id: `inv_${Date.now()}`,
58238
+ type: "sell",
58239
+ asset: params.asset,
58240
+ amount: sellAmountAsset,
58241
+ price,
58242
+ usdValue: swapResult.toAmount,
58243
+ fee: swapResult.fee,
58244
+ tx: swapResult.tx,
58245
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
58246
+ });
58247
+ } catch {
58248
+ }
58195
58249
  if (params.usdAmount === "all" && !params._strategyOnly) {
58196
58250
  this.portfolio.closePosition(params.asset);
58197
58251
  }
@@ -58694,34 +58748,47 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
58694
58748
  for (const meta of swapMetas) {
58695
58749
  const usdValue = meta.estimatedOut / 10 ** meta.toDecimals;
58696
58750
  const price = meta.amount > 0 ? usdValue / meta.amount : 0;
58697
- const pnl = this.portfolio.recordStrategySell(params.strategy, {
58698
- id: `strat_sell_${Date.now()}_${meta.asset}`,
58699
- type: "sell",
58700
- asset: meta.asset,
58701
- amount: meta.amount,
58702
- price,
58703
- usdValue,
58704
- fee: 0,
58705
- tx: digest,
58706
- timestamp: now
58707
- });
58708
- this.portfolio.recordSell({
58709
- id: `inv_sell_${Date.now()}_${meta.asset}`,
58710
- type: "sell",
58711
- asset: meta.asset,
58712
- amount: meta.amount,
58713
- price,
58714
- usdValue,
58715
- fee: 0,
58716
- tx: digest,
58717
- timestamp: now
58718
- });
58751
+ let pnl = 0;
58752
+ try {
58753
+ pnl = this.portfolio.recordStrategySell(params.strategy, {
58754
+ id: `strat_sell_${Date.now()}_${meta.asset}`,
58755
+ type: "sell",
58756
+ asset: meta.asset,
58757
+ amount: meta.amount,
58758
+ price,
58759
+ usdValue,
58760
+ fee: 0,
58761
+ tx: digest,
58762
+ timestamp: now
58763
+ });
58764
+ } catch {
58765
+ }
58766
+ try {
58767
+ this.portfolio.recordSell({
58768
+ id: `inv_sell_${Date.now()}_${meta.asset}`,
58769
+ type: "sell",
58770
+ asset: meta.asset,
58771
+ amount: meta.amount,
58772
+ price,
58773
+ usdValue,
58774
+ fee: 0,
58775
+ tx: digest,
58776
+ timestamp: now
58777
+ });
58778
+ } catch {
58779
+ }
58719
58780
  sells.push({ asset: meta.asset, amount: meta.amount, usdValue, realizedPnL: pnl, tx: digest });
58720
58781
  totalProceeds += usdValue;
58721
58782
  totalPnL += pnl;
58722
58783
  }
58723
- if (unearnFailures.length === 0 && this.portfolio.hasStrategyPositions(params.strategy)) {
58724
- this.portfolio.clearStrategy(params.strategy);
58784
+ if (this.portfolio.hasStrategyPositions(params.strategy)) {
58785
+ if (unearnFailures.length === 0) {
58786
+ this.portfolio.clearStrategy(params.strategy);
58787
+ } else {
58788
+ for (const s of sells) {
58789
+ this.portfolio.closeStrategyPosition(params.strategy, s.asset);
58790
+ }
58791
+ }
58725
58792
  }
58726
58793
  const failed = unearnFailures.map((f) => ({ asset: f.asset, reason: f.error }));
58727
58794
  return {