@clonegod/ttd-sui-common 1.0.92 → 1.0.94

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 (45) hide show
  1. package/README.md +1 -1
  2. package/dist/grpc/grpc-connection.js +2 -2
  3. package/dist/grpc/index.d.ts +1 -1
  4. package/dist/grpc/index.js +3 -3
  5. package/dist/grpc/protos/google/protobuf/timestamp.proto +9 -8
  6. package/dist/grpc/protos/sui/rpc/v2/argument.proto +34 -0
  7. package/dist/grpc/protos/sui/rpc/v2/balance_change.proto +18 -0
  8. package/dist/grpc/protos/sui/rpc/v2/bcs.proto +17 -0
  9. package/dist/grpc/protos/sui/rpc/v2/checkpoint.proto +42 -0
  10. package/dist/grpc/protos/sui/rpc/v2/checkpoint_contents.proto +34 -0
  11. package/dist/grpc/protos/sui/rpc/v2/checkpoint_summary.proto +105 -0
  12. package/dist/grpc/protos/sui/rpc/v2/effects.proto +157 -0
  13. package/dist/grpc/protos/sui/rpc/v2/epoch.proto +34 -0
  14. package/dist/grpc/protos/sui/rpc/v2/error_reason.proto +12 -0
  15. package/dist/grpc/protos/sui/rpc/v2/event.proto +44 -0
  16. package/dist/grpc/protos/sui/rpc/v2/executed_transaction.proto +49 -0
  17. package/dist/grpc/protos/sui/rpc/v2/execution_status.proto +374 -0
  18. package/dist/grpc/protos/sui/rpc/v2/gas_cost_summary.proto +19 -0
  19. package/dist/grpc/protos/sui/rpc/v2/input.proto +55 -0
  20. package/dist/grpc/protos/sui/rpc/v2/jwk.proto +38 -0
  21. package/dist/grpc/protos/sui/rpc/v2/ledger_service.proto +165 -0
  22. package/dist/grpc/protos/sui/rpc/v2/move_package.proto +238 -0
  23. package/dist/grpc/protos/sui/rpc/v2/move_package_service.proto +91 -0
  24. package/dist/grpc/protos/sui/rpc/v2/name_service.proto +67 -0
  25. package/dist/grpc/protos/sui/rpc/v2/object.proto +68 -0
  26. package/dist/grpc/protos/sui/rpc/v2/object_reference.proto +16 -0
  27. package/dist/grpc/protos/sui/rpc/v2/owner.proto +25 -0
  28. package/dist/grpc/protos/sui/rpc/v2/protocol_config.proto +12 -0
  29. package/dist/grpc/protos/sui/rpc/v2/signature.proto +238 -0
  30. package/dist/grpc/protos/sui/rpc/v2/signature_scheme.proto +22 -0
  31. package/dist/grpc/protos/sui/rpc/v2/signature_verification_service.proto +49 -0
  32. package/dist/grpc/protos/sui/rpc/v2/state_service.proto +300 -0
  33. package/dist/grpc/protos/sui/rpc/v2/subscription_service.proto +41 -0
  34. package/dist/grpc/protos/sui/rpc/v2/system_state.proto +340 -0
  35. package/dist/grpc/protos/sui/rpc/v2/transaction.proto +531 -0
  36. package/dist/grpc/protos/sui/rpc/v2/transaction_execution_service.proto +78 -0
  37. package/dist/grpc/state-service.d.ts +11 -0
  38. package/dist/grpc/state-service.js +107 -0
  39. package/dist/grpc/sui-grpc-client.d.ts +2 -2
  40. package/dist/grpc/sui-grpc-client.js +2 -2
  41. package/dist/redis/redis_client.d.ts +1 -1
  42. package/dist/test/test.js +2 -2
  43. package/dist/test/test_grpc.js +9 -9
  44. package/dist/trade/abstract_sui_dex_trade_plus.js +105 -96
  45. package/package.json +2 -2
@@ -0,0 +1,107 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.StateService = void 0;
13
+ const utils_1 = require("../utils");
14
+ class StateService {
15
+ constructor(connection) {
16
+ this.connection = connection;
17
+ this.stateClient = connection.createServiceClient('state_service.proto', 'StateService');
18
+ }
19
+ getBalance(owner, coinType) {
20
+ return __awaiter(this, void 0, void 0, function* () {
21
+ if (!owner) {
22
+ throw new Error('owner 参数是必需的');
23
+ }
24
+ if (!coinType) {
25
+ coinType = '0x2::sui::SUI';
26
+ }
27
+ return new Promise((resolve, reject) => {
28
+ const request = {
29
+ owner: owner,
30
+ coin_type: coinType
31
+ };
32
+ this.stateClient.GetBalance(request, this.connection.getMetadata(), (error, response) => {
33
+ if (error)
34
+ reject(error);
35
+ else
36
+ resolve(response);
37
+ });
38
+ });
39
+ });
40
+ }
41
+ listBalances(owner) {
42
+ return __awaiter(this, void 0, void 0, function* () {
43
+ return new Promise((resolve, reject) => {
44
+ this.stateClient.ListBalances({ owner }, this.connection.getMetadata(), (error, response) => {
45
+ if (error)
46
+ reject(error);
47
+ else
48
+ resolve(response);
49
+ });
50
+ });
51
+ });
52
+ }
53
+ getCoinInfo(coinType) {
54
+ return __awaiter(this, void 0, void 0, function* () {
55
+ return new Promise((resolve, reject) => {
56
+ this.stateClient.GetCoinInfo({ coin_type: coinType }, this.connection.getMetadata(), (error, response) => {
57
+ if (error)
58
+ reject(error);
59
+ else
60
+ resolve(response);
61
+ });
62
+ });
63
+ });
64
+ }
65
+ listOwnedObjects(owner, coinType, limit, readMask) {
66
+ return __awaiter(this, void 0, void 0, function* () {
67
+ return new Promise((resolve, reject) => {
68
+ const request = { owner };
69
+ if (coinType) {
70
+ const objectType = coinType.startsWith('0x2::coin::Coin<')
71
+ ? coinType
72
+ : `0x2::coin::Coin<${coinType}>`;
73
+ request.object_type = objectType;
74
+ }
75
+ if (limit)
76
+ request.page_size = limit;
77
+ if (readMask && readMask.length > 0) {
78
+ request.read_mask = {
79
+ paths: readMask
80
+ };
81
+ }
82
+ else {
83
+ request.read_mask = {
84
+ paths: [
85
+ "object_id",
86
+ "version",
87
+ "digest",
88
+ "owner",
89
+ "object_type",
90
+ "storage_rebate",
91
+ "balance"
92
+ ]
93
+ };
94
+ }
95
+ this.stateClient.ListOwnedObjects(request, this.connection.getMetadata(), (error, response) => {
96
+ if (error)
97
+ reject(error);
98
+ else {
99
+ let res = (0, utils_1.decodeBytes)(response);
100
+ resolve(res);
101
+ }
102
+ });
103
+ });
104
+ });
105
+ }
106
+ }
107
+ exports.StateService = StateService;
@@ -1,12 +1,12 @@
1
1
  import { LedgerService } from "./ledger-service";
2
- import { LiveDataService } from "./live-data-service";
2
+ import { StateService } from "./state-service";
3
3
  import { SubscriptionService } from "./subscription-service";
4
4
  import { TransactionService } from "./transaction-service";
5
5
  import { GasPriceCache } from "./gas-price-cache";
6
6
  export declare class SuiGrpcClient {
7
7
  ledgerService: LedgerService;
8
8
  transactionService: TransactionService;
9
- liveDataService: LiveDataService;
9
+ stateService: StateService;
10
10
  subscriptionService: SubscriptionService;
11
11
  gasPriceCache: GasPriceCache;
12
12
  gas_price: number;
@@ -12,7 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.SuiGrpcClient = void 0;
13
13
  const grpc_connection_1 = require("./grpc-connection");
14
14
  const ledger_service_1 = require("./ledger-service");
15
- const live_data_service_1 = require("./live-data-service");
15
+ const state_service_1 = require("./state-service");
16
16
  const subscription_service_1 = require("./subscription-service");
17
17
  const transaction_service_1 = require("./transaction-service");
18
18
  const gas_price_cache_1 = require("./gas-price-cache");
@@ -25,7 +25,7 @@ class SuiGrpcClient {
25
25
  const grpcClient = grpc_connection_1.GrpcConnection.getInstance(process.env.SUI_GRPC_ENDPOINT, process.env.SUI_GRPC_TOKEN);
26
26
  this.ledgerService = new ledger_service_1.LedgerService(grpcClient);
27
27
  this.transactionService = new transaction_service_1.TransactionService(grpcClient);
28
- this.liveDataService = new live_data_service_1.LiveDataService(grpcClient);
28
+ this.stateService = new state_service_1.StateService(grpcClient);
29
29
  this.subscriptionService = new subscription_service_1.SubscriptionService(grpcClient);
30
30
  this.gasPriceCache = gas_price_cache_1.GasPriceCache.getInstance(this.ledgerService);
31
31
  }
@@ -9,7 +9,7 @@ export declare class SimpleRedisClient {
9
9
  getRedisClient(): Promise<RedisClientType>;
10
10
  private getLockKey;
11
11
  acquireLock(lock_key: string, lock_value: string, expireSeconds?: number): Promise<boolean>;
12
- private releaseLock;
12
+ releaseLock(lock_key: string, lock_value: string): Promise<boolean>;
13
13
  withLock<T>(lock_identifier: string, callback: () => Promise<T>, release_lock_delay_ms?: number): Promise<T>;
14
14
  getValue(key: string): Promise<string>;
15
15
  setValue(key: string, value: string, expireSeconds: number): Promise<any>;
package/dist/test/test.js CHANGED
@@ -38,7 +38,7 @@ dotenv.config();
38
38
  const grpc = __importStar(require("@grpc/grpc-js"));
39
39
  const protoLoader = __importStar(require("@grpc/proto-loader"));
40
40
  const path = __importStar(require("path"));
41
- const PROTO_PATH = path.join(__dirname, 'protos/sui/rpc/v2beta2/ledger_service.proto');
41
+ const PROTO_PATH = path.join(__dirname, 'protos/sui/rpc/v2/ledger_service.proto');
42
42
  const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
43
43
  keepCase: true,
44
44
  longs: String,
@@ -48,7 +48,7 @@ const packageDefinition = protoLoader.loadSync(PROTO_PATH, {
48
48
  includeDirs: [path.join(__dirname, 'protos')],
49
49
  });
50
50
  const suiProto = grpc.loadPackageDefinition(packageDefinition);
51
- const LedgerService = suiProto.sui.rpc.v2beta2.LedgerService;
51
+ const LedgerService = suiProto.sui.rpc.v2.LedgerService;
52
52
  const endpoint = process.env.SUI_GRPC_ENDPOINT;
53
53
  const token = process.env.SUI_GRPC_TOKEN;
54
54
  if (!endpoint || !token) {
@@ -12,7 +12,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
12
12
  const dist_1 = require("@clonegod/ttd-core/dist");
13
13
  const grpc_connection_1 = require("../grpc/grpc-connection");
14
14
  const ledger_service_1 = require("../grpc/ledger-service");
15
- const live_data_service_1 = require("../grpc/live-data-service");
15
+ const state_service_1 = require("../grpc/state-service");
16
16
  const grpc_endpoint = process.env.SUI_GRPC_ENDPOINT;
17
17
  const grpc_token = process.env.SUI_GRPC_TOKEN;
18
18
  const test_get_service_info = () => __awaiter(void 0, void 0, void 0, function* () {
@@ -53,27 +53,27 @@ const test_get_transaction = (txid) => __awaiter(void 0, void 0, void 0, functio
53
53
  });
54
54
  const test_get_balance = (wallet_address, coin_type) => __awaiter(void 0, void 0, void 0, function* () {
55
55
  const connection = grpc_connection_1.GrpcConnection.getInstance(grpc_endpoint, grpc_token);
56
- const liveDataService = new live_data_service_1.LiveDataService(connection);
57
- const balance = yield liveDataService.getBalance(wallet_address, coin_type);
56
+ const stateService = new state_service_1.StateService(connection);
57
+ const balance = yield stateService.getBalance(wallet_address, coin_type);
58
58
  (0, dist_1.log_info)(`balance`, balance);
59
59
  });
60
60
  const test_list_balances = (wallet_address) => __awaiter(void 0, void 0, void 0, function* () {
61
61
  const connection = grpc_connection_1.GrpcConnection.getInstance(grpc_endpoint, grpc_token);
62
- const liveDataService = new live_data_service_1.LiveDataService(connection);
63
- const balances = yield liveDataService.listBalances(wallet_address);
62
+ const stateService = new state_service_1.StateService(connection);
63
+ const balances = yield stateService.listBalances(wallet_address);
64
64
  (0, dist_1.log_info)(`balances`, balances);
65
65
  });
66
66
  const test_get_coin_info = (coin_type) => __awaiter(void 0, void 0, void 0, function* () {
67
67
  const connection = grpc_connection_1.GrpcConnection.getInstance(grpc_endpoint, grpc_token);
68
- const liveDataService = new live_data_service_1.LiveDataService(connection);
69
- const coinInfo = yield liveDataService.getCoinInfo(coin_type);
68
+ const stateService = new state_service_1.StateService(connection);
69
+ const coinInfo = yield stateService.getCoinInfo(coin_type);
70
70
  (0, dist_1.log_info)(`coinInfo`, coinInfo);
71
71
  });
72
72
  const test_list_owned_objects = (wallet_address, coin_type) => __awaiter(void 0, void 0, void 0, function* () {
73
73
  const connection = grpc_connection_1.GrpcConnection.getInstance(grpc_endpoint, grpc_token);
74
74
  const startTime = Date.now();
75
- const liveDataService = new live_data_service_1.LiveDataService(connection);
76
- const ownedObjects = yield liveDataService.listOwnedObjects(wallet_address, coin_type);
75
+ const stateService = new state_service_1.StateService(connection);
76
+ const ownedObjects = yield stateService.listOwnedObjects(wallet_address, coin_type);
77
77
  const duration = Date.now() - startTime;
78
78
  if (!coin_type) {
79
79
  (0, dist_1.log_info)(`list all owned objects, count=${ownedObjects.objects.length}, cost ${duration}ms`);
@@ -90,7 +90,7 @@ class AbstractSuiDexTradePlus extends dist_1.AbastrcatTrade {
90
90
  const maxRetryTime = 200;
91
91
  const retryDelay = 20;
92
92
  do {
93
- lockAcquired = yield this.redisClient.acquireLock(lockKey, lockValue, 200);
93
+ lockAcquired = yield this.redisClient.acquireLock(lockKey, lockValue, 2);
94
94
  if (lockAcquired) {
95
95
  break;
96
96
  }
@@ -100,118 +100,127 @@ class AbstractSuiDexTradePlus extends dist_1.AbastrcatTrade {
100
100
  throw new Error(`choose wallet, acquire lock failed: ${lockKey}, took ${Date.now() - start_time}ms`);
101
101
  }
102
102
  (0, dist_1.log_info)(`choose wallet, acquire lock success: ${lockKey}, took ${Date.now() - start_time}ms`);
103
- const { inputToken } = this.determineInputOutputTokens(context.order_msg, context.pool_info);
104
- console.log('inputToken', inputToken);
105
- const requiredAmount = new decimal_js_1.default(context.order_msg.amount);
106
- const wallet_assets = yield this.redisClient.hgetall('sui:wallet:assets');
107
- if (!wallet_assets || Object.keys(wallet_assets).length === 0) {
108
- throw new Error('没有找到钱包资产信息,请确保钱包监控服务正在运行');
109
- }
110
- const wallet_assets_map = {};
111
- for (const [walletAddress, assetsJson] of Object.entries(wallet_assets)) {
112
- try {
113
- wallet_assets_map[walletAddress] = JSON.parse(assetsJson);
114
- }
115
- catch (error) {
116
- console.warn(`解析钱包资产数据失败: ${walletAddress}`, error);
103
+ try {
104
+ const { inputToken } = this.determineInputOutputTokens(context.order_msg, context.pool_info);
105
+ console.log('inputToken', inputToken);
106
+ const requiredAmount = new decimal_js_1.default(context.order_msg.amount);
107
+ const wallet_assets = yield this.redisClient.hgetall('sui:wallet:assets');
108
+ if (!wallet_assets || Object.keys(wallet_assets).length === 0) {
109
+ throw new Error('没有找到钱包资产信息,请确保钱包监控服务正在运行');
117
110
  }
118
- }
119
- const availableWallets = [];
120
- const allWallets = [];
121
- for (const [walletAddress, assets] of Object.entries(wallet_assets_map)) {
122
- try {
123
- const wallet = (_a = this.group_wallets) === null || _a === void 0 ? void 0 : _a.find(w => w.getPublicKey().toSuiAddress().toLowerCase() === walletAddress.toLowerCase());
124
- if (!wallet) {
125
- continue;
111
+ const wallet_assets_map = {};
112
+ for (const [walletAddress, assetsJson] of Object.entries(wallet_assets)) {
113
+ try {
114
+ wallet_assets_map[walletAddress] = JSON.parse(assetsJson);
126
115
  }
127
- const tokenAsset = (_b = assets.tokens) === null || _b === void 0 ? void 0 : _b.find((token) => (0, index_1.normalizeSuiTokenAddress)(token.address) === (0, index_1.normalizeSuiTokenAddress)(inputToken.address));
128
- let tokenBalance = (tokenAsset === null || tokenAsset === void 0 ? void 0 : tokenAsset.balance) || '0';
129
- const balanceDecimal = new decimal_js_1.default(tokenBalance);
130
- if (balanceDecimal.gte(requiredAmount)) {
131
- availableWallets.push({
116
+ catch (error) {
117
+ console.warn(`解析钱包资产数据失败: ${walletAddress}`, error);
118
+ }
119
+ }
120
+ const availableWallets = [];
121
+ const allWallets = [];
122
+ for (const [walletAddress, assets] of Object.entries(wallet_assets_map)) {
123
+ try {
124
+ const wallet = (_a = this.group_wallets) === null || _a === void 0 ? void 0 : _a.find(w => w.getPublicKey().toSuiAddress().toLowerCase() === walletAddress.toLowerCase());
125
+ if (!wallet) {
126
+ continue;
127
+ }
128
+ const tokenAsset = (_b = assets.tokens) === null || _b === void 0 ? void 0 : _b.find((token) => (0, index_1.normalizeSuiTokenAddress)(token.address) === (0, index_1.normalizeSuiTokenAddress)(inputToken.address));
129
+ let tokenBalance = (tokenAsset === null || tokenAsset === void 0 ? void 0 : tokenAsset.balance) || '0';
130
+ const balanceDecimal = new decimal_js_1.default(tokenBalance);
131
+ if (balanceDecimal.gte(requiredAmount)) {
132
+ availableWallets.push({
133
+ wallet,
134
+ balance: tokenBalance
135
+ });
136
+ }
137
+ else {
138
+ console.log(`钱包 ${walletAddress} 余额不足: ${tokenBalance} ${inputToken.symbol} < ${requiredAmount} ${inputToken.symbol}`);
139
+ }
140
+ allWallets.push({
132
141
  wallet,
133
142
  balance: tokenBalance
134
143
  });
135
144
  }
136
- else {
137
- console.log(`钱包 ${walletAddress} 余额不足: ${tokenBalance} ${inputToken.symbol} < ${requiredAmount} ${inputToken.symbol}`);
145
+ catch (error) {
146
+ console.warn(`处理钱包资产时出错: ${walletAddress}`, error);
138
147
  }
139
- allWallets.push({
140
- wallet,
141
- balance: tokenBalance
142
- });
143
148
  }
144
- catch (error) {
145
- console.warn(`处理钱包资产时出错: ${walletAddress}`, error);
149
+ if (availableWallets.length === 0) {
150
+ let error_msg = `all wallets are insufficient, required: ${requiredAmount} ${inputToken.symbol}`;
151
+ (0, dist_1.log_warn)(error_msg);
152
+ allWallets.forEach((walletInfo, index) => {
153
+ const walletAddress = walletInfo.wallet.getPublicKey().toSuiAddress();
154
+ const shortAddress = walletAddress.substring(0, 6) + '...' + walletAddress.substring(walletAddress.length - 4);
155
+ console.log(`${index + 1}. ${shortAddress}: ${walletInfo.balance} ${inputToken.symbol}`);
156
+ });
157
+ throw new Error(error_msg);
146
158
  }
147
- }
148
- if (availableWallets.length === 0) {
149
- let error_msg = `all wallets are insufficient, required: ${requiredAmount} ${inputToken.symbol}`;
150
- (0, dist_1.log_warn)(error_msg);
151
- allWallets.forEach((walletInfo, index) => {
152
- const walletAddress = walletInfo.wallet.getPublicKey().toSuiAddress();
153
- const shortAddress = walletAddress.substring(0, 6) + '...' + walletAddress.substring(walletAddress.length - 4);
154
- console.log(`${index + 1}. ${shortAddress}: ${walletInfo.balance} ${inputToken.symbol}`);
155
- });
156
- throw new Error(error_msg);
157
- }
158
- console.log('availableWallets', availableWallets.map(w => w.wallet.getPublicKey().toSuiAddress()));
159
- const wallet_last_used = yield this.redisClient.hgetall('sui:wallet:last_used');
160
- for (const availableWallet of availableWallets) {
161
- const walletAddress = availableWallet.wallet.getPublicKey().toSuiAddress();
162
- const lastUsedData = wallet_last_used === null || wallet_last_used === void 0 ? void 0 : wallet_last_used[walletAddress];
163
- if (lastUsedData) {
164
- try {
165
- const lastUsedInfo = JSON.parse(lastUsedData);
166
- availableWallet.lastUsedAt = lastUsedInfo.lastUsedAt;
159
+ console.log('availableWallets', availableWallets.map(w => w.wallet.getPublicKey().toSuiAddress()));
160
+ const wallet_last_used = yield this.redisClient.hgetall('sui:wallet:last_used');
161
+ for (const availableWallet of availableWallets) {
162
+ const walletAddress = availableWallet.wallet.getPublicKey().toSuiAddress();
163
+ const lastUsedData = wallet_last_used === null || wallet_last_used === void 0 ? void 0 : wallet_last_used[walletAddress];
164
+ if (lastUsedData) {
165
+ try {
166
+ const lastUsedInfo = JSON.parse(lastUsedData);
167
+ availableWallet.lastUsedAt = lastUsedInfo.lastUsedAt;
168
+ }
169
+ catch (error) {
170
+ console.warn(`解析钱包最后使用时间失败: ${walletAddress}`, error);
171
+ }
167
172
  }
168
- catch (error) {
169
- console.warn(`解析钱包最后使用时间失败: ${walletAddress}`, error);
173
+ else {
174
+ yield this.redisClient.hsetValue('sui:wallet:last_used', walletAddress, JSON.stringify({
175
+ lastUsedAt: 0,
176
+ lastUsedTime: new Date(0).toISOString()
177
+ }), 24 * 60 * 60);
178
+ availableWallet.lastUsedAt = 0;
170
179
  }
171
180
  }
172
- else {
173
- yield this.redisClient.hsetValue('sui:wallet:last_used', walletAddress, JSON.stringify({
174
- lastUsedAt: 0,
175
- lastUsedTime: new Date(0).toISOString()
176
- }), 24 * 60 * 60);
177
- availableWallet.lastUsedAt = 0;
178
- }
179
- }
180
- let selectedWallet;
181
- let selectionStrategy;
182
- if (availableWallets.length === 1) {
183
- selectedWallet = availableWallets[0].wallet;
184
- selectionStrategy = 'OnlyOne';
185
- }
186
- else {
187
- const hasUsageHistory = wallet_last_used && Object.keys(wallet_last_used).length > 0;
188
- if (hasUsageHistory) {
189
- availableWallets.sort((a, b) => {
190
- const aTime = a.lastUsedAt || 0;
191
- const bTime = b.lastUsedAt || 0;
192
- return aTime - bTime;
193
- });
181
+ let selectedWallet;
182
+ let selectionStrategy;
183
+ if (availableWallets.length === 1) {
194
184
  selectedWallet = availableWallets[0].wallet;
195
- selectionStrategy = 'MaxLastUsed';
185
+ selectionStrategy = 'OnlyOne';
196
186
  }
197
187
  else {
198
- availableWallets.sort((a, b) => {
199
- const aBalance = new decimal_js_1.default(a.balance);
200
- const bBalance = new decimal_js_1.default(b.balance);
201
- return bBalance.cmp(aBalance);
202
- });
203
- selectedWallet = availableWallets[0].wallet;
204
- selectionStrategy = 'MaxBalance';
188
+ const hasUsageHistory = wallet_last_used && Object.keys(wallet_last_used).length > 0;
189
+ if (hasUsageHistory) {
190
+ availableWallets.sort((a, b) => {
191
+ const aTime = a.lastUsedAt || 0;
192
+ const bTime = b.lastUsedAt || 0;
193
+ return aTime - bTime;
194
+ });
195
+ selectedWallet = availableWallets[0].wallet;
196
+ selectionStrategy = 'MaxLastUsed';
197
+ }
198
+ else {
199
+ availableWallets.sort((a, b) => {
200
+ const aBalance = new decimal_js_1.default(a.balance);
201
+ const bBalance = new decimal_js_1.default(b.balance);
202
+ return bBalance.cmp(aBalance);
203
+ });
204
+ selectedWallet = availableWallets[0].wallet;
205
+ selectionStrategy = 'MaxBalance';
206
+ }
205
207
  }
208
+ const selectedWalletAddress = selectedWallet.getPublicKey().toSuiAddress();
209
+ yield this.redisClient.hsetValue('sui:wallet:last_used', selectedWalletAddress, JSON.stringify({
210
+ lastUsedAt: Date.now(),
211
+ lastUsedTime: new Date().toISOString()
212
+ }), 24 * 60 * 60);
213
+ const selectedWalletInfo = availableWallets.find(w => w.wallet.getPublicKey().toSuiAddress() === selectedWalletAddress);
214
+ (0, dist_1.log_info)(`Choose wallet: ${selectionStrategy} -> ${selectedWalletAddress}, balance: ${selectedWalletInfo === null || selectedWalletInfo === void 0 ? void 0 : selectedWalletInfo.balance} ${inputToken.symbol}, required: ${requiredAmount} ${inputToken.symbol}`);
215
+ return selectedWallet;
216
+ }
217
+ catch (error) {
218
+ (0, dist_1.log_error)(`choose wallet failed, error: ${error.message}`, error);
219
+ throw error;
220
+ }
221
+ finally {
222
+ yield this.redisClient.releaseLock(lockKey, lockValue);
206
223
  }
207
- const selectedWalletAddress = selectedWallet.getPublicKey().toSuiAddress();
208
- yield this.redisClient.hsetValue('sui:wallet:last_used', selectedWalletAddress, JSON.stringify({
209
- lastUsedAt: Date.now(),
210
- lastUsedTime: new Date().toISOString()
211
- }), 24 * 60 * 60);
212
- const selectedWalletInfo = availableWallets.find(w => w.wallet.getPublicKey().toSuiAddress() === selectedWalletAddress);
213
- (0, dist_1.log_info)(`Choose wallet: ${selectionStrategy} -> ${selectedWalletAddress}, balance: ${selectedWalletInfo === null || selectedWalletInfo === void 0 ? void 0 : selectedWalletInfo.balance} ${inputToken.symbol}, required: ${requiredAmount} ${inputToken.symbol}`);
214
- return selectedWallet;
215
224
  });
216
225
  }
217
226
  determineInputOutputTokens(order_msg, pool_info) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@clonegod/ttd-sui-common",
3
- "version": "1.0.92",
3
+ "version": "1.0.94",
4
4
  "description": "Sui common library",
5
5
  "license": "UNLICENSED",
6
6
  "main": "dist/index.js",
@@ -15,7 +15,7 @@
15
15
  "push": "npm run build && npm publish"
16
16
  },
17
17
  "dependencies": {
18
- "@clonegod/ttd-core": "2.0.67",
18
+ "@clonegod/ttd-core": "2.0.85",
19
19
  "@grpc/grpc-js": "^1.13.4",
20
20
  "@grpc/proto-loader": "^0.8.0",
21
21
  "@mysten/sui": "^1.37.5",