@t2000/sdk 0.17.4 → 0.17.8

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.
@@ -1,4 +1,4 @@
1
- export { w as AdapterCapability, x as AdapterPositions, y as AdapterTxResult, C as CetusAdapter, K as HealthInfo, L as LendingAdapter, s as LendingRates, N as NaviAdapter, O as PerpsAdapter, X as ProtocolDescriptor, Y as ProtocolRegistry, $ as SuilendAdapter, d as SwapAdapter, a0 as SwapQuote, a3 as allDescriptors, a4 as cetusDescriptor, a7 as naviDescriptor, aa as sentinelDescriptor, ad as suilendDescriptor } from '../index-BzQsrfrc.cjs';
1
+ export { w as AdapterCapability, x as AdapterPositions, y as AdapterTxResult, C as CetusAdapter, K as HealthInfo, L as LendingAdapter, s as LendingRates, N as NaviAdapter, O as PerpsAdapter, X as ProtocolDescriptor, Y as ProtocolRegistry, $ as SuilendAdapter, d as SwapAdapter, a0 as SwapQuote, a3 as allDescriptors, a4 as cetusDescriptor, a7 as naviDescriptor, aa as sentinelDescriptor, ad as suilendDescriptor } from '../index-D4cFY__D.cjs';
2
2
  import '@mysten/sui/transactions';
3
3
  import '@mysten/sui/jsonRpc';
4
4
  import '@mysten/sui/keypairs/ed25519';
@@ -1,4 +1,4 @@
1
- export { w as AdapterCapability, x as AdapterPositions, y as AdapterTxResult, C as CetusAdapter, K as HealthInfo, L as LendingAdapter, s as LendingRates, N as NaviAdapter, O as PerpsAdapter, X as ProtocolDescriptor, Y as ProtocolRegistry, $ as SuilendAdapter, d as SwapAdapter, a0 as SwapQuote, a3 as allDescriptors, a4 as cetusDescriptor, a7 as naviDescriptor, aa as sentinelDescriptor, ad as suilendDescriptor } from '../index-BzQsrfrc.js';
1
+ export { w as AdapterCapability, x as AdapterPositions, y as AdapterTxResult, C as CetusAdapter, K as HealthInfo, L as LendingAdapter, s as LendingRates, N as NaviAdapter, O as PerpsAdapter, X as ProtocolDescriptor, Y as ProtocolRegistry, $ as SuilendAdapter, d as SwapAdapter, a0 as SwapQuote, a3 as allDescriptors, a4 as cetusDescriptor, a7 as naviDescriptor, aa as sentinelDescriptor, ad as suilendDescriptor } from '../index-D4cFY__D.js';
2
2
  import '@mysten/sui/transactions';
3
3
  import '@mysten/sui/jsonRpc';
4
4
  import '@mysten/sui/keypairs/ed25519';
@@ -291,6 +291,10 @@ interface StrategySellResult {
291
291
  realizedPnL: number;
292
292
  tx: string;
293
293
  }>;
294
+ failed?: Array<{
295
+ asset: string;
296
+ reason: string;
297
+ }>;
294
298
  gasCost: number;
295
299
  gasMethod: GasMethod;
296
300
  }
@@ -291,6 +291,10 @@ interface StrategySellResult {
291
291
  realizedPnL: number;
292
292
  tx: string;
293
293
  }>;
294
+ failed?: Array<{
295
+ asset: string;
296
+ reason: string;
297
+ }>;
294
298
  gasCost: number;
295
299
  gasMethod: GasMethod;
296
300
  }
package/dist/index.cjs CHANGED
@@ -3366,6 +3366,10 @@ var AutoInvestManager = class {
3366
3366
  this.save();
3367
3367
  }
3368
3368
  };
3369
+ var LOW_LIQUIDITY_ASSETS = /* @__PURE__ */ new Set(["GOLD"]);
3370
+ function defaultSlippage(asset) {
3371
+ return LOW_LIQUIDITY_ASSETS.has(asset) ? 0.05 : 0.03;
3372
+ }
3369
3373
  var DEFAULT_CONFIG_DIR = path.join(os.homedir(), ".t2000");
3370
3374
  var T2000 = class _T2000 extends eventemitter3.EventEmitter {
3371
3375
  keypair;
@@ -4281,7 +4285,7 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
4281
4285
  from: "USDC",
4282
4286
  to: params.asset,
4283
4287
  amount: params.usdAmount,
4284
- maxSlippage: params.maxSlippage ?? 0.03,
4288
+ maxSlippage: params.maxSlippage ?? defaultSlippage(params.asset),
4285
4289
  _bypassInvestmentGuard: true
4286
4290
  });
4287
4291
  if (swapResult.toAmount === 0) {
@@ -4382,7 +4386,7 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
4382
4386
  from: params.asset,
4383
4387
  to: "USDC",
4384
4388
  amount: sellAmountAsset,
4385
- maxSlippage: params.maxSlippage ?? 0.03,
4389
+ maxSlippage: params.maxSlippage ?? defaultSlippage(params.asset),
4386
4390
  _bypassInvestmentGuard: true
4387
4391
  });
4388
4392
  const price = swapResult.toAmount / sellAmountAsset;
@@ -4621,50 +4625,90 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
4621
4625
  if (stratPositions.length === 0) {
4622
4626
  throw new T2000Error("INSUFFICIENT_INVESTMENT", `No positions in strategy '${params.strategy}'`);
4623
4627
  }
4628
+ const swapAdapter = this.registry.listSwap()[0];
4629
+ if (!swapAdapter?.addSwapToTx) {
4630
+ throw new T2000Error("PROTOCOL_UNAVAILABLE", "Swap adapter does not support composable PTB");
4631
+ }
4632
+ let swapMetas = [];
4633
+ const gasResult = await executeWithGas(this.client, this.keypair, async () => {
4634
+ swapMetas = [];
4635
+ const tx = new transactions.Transaction();
4636
+ tx.setSender(this._address);
4637
+ const usdcOutputs = [];
4638
+ for (const pos of stratPositions) {
4639
+ const assetInfo = SUPPORTED_ASSETS[pos.asset];
4640
+ const coins = await this._fetchCoins(assetInfo.type);
4641
+ if (coins.length === 0) {
4642
+ throw new T2000Error("INSUFFICIENT_BALANCE", `No ${pos.asset} coins in wallet`);
4643
+ }
4644
+ const merged = this._mergeCoinsInTx(tx, coins);
4645
+ const gasReserve = pos.asset === "SUI" ? GAS_RESERVE_MIN : 0;
4646
+ const sellAmount = Math.max(0, pos.totalAmount - gasReserve);
4647
+ const rawAmount = BigInt(Math.floor(sellAmount * 10 ** assetInfo.decimals));
4648
+ const [splitCoin] = tx.splitCoins(merged, [rawAmount]);
4649
+ const assetUsd = sellAmount * (pos.avgPrice || 1);
4650
+ const slippageBps = LOW_LIQUIDITY_ASSETS.has(pos.asset) ? 500 : 300;
4651
+ const { outputCoin, estimatedOut, toDecimals } = await swapAdapter.addSwapToTx(
4652
+ tx,
4653
+ this._address,
4654
+ splitCoin,
4655
+ pos.asset,
4656
+ "USDC",
4657
+ assetUsd,
4658
+ slippageBps
4659
+ );
4660
+ usdcOutputs.push(outputCoin);
4661
+ swapMetas.push({ asset: pos.asset, amount: sellAmount, estimatedOut, toDecimals });
4662
+ }
4663
+ if (usdcOutputs.length > 1) {
4664
+ tx.mergeCoins(usdcOutputs[0], usdcOutputs.slice(1));
4665
+ }
4666
+ tx.transferObjects([usdcOutputs[0]], this._address);
4667
+ return tx;
4668
+ });
4669
+ const digest = gasResult.digest;
4670
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4624
4671
  const sells = [];
4625
4672
  let totalProceeds = 0;
4626
4673
  let totalPnL = 0;
4627
- let totalGas = 0;
4628
- let gasMethod = "self-funded";
4629
- for (const pos of stratPositions) {
4630
- const fullAmount = pos.totalAmount;
4631
- const swapAdapter = this.registry.listSwap()[0];
4632
- let assetPrice = 1;
4633
- try {
4634
- if (swapAdapter) {
4635
- if (pos.asset === "SUI") {
4636
- assetPrice = await swapAdapter.getPoolPrice();
4637
- } else {
4638
- const q = await swapAdapter.getQuote("USDC", pos.asset, 1);
4639
- assetPrice = q.expectedOutput > 0 ? 1 / q.expectedOutput : 1;
4640
- }
4641
- }
4642
- } catch {
4643
- }
4644
- const strategyUsdValue = fullAmount * assetPrice;
4645
- const result = await this.investSell({
4646
- asset: pos.asset,
4647
- usdAmount: strategyUsdValue,
4648
- _strategyOnly: true
4649
- });
4674
+ for (const meta of swapMetas) {
4675
+ const usdValue = meta.estimatedOut / 10 ** meta.toDecimals;
4676
+ const price = meta.amount > 0 ? usdValue / meta.amount : 0;
4650
4677
  const pnl = this.portfolio.recordStrategySell(params.strategy, {
4651
- id: `strat_sell_${Date.now()}_${pos.asset}`,
4678
+ id: `strat_sell_${Date.now()}_${meta.asset}`,
4652
4679
  type: "sell",
4653
- asset: pos.asset,
4654
- amount: fullAmount,
4655
- price: result.price,
4656
- usdValue: result.usdValue,
4657
- fee: result.fee,
4658
- tx: result.tx,
4659
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
4680
+ asset: meta.asset,
4681
+ amount: meta.amount,
4682
+ price,
4683
+ usdValue,
4684
+ fee: 0,
4685
+ tx: digest,
4686
+ timestamp: now
4687
+ });
4688
+ this.portfolio.recordSell({
4689
+ id: `inv_sell_${Date.now()}_${meta.asset}`,
4690
+ type: "sell",
4691
+ asset: meta.asset,
4692
+ amount: meta.amount,
4693
+ price,
4694
+ usdValue,
4695
+ fee: 0,
4696
+ tx: digest,
4697
+ timestamp: now
4660
4698
  });
4661
- sells.push({ asset: pos.asset, amount: result.amount, usdValue: result.usdValue, realizedPnL: pnl, tx: result.tx });
4662
- totalProceeds += result.usdValue;
4699
+ sells.push({ asset: meta.asset, amount: meta.amount, usdValue, realizedPnL: pnl, tx: digest });
4700
+ totalProceeds += usdValue;
4663
4701
  totalPnL += pnl;
4664
- totalGas += result.gasCost;
4665
- gasMethod = result.gasMethod;
4666
4702
  }
4667
- return { success: true, strategy: params.strategy, totalProceeds, realizedPnL: totalPnL, sells, gasCost: totalGas, gasMethod };
4703
+ return {
4704
+ success: true,
4705
+ strategy: params.strategy,
4706
+ totalProceeds,
4707
+ realizedPnL: totalPnL,
4708
+ sells,
4709
+ gasCost: gasResult.gasCostSui,
4710
+ gasMethod: gasResult.gasMethod
4711
+ };
4668
4712
  }
4669
4713
  async rebalanceStrategy(params) {
4670
4714
  this.enforcer.assertNotLocked();
@@ -4698,8 +4742,9 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
4698
4742
  currentWeights[pos.asset] = w;
4699
4743
  beforeWeights[pos.asset] = w;
4700
4744
  }
4701
- const trades = [];
4702
4745
  const threshold = 3;
4746
+ const sellOps = [];
4747
+ const buyOps = [];
4703
4748
  for (const [asset, targetPct] of Object.entries(definition.allocations)) {
4704
4749
  const currentPct = currentWeights[asset] ?? 0;
4705
4750
  const diff = targetPct - currentPct;
@@ -4707,33 +4752,140 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
4707
4752
  const usdDiff = totalValue * (Math.abs(diff) / 100);
4708
4753
  if (usdDiff < 1) continue;
4709
4754
  if (diff > 0) {
4710
- const result = await this.investBuy({ asset, usdAmount: usdDiff });
4711
- this.portfolio.recordStrategyBuy(params.strategy, {
4712
- id: `strat_rebal_${Date.now()}_${asset}`,
4713
- type: "buy",
4714
- asset,
4715
- amount: result.amount,
4716
- price: result.price,
4717
- usdValue: usdDiff,
4718
- fee: result.fee,
4719
- tx: result.tx,
4720
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
4721
- });
4722
- trades.push({ action: "buy", asset, usdAmount: usdDiff, amount: result.amount, tx: result.tx });
4755
+ buyOps.push({ asset, usdAmount: usdDiff });
4723
4756
  } else {
4724
- const result = await this.investSell({ asset, usdAmount: usdDiff });
4757
+ const price = prices[asset] ?? 1;
4758
+ const assetAmount = price > 0 ? usdDiff / price : 0;
4759
+ sellOps.push({ asset, usdAmount: usdDiff, assetAmount });
4760
+ }
4761
+ }
4762
+ if (sellOps.length === 0 && buyOps.length === 0) {
4763
+ return { success: true, strategy: params.strategy, trades: [], beforeWeights, afterWeights: { ...beforeWeights }, targetWeights: { ...definition.allocations } };
4764
+ }
4765
+ if (!swapAdapter?.addSwapToTx) {
4766
+ throw new T2000Error("PROTOCOL_UNAVAILABLE", "Swap adapter does not support composable PTB");
4767
+ }
4768
+ const tradeMetas = [];
4769
+ const gasResult = await executeWithGas(this.client, this.keypair, async () => {
4770
+ tradeMetas.length = 0;
4771
+ const tx = new transactions.Transaction();
4772
+ tx.setSender(this._address);
4773
+ const usdcCoins = [];
4774
+ for (const sell of sellOps) {
4775
+ const assetInfo = SUPPORTED_ASSETS[sell.asset];
4776
+ const coins = await this._fetchCoins(assetInfo.type);
4777
+ if (coins.length === 0) continue;
4778
+ const merged = this._mergeCoinsInTx(tx, coins);
4779
+ const gasReserve = sell.asset === "SUI" ? GAS_RESERVE_MIN : 0;
4780
+ const sellAmount = Math.max(0, sell.assetAmount - gasReserve);
4781
+ const rawAmount = BigInt(Math.floor(sellAmount * 10 ** assetInfo.decimals));
4782
+ const [splitCoin] = tx.splitCoins(merged, [rawAmount]);
4783
+ const slippageBps = LOW_LIQUIDITY_ASSETS.has(sell.asset) ? 500 : 300;
4784
+ const { outputCoin, estimatedOut, toDecimals } = await swapAdapter.addSwapToTx(
4785
+ tx,
4786
+ this._address,
4787
+ splitCoin,
4788
+ sell.asset,
4789
+ "USDC",
4790
+ sell.usdAmount,
4791
+ slippageBps
4792
+ );
4793
+ usdcCoins.push(outputCoin);
4794
+ tradeMetas.push({ action: "sell", asset: sell.asset, usdAmount: sell.usdAmount, estimatedOut, toDecimals });
4795
+ }
4796
+ if (buyOps.length > 0) {
4797
+ const walletUsdc = await this._fetchCoins(SUPPORTED_ASSETS.USDC.type);
4798
+ if (walletUsdc.length > 0) {
4799
+ usdcCoins.push(this._mergeCoinsInTx(tx, walletUsdc));
4800
+ }
4801
+ if (usdcCoins.length === 0) {
4802
+ throw new T2000Error("INSUFFICIENT_BALANCE", "No USDC available for rebalance buys");
4803
+ }
4804
+ if (usdcCoins.length > 1) {
4805
+ tx.mergeCoins(usdcCoins[0], usdcCoins.slice(1));
4806
+ }
4807
+ const mergedUsdc = usdcCoins[0];
4808
+ const splitAmounts = buyOps.map(
4809
+ (b) => BigInt(Math.floor(b.usdAmount * 10 ** SUPPORTED_ASSETS.USDC.decimals))
4810
+ );
4811
+ const splitCoins = tx.splitCoins(mergedUsdc, splitAmounts);
4812
+ const outputCoins = [];
4813
+ for (let i = 0; i < buyOps.length; i++) {
4814
+ const buy = buyOps[i];
4815
+ const slippageBps = LOW_LIQUIDITY_ASSETS.has(buy.asset) ? 500 : 300;
4816
+ const { outputCoin, estimatedOut, toDecimals } = await swapAdapter.addSwapToTx(
4817
+ tx,
4818
+ this._address,
4819
+ splitCoins[i],
4820
+ "USDC",
4821
+ buy.asset,
4822
+ buy.usdAmount,
4823
+ slippageBps
4824
+ );
4825
+ outputCoins.push(outputCoin);
4826
+ tradeMetas.push({ action: "buy", asset: buy.asset, usdAmount: buy.usdAmount, estimatedOut, toDecimals });
4827
+ }
4828
+ tx.transferObjects(outputCoins, this._address);
4829
+ }
4830
+ return tx;
4831
+ });
4832
+ const digest = gasResult.digest;
4833
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4834
+ const trades = [];
4835
+ for (const meta of tradeMetas) {
4836
+ const rawAmount = meta.estimatedOut / 10 ** meta.toDecimals;
4837
+ if (meta.action === "sell") {
4838
+ const price = meta.usdAmount > 0 && rawAmount > 0 ? meta.usdAmount / rawAmount : prices[meta.asset] ?? 0;
4839
+ const assetAmount = prices[meta.asset] > 0 ? meta.usdAmount / prices[meta.asset] : 0;
4725
4840
  this.portfolio.recordStrategySell(params.strategy, {
4726
- id: `strat_rebal_${Date.now()}_${asset}`,
4841
+ id: `strat_rebal_${Date.now()}_${meta.asset}`,
4727
4842
  type: "sell",
4728
- asset,
4729
- amount: result.amount,
4730
- price: result.price,
4731
- usdValue: result.usdValue,
4732
- fee: result.fee,
4733
- tx: result.tx,
4734
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
4843
+ asset: meta.asset,
4844
+ amount: assetAmount,
4845
+ price,
4846
+ usdValue: meta.usdAmount,
4847
+ fee: 0,
4848
+ tx: digest,
4849
+ timestamp: now
4850
+ });
4851
+ this.portfolio.recordSell({
4852
+ id: `inv_rebal_${Date.now()}_${meta.asset}`,
4853
+ type: "sell",
4854
+ asset: meta.asset,
4855
+ amount: assetAmount,
4856
+ price,
4857
+ usdValue: meta.usdAmount,
4858
+ fee: 0,
4859
+ tx: digest,
4860
+ timestamp: now
4861
+ });
4862
+ trades.push({ action: "sell", asset: meta.asset, usdAmount: meta.usdAmount, amount: assetAmount, tx: digest });
4863
+ } else {
4864
+ const amount = rawAmount;
4865
+ const price = meta.usdAmount / amount;
4866
+ this.portfolio.recordBuy({
4867
+ id: `inv_rebal_${Date.now()}_${meta.asset}`,
4868
+ type: "buy",
4869
+ asset: meta.asset,
4870
+ amount,
4871
+ price,
4872
+ usdValue: meta.usdAmount,
4873
+ fee: 0,
4874
+ tx: digest,
4875
+ timestamp: now
4876
+ });
4877
+ this.portfolio.recordStrategyBuy(params.strategy, {
4878
+ id: `strat_rebal_${Date.now()}_${meta.asset}`,
4879
+ type: "buy",
4880
+ asset: meta.asset,
4881
+ amount,
4882
+ price,
4883
+ usdValue: meta.usdAmount,
4884
+ fee: 0,
4885
+ tx: digest,
4886
+ timestamp: now
4735
4887
  });
4736
- trades.push({ action: "sell", asset, usdAmount: result.usdValue, amount: result.amount, tx: result.tx });
4888
+ trades.push({ action: "buy", asset: meta.asset, usdAmount: meta.usdAmount, amount, tx: digest });
4737
4889
  }
4738
4890
  }
4739
4891
  const afterWeights = {};