@t2000/sdk 0.16.1 → 0.16.6

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 t2000
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -71,6 +71,22 @@ await agent.investUnearn({ asset: 'SUI' });
71
71
 
72
72
  // Sell position (auto-withdraws if earning first)
73
73
  await agent.investSell({ asset: 'SUI', usdAmount: 'all' });
74
+
75
+ // Buy into a strategy (single atomic PTB)
76
+ await agent.investStrategy({ strategy: 'bluechip', usdAmount: 200 });
77
+
78
+ // Check strategy status
79
+ const status = await agent.getStrategyStatus({ strategy: 'bluechip' });
80
+ console.log(`Total value: $${status.totalValue}`);
81
+
82
+ // Rebalance strategy to target weights
83
+ await agent.rebalanceStrategy({ strategy: 'bluechip' });
84
+
85
+ // Set up dollar-cost averaging
86
+ await agent.setupAutoInvest({ amount: 50, frequency: 'weekly', strategy: 'bluechip' });
87
+
88
+ // Run pending DCA purchases
89
+ await agent.runAutoInvest();
74
90
  ```
75
91
 
76
92
  ## API Reference
@@ -179,7 +195,28 @@ const agent = T2000.fromPrivateKey('suiprivkey1q...');
179
195
  | `agent.investSell({ asset, usdAmount \| 'all', maxSlippage? })` | Sell crypto back to USDC (auto-withdraws if earning) | `InvestResult` |
180
196
  | `agent.investEarn({ asset })` | Deposit invested asset into best-rate lending for yield | `InvestEarnResult` |
181
197
  | `agent.investUnearn({ asset })` | Withdraw from lending, keep in portfolio | `InvestUnearnResult` |
182
- | `agent.getPortfolio()` | Investment positions + P&L | `PortfolioResult` |
198
+ | `agent.getPortfolio()` | Investment positions + P&L (grouped by strategy) | `PortfolioResult` |
199
+
200
+ ### Strategy Methods
201
+
202
+ | Method | Description | Returns |
203
+ |--------|-------------|---------|
204
+ | `agent.investStrategy({ strategy, usdAmount, maxSlippage?, dryRun? })` | Buy into a strategy (single atomic PTB) | `StrategyBuyResult` |
205
+ | `agent.sellStrategy({ strategy, maxSlippage? })` | Sell all positions in a strategy | `StrategySellResult` |
206
+ | `agent.rebalanceStrategy({ strategy, maxSlippage?, driftThreshold? })` | Rebalance to target weights | `StrategyRebalanceResult` |
207
+ | `agent.getStrategyStatus({ strategy })` | Positions, weights, drift for a strategy | `StrategyStatusResult` |
208
+ | `agent.getStrategies()` | List all available strategies | `StrategyDefinition[]` |
209
+ | `agent.createStrategy({ name, allocations, description? })` | Create a custom strategy | `StrategyDefinition` |
210
+ | `agent.deleteStrategy({ name })` | Delete a custom strategy (no active positions) | `void` |
211
+
212
+ ### Auto-Invest (DCA) Methods
213
+
214
+ | Method | Description | Returns |
215
+ |--------|-------------|---------|
216
+ | `agent.setupAutoInvest({ amount, frequency, strategy?, asset? })` | Schedule recurring purchases | `AutoInvestSchedule` |
217
+ | `agent.getAutoInvestStatus()` | View schedules and pending runs | `AutoInvestStatus` |
218
+ | `agent.runAutoInvest()` | Execute all pending DCA purchases | `AutoInvestRunResult` |
219
+ | `agent.stopAutoInvest({ id? })` | Stop one or all schedules | `void` |
183
220
 
184
221
  ### Key Management
185
222
 
@@ -383,7 +420,7 @@ Fees are collected by the t2000 protocol treasury on-chain.
383
420
 
384
421
  ## MCP Server
385
422
 
386
- The SDK powers the [`@t2000/mcp`](https://www.npmjs.com/package/@t2000/mcp) server — 19 tools and 6 prompts for Claude Desktop, Cursor, and any MCP-compatible AI platform. Run `t2000 mcp` to start.
423
+ The SDK powers the [`@t2000/mcp`](https://www.npmjs.com/package/@t2000/mcp) server — 21 tools and 6 prompts for Claude Desktop, Cursor, and any MCP-compatible AI platform. Run `t2000 mcp` to start.
387
424
 
388
425
  ## License
389
426
 
package/dist/index.cjs CHANGED
@@ -2388,13 +2388,62 @@ function solveHashcash(challenge) {
2388
2388
  }
2389
2389
  }
2390
2390
 
2391
+ // src/gas/autoTopUp.ts
2392
+ var AUTO_TOPUP_MIN_SUI_FOR_GAS = 5000000n;
2393
+ async function shouldAutoTopUp(client, address) {
2394
+ const [suiBalance, usdcBalance] = await Promise.all([
2395
+ client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.SUI.type }),
2396
+ client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.USDC.type })
2397
+ ]);
2398
+ const suiRaw = BigInt(suiBalance.totalBalance);
2399
+ const usdcRaw = BigInt(usdcBalance.totalBalance);
2400
+ return suiRaw < AUTO_TOPUP_THRESHOLD && suiRaw >= AUTO_TOPUP_MIN_SUI_FOR_GAS && usdcRaw >= AUTO_TOPUP_MIN_USDC;
2401
+ }
2402
+ async function executeAutoTopUp(client, keypair) {
2403
+ const address = keypair.getPublicKey().toSuiAddress();
2404
+ const topupAmountHuman = Number(AUTO_TOPUP_AMOUNT) / 1e6;
2405
+ const { tx } = await buildSwapTx({
2406
+ client,
2407
+ address,
2408
+ fromAsset: "USDC",
2409
+ toAsset: "SUI",
2410
+ amount: topupAmountHuman
2411
+ });
2412
+ const result = await client.signAndExecuteTransaction({
2413
+ signer: keypair,
2414
+ transaction: tx,
2415
+ options: { showEffects: true, showBalanceChanges: true }
2416
+ });
2417
+ await client.waitForTransaction({ digest: result.digest });
2418
+ let suiReceived = 0;
2419
+ if (result.balanceChanges) {
2420
+ for (const change of result.balanceChanges) {
2421
+ if (change.coinType === SUPPORTED_ASSETS.SUI.type && change.owner && typeof change.owner === "object" && "AddressOwner" in change.owner && change.owner.AddressOwner === address) {
2422
+ suiReceived += Number(change.amount) / Number(MIST_PER_SUI);
2423
+ }
2424
+ }
2425
+ }
2426
+ return {
2427
+ success: true,
2428
+ tx: result.digest,
2429
+ usdcSpent: topupAmountHuman,
2430
+ suiReceived: Math.abs(suiReceived)
2431
+ };
2432
+ }
2433
+
2391
2434
  // src/gas/gasStation.ts
2392
- async function requestGasSponsorship(txJson, sender, type) {
2393
- const txBytes = Buffer.from(txJson).toString("base64");
2435
+ async function requestGasSponsorship(txJson, sender, type, txBcsBytes) {
2436
+ const payload = { sender, type };
2437
+ if (txBcsBytes) {
2438
+ payload.txBcsBytes = txBcsBytes;
2439
+ } else {
2440
+ payload.txJson = txJson;
2441
+ payload.txBytes = Buffer.from(txJson).toString("base64");
2442
+ }
2394
2443
  const res = await fetch(`${API_BASE_URL}/api/gas`, {
2395
2444
  method: "POST",
2396
2445
  headers: { "Content-Type": "application/json" },
2397
- body: JSON.stringify({ txJson, txBytes, sender, type })
2446
+ body: JSON.stringify(payload)
2398
2447
  });
2399
2448
  const data = await res.json();
2400
2449
  if (!res.ok) {
@@ -2444,53 +2493,6 @@ async function getGasStatus(address) {
2444
2493
  return await res.json();
2445
2494
  }
2446
2495
 
2447
- // src/gas/autoTopUp.ts
2448
- async function shouldAutoTopUp(client, address) {
2449
- const [suiBalance, usdcBalance] = await Promise.all([
2450
- client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.SUI.type }),
2451
- client.getBalance({ owner: address, coinType: SUPPORTED_ASSETS.USDC.type })
2452
- ]);
2453
- const suiRaw = BigInt(suiBalance.totalBalance);
2454
- const usdcRaw = BigInt(usdcBalance.totalBalance);
2455
- return suiRaw < AUTO_TOPUP_THRESHOLD && usdcRaw >= AUTO_TOPUP_MIN_USDC;
2456
- }
2457
- async function executeAutoTopUp(client, keypair) {
2458
- const address = keypair.getPublicKey().toSuiAddress();
2459
- const topupAmountHuman = Number(AUTO_TOPUP_AMOUNT) / 1e6;
2460
- const { tx } = await buildSwapTx({
2461
- client,
2462
- address,
2463
- fromAsset: "USDC",
2464
- toAsset: "SUI",
2465
- amount: topupAmountHuman
2466
- });
2467
- const txJson = tx.serialize();
2468
- const sponsoredResult = await requestGasSponsorship(txJson, address, "auto-topup");
2469
- const sponsoredTxBytes = Buffer.from(sponsoredResult.txBytes, "base64");
2470
- const { signature: agentSig } = await keypair.signTransaction(sponsoredTxBytes);
2471
- const result = await client.executeTransactionBlock({
2472
- transactionBlock: sponsoredResult.txBytes,
2473
- signature: [agentSig, sponsoredResult.sponsorSignature],
2474
- options: { showEffects: true, showBalanceChanges: true }
2475
- });
2476
- await client.waitForTransaction({ digest: result.digest });
2477
- let suiReceived = 0;
2478
- if (result.balanceChanges) {
2479
- for (const change of result.balanceChanges) {
2480
- if (change.coinType === SUPPORTED_ASSETS.SUI.type && change.owner && typeof change.owner === "object" && "AddressOwner" in change.owner && change.owner.AddressOwner === address) {
2481
- suiReceived += Number(change.amount) / Number(MIST_PER_SUI);
2482
- }
2483
- }
2484
- }
2485
- reportGasUsage(address, result.digest, 0, 0, "auto-topup");
2486
- return {
2487
- success: true,
2488
- tx: result.digest,
2489
- usdcSpent: topupAmountHuman,
2490
- suiReceived: Math.abs(suiReceived)
2491
- };
2492
- }
2493
-
2494
2496
  // src/gas/manager.ts
2495
2497
  function extractGasCost(effects) {
2496
2498
  if (!effects?.gasUsed) return 0;
@@ -2518,11 +2520,12 @@ async function trySelfFunded(client, keypair, tx) {
2518
2520
  gasCostSui: extractGasCost(result.effects)
2519
2521
  };
2520
2522
  }
2521
- async function tryAutoTopUpThenSelfFund(client, keypair, tx) {
2523
+ async function tryAutoTopUpThenSelfFund(client, keypair, buildTx) {
2522
2524
  const address = keypair.getPublicKey().toSuiAddress();
2523
2525
  const canTopUp = await shouldAutoTopUp(client, address);
2524
2526
  if (!canTopUp) return null;
2525
2527
  await executeAutoTopUp(client, keypair);
2528
+ const tx = await buildTx();
2526
2529
  tx.setSender(address);
2527
2530
  const result = await client.signAndExecuteTransaction({
2528
2531
  signer: keypair,
@@ -2540,8 +2543,15 @@ async function tryAutoTopUpThenSelfFund(client, keypair, tx) {
2540
2543
  async function trySponsored(client, keypair, tx) {
2541
2544
  const address = keypair.getPublicKey().toSuiAddress();
2542
2545
  tx.setSender(address);
2543
- const txJson = tx.serialize();
2544
- const sponsoredResult = await requestGasSponsorship(txJson, address);
2546
+ let txJson;
2547
+ let txBcsBase64;
2548
+ try {
2549
+ txJson = tx.serialize();
2550
+ } catch {
2551
+ const bcsBytes = await tx.build({ client });
2552
+ txBcsBase64 = Buffer.from(bcsBytes).toString("base64");
2553
+ }
2554
+ const sponsoredResult = await requestGasSponsorship(txJson ?? "", address, void 0, txBcsBase64);
2545
2555
  const sponsoredTxBytes = Buffer.from(sponsoredResult.txBytes, "base64");
2546
2556
  const { signature: agentSig } = await keypair.signTransaction(sponsoredTxBytes);
2547
2557
  const result = await client.executeTransactionBlock({
@@ -2577,8 +2587,7 @@ async function executeWithGas(client, keypair, buildTx, options) {
2577
2587
  errors.push(`self-funded: ${msg}`);
2578
2588
  }
2579
2589
  try {
2580
- const tx = await buildTx();
2581
- const result = await tryAutoTopUpThenSelfFund(client, keypair, tx);
2590
+ const result = await tryAutoTopUpThenSelfFund(client, keypair, buildTx);
2582
2591
  if (result) return result;
2583
2592
  errors.push("auto-topup: not eligible (low USDC or sufficient SUI)");
2584
2593
  } catch (err) {
@@ -4340,20 +4349,22 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
4340
4349
  if (!params.usdAmount || params.usdAmount <= 0) {
4341
4350
  throw new T2000Error("INVALID_AMOUNT", "Strategy investment must be > $0");
4342
4351
  }
4352
+ this.enforcer.check({ operation: "invest", amount: params.usdAmount });
4343
4353
  const bal = await queryBalance(this.client, this._address);
4344
4354
  if (bal.available < params.usdAmount) {
4345
4355
  throw new T2000Error("INSUFFICIENT_BALANCE", `Insufficient balance. Available: $${bal.available.toFixed(2)}, requested: $${params.usdAmount.toFixed(2)}`);
4346
4356
  }
4347
4357
  const buys = [];
4358
+ const allocEntries = Object.entries(definition.allocations);
4348
4359
  if (params.dryRun) {
4349
- const swapAdapter = this.registry.listSwap()[0];
4350
- for (const [asset, pct] of Object.entries(definition.allocations)) {
4360
+ const swapAdapter2 = this.registry.listSwap()[0];
4361
+ for (const [asset, pct] of allocEntries) {
4351
4362
  const assetUsd = params.usdAmount * (pct / 100);
4352
4363
  let estAmount = 0;
4353
4364
  let estPrice = 0;
4354
4365
  try {
4355
- if (swapAdapter) {
4356
- const quote = await swapAdapter.getQuote("USDC", asset, assetUsd);
4366
+ if (swapAdapter2) {
4367
+ const quote = await swapAdapter2.getQuote("USDC", asset, assetUsd);
4357
4368
  estAmount = quote.expectedOutput;
4358
4369
  estPrice = assetUsd / estAmount;
4359
4370
  }
@@ -4363,27 +4374,76 @@ To sell investment: t2000 invest sell ${params.amount} ${fromAsset}`,
4363
4374
  }
4364
4375
  return { success: true, strategy: params.strategy, totalInvested: params.usdAmount, buys, gasCost: 0, gasMethod: "self-funded" };
4365
4376
  }
4366
- let totalGas = 0;
4367
- let gasMethod = "self-funded";
4368
- for (const [asset, pct] of Object.entries(definition.allocations)) {
4369
- const assetUsd = params.usdAmount * (pct / 100);
4370
- const result = await this.investBuy({ asset, usdAmount: assetUsd });
4377
+ const swapAdapter = this.registry.listSwap()[0];
4378
+ if (!swapAdapter?.addSwapToTx) {
4379
+ throw new T2000Error("PROTOCOL_UNAVAILABLE", "Swap adapter does not support composable PTB");
4380
+ }
4381
+ const swapMetas = [];
4382
+ const gasResult = await executeWithGas(this.client, this.keypair, async () => {
4383
+ const tx = new transactions.Transaction();
4384
+ tx.setSender(this._address);
4385
+ const usdcCoins = await this._fetchCoins(SUPPORTED_ASSETS.USDC.type);
4386
+ if (usdcCoins.length === 0) throw new T2000Error("INSUFFICIENT_BALANCE", "No USDC coins found");
4387
+ const mergedUsdc = this._mergeCoinsInTx(tx, usdcCoins);
4388
+ const splitAmounts = allocEntries.map(
4389
+ ([, pct]) => BigInt(Math.floor(params.usdAmount * (pct / 100) * 10 ** SUPPORTED_ASSETS.USDC.decimals))
4390
+ );
4391
+ const splitCoins = tx.splitCoins(mergedUsdc, splitAmounts);
4392
+ const outputCoins = [];
4393
+ for (let i = 0; i < allocEntries.length; i++) {
4394
+ const [asset] = allocEntries[i];
4395
+ const assetUsd = params.usdAmount * (allocEntries[i][1] / 100);
4396
+ const { outputCoin, estimatedOut, toDecimals } = await swapAdapter.addSwapToTx(
4397
+ tx,
4398
+ this._address,
4399
+ splitCoins[i],
4400
+ "USDC",
4401
+ asset,
4402
+ assetUsd
4403
+ );
4404
+ outputCoins.push(outputCoin);
4405
+ swapMetas.push({ asset, usdAmount: assetUsd, estimatedOut, toDecimals });
4406
+ }
4407
+ tx.transferObjects(outputCoins, this._address);
4408
+ return tx;
4409
+ });
4410
+ const digest = gasResult.digest;
4411
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4412
+ for (const meta of swapMetas) {
4413
+ const amount = meta.estimatedOut / 10 ** meta.toDecimals;
4414
+ const price = meta.usdAmount / amount;
4415
+ this.portfolio.recordBuy({
4416
+ id: `inv_${Date.now()}_${meta.asset}`,
4417
+ type: "buy",
4418
+ asset: meta.asset,
4419
+ amount,
4420
+ price,
4421
+ usdValue: meta.usdAmount,
4422
+ fee: 0,
4423
+ tx: digest,
4424
+ timestamp: now
4425
+ });
4371
4426
  this.portfolio.recordStrategyBuy(params.strategy, {
4372
- id: `strat_${Date.now()}_${asset}`,
4427
+ id: `strat_${Date.now()}_${meta.asset}`,
4373
4428
  type: "buy",
4374
- asset,
4375
- amount: result.amount,
4376
- price: result.price,
4377
- usdValue: assetUsd,
4378
- fee: result.fee,
4379
- tx: result.tx,
4380
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
4429
+ asset: meta.asset,
4430
+ amount,
4431
+ price,
4432
+ usdValue: meta.usdAmount,
4433
+ fee: 0,
4434
+ tx: digest,
4435
+ timestamp: now
4381
4436
  });
4382
- buys.push({ asset, usdAmount: assetUsd, amount: result.amount, price: result.price, tx: result.tx });
4383
- totalGas += result.gasCost;
4384
- gasMethod = result.gasMethod;
4437
+ buys.push({ asset: meta.asset, usdAmount: meta.usdAmount, amount, price, tx: digest });
4385
4438
  }
4386
- return { success: true, strategy: params.strategy, totalInvested: params.usdAmount, buys, gasCost: totalGas, gasMethod };
4439
+ return {
4440
+ success: true,
4441
+ strategy: params.strategy,
4442
+ totalInvested: params.usdAmount,
4443
+ buys,
4444
+ gasCost: gasResult.gasCostSui,
4445
+ gasMethod: gasResult.gasMethod
4446
+ };
4387
4447
  }
4388
4448
  async sellStrategy(params) {
4389
4449
  this.enforcer.assertNotLocked();