@t2000/sdk 1.0.1 → 1.1.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/browser.js CHANGED
@@ -1,5 +1,105 @@
1
1
  import '@mysten/sui/jsonRpc';
2
2
  import { normalizeSuiAddress, isValidSuiAddress } from '@mysten/sui/utils';
3
+ import { AggregatorClient, Env } from '@cetusprotocol/aggregator-sdk';
4
+
5
+ var __defProp = Object.defineProperty;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __esm = (fn, res) => function __init() {
8
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
9
+ };
10
+ var __export = (target, all) => {
11
+ for (var name in all)
12
+ __defProp(target, name, { get: all[name], enumerable: true });
13
+ };
14
+
15
+ // src/errors.ts
16
+ var errors_exports = {};
17
+ __export(errors_exports, {
18
+ T2000Error: () => T2000Error,
19
+ isMoveAbort: () => isMoveAbort,
20
+ mapMoveAbortCode: () => mapMoveAbortCode,
21
+ mapWalletError: () => mapWalletError,
22
+ parseMoveAbortMessage: () => parseMoveAbortMessage
23
+ });
24
+ function mapWalletError(error) {
25
+ const msg = error instanceof Error ? error.message : String(error);
26
+ if (msg.includes("rejected") || msg.includes("cancelled")) {
27
+ return new T2000Error("TRANSACTION_FAILED", "Transaction cancelled");
28
+ }
29
+ if (msg.includes("Insufficient") || msg.includes("insufficient")) {
30
+ return new T2000Error("INSUFFICIENT_BALANCE", "Insufficient balance");
31
+ }
32
+ return new T2000Error("UNKNOWN", msg, void 0, true);
33
+ }
34
+ function mapMoveAbortCode(code) {
35
+ const abortMessages = {
36
+ 1: "Protocol is temporarily paused",
37
+ 2: "Amount must be greater than zero",
38
+ 3: "Invalid operation type",
39
+ 4: "Fee rate exceeds maximum",
40
+ 5: "Insufficient treasury balance",
41
+ 6: "Not authorized",
42
+ 7: "Package version mismatch \u2014 upgrade required",
43
+ 8: "Timelock is active \u2014 wait for expiry",
44
+ 9: "No pending change to execute",
45
+ 10: "Already at current version",
46
+ // NAVI Protocol abort codes
47
+ 1502: "Oracle price is stale \u2014 try again in a moment",
48
+ 1503: 'Withdrawal amount is invalid (zero or dust) \u2014 try a specific amount instead of "all"',
49
+ 1600: "Health factor too low \u2014 withdrawal would risk liquidation",
50
+ 1605: "Asset borrowing is disabled or at capacity on this protocol",
51
+ // NAVI utils abort codes
52
+ 46e3: "Insufficient balance to repay \u2014 withdraw some savings first to get cash"
53
+ };
54
+ return abortMessages[code] ?? `Move abort code: ${code}`;
55
+ }
56
+ function isMoveAbort(msg) {
57
+ return msg.includes("MoveAbort") || msg.includes("MovePrimitiveRuntimeError");
58
+ }
59
+ function parseMoveAbortMessage(msg) {
60
+ const abortMatch = msg.match(/abort code:\s*(\d+)/i) ?? msg.match(/MoveAbort[^,]*,\s*(\d+)/);
61
+ if (abortMatch) {
62
+ const code = parseInt(abortMatch[1], 10);
63
+ const moduleMatch = msg.match(/Identifier\("([^"]+)"\)/) ?? msg.match(/in '([^']+)'/);
64
+ const fnMatch = msg.match(/function_name:\s*Some\("([^"]+)"\)/);
65
+ const context = `${moduleMatch?.[1] ?? ""}${fnMatch ? `::${fnMatch[1]}` : ""}`.toLowerCase();
66
+ const suffix = moduleMatch ? ` [${moduleMatch[1]}${fnMatch ? `::${fnMatch[1]}` : ""}]` : "";
67
+ if (context.includes("slippage")) {
68
+ return `Slippage too high \u2014 price moved during execution${suffix}`;
69
+ }
70
+ if (context.includes("balance::split") || context.includes("balance::ENotEnough")) {
71
+ return `Insufficient on-chain balance${suffix}`;
72
+ }
73
+ const mapped = mapMoveAbortCode(code);
74
+ return `${mapped}${suffix}`;
75
+ }
76
+ return msg;
77
+ }
78
+ var T2000Error;
79
+ var init_errors = __esm({
80
+ "src/errors.ts"() {
81
+ T2000Error = class extends Error {
82
+ code;
83
+ data;
84
+ retryable;
85
+ constructor(code, message, data, retryable = false) {
86
+ super(message);
87
+ this.name = "T2000Error";
88
+ this.code = code;
89
+ this.data = data;
90
+ this.retryable = retryable;
91
+ }
92
+ toJSON() {
93
+ return {
94
+ error: this.code,
95
+ message: this.message,
96
+ ...this.data && { data: this.data },
97
+ retryable: this.retryable
98
+ };
99
+ }
100
+ };
101
+ }
102
+ });
3
103
 
4
104
  // src/wallet/keypairSigner.ts
5
105
  var KeypairSigner = class {
@@ -45,61 +145,11 @@ var ZkLoginSigner = class {
45
145
  }
46
146
  };
47
147
 
48
- // src/errors.ts
49
- var T2000Error = class extends Error {
50
- code;
51
- data;
52
- retryable;
53
- constructor(code, message, data, retryable = false) {
54
- super(message);
55
- this.name = "T2000Error";
56
- this.code = code;
57
- this.data = data;
58
- this.retryable = retryable;
59
- }
60
- toJSON() {
61
- return {
62
- error: this.code,
63
- message: this.message,
64
- ...this.data && { data: this.data },
65
- retryable: this.retryable
66
- };
67
- }
68
- };
69
- function mapWalletError(error) {
70
- const msg = error instanceof Error ? error.message : String(error);
71
- if (msg.includes("rejected") || msg.includes("cancelled")) {
72
- return new T2000Error("TRANSACTION_FAILED", "Transaction cancelled");
73
- }
74
- if (msg.includes("Insufficient") || msg.includes("insufficient")) {
75
- return new T2000Error("INSUFFICIENT_BALANCE", "Insufficient balance");
76
- }
77
- return new T2000Error("UNKNOWN", msg, void 0, true);
78
- }
79
- function mapMoveAbortCode(code) {
80
- const abortMessages = {
81
- 1: "Protocol is temporarily paused",
82
- 2: "Amount must be greater than zero",
83
- 3: "Invalid operation type",
84
- 4: "Fee rate exceeds maximum",
85
- 5: "Insufficient treasury balance",
86
- 6: "Not authorized",
87
- 7: "Package version mismatch \u2014 upgrade required",
88
- 8: "Timelock is active \u2014 wait for expiry",
89
- 9: "No pending change to execute",
90
- 10: "Already at current version",
91
- // NAVI Protocol abort codes
92
- 1502: "Oracle price is stale \u2014 try again in a moment",
93
- 1503: 'Withdrawal amount is invalid (zero or dust) \u2014 try a specific amount instead of "all"',
94
- 1600: "Health factor too low \u2014 withdrawal would risk liquidation",
95
- 1605: "Asset borrowing is disabled or at capacity on this protocol",
96
- // NAVI utils abort codes
97
- 46e3: "Insufficient balance to repay \u2014 withdraw some savings first to get cash"
98
- };
99
- return abortMessages[code] ?? `Move abort code: ${code}`;
100
- }
148
+ // src/browser.ts
149
+ init_errors();
101
150
 
102
151
  // src/constants.ts
152
+ init_errors();
103
153
  var MIST_PER_SUI = 1000000000n;
104
154
  var SUI_DECIMALS = 9;
105
155
  var USDC_DECIMALS = 6;
@@ -165,12 +215,13 @@ var SUPPORTED_ASSETS = {
165
215
  };
166
216
  var STABLE_ASSETS = ["USDC"];
167
217
  var ALL_NAVI_ASSETS = Object.keys(SUPPORTED_ASSETS);
168
- var T2000_PACKAGE_ID = process.env.T2000_PACKAGE_ID ?? "0xd775fcc66eae26797654d435d751dea56b82eeb999de51fd285348e573b968ad";
169
- var T2000_CONFIG_ID = process.env.T2000_CONFIG_ID ?? "0x08ba26f0d260b5edf6a19c71492b3eb914906a7419baf2df1426765157e5862a";
170
- var T2000_TREASURY_ID = process.env.T2000_TREASURY_ID ?? "0xf420ec0dcad44433042fb56e1413fb88d3ff65be94fcf425ef9ff750164590e8";
218
+ process.env.T2000_PACKAGE_ID ?? "0xd775fcc66eae26797654d435d751dea56b82eeb999de51fd285348e573b968ad";
219
+ process.env.T2000_CONFIG_ID ?? "0x08ba26f0d260b5edf6a19c71492b3eb914906a7419baf2df1426765157e5862a";
220
+ var T2000_OVERLAY_FEE_WALLET = process.env.T2000_OVERLAY_FEE_WALLET ?? "0x5366efbf2b4fe5767fe2e78eb197aa5f5d138d88ac3333fbf3f80a1927da473a";
171
221
  var DEFAULT_NETWORK = "mainnet";
172
222
  process.env.T2000_API_URL ?? "https://api.t2000.ai";
173
223
  var GAS_RESERVE_MIN = 0.05;
224
+ init_errors();
174
225
  function validateAddress(address) {
175
226
  const normalized = normalizeSuiAddress(address);
176
227
  if (!isValidSuiAddress(normalized)) {
@@ -523,11 +574,12 @@ function fromBase64(b64) {
523
574
  // src/protocols/protocolFee.ts
524
575
  var FEE_RATES = {
525
576
  save: SAVE_FEE_BPS,
526
- borrow: BORROW_FEE_BPS
527
- };
528
- var OP_CODES = {
529
- save: 0,
530
- borrow: 2
577
+ borrow: BORROW_FEE_BPS,
578
+ // Swap uses Cetus's overlay-fee mechanism (taken from output by the aggregator
579
+ // and transferred to `overlayFee.receiver`). We list the rate here for display
580
+ // / quote calculations only — `addFeeTransfer` is NOT called for swaps.
581
+ swap: 10n
582
+ // 0.1%
531
583
  };
532
584
  function calculateFee(operation, amount) {
533
585
  const bps = FEE_RATES[operation];
@@ -540,22 +592,82 @@ function calculateFee(operation, amount) {
540
592
  rawAmount
541
593
  };
542
594
  }
543
- function addCollectFeeToTx(tx, paymentCoin, operation) {
544
- const bps = FEE_RATES[operation];
545
- if (bps <= 0n) return;
546
- tx.moveCall({
547
- target: `${T2000_PACKAGE_ID}::treasury::collect_fee`,
548
- typeArguments: [SUPPORTED_ASSETS.USDC.type],
549
- arguments: [
550
- tx.object(T2000_TREASURY_ID),
551
- tx.object(T2000_CONFIG_ID),
552
- paymentCoin,
553
- tx.pure.u8(OP_CODES[operation])
554
- ]
595
+ function addFeeTransfer(tx, paymentCoin, feeBps, receiver, amount) {
596
+ if (feeBps <= 0n) return;
597
+ if (amount <= 0) return;
598
+ const feeAmount = amount * Number(feeBps) / Number(BPS_DENOMINATOR);
599
+ const rawFee = usdcToRaw(feeAmount);
600
+ if (rawFee <= 0n) return;
601
+ const [feeCoin] = tx.splitCoins(paymentCoin, [tx.pure.u64(rawFee)]);
602
+ tx.transferObjects([feeCoin], tx.pure.address(receiver));
603
+ }
604
+ var OVERLAY_FEE_RATE = 1e-3;
605
+ var clientCache = /* @__PURE__ */ new Map();
606
+ function getClient(walletAddress, overlayFee) {
607
+ const rate = overlayFee?.rate ?? 0;
608
+ const receiver = overlayFee?.receiver ?? "";
609
+ const key = `${walletAddress}|${rate}|${receiver}`;
610
+ const cached = clientCache.get(key);
611
+ if (cached) return cached;
612
+ const client = new AggregatorClient({
613
+ signer: walletAddress,
614
+ env: Env.Mainnet,
615
+ ...rate > 0 && receiver ? { overlayFeeRate: rate, overlayFeeReceiver: receiver } : {}
616
+ });
617
+ clientCache.set(key, client);
618
+ return client;
619
+ }
620
+ async function findSwapRoute(params) {
621
+ const client = getClient(params.walletAddress, params.overlayFee);
622
+ const findParams = {
623
+ from: params.from,
624
+ target: params.to,
625
+ amount: params.amount.toString(),
626
+ byAmountIn: params.byAmountIn
627
+ };
628
+ const routerData = await client.findRouters(findParams);
629
+ if (!routerData) return null;
630
+ if (routerData.insufficientLiquidity) {
631
+ return {
632
+ routerData,
633
+ amountIn: routerData.amountIn.toString(),
634
+ amountOut: routerData.amountOut.toString(),
635
+ byAmountIn: params.byAmountIn,
636
+ priceImpact: normalizePriceImpact(routerData.deviationRatio),
637
+ insufficientLiquidity: true
638
+ };
639
+ }
640
+ if (routerData.error) {
641
+ const { T2000Error: T2000Error2 } = await Promise.resolve().then(() => (init_errors(), errors_exports));
642
+ throw new T2000Error2("SWAP_FAILED", `Cetus routing error: ${routerData.error.msg} (code ${routerData.error.code})`);
643
+ }
644
+ return {
645
+ routerData,
646
+ amountIn: routerData.amountIn.toString(),
647
+ amountOut: routerData.amountOut.toString(),
648
+ byAmountIn: params.byAmountIn,
649
+ priceImpact: normalizePriceImpact(routerData.deviationRatio),
650
+ insufficientLiquidity: false
651
+ };
652
+ }
653
+ function normalizePriceImpact(value) {
654
+ const n = typeof value === "number" ? value : Number(value);
655
+ return Number.isFinite(n) ? n : 0;
656
+ }
657
+ async function buildSwapTx(params) {
658
+ const client = getClient(params.walletAddress, params.overlayFee);
659
+ const clampedSlippage = Math.max(1e-3, Math.min(params.slippage, 0.05));
660
+ const outputCoin = await client.routerSwap({
661
+ router: params.route.routerData,
662
+ inputCoin: params.inputCoin,
663
+ slippage: clampedSlippage,
664
+ txb: params.tx
555
665
  });
666
+ return outputCoin;
556
667
  }
557
668
 
558
669
  // src/safeguards/errors.ts
670
+ init_errors();
559
671
  var SafeguardError = class extends T2000Error {
560
672
  rule;
561
673
  details;
@@ -599,6 +711,6 @@ var DEFAULT_SAFEGUARD_CONFIG = {
599
711
  dailyResetDate: ""
600
712
  };
601
713
 
602
- export { ALL_NAVI_ASSETS, BPS_DENOMINATOR, CLOCK_ID, COIN_REGISTRY, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, ETH_TYPE, GAS_RESERVE_MIN, IKA_TYPE, KNOWN_TARGETS, KeypairSigner, LABEL_PATTERNS, LOFI_TYPE, MANIFEST_TYPE, MIST_PER_SUI, NAVX_TYPE, OUTBOUND_OPS, STABLE_ASSETS, SUI_DECIMALS, SUI_TYPE, SUPPORTED_ASSETS, SafeguardError, T2000Error, TOKEN_MAP, USDC_DECIMALS, USDC_TYPE, USDE_TYPE, USDSUI_TYPE, USDT_TYPE, WAL_TYPE, WBTC_TYPE, ZkLoginSigner, addCollectFeeToTx, calculateFee, classifyAction, classifyLabel, classifyTransaction, extractTransferDetails, extractTxCommands, extractTxSender, fallbackLabel, formatAssetAmount, formatSui, formatUsd, fromBase64, getDecimals, getDecimalsForCoinType, getTier, isSupported, isTier1, isTier2, mapMoveAbortCode, mapWalletError, mistToSui, parseSuiRpcTx, rawToStable, rawToUsdc, refineLendingLabel, resolveSymbol, resolveTokenType, stableToRaw, suiToMist, toBase64, truncateAddress, usdcToRaw, validateAddress };
714
+ export { ALL_NAVI_ASSETS, BORROW_FEE_BPS, BPS_DENOMINATOR, CLOCK_ID, COIN_REGISTRY, DEFAULT_NETWORK, DEFAULT_SAFEGUARD_CONFIG, ETH_TYPE, GAS_RESERVE_MIN, IKA_TYPE, KNOWN_TARGETS, KeypairSigner, LABEL_PATTERNS, LOFI_TYPE, MANIFEST_TYPE, MIST_PER_SUI, NAVX_TYPE, OUTBOUND_OPS, OVERLAY_FEE_RATE, SAVE_FEE_BPS, STABLE_ASSETS, SUI_DECIMALS, SUI_TYPE, SUPPORTED_ASSETS, SafeguardError, T2000Error, T2000_OVERLAY_FEE_WALLET, TOKEN_MAP, USDC_DECIMALS, USDC_TYPE, USDE_TYPE, USDSUI_TYPE, USDT_TYPE, WAL_TYPE, WBTC_TYPE, ZkLoginSigner, addFeeTransfer, buildSwapTx, calculateFee, classifyAction, classifyLabel, classifyTransaction, extractTransferDetails, extractTxCommands, extractTxSender, fallbackLabel, findSwapRoute, formatAssetAmount, formatSui, formatUsd, fromBase64, getDecimals, getDecimalsForCoinType, getTier, isSupported, isTier1, isTier2, mapMoveAbortCode, mapWalletError, mistToSui, parseSuiRpcTx, rawToStable, rawToUsdc, refineLendingLabel, resolveSymbol, resolveTokenType, stableToRaw, suiToMist, toBase64, truncateAddress, usdcToRaw, validateAddress };
603
715
  //# sourceMappingURL=browser.js.map
604
716
  //# sourceMappingURL=browser.js.map