This repository was archived by the owner on Sep 8, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
Expand file tree
/
Copy pathuseBbnQuery.ts
More file actions
298 lines (279 loc) · 9.43 KB
/
Copy pathuseBbnQuery.ts
File metadata and controls
298 lines (279 loc) · 9.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
import {
btclightclientquery,
incentivequery,
} from "@babylonlabs-io/babylon-proto-ts";
import {
QueryClient,
createProtobufRpcClient,
setupBankExtension,
} from "@cosmjs/stargate";
import { ONE_MINUTE, ONE_SECOND } from "@/ui/common/constants";
import { useBbnRpc } from "@/ui/common/context/rpc/BbnRpcProvider";
import { useCosmosWallet } from "@/ui/common/context/wallet/CosmosWalletProvider";
import { ClientError } from "@/ui/common/errors";
import { ERROR_CODES } from "@/ui/common/errors/codes";
import { useHealthCheck } from "@/ui/common/hooks/useHealthCheck";
import { useClientQuery } from "../../useClient";
import { useRpcErrorHandler } from "../useRpcErrorHandler";
const BBN_BTCLIGHTCLIENT_TIP_KEY = "BBN_BTCLIGHTCLIENT_TIP";
const BBN_BALANCE_KEY = "BBN_BALANCE";
const BBN_REWARDS_KEY = "BBN_REWARDS";
const BBN_REWARDS_COINS_KEY = "BBN_REWARDS_COINS";
const BBN_HEIGHT_KEY = "BBN_HEIGHT";
const REWARD_GAUGE_KEY_BTC_DELEGATION = "BTC_STAKER";
/**
* Query service for Babylon which contains all the queries for
* interacting with Babylon RPC nodes
*/
export const useBbnQuery = () => {
const { isGeoBlocked, isLoading: isHealthcheckLoading } = useHealthCheck();
const { bech32Address, connected } = useCosmosWallet();
const { queryClient, tmClient } = useBbnRpc();
const { hasRpcError, reconnect } = useRpcErrorHandler();
/**
* Gets the rewards from the user's account.
* @returns {Promise<number>} - The rewards from the user's account.
*/
const rewardsQuery = useClientQuery({
queryKey: [BBN_REWARDS_KEY, bech32Address, connected],
queryFn: async () => {
if (!connected || !queryClient || !bech32Address) {
return undefined;
}
const { incentive } = setupIncentiveExtension(queryClient);
const req: incentivequery.QueryRewardGaugesRequest =
incentivequery.QueryRewardGaugesRequest.fromPartial({
address: bech32Address,
});
let rewards: incentivequery.QueryRewardGaugesResponse;
try {
rewards = await incentive.RewardGauges(req);
} catch (error) {
// If error message contains "reward gauge not found", silently return 0
// This is to handle the case where the user has no rewards, meaning
// they have not staked
if (
error instanceof Error &&
error.message.includes("reward gauge not found")
) {
return 0;
}
throw new ClientError(
ERROR_CODES.EXTERNAL_SERVICE_UNAVAILABLE,
"Error getting rewards",
{ cause: error as Error },
);
}
if (!rewards) {
return 0;
}
const coins = rewards.rewardGauges[
REWARD_GAUGE_KEY_BTC_DELEGATION
]?.coins?.filter((c) => c.denom === "ubbn");
if (!coins) {
return 0;
}
const withdrawnCoins = rewards.rewardGauges[
REWARD_GAUGE_KEY_BTC_DELEGATION
]?.withdrawnCoins
.filter((c) => c.denom === "ubbn")
.reduce((acc, coin) => acc + Number(coin.amount), 0);
return (
coins.reduce((acc, coin) => acc + Number(coin.amount), 0) -
(withdrawnCoins || 0)
);
},
enabled: Boolean(
queryClient &&
connected &&
bech32Address &&
!isGeoBlocked &&
!isHealthcheckLoading,
),
staleTime: ONE_MINUTE,
refetchInterval: ONE_MINUTE,
});
/**
* Gets per-denom rewards coins for BTC_STAKER gauge.
* Returns an array of { denom: string; amount: number } with withdrawn amounts subtracted.
*/
const rewardCoinsQuery = useClientQuery({
queryKey: [BBN_REWARDS_COINS_KEY, bech32Address, connected],
queryFn: async () => {
if (!connected || !queryClient || !bech32Address) {
return [] as Array<{ denom: string; amount: number }>;
}
console.log("[BbnQuery] Fetching per-denom reward coins", {
address: bech32Address,
});
const { incentive } = setupIncentiveExtension(queryClient);
const req: incentivequery.QueryRewardGaugesRequest =
incentivequery.QueryRewardGaugesRequest.fromPartial({
address: bech32Address,
});
let rewards: incentivequery.QueryRewardGaugesResponse;
try {
rewards = await incentive.RewardGauges(req);
console.log("[BbnQuery] Raw RewardGauges response", rewards);
} catch (error) {
if (
error instanceof Error &&
error.message.includes("reward gauge not found")
) {
console.log(
"[BbnQuery] Reward gauge not found; returning empty rewards",
);
return [] as Array<{ denom: string; amount: number }>;
}
throw new ClientError(
ERROR_CODES.EXTERNAL_SERVICE_UNAVAILABLE,
"Error getting rewards",
{ cause: error as Error },
);
}
const gauge = rewards.rewardGauges[REWARD_GAUGE_KEY_BTC_DELEGATION];
if (!gauge) {
console.log(
"[BbnQuery] BTC_STAKER gauge missing in response; returning empty",
);
return [] as Array<{ denom: string; amount: number }>;
}
console.log("[BbnQuery] Gauge coins", gauge.coins);
console.log("[BbnQuery] Gauge withdrawnCoins", gauge.withdrawnCoins);
const totalByDenom = new Map<string, number>();
const withdrawnByDenom = new Map<string, number>();
for (const coin of gauge.coins ?? []) {
const prev = totalByDenom.get(coin.denom) ?? 0;
totalByDenom.set(coin.denom, prev + Number(coin.amount));
}
for (const coin of gauge.withdrawnCoins ?? []) {
const prev = withdrawnByDenom.get(coin.denom) ?? 0;
withdrawnByDenom.set(coin.denom, prev + Number(coin.amount));
}
console.log(
"[BbnQuery] totalByDenom",
Array.from(totalByDenom.entries()),
);
console.log(
"[BbnQuery] withdrawnByDenom",
Array.from(withdrawnByDenom.entries()),
);
const results: Array<{ denom: string; amount: number }> = [];
for (const [denom, total] of totalByDenom.entries()) {
const withdrawn = withdrawnByDenom.get(denom) ?? 0;
const net = Math.max(0, total - withdrawn);
if (net > 0) {
results.push({ denom, amount: net });
}
}
console.log("[BbnQuery] Net per-denom rewards", results);
return results;
},
enabled: Boolean(
queryClient &&
connected &&
bech32Address &&
!isGeoBlocked &&
!isHealthcheckLoading,
),
staleTime: ONE_MINUTE,
refetchInterval: ONE_MINUTE,
});
/**
* Gets the balance of the user's account.
* @returns {Promise<Object>} - The balance of the user's account.
*/
const balanceQuery = useClientQuery({
queryKey: [BBN_BALANCE_KEY, bech32Address, connected],
queryFn: async () => {
if (!connected || !queryClient || !bech32Address) {
return 0;
}
const { bank } = setupBankExtension(queryClient);
const balance = await bank.balance(bech32Address, "ubbn");
return Number(balance?.amount ?? 0);
},
enabled: Boolean(
queryClient &&
connected &&
bech32Address &&
!isGeoBlocked &&
!isHealthcheckLoading,
),
staleTime: ONE_MINUTE,
refetchInterval: ONE_MINUTE,
});
/**
* Gets the tip of the Bitcoin blockchain.
* @returns {Promise<Object>} - The tip of the Bitcoin blockchain.
*/
const btcTipQuery = useClientQuery({
queryKey: [BBN_BTCLIGHTCLIENT_TIP_KEY],
queryFn: async () => {
if (!queryClient) {
return undefined;
}
const { btclightQueryClient } = setupBtclightClientExtension(queryClient);
const req = btclightclientquery.QueryTipRequest.fromPartial({});
const { header } = await btclightQueryClient.Tip(req);
return header;
},
enabled: Boolean(queryClient && !isGeoBlocked && !isHealthcheckLoading),
staleTime: ONE_MINUTE,
refetchInterval: false, // Disable automatic periodic refetching
});
/**
* Gets the current height of the Babylon Genesis chain.
* @returns {Promise<number>} - The current height of the Babylon Genesis chain.
*/
const babyTipQuery = useClientQuery({
queryKey: [BBN_HEIGHT_KEY],
queryFn: async () => {
if (!tmClient) {
return 0;
}
try {
const status = await tmClient.status();
return status.syncInfo.latestBlockHeight;
} catch (error) {
throw new ClientError(
ERROR_CODES.EXTERNAL_SERVICE_UNAVAILABLE,
"Error getting Babylon chain height",
{ cause: error as Error },
);
}
},
enabled: Boolean(tmClient && connected),
staleTime: ONE_SECOND * 10,
refetchInterval: false, // Disable automatic periodic refetching
});
return {
rewardsQuery,
rewardCoinsQuery,
balanceQuery,
btcTipQuery,
babyTipQuery,
hasRpcError,
reconnectRpc: reconnect,
queryClient,
};
};
// Extend the QueryClient with the Incentive module
const setupIncentiveExtension = (
base: QueryClient,
): {
incentive: incentivequery.QueryClientImpl;
} => {
const rpc = createProtobufRpcClient(base);
const incentiveQueryClient = new incentivequery.QueryClientImpl(rpc);
return { incentive: incentiveQueryClient };
};
const setupBtclightClientExtension = (
base: QueryClient,
): {
btclightQueryClient: btclightclientquery.QueryClientImpl;
} => {
const rpc = createProtobufRpcClient(base);
const btclightQueryClient = new btclightclientquery.QueryClientImpl(rpc);
return { btclightQueryClient };
};