@t2000/sdk 1.0.1 → 1.1.2

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,11 @@ 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
+ var T2000_OVERLAY_FEE_WALLET = process.env.T2000_OVERLAY_FEE_WALLET ?? "0x5366efbf2b4fe5767fe2e78eb197aa5f5d138d88ac3333fbf3f80a1927da473a";
171
219
  var DEFAULT_NETWORK = "mainnet";
172
220
  process.env.T2000_API_URL ?? "https://api.t2000.ai";
173
221
  var GAS_RESERVE_MIN = 0.05;
222
+ init_errors();
174
223
  function validateAddress(address) {
175
224
  const normalized = normalizeSuiAddress(address);
176
225
  if (!isValidSuiAddress(normalized)) {
@@ -523,11 +572,12 @@ function fromBase64(b64) {
523
572
  // src/protocols/protocolFee.ts
524
573
  var FEE_RATES = {
525
574
  save: SAVE_FEE_BPS,
526
- borrow: BORROW_FEE_BPS
527
- };
528
- var OP_CODES = {
529
- save: 0,
530
- borrow: 2
575
+ borrow: BORROW_FEE_BPS,
576
+ // Swap uses Cetus's overlay-fee mechanism (taken from output by the aggregator
577
+ // and transferred to `overlayFee.receiver`). We list the rate here for display
578
+ // / quote calculations only — `addFeeTransfer` is NOT called for swaps.
579
+ swap: 10n
580
+ // 0.1%
531
581
  };
532
582
  function calculateFee(operation, amount) {
533
583
  const bps = FEE_RATES[operation];
@@ -540,22 +590,82 @@ function calculateFee(operation, amount) {
540
590
  rawAmount
541
591
  };
542
592
  }
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
- ]
593
+ function addFeeTransfer(tx, paymentCoin, feeBps, receiver, amount) {
594
+ if (feeBps <= 0n) return;
595
+ if (amount <= 0) return;
596
+ const feeAmount = amount * Number(feeBps) / Number(BPS_DENOMINATOR);
597
+ const rawFee = usdcToRaw(feeAmount);
598
+ if (rawFee <= 0n) return;
599
+ const [feeCoin] = tx.splitCoins(paymentCoin, [tx.pure.u64(rawFee)]);
600
+ tx.transferObjects([feeCoin], tx.pure.address(receiver));
601
+ }
602
+ var OVERLAY_FEE_RATE = 1e-3;
603
+ var clientCache = /* @__PURE__ */ new Map();
604
+ function getClient(walletAddress, overlayFee) {
605
+ const rate = overlayFee?.rate ?? 0;
606
+ const receiver = overlayFee?.receiver ?? "";
607
+ const key = `${walletAddress}|${rate}|${receiver}`;
608
+ const cached = clientCache.get(key);
609
+ if (cached) return cached;
610
+ const client = new AggregatorClient({
611
+ signer: walletAddress,
612
+ env: Env.Mainnet,
613
+ ...rate > 0 && receiver ? { overlayFeeRate: rate, overlayFeeReceiver: receiver } : {}
614
+ });
615
+ clientCache.set(key, client);
616
+ return client;
617
+ }
618
+ async function findSwapRoute(params) {
619
+ const client = getClient(params.walletAddress, params.overlayFee);
620
+ const findParams = {
621
+ from: params.from,
622
+ target: params.to,
623
+ amount: params.amount.toString(),
624
+ byAmountIn: params.byAmountIn
625
+ };
626
+ const routerData = await client.findRouters(findParams);
627
+ if (!routerData) return null;
628
+ if (routerData.insufficientLiquidity) {
629
+ return {
630
+ routerData,
631
+ amountIn: routerData.amountIn.toString(),
632
+ amountOut: routerData.amountOut.toString(),
633
+ byAmountIn: params.byAmountIn,
634
+ priceImpact: normalizePriceImpact(routerData.deviationRatio),
635
+ insufficientLiquidity: true
636
+ };
637
+ }
638
+ if (routerData.error) {
639
+ const { T2000Error: T2000Error2 } = await Promise.resolve().then(() => (init_errors(), errors_exports));
640
+ throw new T2000Error2("SWAP_FAILED", `Cetus routing error: ${routerData.error.msg} (code ${routerData.error.code})`);
641
+ }
642
+ return {
643
+ routerData,
644
+ amountIn: routerData.amountIn.toString(),
645
+ amountOut: routerData.amountOut.toString(),
646
+ byAmountIn: params.byAmountIn,
647
+ priceImpact: normalizePriceImpact(routerData.deviationRatio),
648
+ insufficientLiquidity: false
649
+ };
650
+ }
651
+ function normalizePriceImpact(value) {
652
+ const n = typeof value === "number" ? value : Number(value);
653
+ return Number.isFinite(n) ? n : 0;
654
+ }
655
+ async function buildSwapTx(params) {
656
+ const client = getClient(params.walletAddress, params.overlayFee);
657
+ const clampedSlippage = Math.max(1e-3, Math.min(params.slippage, 0.05));
658
+ const outputCoin = await client.routerSwap({
659
+ router: params.route.routerData,
660
+ inputCoin: params.inputCoin,
661
+ slippage: clampedSlippage,
662
+ txb: params.tx
555
663
  });
664
+ return outputCoin;
556
665
  }
557
666
 
558
667
  // src/safeguards/errors.ts
668
+ init_errors();
559
669
  var SafeguardError = class extends T2000Error {
560
670
  rule;
561
671
  details;
@@ -599,6 +709,6 @@ var DEFAULT_SAFEGUARD_CONFIG = {
599
709
  dailyResetDate: ""
600
710
  };
601
711
 
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 };
712
+ 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
713
  //# sourceMappingURL=browser.js.map
604
714
  //# sourceMappingURL=browser.js.map