@t2000/engine 0.5.6 → 0.5.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.
package/dist/index.d.ts CHANGED
@@ -798,10 +798,19 @@ declare const healthCheckTool: Tool<{}, {
798
798
 
799
799
  declare const ratesInfoTool: Tool<{}, _t2000_sdk.RatesResult>;
800
800
 
801
+ interface TxRecord {
802
+ digest: string;
803
+ action: string;
804
+ amount?: number;
805
+ asset?: string;
806
+ recipient?: string;
807
+ timestamp: number;
808
+ gasCost?: number;
809
+ }
801
810
  declare const transactionHistoryTool: Tool<{
802
811
  limit?: number | undefined;
803
812
  }, {
804
- transactions: _t2000_sdk.TransactionRecord[];
813
+ transactions: TxRecord[];
805
814
  count: number;
806
815
  }>;
807
816
 
@@ -812,7 +821,7 @@ declare const saveDepositTool: Tool<{
812
821
  success: boolean;
813
822
  tx: string;
814
823
  amount: number;
815
- asset: "SUI" | "USDC" | "USDT" | "USDe" | "USDsui";
824
+ asset: string;
816
825
  apy: number;
817
826
  fee: number;
818
827
  gasCost: number;
@@ -826,6 +835,7 @@ declare const withdrawTool: Tool<{
826
835
  success: boolean;
827
836
  tx: string;
828
837
  amount: number;
838
+ asset: string;
829
839
  gasCost: number;
830
840
  }>;
831
841
 
@@ -1077,6 +1087,6 @@ declare function fetchWalletCoins(address: string, rpcUrl?: string): Promise<Wal
1077
1087
  declare function fetchTokenPrices(coinTypes: string[]): Promise<Record<string, number>>;
1078
1088
  declare function clearPriceCache(): void;
1079
1089
 
1080
- declare const DEFAULT_SYSTEM_PROMPT = "You are a financial agent on Sui. You manage money and access paid APIs via MPP micropayments.\n\n## Response rules\n- 1-2 sentences max. No bullet lists unless asked. No preambles.\n- Never say \"Would you like me to...\", \"Sure!\", \"Great question!\", \"Absolutely!\" \u2014 just do it or say you can't.\n- Lead with the result. After tool calls, state the outcome with real numbers. Done.\n- Present amounts as $1,234.56 and rates as X.XX% APY.\n- Show top 3 results unless asked for more. Summarize totals in one line.\n\n## Execution rule\nOnly offer to execute actions you have tools for. If you retrieved a quote, data, or information but have no tool to act on it, give the user the result and tell them where to execute manually \u2014 in one sentence. Never say \"Would you like me to proceed?\" unless you have a tool that can actually proceed.\n\n## Before acting\n- ALWAYS call a read tool first before any write tool \u2014 balance_check before save/send/borrow, savings_info before withdraw.\n- Show real numbers from tools \u2014 never fabricate rates, amounts, or balances.\n- When user says \"all\" or an imprecise amount, call the read tool first to get the exact number.\n\n## Tool usage\n- Use tools proactively \u2014 don't refuse requests you can handle.\n- For real-world questions (weather, search, news, prices), use pay_api. Tell the user the cost first.\n- For broad market data (yields across protocols, token prices, TVL, protocol comparisons), use defillama_* tools.\n- To discover Sui protocols, use defillama_sui_protocols first, then defillama_protocol_info with the slug.\n- Run multiple read-only tools in parallel when you need several data points.\n- If a tool errors, say what went wrong and what to try instead. One sentence.\n\n## Multi-step flows\n- \"How much X for Y?\": swap_quote first, then swap_execute if user confirms.\n- \"Swap then save\": swap_execute \u2192 balance_check \u2192 save_deposit. Confirm each step.\n- \"Buy $X of token\": defillama_token_prices \u2192 calculate amount \u2192 swap_execute.\n- \"Best yield on SUI\": compare rates_info (NAVI lending) + defillama_yield_pools (broader) + volo_stats.\n- save_deposit supports any NAVI asset: USDC (default), USDT, SUI, USDe, USDsui. Pass asset param for non-USDC.\n- \"Deposit SUI to earn yield\": save_deposit with asset=\"SUI\" for NAVI lending, or volo_stake for liquid staking.\n- \"What protocols are on Sui?\": defillama_sui_protocols \u2192 defillama_protocol_info for details.\n\n## Safety\n- Never encourage risky financial behavior.\n- Warn when health factor < 1.5.\n- All amounts in USDC unless stated otherwise.";
1090
+ declare const DEFAULT_SYSTEM_PROMPT = "You are a financial agent on Sui. You manage money and access paid APIs via MPP micropayments.\n\n## Response rules\n- 1-2 sentences max. No bullet lists unless asked. No preambles.\n- Never say \"Would you like me to...\", \"Sure!\", \"Great question!\", \"Absolutely!\" \u2014 just do it or say you can't.\n- Lead with the result. After tool calls, state the outcome with real numbers. Done.\n- Present amounts as $1,234.56 and rates as X.XX% APY.\n- Show top 3 results unless asked for more. Summarize totals in one line.\n\n## Execution rule\nOnly offer to execute actions you have tools for. If you retrieved a quote, data, or information but have no tool to act on it, give the user the result and tell them where to execute manually \u2014 in one sentence. Never say \"Would you like me to proceed?\" unless you have a tool that can actually proceed.\n\n## Before acting\n- ALWAYS call a read tool first before any write tool \u2014 balance_check before save/send/borrow, savings_info before withdraw.\n- Show real numbers from tools \u2014 never fabricate rates, amounts, or balances.\n- When user says \"all\" or an imprecise amount, call the read tool first to get the exact number.\n\n## Tool usage\n- Use tools proactively \u2014 don't refuse requests you can handle.\n- For real-world questions (weather, search, news, prices), use pay_api. Tell the user the cost first.\n- For broad market data (yields across protocols, token prices, TVL, protocol comparisons), use defillama_* tools.\n- To discover Sui protocols, use defillama_sui_protocols first, then defillama_protocol_info with the slug.\n- Run multiple read-only tools in parallel when you need several data points.\n- If a tool errors, say what went wrong and what to try instead. One sentence.\n\n## Multi-step flows\n- \"How much X for Y?\": swap_quote first, then swap_execute if user confirms.\n- \"Swap then save\": swap_execute \u2192 balance_check \u2192 save_deposit. Confirm each step.\n- \"Buy $X of token\": defillama_token_prices \u2192 calculate amount \u2192 swap_execute.\n- \"Best yield on SUI\": compare rates_info (NAVI lending) + defillama_yield_pools (broader) + volo_stats.\n- save_deposit supports any NAVI asset: USDC (default), USDT, SUI, WAL, ETH, NAVX, GOLD, USDe, USDsui. Pass asset param for non-USDC.\n- withdraw supports any deposited NAVI asset. Pass asset param to withdraw a specific token.\n- \"Deposit WAL/ETH/SUI to earn yield\": save_deposit with asset=\"WAL\"/\"ETH\"/\"SUI\" for NAVI lending, or volo_stake for SUI liquid staking.\n- \"What protocols are on Sui?\": defillama_sui_protocols \u2192 defillama_protocol_info for details.\n\n## Safety\n- Never encourage risky financial behavior.\n- Warn when health factor < 1.5.\n- All amounts in USDC unless stated otherwise.";
1081
1091
 
1082
1092
  export { AnthropicProvider, type AnthropicProviderConfig, type BalancePrices, type BalanceResult, type BuildToolOptions, type ChatParams, type CompactOptions, type ContentBlock, type CostSnapshot, CostTracker, type CostTrackerConfig, DEFAULT_SYSTEM_PROMPT, type EngineConfig, type EngineEvent, type HealthFactorResult, type LLMProvider, type McpCallResult, McpClientManager, McpResponseCache, type McpServerConfig, type McpServerConnection, type McpToolAdapterConfig, type McpToolDescriptor, MemorySessionStore, type Message, NAVI_MCP_CONFIG, NAVI_MCP_URL, NAVI_SERVER_NAME, type NaviRawCoin, type NaviRawHealthFactor, type NaviRawPool, type NaviRawPosition, type NaviRawPositionsResponse, type NaviRawProtocolStats, type NaviRawRewardsResponse, type NaviReadOptions, NaviTools, type PendingAction, type PendingReward, type PendingToolCall, type PermissionLevel, type PermissionResponse, type PositionEntry, type ProtocolStats, type ProviderEvent, QueryEngine, READ_TOOLS, type RatesResult, type SSEEvent, type SavingsResult, type ServerPositionData, type SessionData, type SessionStore, type StopReason, type SuiCoinBalance, type Tool, type ToolChoice, type ToolContext, type ToolDefinition, type ToolJsonSchema, type ToolResult, TxMutex, WRITE_TOOLS, type WalletCoin, adaptAllMcpTools, adaptAllServerTools, adaptMcpTool, balanceCheckTool, borrowTool, buildMcpTools, buildTool, claimRewardsTool, clearPriceCache, compactMessages, defillamaChainTvlTool, defillamaPriceChangeTool, defillamaProtocolFeesTool, defillamaProtocolInfoTool, defillamaSuiProtocolsTool, defillamaTokenPricesTool, defillamaYieldPoolsTool, engineToSSE, estimateTokens, extractMcpText, fetchAvailableRewards, fetchBalance, fetchHealthFactor, fetchPositions, fetchProtocolStats, fetchRates, fetchSavings, fetchTokenPrices, fetchWalletCoins, findTool, getDefaultTools, getMcpManager, getWalletAddress, hasNaviMcp, healthCheckTool, mppServicesTool, parseMcpJson, parseSSE, payApiTool, ratesInfoTool, registerEngineTools, repayDebtTool, requireAgent, runTools, saveContactTool, saveDepositTool, savingsInfoTool, sendTransferTool, serializeSSE, swapExecuteTool, swapQuoteTool, toolsToDefinitions, transactionHistoryTool, transformBalance, transformHealthFactor, transformPositions, transformRates, transformRewards, transformSavings, validateHistory, voloStakeTool, voloStatsTool, voloUnstakeTool, withdrawTool };
package/dist/index.js CHANGED
@@ -161,7 +161,10 @@ var KNOWN_COINS = {
161
161
  "0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN": { symbol: "USDT", decimals: 6 },
162
162
  "0x375f70cf2ae4c00bf37117d0c85a2c71545e6ee05c4a5c7d282cd66a4504b068::usdt::USDT": { symbol: "USDT", decimals: 6 },
163
163
  "0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH": { symbol: "ETH", decimals: 8 },
164
- "0x0041f9f9344cac094454cd574e333c4fdb132d7bcc9379bcd4aab485b2a63942::wbtc::WBTC": { symbol: "BTC", decimals: 8 }
164
+ "0x0041f9f9344cac094454cd574e333c4fdb132d7bcc9379bcd4aab485b2a63942::wbtc::WBTC": { symbol: "BTC", decimals: 8 },
165
+ "0x356a26eb9e012a68958082340d4c4116e7f55615cf27affcff209cf0ae544f59::wal::WAL": { symbol: "WAL", decimals: 9 },
166
+ "0xa99b8952d4f7d947ea77fe0ecdcc9e5fc0bcab2841d6e2a5aa00c3044e5544b5::navx::NAVX": { symbol: "NAVX", decimals: 9 },
167
+ "0x9d297676e7a4b771ab023291377b2adfaa4938fb9080b8d12430e4b108b836a9::xaum::XAUM": { symbol: "GOLD", decimals: 6 }
165
168
  };
166
169
  async function fetchWalletCoins(address, rpcUrl) {
167
170
  const url = rpcUrl || SUI_MAINNET_URL;
@@ -866,6 +869,97 @@ var ratesInfoTool = buildTool({
866
869
  };
867
870
  }
868
871
  });
872
+ var SUI_TYPE = "0x2::sui::SUI";
873
+ var KNOWN_TARGETS = [
874
+ [/::suilend|::obligation/, "lending"],
875
+ [/::navi|::incentive_v\d+|::oracle_pro/, "lending"],
876
+ [/::cetus|::pool/, "swap"],
877
+ [/::deepbook/, "swap"],
878
+ [/::transfer::public_transfer/, "send"]
879
+ ];
880
+ function resolveOwner(owner) {
881
+ if (typeof owner === "object" && owner.AddressOwner) return owner.AddressOwner;
882
+ if (typeof owner === "string") return owner;
883
+ return null;
884
+ }
885
+ function classifyAction(targets, commandTypes) {
886
+ for (const target of targets) {
887
+ for (const [pattern, label] of KNOWN_TARGETS) {
888
+ if (pattern.test(target)) return label;
889
+ }
890
+ }
891
+ if (commandTypes.includes("TransferObjects") && !commandTypes.includes("MoveCall")) return "send";
892
+ return "transaction";
893
+ }
894
+ function parseRpcTx(tx, address) {
895
+ const gasUsed = tx.effects?.gasUsed;
896
+ const gasCost = gasUsed ? (Number(gasUsed.computationCost) + Number(gasUsed.storageCost) - Number(gasUsed.storageRebate)) / 1e9 : void 0;
897
+ const moveCallTargets = [];
898
+ const commandTypes = [];
899
+ try {
900
+ const data = tx.transaction?.data;
901
+ const inner = data?.transaction;
902
+ const commands = inner?.commands;
903
+ if (commands) {
904
+ for (const cmd of commands) {
905
+ if (cmd.MoveCall) {
906
+ const mc = cmd.MoveCall;
907
+ moveCallTargets.push(`${mc.package}::${mc.module}::${mc.function}`);
908
+ commandTypes.push("MoveCall");
909
+ } else if (cmd.TransferObjects) {
910
+ commandTypes.push("TransferObjects");
911
+ }
912
+ }
913
+ }
914
+ } catch {
915
+ }
916
+ const changes = tx.balanceChanges ?? [];
917
+ const outflows = changes.filter((c) => resolveOwner(c.owner) === address && BigInt(c.amount) < 0n);
918
+ const inflows = changes.filter((c) => resolveOwner(c.owner) !== address && BigInt(c.amount) > 0n);
919
+ const primaryOutflow = outflows.filter((c) => c.coinType !== SUI_TYPE).sort((a, b) => Number(BigInt(a.amount) - BigInt(b.amount)))[0] ?? outflows[0];
920
+ let amount;
921
+ let asset;
922
+ let recipient;
923
+ if (primaryOutflow) {
924
+ const coinType = primaryOutflow.coinType;
925
+ const decimals = coinType.includes("::usdc::") ? 6 : 9;
926
+ amount = Math.abs(Number(BigInt(primaryOutflow.amount))) / 10 ** decimals;
927
+ asset = coinType === SUI_TYPE ? "SUI" : coinType.includes("::usdc::") ? "USDC" : coinType.split("::").pop() ?? "unknown";
928
+ const recipientChange = inflows.find((c) => c.coinType === coinType);
929
+ recipient = recipientChange ? resolveOwner(recipientChange.owner) ?? void 0 : void 0;
930
+ }
931
+ return {
932
+ digest: tx.digest,
933
+ action: classifyAction(moveCallTargets, commandTypes),
934
+ amount,
935
+ asset,
936
+ recipient,
937
+ timestamp: Number(tx.timestampMs ?? 0),
938
+ gasCost
939
+ };
940
+ }
941
+ async function queryHistoryRpc(rpcUrl, address, limit) {
942
+ const res = await fetch(rpcUrl, {
943
+ method: "POST",
944
+ headers: { "Content-Type": "application/json" },
945
+ body: JSON.stringify({
946
+ jsonrpc: "2.0",
947
+ id: 1,
948
+ method: "suix_queryTransactionBlocks",
949
+ params: [
950
+ { filter: { FromAddress: address }, options: { showEffects: true, showInput: true, showBalanceChanges: true } },
951
+ null,
952
+ limit,
953
+ true
954
+ ]
955
+ }),
956
+ signal: AbortSignal.timeout(1e4)
957
+ });
958
+ if (!res.ok) throw new Error(`Sui RPC error: ${res.status}`);
959
+ const json = await res.json();
960
+ if (json.error) throw new Error(`RPC error: ${json.error.message}`);
961
+ return (json.result?.data ?? []).map((tx) => parseRpcTx(tx, address));
962
+ }
869
963
  var transactionHistoryTool = buildTool({
870
964
  name: "transaction_history",
871
965
  description: "Retrieve recent transaction history: past sends, saves, withdrawals, borrows, repayments, and rewards claims. Optionally limit the number of results.",
@@ -883,33 +977,41 @@ var transactionHistoryTool = buildTool({
883
977
  },
884
978
  isReadOnly: true,
885
979
  async call(input, context) {
886
- const agent = requireAgent(context);
887
- const records = await agent.history({ limit: input.limit ?? 10 });
980
+ const limit = input.limit ?? 10;
981
+ if (context.agent) {
982
+ const agent = requireAgent(context);
983
+ const records2 = await agent.history({ limit });
984
+ return {
985
+ data: { transactions: records2, count: records2.length },
986
+ displayText: `${records2.length} recent transaction(s)`
987
+ };
988
+ }
989
+ if (!context.walletAddress || !context.suiRpcUrl) {
990
+ throw new Error("Transaction history requires a wallet address");
991
+ }
992
+ const records = await queryHistoryRpc(context.suiRpcUrl, context.walletAddress, limit);
888
993
  return {
889
- data: {
890
- transactions: records,
891
- count: records.length
892
- },
994
+ data: { transactions: records, count: records.length },
893
995
  displayText: `${records.length} recent transaction(s)`
894
996
  };
895
997
  }
896
998
  });
897
999
  var saveDepositTool = buildTool({
898
1000
  name: "save_deposit",
899
- description: "Deposit into NAVI lending to earn yield. Supports USDC (default), USDT, SUI, and other NAVI-supported assets. Always call balance_check first to know the available amount.",
1001
+ description: "Deposit into NAVI lending to earn yield. Supports any NAVI-listed asset: USDC, USDT, SUI, WAL, ETH, NAVX, GOLD, USDe, USDsui. Always call balance_check first to know the available amount.",
900
1002
  inputSchema: z.object({
901
1003
  amount: z.number().positive(),
902
- asset: z.string().optional().describe("Asset to deposit (default: USDC). Options: USDC, USDT, SUI, USDe, USDsui")
1004
+ asset: z.string().optional().describe("Asset to deposit (default: USDC). Supports: USDC, USDT, SUI, WAL, ETH, NAVX, GOLD, USDe, USDsui")
903
1005
  }),
904
1006
  jsonSchema: {
905
1007
  type: "object",
906
1008
  properties: {
907
1009
  amount: {
908
- description: "Exact amount to save (call balance_check first to get available amount)"
1010
+ description: "Exact amount to save in token units (call balance_check first)"
909
1011
  },
910
1012
  asset: {
911
1013
  type: "string",
912
- description: "Asset to deposit (default: USDC). Options: USDC, USDT, SUI, USDe, USDsui"
1014
+ description: "Asset to deposit (default: USDC). Supports: USDC, USDT, SUI, WAL, ETH, NAVX, GOLD, USDe, USDsui"
913
1015
  }
914
1016
  },
915
1017
  required: ["amount"]
@@ -931,16 +1033,16 @@ var saveDepositTool = buildTool({
931
1033
  gasCost: result.gasCost,
932
1034
  savingsBalance: result.savingsBalance
933
1035
  },
934
- displayText: `Saved ${result.amount.toFixed(2)} ${asset} at ${(result.apy * 100).toFixed(2)}% APY (tx: ${result.tx.slice(0, 8)}\u2026)`
1036
+ displayText: `Saved ${result.amount.toFixed(result.amount < 1 ? 6 : 2)} ${asset} at ${(result.apy * 100).toFixed(2)}% APY (tx: ${result.tx.slice(0, 8)}\u2026)`
935
1037
  };
936
1038
  }
937
1039
  });
938
1040
  var withdrawTool = buildTool({
939
1041
  name: "withdraw",
940
- description: "Withdraw from NAVI lending back to wallet. Supports any deposited asset (USDC, USDT, SUI, etc). Always call savings_info first. Checks health factor to prevent liquidation if there is outstanding debt.",
1042
+ description: "Withdraw from NAVI lending back to wallet. Supports any deposited asset (USDC, USDT, SUI, WAL, ETH, NAVX, GOLD, etc). Always call savings_info first. Checks health factor to prevent liquidation if there is outstanding debt.",
941
1043
  inputSchema: z.object({
942
1044
  amount: z.number().positive(),
943
- asset: z.string().optional().describe("Asset to withdraw (default: picks largest position). Options: USDC, USDT, SUI, USDe, USDsui")
1045
+ asset: z.string().optional().describe("Asset to withdraw (default: picks largest position). Supports: USDC, USDT, SUI, WAL, ETH, NAVX, GOLD, USDe, USDsui")
944
1046
  }),
945
1047
  jsonSchema: {
946
1048
  type: "object",
@@ -950,7 +1052,7 @@ var withdrawTool = buildTool({
950
1052
  },
951
1053
  asset: {
952
1054
  type: "string",
953
- description: "Asset to withdraw (default: picks largest position). Options: USDC, USDT, SUI, USDe, USDsui"
1055
+ description: "Asset to withdraw (default: picks largest position). Supports: USDC, USDT, SUI, WAL, ETH, NAVX, GOLD, USDe, USDsui"
954
1056
  }
955
1057
  },
956
1058
  required: ["amount"]
@@ -963,14 +1065,16 @@ var withdrawTool = buildTool({
963
1065
  amount: input.amount,
964
1066
  asset: input.asset
965
1067
  });
1068
+ const withdrawnAsset = result.asset ?? input.asset ?? "";
966
1069
  return {
967
1070
  data: {
968
1071
  success: result.success,
969
1072
  tx: result.tx,
970
1073
  amount: result.amount,
1074
+ asset: withdrawnAsset,
971
1075
  gasCost: result.gasCost
972
1076
  },
973
- displayText: `Withdrew ${result.amount.toFixed(2)}${input.asset ? " " + input.asset : ""} (tx: ${result.tx.slice(0, 8)}\u2026)`
1077
+ displayText: `Withdrew ${result.amount.toFixed(result.amount < 1 ? 6 : 2)}${withdrawnAsset ? " " + withdrawnAsset : ""} (tx: ${result.tx.slice(0, 8)}\u2026)`
974
1078
  };
975
1079
  }
976
1080
  });
@@ -1753,8 +1857,9 @@ Only offer to execute actions you have tools for. If you retrieved a quote, data
1753
1857
  - "Swap then save": swap_execute \u2192 balance_check \u2192 save_deposit. Confirm each step.
1754
1858
  - "Buy $X of token": defillama_token_prices \u2192 calculate amount \u2192 swap_execute.
1755
1859
  - "Best yield on SUI": compare rates_info (NAVI lending) + defillama_yield_pools (broader) + volo_stats.
1756
- - save_deposit supports any NAVI asset: USDC (default), USDT, SUI, USDe, USDsui. Pass asset param for non-USDC.
1757
- - "Deposit SUI to earn yield": save_deposit with asset="SUI" for NAVI lending, or volo_stake for liquid staking.
1860
+ - save_deposit supports any NAVI asset: USDC (default), USDT, SUI, WAL, ETH, NAVX, GOLD, USDe, USDsui. Pass asset param for non-USDC.
1861
+ - withdraw supports any deposited NAVI asset. Pass asset param to withdraw a specific token.
1862
+ - "Deposit WAL/ETH/SUI to earn yield": save_deposit with asset="WAL"/"ETH"/"SUI" for NAVI lending, or volo_stake for SUI liquid staking.
1758
1863
  - "What protocols are on Sui?": defillama_sui_protocols \u2192 defillama_protocol_info for details.
1759
1864
 
1760
1865
  ## Safety