@clonegod/ttd-sui-common 1.0.101 → 2.0.1

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.
Files changed (126) hide show
  1. package/dist/appconfig/SuiQuoteAppConfig.d.ts +10 -0
  2. package/dist/appconfig/SuiQuoteAppConfig.js +35 -0
  3. package/dist/appconfig/SuiTradeAppConfig.d.ts +7 -0
  4. package/dist/appconfig/SuiTradeAppConfig.js +13 -0
  5. package/dist/appconfig/ensure_core_env.d.ts +1 -0
  6. package/dist/appconfig/ensure_core_env.js +18 -0
  7. package/dist/appconfig/index.d.ts +5 -0
  8. package/dist/appconfig/index.js +21 -0
  9. package/dist/appconfig/sui_dex_env_args.d.ts +5 -0
  10. package/dist/appconfig/sui_dex_env_args.js +28 -0
  11. package/dist/appconfig/sui_env_args.d.ts +4 -0
  12. package/dist/appconfig/sui_env_args.js +20 -0
  13. package/dist/grpc/gas-price-cache.js +19 -32
  14. package/dist/grpc/grpc-connection.js +5 -3
  15. package/dist/grpc/grpc_provider_registry.d.ts +14 -0
  16. package/dist/grpc/grpc_provider_registry.js +60 -0
  17. package/dist/grpc/index.d.ts +3 -0
  18. package/dist/grpc/index.js +13 -1
  19. package/dist/grpc/ledger-service.js +107 -128
  20. package/dist/grpc/proto_value.d.ts +4 -0
  21. package/dist/grpc/proto_value.js +59 -0
  22. package/dist/grpc/state-service.d.ts +1 -0
  23. package/dist/grpc/state-service.js +99 -102
  24. package/dist/grpc/sui-grpc-client.js +2 -13
  25. package/dist/grpc/sui_object_reader.d.ts +15 -0
  26. package/dist/grpc/sui_object_reader.js +60 -0
  27. package/dist/grpc/transaction-service.js +26 -37
  28. package/dist/index.d.ts +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/quote/abstract_dex_quote.d.ts +60 -0
  31. package/dist/quote/abstract_dex_quote.js +186 -0
  32. package/dist/quote/chain_ops.d.ts +17 -0
  33. package/dist/quote/chain_ops.js +52 -0
  34. package/dist/quote/index.d.ts +7 -0
  35. package/dist/quote/index.js +7 -0
  36. package/dist/quote/pool_event.d.ts +21 -0
  37. package/dist/quote/pool_event.js +6 -0
  38. package/dist/quote/pricing/token_price_cache.js +18 -29
  39. package/dist/quote/quote_amount.d.ts +4 -0
  40. package/dist/quote/quote_amount.js +24 -0
  41. package/dist/quote/quote_trace.d.ts +16 -0
  42. package/dist/quote/quote_trace.js +40 -0
  43. package/dist/quote/tick/clmm_v3_engine.d.ts +32 -0
  44. package/dist/quote/tick/clmm_v3_engine.js +48 -0
  45. package/dist/quote/tick/index.d.ts +4 -0
  46. package/dist/quote/tick/index.js +20 -0
  47. package/dist/quote/tick/local_clmm_state.d.ts +17 -0
  48. package/dist/quote/tick/local_clmm_state.js +22 -0
  49. package/dist/quote/tick/sui_clmm_tick_cache.d.ts +42 -0
  50. package/dist/quote/tick/sui_clmm_tick_cache.js +163 -0
  51. package/dist/quote/tick/sui_tick_data_provider.d.ts +2 -0
  52. package/dist/quote/tick/sui_tick_data_provider.js +6 -0
  53. package/dist/quote/verify/index.d.ts +1 -0
  54. package/dist/quote/verify/index.js +17 -0
  55. package/dist/quote/verify/quote_price_verify.d.ts +30 -0
  56. package/dist/quote/verify/quote_price_verify.js +247 -0
  57. package/dist/redis/redis_client.d.ts +1 -0
  58. package/dist/redis/redis_client.js +88 -117
  59. package/dist/rpc/index.js +59 -75
  60. package/dist/test/test.js +1 -1
  61. package/dist/test/test_checkpoint.js +4 -13
  62. package/dist/test/test_grpc.js +32 -41
  63. package/dist/trade/abstract_sui_dex_trade.d.ts +43 -0
  64. package/dist/trade/abstract_sui_dex_trade.js +380 -0
  65. package/dist/trade/abstract_sui_dex_trade_plus.d.ts +3 -1
  66. package/dist/trade/abstract_sui_dex_trade_plus.js +232 -212
  67. package/dist/trade/check/tx_result_checker.js +65 -75
  68. package/dist/trade/coin/index.d.ts +1 -0
  69. package/dist/trade/coin/index.js +17 -0
  70. package/dist/trade/coin/lua_scripts.d.ts +5 -0
  71. package/dist/trade/coin/lua_scripts.js +130 -0
  72. package/dist/trade/coin/types.d.ts +30 -0
  73. package/dist/trade/coin/types.js +2 -0
  74. package/dist/trade/coin/wallet_coin_ledger.d.ts +22 -0
  75. package/dist/trade/coin/wallet_coin_ledger.js +85 -0
  76. package/dist/trade/executor/central_executor.d.ts +72 -0
  77. package/dist/trade/executor/central_executor.js +240 -0
  78. package/dist/trade/executor/coin_cache.d.ts +21 -0
  79. package/dist/trade/executor/coin_cache.js +143 -0
  80. package/dist/trade/executor/coin_maintainer.d.ts +32 -0
  81. package/dist/trade/executor/coin_maintainer.js +123 -0
  82. package/dist/trade/executor/core_channel.d.ts +38 -0
  83. package/dist/trade/executor/core_channel.js +131 -0
  84. package/dist/trade/executor/data_channel.d.ts +27 -0
  85. package/dist/trade/executor/data_channel.js +2 -0
  86. package/dist/trade/executor/effects.d.ts +16 -0
  87. package/dist/trade/executor/effects.js +63 -0
  88. package/dist/trade/executor/executor_client.d.ts +13 -0
  89. package/dist/trade/executor/executor_client.js +55 -0
  90. package/dist/trade/executor/executor_protocol.d.ts +26 -0
  91. package/dist/trade/executor/executor_protocol.js +32 -0
  92. package/dist/trade/executor/executor_server.d.ts +8 -0
  93. package/dist/trade/executor/executor_server.js +33 -0
  94. package/dist/trade/executor/executor_ws_client.d.ts +13 -0
  95. package/dist/trade/executor/executor_ws_client.js +58 -0
  96. package/dist/trade/executor/grpc_channel.d.ts +14 -0
  97. package/dist/trade/executor/grpc_channel.js +73 -0
  98. package/dist/trade/executor/index.d.ts +7 -0
  99. package/dist/trade/executor/index.js +23 -0
  100. package/dist/trade/executor/json_rpc_channel.d.ts +14 -0
  101. package/dist/trade/executor/json_rpc_channel.js +77 -0
  102. package/dist/trade/index.d.ts +5 -1
  103. package/dist/trade/index.js +5 -1
  104. package/dist/trade/parse/sui_tx_parser.js +98 -81
  105. package/dist/trade/send_tx/index.js +34 -47
  106. package/dist/trade/swap/builders/bluefin.d.ts +9 -0
  107. package/dist/trade/swap/builders/bluefin.js +60 -0
  108. package/dist/trade/swap/builders/cetus_magma.d.ts +13 -0
  109. package/dist/trade/swap/builders/cetus_magma.js +52 -0
  110. package/dist/trade/swap/builders/momentum.d.ts +9 -0
  111. package/dist/trade/swap/builders/momentum.js +80 -0
  112. package/dist/trade/swap/dex_swap_config.d.ts +28 -0
  113. package/dist/trade/swap/dex_swap_config.js +40 -0
  114. package/dist/trade/swap/index.d.ts +7 -0
  115. package/dist/trade/swap/index.js +36 -0
  116. package/dist/trade/swap/types.d.ts +20 -0
  117. package/dist/trade/swap/types.js +2 -0
  118. package/dist/trade/test/test_parse_sui_tx_result.js +33 -44
  119. package/dist/trade/tx_result_channel.d.ts +7 -0
  120. package/dist/trade/tx_result_channel.js +7 -0
  121. package/dist/utils/decode.js +1 -2
  122. package/dist/utils/index.d.ts +1 -0
  123. package/dist/utils/index.js +1 -0
  124. package/dist/utils/trade_direction.d.ts +14 -0
  125. package/dist/utils/trade_direction.js +23 -0
  126. package/package.json +3 -2
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.QuotePriceVerify = void 0;
4
+ const trade_direction_1 = require("../../utils/trade_direction");
5
+ const ttd_core_1 = require("@clonegod/ttd-core");
6
+ function pickMatchingTier(tiers, actualAmountIn) {
7
+ if (!tiers || tiers.length === 0)
8
+ return null;
9
+ if (tiers.length === 1)
10
+ return { tier: tiers[0], mode: 'single_tier', lo_pct: tiers[0].pct, hi_pct: tiers[0].pct };
11
+ const sorted = [...tiers].sort((a, b) => a.amount_in - b.amount_in);
12
+ const top = sorted[sorted.length - 1];
13
+ if (actualAmountIn < sorted[0].amount_in) {
14
+ return { tier: sorted[0], mode: 'extrapolated_low', lo_pct: null, hi_pct: sorted[0].pct };
15
+ }
16
+ if (actualAmountIn > top.amount_in) {
17
+ return { tier: top, mode: 'extrapolated_high', lo_pct: top.pct, hi_pct: null };
18
+ }
19
+ for (let i = 0; i < sorted.length - 1; i++) {
20
+ const lower = sorted[i];
21
+ const upper = sorted[i + 1];
22
+ if (actualAmountIn >= lower.amount_in && actualAmountIn <= upper.amount_in) {
23
+ if (actualAmountIn === lower.amount_in)
24
+ return { tier: lower, mode: 'exact', lo_pct: lower.pct, hi_pct: lower.pct };
25
+ if (actualAmountIn === upper.amount_in)
26
+ return { tier: upper, mode: 'exact', lo_pct: upper.pct, hi_pct: upper.pct };
27
+ const span = upper.amount_in - lower.amount_in;
28
+ if (span <= 0)
29
+ return { tier: lower, mode: 'exact', lo_pct: lower.pct, hi_pct: lower.pct };
30
+ const ratio = (actualAmountIn - lower.amount_in) / span;
31
+ const lerp = (a, b) => a + ratio * (b - a);
32
+ return {
33
+ tier: {
34
+ pct: lerp(lower.pct, upper.pct),
35
+ price: lerp(lower.price, upper.price),
36
+ amount: lerp(lower.amount, upper.amount),
37
+ amount_in: actualAmountIn,
38
+ amount_in_usd: lerp(lower.amount_in_usd, upper.amount_in_usd),
39
+ fee: lerp(lower.fee, upper.fee),
40
+ fee_usd: lerp(lower.fee_usd, upper.fee_usd),
41
+ },
42
+ mode: 'interpolated',
43
+ lo_pct: lower.pct,
44
+ hi_pct: upper.pct,
45
+ };
46
+ }
47
+ }
48
+ return { tier: top, mode: 'extrapolated_high', lo_pct: top.pct, hi_pct: null };
49
+ }
50
+ class QuotePriceVerify {
51
+ constructor() {
52
+ this.quoteCache = new Map();
53
+ }
54
+ get enabled() {
55
+ return process.env.VERIFY_QUOTE_PRICE === 'true';
56
+ }
57
+ cacheQuote(poolAddress, priceId, source, askPrice, bidPrice, blockNumber, quoteAmountUsd, token0PriceUsd = 0, token1PriceUsd = 0, tiers) {
58
+ if (!this.enabled)
59
+ return;
60
+ if (!source)
61
+ return;
62
+ let sourceMap = this.quoteCache.get(poolAddress);
63
+ if (!sourceMap) {
64
+ sourceMap = new Map();
65
+ this.quoteCache.set(poolAddress, sourceMap);
66
+ }
67
+ const existing = sourceMap.get(source);
68
+ const verifiedReferenceBlock = (existing && existing.referenceBlock === blockNumber)
69
+ ? existing.verifiedReferenceBlock
70
+ : 0;
71
+ sourceMap.set(source, {
72
+ priceId, source, askPrice, bidPrice,
73
+ askTiers: tiers?.askTiers,
74
+ bidTiers: tiers?.bidTiers,
75
+ referenceBlock: blockNumber,
76
+ verifiedReferenceBlock,
77
+ quoteAmountUsd,
78
+ token0PriceUsd, token1PriceUsd,
79
+ });
80
+ }
81
+ checkSwap(params) {
82
+ if (!this.enabled)
83
+ return;
84
+ const { poolAddress, blockNumber, txHash, poolInfo, token0Address } = params;
85
+ const sourceMap = this.quoteCache.get(poolAddress);
86
+ if (!sourceMap || sourceMap.size === 0)
87
+ return;
88
+ const swapData = this.deriveSwapDirection(params);
89
+ if (!swapData)
90
+ return;
91
+ const direction = (0, trade_direction_1.resolveTradeDirection)(poolInfo, true);
92
+ const inputIsQuoteToken = swapData.inputTokenAddress.toLowerCase() === direction.quoteToken.address.toLowerCase();
93
+ const isBuy = inputIsQuoteToken;
94
+ const execPriceStr = (0, trade_direction_1.calculateStandardPrice)(swapData.inputAmountUi, swapData.outputAmountUi, isBuy);
95
+ const execPrice = Number(execPriceStr);
96
+ if (execPrice <= 0)
97
+ return;
98
+ const verifiable = [];
99
+ for (const [source, cached] of sourceMap) {
100
+ if (blockNumber <= cached.referenceBlock)
101
+ continue;
102
+ if (cached.verifiedReferenceBlock === cached.referenceBlock)
103
+ continue;
104
+ const tiers = isBuy ? cached.askTiers : cached.bidTiers;
105
+ let refPrice;
106
+ let tierInfo;
107
+ if (tiers && tiers.length > 0) {
108
+ const match = pickMatchingTier(tiers, swapData.inputAmountUi);
109
+ if (!match)
110
+ continue;
111
+ refPrice = match.tier.price;
112
+ tierInfo = {
113
+ matched_pct: parseFloat(match.tier.pct.toFixed(4)),
114
+ mode: match.mode,
115
+ tier_amount_in: match.tier.amount_in,
116
+ lo_pct: match.lo_pct,
117
+ hi_pct: match.hi_pct,
118
+ };
119
+ }
120
+ else {
121
+ refPrice = isBuy ? cached.askPrice : cached.bidPrice;
122
+ }
123
+ if (refPrice <= 0)
124
+ continue;
125
+ cached.verifiedReferenceBlock = cached.referenceBlock;
126
+ const diff_bps = (refPrice - execPrice) / refPrice * 10000;
127
+ verifiable.push({ source, cached, refPrice, diff_bps, tierInfo });
128
+ }
129
+ if (verifiable.length === 0)
130
+ return;
131
+ verifiable.sort((a, b) => b.cached.referenceBlock - a.cached.referenceBlock);
132
+ const primary = verifiable[0];
133
+ const sources = {};
134
+ for (const r of verifiable) {
135
+ sources[r.source] = {
136
+ ask: r.cached.askPrice,
137
+ bid: r.cached.bidPrice,
138
+ matched_ref_price: r.refPrice,
139
+ diff_bps: parseFloat(r.diff_bps.toFixed(1)),
140
+ quote_block: r.cached.referenceBlock,
141
+ ...(r.tierInfo && {
142
+ matched_pct: r.tierInfo.matched_pct,
143
+ tier_mode: r.tierInfo.mode,
144
+ tier_amount_in: r.tierInfo.tier_amount_in,
145
+ }),
146
+ };
147
+ }
148
+ return this.compareAndLog(poolAddress, params.poolName, poolInfo, primary.cached, swapData.inputTokenAddress, swapData.outputTokenAddress, swapData.inputAmountUi, swapData.outputAmountUi, primary.refPrice, execPrice, primary.cached.token0PriceUsd, primary.cached.token1PriceUsd, token0Address, blockNumber, txHash, sources, primary.tierInfo);
149
+ }
150
+ deriveSwapDirection(params) {
151
+ const { amount0, amount1, token0Address, token1Address, token0Decimals, token1Decimals } = params;
152
+ const sign = params.swapperDeltaConvention ? -1n : 1n;
153
+ const amt0 = BigInt(amount0) * sign;
154
+ const amt1 = BigInt(amount1) * sign;
155
+ if (amt0 === 0n && amt1 === 0n)
156
+ return null;
157
+ if (amt0 > 0n && amt1 < 0n) {
158
+ return {
159
+ inputTokenAddress: token0Address,
160
+ outputTokenAddress: token1Address,
161
+ inputAmountUi: Number(amt0) / Math.pow(10, token0Decimals),
162
+ outputAmountUi: Number(-amt1) / Math.pow(10, token1Decimals),
163
+ };
164
+ }
165
+ else if (amt0 < 0n && amt1 > 0n) {
166
+ return {
167
+ inputTokenAddress: token1Address,
168
+ outputTokenAddress: token0Address,
169
+ inputAmountUi: Number(amt1) / Math.pow(10, token1Decimals),
170
+ outputAmountUi: Number(-amt0) / Math.pow(10, token0Decimals),
171
+ };
172
+ }
173
+ return null;
174
+ }
175
+ compareAndLog(poolAddress, poolName, poolInfo, cached, inputTokenAddress, outputTokenAddress, inputAmountUi, outputAmountUi, refPrice, execPriceNum, token0PriceUsd, token1PriceUsd, token0Address, swapBlockNumber, txHash, sources, primaryTierInfo) {
176
+ if (inputAmountUi <= 0 || outputAmountUi <= 0)
177
+ return;
178
+ let swapUsd = 0;
179
+ if (token0PriceUsd && token1PriceUsd && token0Address) {
180
+ const inputIsToken0 = inputTokenAddress.toLowerCase() === token0Address.toLowerCase();
181
+ swapUsd = inputIsToken0
182
+ ? inputAmountUi * token0PriceUsd
183
+ : inputAmountUi * token1PriceUsd;
184
+ }
185
+ const direction = (0, trade_direction_1.resolveTradeDirection)(poolInfo, true);
186
+ const baseToken = direction.baseToken;
187
+ const quoteToken = direction.quoteToken;
188
+ const inputIsQuoteToken = inputTokenAddress.toLowerCase() === quoteToken.address.toLowerCase();
189
+ const isBuy = inputIsQuoteToken;
190
+ const side = isBuy ? 'BUY' : 'SELL';
191
+ if (refPrice <= 0 || execPriceNum <= 0)
192
+ return;
193
+ const diffBps = (refPrice - execPriceNum) / refPrice * 10000;
194
+ const absDiffBps = Math.abs(diffBps);
195
+ const status = absDiffBps < 5 ? '✅' : absDiffBps < 10 ? '⚠️' : '❌';
196
+ const usdStr = swapUsd > 0 ? `$${swapUsd.toFixed(0)}` : '$?';
197
+ const maxUsd = cached.quoteAmountUsd * 2;
198
+ const inRange = swapUsd <= 0 || swapUsd <= maxUsd;
199
+ const rangeTag = inRange ? '' : ' [out]';
200
+ const tradeFlow = isBuy
201
+ ? `${inputAmountUi.toFixed(4)} ${quoteToken.symbol} -> ${outputAmountUi.toFixed(4)} ${baseToken.symbol}`
202
+ : `${inputAmountUi.toFixed(4)} ${baseToken.symbol} -> ${outputAmountUi.toFixed(4)} ${quoteToken.symbol}`;
203
+ const quoteSrc = cached.source || '?';
204
+ const quoteTag = `quote[${quoteSrc} blk:${cached.referenceBlock}]`;
205
+ const swapBlk = swapBlockNumber || '?';
206
+ const swapTx = txHash ? ` ${txHash.slice(0, 10)}` : '';
207
+ const swapTag = `swap[blk:${swapBlk}${swapTx}]`;
208
+ const priceLabel = isBuy ? 'ask' : 'bid';
209
+ const msg = ` ↳ [Verify] ${side} ${usdStr} (${tradeFlow}) ${quoteTag} ${priceLabel}=${refPrice.toFixed(12)} vs ${swapTag} exec=${execPriceNum.toFixed(12)} diff=${diffBps > 0 ? '+' : ''}${diffBps.toFixed(1)}bps ${status}${rangeTag}`;
210
+ try {
211
+ (0, ttd_core_1.report_data_to_analyze)('QuoteVerify', {
212
+ pool_address: poolAddress,
213
+ pool_name: poolName,
214
+ price_id: cached.priceId,
215
+ source: cached.source,
216
+ quote_amount_usd: cached.quoteAmountUsd,
217
+ quote_block: cached.referenceBlock,
218
+ swap_block: swapBlockNumber,
219
+ tx_hash: txHash || '',
220
+ side,
221
+ ref_price: refPrice,
222
+ exec_price: execPriceNum,
223
+ diff_bps: parseFloat(diffBps.toFixed(1)),
224
+ swap_usd: parseFloat(swapUsd.toFixed(0)),
225
+ in_range: inRange,
226
+ input_amount: inputAmountUi,
227
+ output_amount: outputAmountUi,
228
+ input_symbol: isBuy ? quoteToken.symbol : baseToken.symbol,
229
+ output_symbol: isBuy ? baseToken.symbol : quoteToken.symbol,
230
+ status,
231
+ time: Date.now(),
232
+ sources: sources || undefined,
233
+ ...(primaryTierInfo && {
234
+ matched_tier_pct: primaryTierInfo.matched_pct,
235
+ matched_tier_mode: primaryTierInfo.mode,
236
+ matched_tier_amount_in: primaryTierInfo.tier_amount_in,
237
+ matched_tier_lo_pct: primaryTierInfo.lo_pct,
238
+ matched_tier_hi_pct: primaryTierInfo.hi_pct,
239
+ }),
240
+ });
241
+ }
242
+ catch (_) {
243
+ }
244
+ return msg;
245
+ }
246
+ }
247
+ exports.QuotePriceVerify = QuotePriceVerify;
@@ -2,6 +2,7 @@ import { RedisClientType } from "redis";
2
2
  export declare class SimpleRedisClient {
3
3
  private lock_prefix;
4
4
  private redisClient;
5
+ private coreRedis;
5
6
  private lockMaxRetries;
6
7
  private lockRetryDelayMs;
7
8
  private lockExpireSeconds;
@@ -1,13 +1,4 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.SimpleRedisClient = void 0;
13
4
  const dist_1 = require("@clonegod/ttd-core/dist");
@@ -15,145 +6,125 @@ class SimpleRedisClient {
15
6
  constructor(lock_prefix) {
16
7
  this.lock_prefix = lock_prefix;
17
8
  this.redisClient = null;
9
+ this.coreRedis = (0, dist_1.getRedisClient)();
18
10
  this.lockMaxRetries = 10;
19
11
  this.lockRetryDelayMs = 300;
20
12
  this.lockExpireSeconds = 3;
21
13
  }
22
- getRedisClient() {
23
- return __awaiter(this, void 0, void 0, function* () {
24
- if (!this.redisClient) {
25
- this.redisClient = yield (0, dist_1.getRedisCache)();
26
- }
27
- return this.redisClient;
28
- });
14
+ async getRedisClient() {
15
+ if (!this.redisClient) {
16
+ await this.coreRedis.init();
17
+ this.redisClient = this.coreRedis.redis_client;
18
+ }
19
+ return this.redisClient;
29
20
  }
30
21
  getLockKey(lock_identifier) {
31
22
  return `${this.lock_prefix}:lock:${lock_identifier}`;
32
23
  }
33
- acquireLock(lock_key_1, lock_value_1) {
34
- return __awaiter(this, arguments, void 0, function* (lock_key, lock_value, expireSeconds = this.lockExpireSeconds) {
35
- const redisClient = yield this.getRedisClient();
36
- const result = yield redisClient.set(lock_key, lock_value, {
37
- NX: true,
38
- EX: expireSeconds
39
- });
40
- (0, dist_1.log_info)(`try acquireLock: lock_key=${lock_key}, lock_value=${lock_value}, expireSeconds=${expireSeconds}, result=${result}`);
41
- const success = result === 'OK';
42
- if (success) {
43
- (0, dist_1.log_info)(`acquire lock success: lock_key=${lock_key}, lock_value=${lock_value}`);
44
- }
45
- return success;
24
+ async acquireLock(lock_key, lock_value, expireSeconds = this.lockExpireSeconds) {
25
+ const redisClient = await this.getRedisClient();
26
+ const result = await redisClient.set(lock_key, lock_value, {
27
+ NX: true,
28
+ EX: expireSeconds
46
29
  });
30
+ (0, dist_1.log_info)(`try acquireLock: lock_key=${lock_key}, lock_value=${lock_value}, expireSeconds=${expireSeconds}, result=${result}`);
31
+ const success = result === 'OK';
32
+ if (success) {
33
+ (0, dist_1.log_info)(`acquire lock success: lock_key=${lock_key}, lock_value=${lock_value}`);
34
+ }
35
+ return success;
47
36
  }
48
- releaseLock(lock_key, lock_value) {
49
- return __awaiter(this, void 0, void 0, function* () {
50
- const redisClient = yield this.getRedisClient();
51
- const script = `
37
+ async releaseLock(lock_key, lock_value) {
38
+ const redisClient = await this.getRedisClient();
39
+ const script = `
52
40
  if redis.call('get', KEYS[1]) == ARGV[1] then
53
41
  return redis.call('del', KEYS[1])
54
42
  else
55
43
  return 0
56
44
  end
57
45
  `;
58
- const result = yield redisClient.eval(script, {
59
- keys: [lock_key],
60
- arguments: [lock_value]
61
- });
62
- const success = Number(result) === 1;
63
- if (success) {
64
- (0, dist_1.log_info)(`release lock success: lock_key=${lock_key}, lock_value=${lock_value}`);
65
- }
66
- else {
67
- (0, dist_1.log_info)(`release lock failed: lock_key=${lock_key}, lock_value=${lock_value}, maybe expired or locked by other process`);
68
- }
69
- return success;
46
+ const result = await redisClient.eval(script, {
47
+ keys: [lock_key],
48
+ arguments: [lock_value]
70
49
  });
50
+ const success = Number(result) === 1;
51
+ if (success) {
52
+ (0, dist_1.log_info)(`release lock success: lock_key=${lock_key}, lock_value=${lock_value}`);
53
+ }
54
+ else {
55
+ (0, dist_1.log_info)(`release lock failed: lock_key=${lock_key}, lock_value=${lock_value}, maybe expired or locked by other process`);
56
+ }
57
+ return success;
71
58
  }
72
- withLock(lock_identifier_1, callback_1) {
73
- return __awaiter(this, arguments, void 0, function* (lock_identifier, callback, release_lock_delay_ms = 500) {
74
- const lock_key = this.getLockKey(lock_identifier);
75
- const lock_value = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
76
- let retries = 0;
77
- let acquired = false;
78
- let lock_start_time = Date.now();
79
- let lock_acquired_time = 0;
80
- try {
81
- while (retries < this.lockMaxRetries) {
82
- acquired = yield this.acquireLock(lock_key, lock_value);
83
- if (acquired) {
84
- lock_acquired_time = Date.now();
85
- break;
86
- }
87
- yield new Promise(resolve => setTimeout(resolve, this.lockRetryDelayMs));
88
- (0, dist_1.log_warn)(`withLock failed: lock_key=${lock_key}, lock_value=${lock_value}, retry times=${retries}`);
89
- retries++;
90
- }
59
+ async withLock(lock_identifier, callback, release_lock_delay_ms = 500) {
60
+ const lock_key = this.getLockKey(lock_identifier);
61
+ const lock_value = `${Date.now()}-${Math.random().toString(36).substring(2, 15)}`;
62
+ let retries = 0;
63
+ let acquired = false;
64
+ let lock_start_time = Date.now();
65
+ let lock_acquired_time = 0;
66
+ try {
67
+ while (retries < this.lockMaxRetries) {
68
+ acquired = await this.acquireLock(lock_key, lock_value);
91
69
  if (acquired) {
92
- return yield callback();
70
+ lock_acquired_time = Date.now();
71
+ break;
93
72
  }
73
+ await new Promise(resolve => setTimeout(resolve, this.lockRetryDelayMs));
74
+ (0, dist_1.log_warn)(`withLock failed: lock_key=${lock_key}, lock_value=${lock_value}, retry times=${retries}`);
75
+ retries++;
94
76
  }
95
- finally {
96
- if (acquired) {
97
- const release_delay = parseInt(process.env.NONCE_LOCK_RELEASE_DELAY_MS || String(release_lock_delay_ms));
98
- if (release_delay > 0) {
99
- yield (0, dist_1.sleep)(release_delay);
100
- }
101
- yield this.releaseLock(lock_key, lock_value);
102
- (0, dist_1.log_info)(`withLock success: lock_key=${lock_key}, retry_times=${retries}, release_lock_delay=${release_delay}ms, hold_lock=${Date.now() - lock_acquired_time}ms`);
103
- }
104
- else {
105
- (0, dist_1.log_warn)(`withLock failed: lock_key=${lock_key}, retry_times=${retries}, total_time=${Date.now() - lock_start_time}ms`);
77
+ if (acquired) {
78
+ return await callback();
79
+ }
80
+ }
81
+ finally {
82
+ if (acquired) {
83
+ const release_delay = parseInt(process.env.NONCE_LOCK_RELEASE_DELAY_MS || String(release_lock_delay_ms));
84
+ if (release_delay > 0) {
85
+ await (0, dist_1.sleep)(release_delay);
106
86
  }
87
+ await this.releaseLock(lock_key, lock_value);
88
+ (0, dist_1.log_info)(`withLock success: lock_key=${lock_key}, retry_times=${retries}, release_lock_delay=${release_delay}ms, hold_lock=${Date.now() - lock_acquired_time}ms`);
107
89
  }
108
- });
90
+ else {
91
+ (0, dist_1.log_warn)(`withLock failed: lock_key=${lock_key}, retry_times=${retries}, total_time=${Date.now() - lock_start_time}ms`);
92
+ }
93
+ }
109
94
  }
110
- getValue(key) {
111
- return __awaiter(this, void 0, void 0, function* () {
112
- const redisClient = yield this.getRedisClient();
113
- return yield redisClient.get(key);
114
- });
95
+ async getValue(key) {
96
+ const redisClient = await this.getRedisClient();
97
+ return await redisClient.get(key);
115
98
  }
116
- setValue(key, value, expireSeconds) {
117
- return __awaiter(this, void 0, void 0, function* () {
118
- const redisClient = yield this.getRedisClient();
119
- return yield redisClient.set(key, value, {
120
- EX: expireSeconds
121
- });
99
+ async setValue(key, value, expireSeconds) {
100
+ const redisClient = await this.getRedisClient();
101
+ return await redisClient.set(key, value, {
102
+ EX: expireSeconds
122
103
  });
123
104
  }
124
- hsetValue(key, field, value, expireSeconds) {
125
- return __awaiter(this, void 0, void 0, function* () {
126
- const redisClient = yield this.getRedisClient();
127
- yield redisClient.hSet(key, field, value);
128
- yield redisClient.hExpire(key, field, expireSeconds);
129
- });
105
+ async hsetValue(key, field, value, expireSeconds) {
106
+ const redisClient = await this.getRedisClient();
107
+ await redisClient.hSet(key, field, value);
108
+ await redisClient.hExpire(key, field, expireSeconds);
130
109
  }
131
- hgetvalue(key, field) {
132
- return __awaiter(this, void 0, void 0, function* () {
133
- const redisClient = yield this.getRedisClient();
134
- return yield redisClient.hGet(key, field);
135
- });
110
+ async hgetvalue(key, field) {
111
+ const redisClient = await this.getRedisClient();
112
+ return await redisClient.hGet(key, field);
136
113
  }
137
- hkeys(key) {
138
- return __awaiter(this, void 0, void 0, function* () {
139
- const redisClient = yield this.getRedisClient();
140
- return yield redisClient.hKeys(key);
141
- });
114
+ async hkeys(key) {
115
+ const redisClient = await this.getRedisClient();
116
+ return await redisClient.hKeys(key);
142
117
  }
143
- hgetall(key) {
144
- return __awaiter(this, void 0, void 0, function* () {
145
- const redisClient = yield this.getRedisClient();
146
- return yield redisClient.hGetAll(key);
147
- });
118
+ async hgetall(key) {
119
+ const redisClient = await this.getRedisClient();
120
+ return await redisClient.hGetAll(key);
148
121
  }
149
- del(key_1) {
150
- return __awaiter(this, arguments, void 0, function* (key, field = '') {
151
- const redisClient = yield this.getRedisClient();
152
- if (field) {
153
- return yield redisClient.hDel(key, field);
154
- }
155
- return yield redisClient.del(key);
156
- });
122
+ async del(key, field = '') {
123
+ const redisClient = await this.getRedisClient();
124
+ if (field) {
125
+ return await redisClient.hDel(key, field);
126
+ }
127
+ return await redisClient.del(key);
157
128
  }
158
129
  }
159
130
  exports.SimpleRedisClient = SimpleRedisClient;
package/dist/rpc/index.js CHANGED
@@ -1,85 +1,69 @@
1
1
  "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
2
  Object.defineProperty(exports, "__esModule", { value: true });
12
3
  exports.get_all_objects_in_wallet = get_all_objects_in_wallet;
13
4
  exports.print_group_objects = print_group_objects;
14
- function get_all_objects_in_wallet(suiClient_1, walletAddress_1) {
15
- return __awaiter(this, arguments, void 0, function* (suiClient, walletAddress, limit = 50) {
16
- if (!walletAddress) {
17
- throw new Error('walletAddress is required');
18
- }
19
- let allObjects = [];
20
- let hasNextPage = true;
21
- let cursor = null;
22
- while (hasNextPage) {
23
- const response = yield suiClient.getOwnedObjects({
24
- owner: walletAddress,
25
- limit: limit,
26
- cursor: cursor,
27
- options: {
28
- showType: true,
29
- showContent: true,
30
- showDisplay: true,
31
- showPreviousTransaction: true,
32
- showStorageRebate: true
33
- }
34
- });
35
- allObjects = allObjects.concat(response.data);
36
- hasNextPage = response.hasNextPage;
37
- cursor = response.nextCursor || null;
38
- console.log(`当前已查询到 ${allObjects.length} 个对象。 hasNextPage= ${hasNextPage}`);
39
- }
40
- return allObjects;
41
- });
42
- }
43
- function print_group_objects(allObjects) {
44
- return __awaiter(this, void 0, void 0, function* () {
45
- const objectTypeMap = new Map();
46
- allObjects.forEach(obj => {
47
- var _a;
48
- const type = ((_a = obj.data) === null || _a === void 0 ? void 0 : _a.type) || 'unknown';
49
- const count = objectTypeMap.get(type) || 0;
50
- objectTypeMap.set(type, count + 1);
51
- });
52
- console.log(`\n=== 按类型分组的所有对象 ===`);
53
- objectTypeMap.forEach((count, type) => {
54
- console.log(`${type}: ${count} 个对象`);
55
- });
56
- console.log(`\n=== Coins ===`);
57
- const typeGroups = new Map();
58
- allObjects.forEach(obj => {
59
- var _a;
60
- const type = ((_a = obj.data) === null || _a === void 0 ? void 0 : _a.type) || 'unknown';
61
- if (!typeGroups.has(type)) {
62
- typeGroups.set(type, []);
5
+ async function get_all_objects_in_wallet(suiClient, walletAddress, limit = 50) {
6
+ if (!walletAddress) {
7
+ throw new Error('walletAddress is required');
8
+ }
9
+ let allObjects = [];
10
+ let hasNextPage = true;
11
+ let cursor = null;
12
+ while (hasNextPage) {
13
+ const response = await suiClient.getOwnedObjects({
14
+ owner: walletAddress,
15
+ limit: limit,
16
+ cursor: cursor,
17
+ options: {
18
+ showType: true,
19
+ showContent: true,
20
+ showDisplay: true,
21
+ showPreviousTransaction: true,
22
+ showStorageRebate: true
63
23
  }
64
- typeGroups.get(type).push(obj);
65
24
  });
66
- let coinIndex = 1;
67
- typeGroups.forEach((objects, type) => {
68
- console.log(`\nCoin ${coinIndex} - ${type} (${objects.length} 个对象):`);
69
- objects.forEach((obj, objIndex) => {
70
- var _a, _b, _c, _d;
71
- console.log(` object ${objIndex + 1}:`);
72
- console.log(` - objectId: ${(_a = obj.data) === null || _a === void 0 ? void 0 : _a.objectId}`);
73
- console.log(` - version: ${(_b = obj.data) === null || _b === void 0 ? void 0 : _b.version}`);
74
- console.log(` - digest: ${(_c = obj.data) === null || _c === void 0 ? void 0 : _c.digest}`);
75
- if (((_d = obj.data) === null || _d === void 0 ? void 0 : _d.content) && 'fields' in obj.data.content) {
76
- const fields = obj.data.content.fields;
77
- if (fields.balance) {
78
- console.log(` - balance: ${fields.balance}`);
79
- }
25
+ allObjects = allObjects.concat(response.data);
26
+ hasNextPage = response.hasNextPage;
27
+ cursor = response.nextCursor || null;
28
+ console.log(`当前已查询到 ${allObjects.length} 个对象。 hasNextPage= ${hasNextPage}`);
29
+ }
30
+ return allObjects;
31
+ }
32
+ async function print_group_objects(allObjects) {
33
+ const objectTypeMap = new Map();
34
+ allObjects.forEach(obj => {
35
+ const type = obj.data?.type || 'unknown';
36
+ const count = objectTypeMap.get(type) || 0;
37
+ objectTypeMap.set(type, count + 1);
38
+ });
39
+ console.log(`\n=== 按类型分组的所有对象 ===`);
40
+ objectTypeMap.forEach((count, type) => {
41
+ console.log(`${type}: ${count} 个对象`);
42
+ });
43
+ console.log(`\n=== Coins ===`);
44
+ const typeGroups = new Map();
45
+ allObjects.forEach(obj => {
46
+ const type = obj.data?.type || 'unknown';
47
+ if (!typeGroups.has(type)) {
48
+ typeGroups.set(type, []);
49
+ }
50
+ typeGroups.get(type).push(obj);
51
+ });
52
+ let coinIndex = 1;
53
+ typeGroups.forEach((objects, type) => {
54
+ console.log(`\nCoin ${coinIndex} - ${type} (${objects.length} 个对象):`);
55
+ objects.forEach((obj, objIndex) => {
56
+ console.log(` object ${objIndex + 1}:`);
57
+ console.log(` - objectId: ${obj.data?.objectId}`);
58
+ console.log(` - version: ${obj.data?.version}`);
59
+ console.log(` - digest: ${obj.data?.digest}`);
60
+ if (obj.data?.content && 'fields' in obj.data.content) {
61
+ const fields = obj.data.content.fields;
62
+ if (fields.balance) {
63
+ console.log(` - balance: ${fields.balance}`);
80
64
  }
81
- });
82
- coinIndex++;
65
+ }
83
66
  });
67
+ coinIndex++;
84
68
  });
85
69
  }
package/dist/test/test.js CHANGED
@@ -88,7 +88,7 @@ function decodeBytes(obj) {
88
88
  const result = {};
89
89
  for (const key in obj) {
90
90
  const val = obj[key];
91
- if (val instanceof Uint8Array || ((val === null || val === void 0 ? void 0 : val.type) === 'Buffer' && Array.isArray(val.data))) {
91
+ if (val instanceof Uint8Array || (val?.type === 'Buffer' && Array.isArray(val.data))) {
92
92
  const buffer = val instanceof Uint8Array ? val : Buffer.from(val.data);
93
93
  result[key] = buffer.toString('hex');
94
94
  }