@berachain/berajs 0.2.6-patch.2 → 0.2.7
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/abi/exports.cjs.map +1 -1
- package/dist/actions/exports.cjs +1 -1
- package/dist/actions/exports.cjs.map +1 -1
- package/dist/actions/exports.d.cts +10 -5
- package/dist/actions/exports.d.ts +10 -5
- package/dist/actions/exports.mjs +1 -1
- package/dist/actions/exports.mjs.map +1 -1
- package/dist/chunk-2YBHAMDV.cjs.map +1 -1
- package/dist/{chunk-I4V54RRZ.cjs → chunk-4436B2EF.cjs} +3 -3
- package/dist/chunk-4436B2EF.cjs.map +1 -0
- package/dist/chunk-57RINXU6.cjs.map +1 -1
- package/dist/chunk-74WA35RI.cjs.map +1 -1
- package/dist/{chunk-WIN4PK2Z.mjs → chunk-7VQA45R5.mjs} +3 -3
- package/dist/{chunk-WIN4PK2Z.mjs.map → chunk-7VQA45R5.mjs.map} +1 -1
- package/dist/{chunk-NVOJIQUM.cjs → chunk-CF3LFNXG.cjs} +2 -2
- package/dist/chunk-CF3LFNXG.cjs.map +1 -0
- package/dist/{chunk-KRVNPZLF.mjs → chunk-COMMLZ3O.mjs} +2 -2
- package/dist/chunk-DDEQFR3M.cjs.map +1 -1
- package/dist/chunk-DK42F2ZM.cjs.map +1 -1
- package/dist/{chunk-3ZTAIOHH.mjs → chunk-FM3WDBFH.mjs} +2 -2
- package/dist/chunk-I7M43BB4.cjs.map +1 -1
- package/dist/{chunk-QXNF3YT7.cjs → chunk-LNVR4BW6.cjs} +2 -2
- package/dist/chunk-LNVR4BW6.cjs.map +1 -0
- package/dist/chunk-NMH7LHPW.cjs.map +1 -1
- package/dist/chunk-NVHV2LDK.cjs.map +1 -1
- package/dist/chunk-OIYXOKTT.cjs.map +1 -1
- package/dist/chunk-OUD27MU7.cjs.map +1 -1
- package/dist/chunk-RWOICHRW.cjs.map +1 -1
- package/dist/chunk-WRFDB3QJ.cjs.map +1 -1
- package/dist/chunk-XNJLSA6P.cjs.map +1 -1
- package/dist/contexts/exports.cjs +1 -1
- package/dist/contexts/exports.cjs.map +1 -1
- package/dist/contexts/exports.mjs +1 -1
- package/dist/enum/exports.cjs.map +1 -1
- package/dist/errors/exports.cjs.map +1 -1
- package/dist/{getValidatorQueuedOperatorAddress-CmiPJmsr.d.ts → getValidatorQueuedOperatorAddress-B5T8_BMr.d.ts} +3 -3
- package/dist/{getValidatorQueuedOperatorAddress-BdDYHycN.d.cts → getValidatorQueuedOperatorAddress-BtCefJyH.d.cts} +3 -3
- package/dist/{global.d-CwT1Phzf.d.cts → global.d-6aSWIkV_.d.cts} +1 -1
- package/dist/{global.d-3GQMgC9k.d.ts → global.d-SU9Epq0M.d.ts} +1 -1
- package/dist/hooks/exports.cjs +2 -2
- package/dist/hooks/exports.cjs.map +1 -1
- package/dist/hooks/exports.d.cts +4 -4
- package/dist/hooks/exports.d.ts +4 -4
- package/dist/hooks/exports.mjs +1 -1
- package/dist/types/exports.cjs.map +1 -1
- package/dist/types/exports.d.cts +1 -1
- package/dist/types/exports.d.ts +1 -1
- package/dist/utils/exports.cjs.map +1 -1
- package/package.json +7 -7
- package/src/actions/exports.ts +1 -0
- package/src/actions/validators/getUserActiveValidators.ts +2 -2
- package/src/actions/validators/utils/__tests__/validatorUtils.integration.test.ts +20 -4
- package/src/actions/validators/utils/aggregateValidatorIncentives.ts +64 -0
- package/src/actions/validators/utils/aggregateValidatorIncentives.unit.test.ts +270 -0
- package/src/types/pol.d.ts +1 -1
- package/dist/chunk-I4V54RRZ.cjs.map +0 -1
- package/dist/chunk-NVOJIQUM.cjs.map +0 -1
- package/dist/chunk-QXNF3YT7.cjs.map +0 -1
- /package/dist/{chunk-KRVNPZLF.mjs.map → chunk-COMMLZ3O.mjs.map} +0 -0
- /package/dist/{chunk-3ZTAIOHH.mjs.map → chunk-FM3WDBFH.mjs.map} +0 -0
|
@@ -0,0 +1,270 @@
|
|
|
1
|
+
import BigNumber from "@berachain/utils/pkg/bignumber.js";
|
|
2
|
+
|
|
3
|
+
import type { MinimalERC20 } from "../../../types/dex";
|
|
4
|
+
import { getHoneyToken, wBeraToken } from "../../../utils/tokens";
|
|
5
|
+
import { aggregateValidatorIncentives } from "./aggregateValidatorIncentives";
|
|
6
|
+
|
|
7
|
+
function createIncentive({
|
|
8
|
+
token,
|
|
9
|
+
remainingAmount,
|
|
10
|
+
price,
|
|
11
|
+
}: {
|
|
12
|
+
token: Omit<MinimalERC20, "chainId">;
|
|
13
|
+
remainingAmount: string;
|
|
14
|
+
price: number;
|
|
15
|
+
}) {
|
|
16
|
+
return {
|
|
17
|
+
token: token,
|
|
18
|
+
remainingAmount: remainingAmount,
|
|
19
|
+
remainingAmountUsd: new BigNumber(remainingAmount).times(price).toString(),
|
|
20
|
+
incentiveRate: new BigNumber(1).times(price).toString(),
|
|
21
|
+
incentiveRateUsd: price.toString(),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
describe("aggregateValidatorIncentives", () => {
|
|
26
|
+
const price1 = 1;
|
|
27
|
+
const price2 = 2;
|
|
28
|
+
const incentive1 = createIncentive({
|
|
29
|
+
token: wBeraToken,
|
|
30
|
+
remainingAmount: "1",
|
|
31
|
+
price: price1,
|
|
32
|
+
});
|
|
33
|
+
const incentive2 = createIncentive({
|
|
34
|
+
token: getHoneyToken({}),
|
|
35
|
+
remainingAmount: "1",
|
|
36
|
+
price: price2,
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
it("returns empty array for empty rewardAllocationWeights", () => {
|
|
40
|
+
const incentives = aggregateValidatorIncentives({
|
|
41
|
+
rewardAllocationWeights: [],
|
|
42
|
+
});
|
|
43
|
+
expect(incentives).toEqual([]);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
it("aggregates same token across two vaults with equal weights", () => {
|
|
47
|
+
const incentives = aggregateValidatorIncentives({
|
|
48
|
+
rewardAllocationWeights: [
|
|
49
|
+
{
|
|
50
|
+
percentage: 0.5,
|
|
51
|
+
receivingVault: {
|
|
52
|
+
activeIncentives: [incentive1],
|
|
53
|
+
},
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
percentage: 0.5,
|
|
57
|
+
receivingVault: {
|
|
58
|
+
activeIncentives: [incentive1],
|
|
59
|
+
},
|
|
60
|
+
},
|
|
61
|
+
],
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
expect(incentives).toHaveLength(1);
|
|
65
|
+
expect(incentives[0]?.token.address).toBe(wBeraToken.address);
|
|
66
|
+
expect(incentives[0]?.remainingAmount).toBe("2");
|
|
67
|
+
expect(incentives[0]?.remainingAmountUsd).toBe("2");
|
|
68
|
+
expect(incentives[0]?.incentiveRate).toBe("1");
|
|
69
|
+
// 1*0.5 + 1*0.5 = 1
|
|
70
|
+
expect(incentives[0]?.incentiveRateUsd).toBe("1");
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
it("aggregates two different tokens across vaults", () => {
|
|
74
|
+
const incentives = aggregateValidatorIncentives({
|
|
75
|
+
rewardAllocationWeights: [
|
|
76
|
+
{
|
|
77
|
+
percentage: 0.5,
|
|
78
|
+
receivingVault: {
|
|
79
|
+
activeIncentives: [incentive1],
|
|
80
|
+
},
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
percentage: 0.5,
|
|
84
|
+
receivingVault: {
|
|
85
|
+
activeIncentives: [incentive2],
|
|
86
|
+
},
|
|
87
|
+
},
|
|
88
|
+
],
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
expect(incentives).toHaveLength(2);
|
|
92
|
+
|
|
93
|
+
const wBeraResult = incentives.find(
|
|
94
|
+
(i) => i.token.address === wBeraToken.address,
|
|
95
|
+
);
|
|
96
|
+
const honeyResult = incentives.find(
|
|
97
|
+
(i) => i.token.address === getHoneyToken({}).address,
|
|
98
|
+
);
|
|
99
|
+
|
|
100
|
+
expect(wBeraResult).toBeDefined();
|
|
101
|
+
expect(wBeraResult?.remainingAmount).toBe("1");
|
|
102
|
+
expect(wBeraResult?.incentiveRate).toBe("0.5");
|
|
103
|
+
|
|
104
|
+
expect(honeyResult).toBeDefined();
|
|
105
|
+
expect(honeyResult?.remainingAmount).toBe("1");
|
|
106
|
+
expect(honeyResult?.incentiveRate).toBe("1");
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
it("aggregates same token + different token in one vault", () => {
|
|
110
|
+
const incentives = aggregateValidatorIncentives({
|
|
111
|
+
rewardAllocationWeights: [
|
|
112
|
+
{
|
|
113
|
+
percentage: 0.5,
|
|
114
|
+
receivingVault: {
|
|
115
|
+
activeIncentives: [incentive1],
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
{
|
|
119
|
+
percentage: 0.5,
|
|
120
|
+
receivingVault: {
|
|
121
|
+
activeIncentives: [incentive1, incentive2],
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
],
|
|
125
|
+
});
|
|
126
|
+
|
|
127
|
+
expect(incentives).toHaveLength(2);
|
|
128
|
+
|
|
129
|
+
const wBeraResult = incentives.find(
|
|
130
|
+
(i) => i.token.address === wBeraToken.address,
|
|
131
|
+
);
|
|
132
|
+
const honeyResult = incentives.find(
|
|
133
|
+
(i) => i.token.address === getHoneyToken({}).address,
|
|
134
|
+
);
|
|
135
|
+
|
|
136
|
+
expect(wBeraResult).toBeDefined();
|
|
137
|
+
expect(wBeraResult?.remainingAmount).toBe("2");
|
|
138
|
+
expect(wBeraResult?.remainingAmountUsd).toBe("2");
|
|
139
|
+
expect(wBeraResult?.incentiveRate).toBe("1");
|
|
140
|
+
// 1*0.5 + 1*0.5 = 1
|
|
141
|
+
expect(wBeraResult?.incentiveRateUsd).toBe("1");
|
|
142
|
+
|
|
143
|
+
expect(honeyResult).toBeDefined();
|
|
144
|
+
expect(honeyResult?.remainingAmount).toBe("1");
|
|
145
|
+
expect(honeyResult?.remainingAmountUsd).toBe("2");
|
|
146
|
+
// 2*0.5 = 1
|
|
147
|
+
expect(honeyResult?.incentiveRate).toBe("1");
|
|
148
|
+
expect(honeyResult?.incentiveRateUsd).toBe("1");
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
it("filters out incentives with zero remainingAmount", () => {
|
|
152
|
+
const zeroIncentive = createIncentive({
|
|
153
|
+
token: wBeraToken,
|
|
154
|
+
remainingAmount: "0",
|
|
155
|
+
price: price1,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
const incentives = aggregateValidatorIncentives({
|
|
159
|
+
rewardAllocationWeights: [
|
|
160
|
+
{
|
|
161
|
+
percentage: 1,
|
|
162
|
+
receivingVault: {
|
|
163
|
+
activeIncentives: [zeroIncentive],
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
],
|
|
167
|
+
});
|
|
168
|
+
|
|
169
|
+
expect(incentives).toEqual([]);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it("skips allocations with null receivingVault", () => {
|
|
173
|
+
const incentives = aggregateValidatorIncentives({
|
|
174
|
+
rewardAllocationWeights: [
|
|
175
|
+
{
|
|
176
|
+
percentage: 0.5,
|
|
177
|
+
receivingVault: null,
|
|
178
|
+
},
|
|
179
|
+
{
|
|
180
|
+
percentage: 0.5,
|
|
181
|
+
receivingVault: {
|
|
182
|
+
activeIncentives: [incentive1],
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
],
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
expect(incentives).toHaveLength(1);
|
|
189
|
+
expect(incentives[0]?.token.address).toBe(wBeraToken.address);
|
|
190
|
+
expect(incentives[0]?.remainingAmount).toBe("1");
|
|
191
|
+
expect(incentives[0]?.incentiveRate).toBe("0.5");
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
it("applies percentage weights correctly to incentiveRate", () => {
|
|
195
|
+
const incentives = aggregateValidatorIncentives({
|
|
196
|
+
rewardAllocationWeights: [
|
|
197
|
+
{
|
|
198
|
+
percentage: 0.3,
|
|
199
|
+
receivingVault: {
|
|
200
|
+
activeIncentives: [incentive1],
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
percentage: 0.7,
|
|
205
|
+
receivingVault: {
|
|
206
|
+
activeIncentives: [incentive1],
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
],
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
expect(incentives).toHaveLength(1);
|
|
213
|
+
expect(incentives[0]?.remainingAmount).toBe("2");
|
|
214
|
+
// incentiveRate: 1*0.3 + 1*0.7 = 1
|
|
215
|
+
expect(incentives[0]?.incentiveRate).toBe("1");
|
|
216
|
+
// incentiveRateUsd: 1*0.3 + 1*0.7 = 1
|
|
217
|
+
expect(incentives[0]?.incentiveRateUsd).toBe("1");
|
|
218
|
+
});
|
|
219
|
+
|
|
220
|
+
it("handles single allocation with 100% weight", () => {
|
|
221
|
+
const incentives = aggregateValidatorIncentives({
|
|
222
|
+
rewardAllocationWeights: [
|
|
223
|
+
{
|
|
224
|
+
percentage: 1,
|
|
225
|
+
receivingVault: {
|
|
226
|
+
activeIncentives: [incentive1],
|
|
227
|
+
},
|
|
228
|
+
},
|
|
229
|
+
],
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
expect(incentives).toHaveLength(1);
|
|
233
|
+
expect(incentives[0]?.token.address).toBe(wBeraToken.address);
|
|
234
|
+
expect(incentives[0]?.remainingAmount).toBe("1");
|
|
235
|
+
expect(incentives[0]?.incentiveRate).toBe("1");
|
|
236
|
+
expect(incentives[0]?.incentiveRateUsd).toBe("1");
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
it("handles vault with empty activeIncentives", () => {
|
|
240
|
+
const incentives = aggregateValidatorIncentives({
|
|
241
|
+
rewardAllocationWeights: [
|
|
242
|
+
{
|
|
243
|
+
percentage: 1,
|
|
244
|
+
receivingVault: {
|
|
245
|
+
activeIncentives: [],
|
|
246
|
+
},
|
|
247
|
+
},
|
|
248
|
+
],
|
|
249
|
+
});
|
|
250
|
+
|
|
251
|
+
expect(incentives).toEqual([]);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
it("keeps token metadata as nested object", () => {
|
|
255
|
+
const incentives = aggregateValidatorIncentives({
|
|
256
|
+
rewardAllocationWeights: [
|
|
257
|
+
{
|
|
258
|
+
percentage: 1,
|
|
259
|
+
receivingVault: {
|
|
260
|
+
activeIncentives: [incentive1],
|
|
261
|
+
},
|
|
262
|
+
},
|
|
263
|
+
],
|
|
264
|
+
});
|
|
265
|
+
|
|
266
|
+
expect(incentives[0]?.token.symbol).toBe(wBeraToken.symbol);
|
|
267
|
+
expect(incentives[0]?.token.name).toBe(wBeraToken.name);
|
|
268
|
+
expect(incentives[0]?.token.decimals).toBe(wBeraToken.decimals);
|
|
269
|
+
});
|
|
270
|
+
});
|
package/src/types/pol.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ export type IncentiveReward = {
|
|
|
18
18
|
available_at: number;
|
|
19
19
|
};
|
|
20
20
|
export interface IncentiveRewardChunksWithValidatorData {
|
|
21
|
-
validator: ApiValidatorFragment | undefined;
|
|
21
|
+
validator: ApiValidatorInListFragment | ApiValidatorFragment | undefined;
|
|
22
22
|
maxTimestamp: number | undefined;
|
|
23
23
|
minTimestamp: number | undefined;
|
|
24
24
|
totalValue: number;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/snowbera/Documents/workspace/monobera/packages/berajs/dist/chunk-I4V54RRZ.cjs","../src/actions/bend/getConvertToAssets.ts","../src/actions/clients/BeraApolloClient.ts","../src/actions/governance/parseProposalBody.ts","../src/actions/governance/getProposalFromTx.ts"],"names":["getConvertToAssets","sharesAmount","vaultAddress","publicClient","convertToAssets","metaMorphoAbi","formatEther","BeraApolloClient","ApolloClient","options","queryName","getQueryName","endpoint","tags","executeQuery","res","BeraTracing"],"mappings":"AAAA,q+CAAyC,wDAAuJ,wDAAgE,wDAAyD,wDAAsE,wDAA+E,4BCAjZ,8EAEX,MAQlD,SAAsBA,EAAAA,CAAmB,CACvC,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CAAAA,CACA,YAAA,CAAAC,CACF,CAAA,CAAyE,CACvE,IAAMC,CAAAA,CAAkB,MAAMD,CAAAA,CAAa,YAAA,CAAa,CACtD,OAAA,CAASD,CAAAA,CACT,GAAA,CAAKG,+BAAAA,CACL,YAAA,CAAc,iBAAA,CACd,IAAA,CAAM,CAACJ,CAAY,CACrB,CAAC,CAAA,CACD,MAAO,CAAE,GAAA,CAAKG,CAAAA,CAAiB,SAAA,CAAWE,+BAAAA,CAA2B,CAAE,CACzE,CCtBA,wCAMO,sDAEmB,IAYbC,EAAAA,CAAN,MAAA,QAA+BC,oBAAa,CAIvC,WAEV,CACEC,CAAAA,CAMA,CACA,KAAA,CAAMA,CAAO,CAAA,CACb,IAAA,CAAK,GAAA,CAAMA,CAAAA,CAAQ,GACrB,CAEA,MAAM,KAAA,CAKJA,CAAAA,CAIC,CACD,IAAMC,CAAAA,CAAYC,EAAAA,CAAaF,CAAAA,CAAQ,KAAK,CAAA,CACtCG,CAAAA,CAAW,CACf,GAAA,CAAK,IAAA,CAAK,GAAA,CACV,IAAA,CAAM,SACR,CAAA,CAEMC,CAAAA,CAAO,CACX,gBAAA,CAAkB,OAAA,CAClB,sBAAA,CAAwBD,CAAAA,CAAS,GAAA,CACjC,uBAAA,CAAyBA,CAAAA,CAAS,IAAA,CAClC,4BAAA,CAA8BF,CAChC,CAAA,CAEA,GAAI,CACF,IAAMI,CAAAA,CAAe,CAAA,CAAA,EACnB,KAAA,CAAM,KAAA,CACJL,CACF,CAAA,CAEIM,CAAAA,CAAM,MAAMC,mBAAAA,CAAY,SAAA,CAC5B,CACE,IAAA,CAAM,CAAA,QAAA,EAAWN,CAAS,CAAA,CAAA;ACNQ;ACyBxC","file":"/Users/snowbera/Documents/workspace/monobera/packages/berajs/dist/chunk-I4V54RRZ.cjs","sourcesContent":[null,"import { type Address, formatEther, type PublicClient } from \"viem\";\n\nimport { metaMorphoV11Abi as metaMorphoAbi } from \"@berachain/abis/bend-metamorpho/metaMorphoV11\";\n\nexport interface GetConvertToAssetsProps {\n sharesAmount: bigint;\n vaultAddress: Address;\n publicClient: PublicClient;\n}\n\nexport async function getConvertToAssets({\n sharesAmount,\n vaultAddress,\n publicClient,\n}: GetConvertToAssetsProps): Promise<{ raw: bigint; formatted: string }> {\n const convertToAssets = await publicClient.readContract({\n address: vaultAddress,\n abi: metaMorphoAbi,\n functionName: \"convertToAssets\",\n args: [sharesAmount],\n });\n return { raw: convertToAssets, formatted: formatEther(convertToAssets) };\n}\n","import {\n ApolloClient,\n type DocumentNode,\n type ErrorLike,\n type OperationVariables,\n ServerError,\n} from \"@apollo/client\";\n\nimport { appConfig } from \"@berachain/config/internal\";\n\nimport { BeraError } from \"../../errors/BeraError\";\nimport { BeraTracing } from \"../../errors/BeraTracing\";\nimport { RequestError } from \"../../errors/RequestError\";\n\n/**\n * This is a wrapper around the ApolloClient that throws a BeraError if the query returns an error or no data.\n *\n * It's mostly a typescript helper that keeps data always defined since we use errorPolicy: \"none\" by default.\n * Such setting will throw an error if the query returns an error, rather than returning an object with undefined data and an error property.\n */\nexport class BeraApolloClient extends ApolloClient {\n /**\n * The URL of the endpoint. Used for error reporting only.\n */\n protected url: string;\n\n constructor(\n options: ApolloClient.Options & {\n /**\n * The URL of the endpoint. Used for error reporting only.\n */\n url: string;\n },\n ) {\n super(options);\n this.url = options.url;\n }\n\n async query<\n TData = unknown,\n TVariables extends OperationVariables = OperationVariables,\n >(\n // We handle errors in our custom logic so we don't need to pass errorPolicy here\n options: Omit<ApolloClient.QueryOptions<TData, TVariables>, \"errorPolicy\">,\n ): Promise<{\n // Only data is returned and we're sure it's not undefined due to errorPolicy\n data: TData;\n }> {\n const queryName = getQueryName(options.query);\n const endpoint = {\n url: this.url,\n type: \"graphql\",\n } as const;\n\n const tags = {\n \"operation.type\": \"query\",\n \"operation.source.url\": endpoint.url,\n \"operation.source.type\": endpoint.type,\n \"operation.source.queryName\": queryName,\n };\n\n try {\n const executeQuery = () =>\n super.query<TData, TVariables>(\n options as ApolloClient.QueryOptions<TData, TVariables>,\n );\n\n const res = await BeraTracing.startSpan(\n {\n name: `GraphQL ${queryName}`,\n op: \"BeraApolloClient.query\",\n attributes: tags,\n },\n executeQuery,\n );\n\n if (res.error || res.data === undefined) {\n throw new BeraError({\n level: \"fatal\",\n tags,\n message:\n \"Bera Apollo Client: No data returned from query, but error should be thrown since errorPolicy is none\",\n });\n }\n\n return { data: res.data } as const;\n } catch (error) {\n !appConfig.env.isProduction &&\n console.error(\"BeraApolloClient error\", error);\n\n if (ServerError.is(error)) {\n throw new RequestError({\n // reason: error,\n response: error.response,\n cause: error,\n statusCode: error.statusCode,\n endpoint,\n tags,\n });\n }\n if (error instanceof TypeError) {\n throw new RequestError({\n level: \"fatal\",\n reason: \"TypeError\",\n response: error,\n cause: error,\n endpoint,\n tags,\n });\n }\n throw new RequestError({\n response: error as ErrorLike,\n tags,\n cause: error,\n endpoint,\n });\n }\n }\n}\n\nfunction getQueryName(queryDefinition: DocumentNode) {\n const likelyNode = queryDefinition.definitions.find(\n (def) => def.kind === (\"OperationDefinition\" as const),\n );\n\n return likelyNode?.name?.value;\n}\n","import graymatter from \"gray-matter\";\n\nimport type { ProposalSelectionFragment } from \"@berachain/graphql/governance\";\n\nconst parseLegacyBody = (\n s: string,\n): { type: string | null; title: string; content: string } => {\n const pattern = /#(?:([\\w-]+)# )?(.+)\\n([\\s\\S]*)/;\n const match = s.match(pattern);\n\n if (match) {\n const type = match[1] || null;\n const title = match[2];\n const content = match[3].replace(\"\\n\", \"<br />\");\n return {\n type,\n title,\n content,\n };\n }\n\n throw new Error(\"Invalid proposal body\");\n};\n\nexport const parseProposalBody = (\n proposal?: Pick<ProposalSelectionFragment, \"description\">,\n): graymatter.GrayMatterFile<string> & {\n isFrontMatter: boolean;\n} => {\n if (!proposal) {\n return {\n isFrontMatter: false,\n data: { title: \"Loading...\" },\n content: \"\",\n matter: \"\",\n language: \"\",\n orig: \"\",\n stringify: () => \"\",\n };\n }\n\n const body = proposal?.description ?? \"\";\n\n if (graymatter.test(body)) {\n return { ...graymatter(body), isFrontMatter: true };\n }\n\n try {\n const legacyBody = parseLegacyBody(body);\n\n return {\n isFrontMatter: false,\n data: { title: legacyBody.title },\n content: legacyBody.content,\n matter: \"\",\n language: \"\",\n orig: body,\n stringify: () => body,\n };\n } catch {\n return {\n isFrontMatter: false,\n data: {\n title: proposal?.description?.split(\"\\n\")[0].slice(0, 100),\n },\n content: body,\n matter: \"\",\n language: \"\",\n orig: body,\n stringify: () => body,\n };\n }\n};\n","import {\n type Address,\n type PublicClient,\n parseEventLogs,\n type TransactionReceipt,\n} from \"viem\";\n\nimport { berachainGovernanceAbi as governanceAbi } from \"@berachain/abis/gov/berachainGovernance\";\n\nimport {\n type ExecutableCallSubsetFragment,\n ProposalStatus,\n type ProposalWithVotesFragment,\n} from \"@berachain/graphql/governance\";\n\nimport { assertPublicClient } from \"../../errors/assert\";\nimport { parseProposalBody } from \"./parseProposalBody\";\n\nexport async function getProposalFromTx(\n args: {\n publicClient: PublicClient | undefined;\n } & (\n | {\n tx: TransactionReceipt;\n }\n | {\n txHash: Address;\n }\n ),\n): Promise<ProposalWithVotesFragment | null> {\n assertPublicClient(args.publicClient);\n\n let tx: TransactionReceipt;\n\n if (\"tx\" in args) {\n tx = args.tx;\n } else {\n tx = await args.publicClient.getTransactionReceipt({ hash: args.txHash });\n }\n\n const creationEvent = tx?.logs\n ? parseEventLogs({\n abi: governanceAbi,\n logs: tx.logs,\n eventName: \"ProposalCreated\",\n })?.at(0)\n : undefined;\n\n if (!tx || !creationEvent) {\n return null;\n }\n\n const block = await args.publicClient.getBlock({\n blockNumber: tx.blockNumber,\n });\n const fm = parseProposalBody({\n description: creationEvent?.args.description as string,\n });\n\n return {\n id: String(creationEvent.args.proposalId),\n proposalId: String(creationEvent?.args.proposalId),\n createdAt: block.timestamp.toString(),\n title: fm.data.title,\n createdAtBlock: block.timestamp.toString(),\n voteStartAt: String(creationEvent?.args.voteStart),\n voteEndAt: String(creationEvent?.args.voteEnd),\n proposer: creationEvent?.args.proposer,\n description: fm.content,\n unverifiedForumLink: fm.data.forumLink,\n pollResult: {\n for: \"0\",\n forVotersCount: 0,\n forPercentage: \"0\",\n against: \"0\",\n againstVotersCount: 0,\n againstPercentage: \"0\",\n abstain: \"0\",\n abstainVotersCount: 0,\n abstainPercentage: \"0\",\n total: \"0\",\n totalVotersCount: 0,\n totalTowardsQuorum: \"0\",\n },\n status: ProposalStatus.Pending,\n quorum: null,\n topics: fm.data.topics,\n votes: [],\n executableCalls: creationEvent?.args.targets.map(\n (target, index) =>\n ({\n __typename: \"ExecutableCall\",\n id: `${tx.transactionHash}-${index}`,\n target: target as Address,\n value: String(creationEvent?.args.values[index]),\n calldata: creationEvent?.args.calldatas[index],\n }) satisfies ExecutableCallSubsetFragment,\n ),\n timelock: undefined,\n } satisfies ProposalWithVotesFragment;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/snowbera/Documents/workspace/monobera/packages/berajs/dist/chunk-NVOJIQUM.cjs","../src/actions/clients/getEnsoClient.ts"],"names":["isProduction","getEnsoClient","useProxy","args","config","parseBaseArgs","EnsoClient"],"mappings":"AAAA,yuBAAwC,wDAAgD,wDAAuD,uCCApH,sDAED,IAIpBA,CAAAA,CACJ,OAAA,CAAQ,GAAA,CAAI,QAAA,GAAa,aAAA,EAAiB,OAAA,CAAQ,GAAA,CAAI,QAAA,GAAa,MAAA,CAE9D,SAASC,CAAAA,CAAc,CAC5B,QAAA,CAAAC,CAAAA,CAAWF,CAAAA,CACX,GAAGG,CACL,CAAA,CAAsD,CAAC,CAAA,CAAG,CACxD,GAAM,CAAE,MAAA,CAAAC,CAAO,CAAA,CAAIC,iCAAAA,CAAkB,CAAA,CACrC,OAAO,IAAIC,oBAAAA,CAAW,CACpB,OAAA,CAASJ,CAAAA,CACL,CAAA,EAAA","file":"/Users/snowbera/Documents/workspace/monobera/packages/berajs/dist/chunk-NVOJIQUM.cjs","sourcesContent":[null,"import { EnsoClient } from \"@ensofinance/sdk\";\n\nimport { appConfig } from \"@berachain/config/internal\";\n\nimport { parseBaseArgs } from \"../../utils/parseBaseArgs\";\n\nconst isProduction =\n process.env.NODE_ENV !== \"development\" && process.env.NODE_ENV !== \"test\";\n\nexport function getEnsoClient({\n useProxy = isProduction,\n ...args\n}: BeraJS.BaseFunctionArgs & { useProxy?: boolean } = {}) {\n const { config } = parseBaseArgs(args);\n return new EnsoClient({\n baseURL: useProxy\n ? `${config.bex.aggregatorsProxyUrl}/enso/api/v1/`\n : undefined,\n apiKey: useProxy\n ? // no API key since proxy has CORS for .berachain.com domains\n \"\"\n : appConfig.apiKeys.public.enso,\n });\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["/Users/snowbera/Documents/workspace/monobera/packages/berajs/dist/chunk-QXNF3YT7.cjs","../src/contexts/BeraFlags/BeraFlags.tsx","../src/contexts/BexStatusProvider.tsx","../src/contexts/block-time-provider.tsx","../src/contexts/HoneyConfigProvider.tsx","../src/hooks/enso/useEnsoUserTokensWithBalances.ts","../src/actions/enso/getEnsoUserTokensWithBalances.ts","../src/contexts/TokensProvider.tsx","../src/utils/formatTokenList.ts"],"names":["BeraFlagContext","createContext","BeraFlagsProvider","children","flags","aggregators","swberaAprWindow","jsx","defaultFlags","value","isFlagEnabled","key","useBeraFlags","context","useContext","useBeraFlag","BexStateContext","useBexStatus","BeraError","BexStatusProvider","isVaultPaused","labels","factories","poolState","setPoolState","useState","disablePoolWithdrawals","disablePoolDeposits","useBlockTime","BlockTimeContext","mainnet","BlockTimeProvider","blockTime","args","config","parseBaseArgs","HoneyConfigContext","HoneyConfigProvider","props","useHoneyConfig","getEnsoUserTokensWithBalances","account","wagmiConfig","chainId","ensoClient","tokens","balance","isToken","beraToken","formatUnits","tokenByChainId","a","balances","chainTokens","chainConfig","getChains","chain","multicallAddress","BeraMonitoring","InvalidArgumentError","multicall","token","getBalanceCall","tokensWithBalances","index","initBeraError","flattenedBalances","result","b","aValue","useEnsoUserTokensWithBalances","options","fromAddress","useBeraWallet","useConfig","isEnabled","swrResponse","useSWR","getEnsoClient","formatTokenList","defaultTokenList","externalList","defaultList","featuredTokenList","tag","mergedList","item","i","TokenContext","TokensProvider","defaultTokens","edgeConfigTokenList","userTokens","onAddToken","onRemoveToken","ensoTokens","refresh","tokenList","useMemo","t","tk"],"mappings":"AAAA,y0BAA+C,wDAAyC,wDAAuD,wDAA2C,wDAAgD,8BCAhM,oEAKnC,+CAiCH,IAhBEA,CAAAA,CAAkBC,kCAAAA,KACtB,CACF,CAAA,CAEO,SAASC,EAAAA,CAAkB,CAChC,QAAA,CAAAC,CAAAA,CACA,KAAA,CAAAC,CAAAA,CACA,WAAA,CAAAC,CAAAA,CACA,eAAA,CAAAC,CAAAA,CAAkB,KACpB,CAAA,CAKG,CACD,OACEC,6BAAAA,CAACP,CAAgB,QAAA,CAAhB,CACC,KAAA,CAAO,CACL,GAAGQ,mBAAAA,CACH,GAAGJ,CAAAA,CACH,WAAA,CAAaC,CAAAA,CACT,MAAA,CAAO,OAAA,CAAQA,CAAW,CAAA,CACvB,MAAA,CAAO,CAAC,CAAC,CAAEI,CAAK,CAAA,CAAA,EAAMC,uCAAAA,CAAmB,CAAC,CAAA,CAC1C,GAAA,CAAI,CAAC,CAACC,CAAG,CAAA,CAAA,EAAMA,CAAG,CAAA,CACrB,KAAA,CAAA,CACJ,eAAA,CAAAL,CACF,CAAA,CAEC,QAAA,CAAAH,CAAAA,CACH,CAEJ,CAEO,SAASS,CAAAA,CAAAA,CAAe,CAC7B,IAAMC,CAAAA,CAAUC,+BAAAA,CAA0B,CAAA,CAC1C,EAAA,CAAI,CAACD,CAAAA,CACH,MAAM,IAAI,KAAA,CAAM,6BAA6B,CAAA,CAE/C,OAAOA,CACT,CAEO,SAASE,EAAAA,CACdJ,CAAAA,CAC2B,CAE3B,OADcC,CAAA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KAAA,CAAA,CACT,KAAA,CAAO,KAAA,CACT,CAAA,CAAE,CACJ,CACF,CAAC,CAAA,CACH,CAACT,CAAAA,CAAeE,CAAAA,CAAYD,CAAAA,CAAqBI,CAAU,CAC7D,CAAA,CAEA,OACExF,6BAAAA,EAACiF,CAAa,QAAA,CAAb,CACC,KAAA,CAAO,CACL,SAAA,CAAAS,CAAAA,CACA,UAAA,CAAAL,CAAAA,CACA,cAAA,CAAgBT,CAAAA,CAChB,UAAA,CAAAY,CAAAA,CACA,UAAA,CAAWK,CAAAA,CAAI,CACbP,CAAAA,CAAWO,CAAAA,CAAI,CAAE,aAAA,CAAAV,CAAAA,CAAe,UAAA,CAAAE,CAAAA,CAAY,SAAA,CAAAK,CAAU,CAAC,CACzD,CAAA,CACA,aAAA,CAAAH,CAAAA,CACA,OAAA,CAAS,CAAA,CAAA,EAAM,CACbE,CAAAA,CAAQ,CACV,CACF,CAAA,CAEC,QAAA,CAAA7F,CAAAA,CACH,CAEJ,CAAA,0OAAA","file":"/Users/snowbera/Documents/workspace/monobera/packages/berajs/dist/chunk-QXNF3YT7.cjs","sourcesContent":[null,"import { createContext, useContext } from \"react\";\n\nimport {\n type EdgeConfigSchema,\n isFlagEnabled,\n} from \"@berachain/config/internal/edge-config\";\n\nimport { type BeraFlags, defaultFlags } from \"./defaultFlags\";\n\nexport type { BeraFlags };\n\nexport type BeraFlagsContextReturn = BeraFlags & {\n /**\n * A list of aggregators that are enabled. If not provided, all aggregators are enabled.\n */\n aggregators: string[] | undefined;\n swberaAprWindow: Exclude<\n EdgeConfigSchema[\"pol\"][\"swberaAprWindow\"],\n undefined\n >;\n};\n\nconst BeraFlagContext = createContext<BeraFlagsContextReturn | undefined>(\n undefined,\n);\n\nexport function BeraFlagsProvider({\n children,\n flags,\n aggregators,\n swberaAprWindow = \"DAY\",\n}: {\n children: React.ReactNode;\n flags: BeraFlags;\n aggregators?: NonNullable<EdgeConfigSchema[\"bex\"]>[\"aggregators\"];\n swberaAprWindow?: EdgeConfigSchema[\"pol\"][\"swberaAprWindow\"];\n}) {\n return (\n <BeraFlagContext.Provider\n value={{\n ...defaultFlags,\n ...flags,\n aggregators: aggregators\n ? Object.entries(aggregators)\n .filter(([, value]) => isFlagEnabled(value))\n .map(([key]) => key)\n : undefined,\n swberaAprWindow,\n }}\n >\n {children}\n </BeraFlagContext.Provider>\n );\n}\n\nexport function useBeraFlags() {\n const context = useContext(BeraFlagContext);\n if (!context) {\n throw new Error(\"BeraFlagsProvider not found\");\n }\n return context;\n}\n\nexport function useBeraFlag<T extends keyof BeraFlagsContextReturn>(\n key: T,\n): BeraFlagsContextReturn[T] {\n const flags = useBeraFlags();\n return flags[key];\n}\n","import {\n createContext,\n type Dispatch,\n type PropsWithChildren,\n type SetStateAction,\n useContext,\n useState,\n} from \"react\";\nimport type { Hex } from \"viem\";\n\nimport type { EdgeConfigSchema } from \"@berachain/config/internal/edge-config\";\n\nimport { BeraError } from \"../errors/BeraError\";\n\ntype FactoryStatus = {\n /**\n * If the composable stable factory is enabled\n */\n composableStable: \"paused\" | \"enabled\";\n /**\n * If the weighted factory is enabled\n */\n weighted: \"paused\" | \"enabled\";\n};\nexport interface BexStatusProviderProps {\n isVaultPaused: boolean;\n pool?: {\n id: Hex;\n isInRecoveryMode: boolean;\n isPaused: boolean;\n };\n factories: FactoryStatus;\n labels?: NonNullable<EdgeConfigSchema[\"bex\"]>[\"emergencyLabels\"];\n}\n\nexport const BexStateContext = createContext<{\n protocol: {\n isPaused: boolean;\n factories: FactoryStatus & { allPaused: boolean };\n };\n onPoolChange: Dispatch<SetStateAction<BexStatusProviderProps[\"pool\"]>>;\n pool?: {\n id: Hex;\n isInRecoveryMode: boolean;\n isPaused: boolean;\n disablePoolWithdrawals: boolean;\n disablePoolDeposits: boolean;\n };\n labels?: NonNullable<EdgeConfigSchema[\"bex\"]>[\"emergencyLabels\"];\n}>({\n protocol: {\n isPaused: false,\n factories: {\n composableStable: \"enabled\",\n weighted: \"enabled\",\n allPaused: false,\n },\n },\n onPoolChange: () => {},\n pool: undefined,\n});\n\n/**\n * @description Determines the status of a pool or vault and returns the appropriate messages and flags to disable functionality.\n * More information here https://www.notion.so/berachain/BEX-RecoveryMode-and-Pause-explained-17c6120abced80e0985dd589b57ff018\n *\n * @returns status flags to enable/disable/notify users across the BEX\n *\n **/\nexport function useBexStatus() {\n const context = useContext(BexStateContext);\n\n if (!context) {\n throw new BeraError({\n level: \"fatal\",\n message: \"BexStateContext is not defined\",\n });\n }\n\n return context;\n}\n\nexport function BexStatusProvider({\n children,\n isVaultPaused,\n labels,\n factories,\n}: PropsWithChildren<BexStatusProviderProps>) {\n const [poolState, setPoolState] = useState<BexStatusProviderProps[\"pool\"]>();\n // Determine whether to disable withdrawals for a pool (vault pause does not impact this)\n const disablePoolWithdrawals =\n (poolState?.isPaused && !poolState?.isInRecoveryMode) ?? false;\n\n // Determine whether to disable deposits for a pool (vault pause does not impact this)\n const disablePoolDeposits = isVaultPaused || poolState?.isPaused;\n\n // TODO: we dont yet support anything to disable staking/unstaking within reward vaults if they get paused\n\n return (\n <BexStateContext.Provider\n value={{\n protocol: {\n isPaused: isVaultPaused,\n factories: {\n ...factories,\n allPaused:\n factories.composableStable === \"paused\" &&\n factories.weighted === \"paused\",\n },\n },\n labels,\n onPoolChange: setPoolState,\n pool: poolState\n ? {\n ...poolState,\n disablePoolWithdrawals: !!disablePoolWithdrawals,\n disablePoolDeposits: !!disablePoolDeposits,\n }\n : undefined,\n }}\n >\n {children}\n </BexStateContext.Provider>\n );\n}\n","import { createContext, type PropsWithChildren, useContext } from \"react\";\n\nimport { mainnet } from \"@berachain/config/mainnet\";\n\nimport { parseBaseArgs } from \"../utils/parseBaseArgs\";\n\n/**\n * Average berachain block time in seconds\n */\nexport function useBlockTime(): number {\n return useContext(BlockTimeContext);\n}\n\nexport const BlockTimeContext = createContext<number>(\n // this is the default block time for berachain, but actually overridden by the block time provider\n mainnet.averageBlockTime,\n);\n\nexport function BlockTimeProvider({\n children,\n blockTime,\n ...args\n}: PropsWithChildren<{\n blockTime?: number;\n}> &\n BeraJS.BaseFunctionArgs) {\n const { config } = parseBaseArgs(args);\n\n return (\n <BlockTimeContext.Provider value={blockTime ?? config.averageBlockTime}>\n {children}\n </BlockTimeContext.Provider>\n );\n}\n","import { createContext, useContext } from \"react\";\n\nimport type { HoneyFeeMap } from \"../actions/honey/getHoneyFees\";\nimport type { TokenWithMetadata } from \"../types/dex\";\nimport type { PythPriceFeedMap } from \"../types/honeySwap\";\n\nexport const HoneyConfigContext = createContext<\n HoneyConfigContextReturn | undefined\n>(undefined);\n\nexport type TokenWithOrder = TokenWithMetadata & {\n order: number;\n};\nexport interface HoneyConfigContextReturn {\n /**\n * Map of the Pyth price feed ids for each collateral\n */\n priceFeedMap: PythPriceFeedMap;\n /**\n * This is the list of all the collaterals that are supported by the Honey protocol\n */\n collateralList: TokenWithOrder[];\n /**\n * This is the main collateral that is used to calculate the relative cap limit\n */\n referenceCollateral: TokenWithOrder;\n /**\n * An object that maps the redeem/mint rate for each collateral and the weighted rates for the basket mode\n */\n feeMap: HoneyFeeMap;\n flags: {\n /**\n * If true, mint/redeem will also update pyth prices\n */\n isPythWrapperEnabled: boolean;\n };\n /**\n * Honey protocol configs\n */\n protocol: {\n /**\n * Honey protocol paused state\n */\n isPaused: boolean;\n /**\n * The label for the Honey protocol paused message\n */\n pausedBannerLabel?: string;\n };\n}\n\nexport interface HoneyConfigProviderProps extends HoneyConfigContextReturn {\n children: React.ReactNode;\n}\n\nexport function HoneyConfigProvider({\n children,\n ...props\n}: HoneyConfigProviderProps) {\n return (\n <HoneyConfigContext.Provider value={props}>\n {children}\n </HoneyConfigContext.Provider>\n );\n}\n\nexport function useHoneyConfig() {\n const context = useContext(HoneyConfigContext);\n if (!context) {\n throw new Error(\"useHoneyConfig must be used within a HoneyConfigProvider\");\n }\n return context;\n}\n","import useSWR from \"swr\";\n\nimport { useBeraWallet, useConfig } from \"@berachain/wagmi/hooks\";\n\nimport { getEnsoClient } from \"../../actions/clients/getEnsoClient\";\nimport { getEnsoUserTokensWithBalances } from \"../../actions/enso/getEnsoUserTokensWithBalances\";\nimport { POLLING } from \"../../enum/polling\";\nimport type { BalanceToken } from \"../../types/dex\";\nimport type { DefaultHookOptions } from \"../../types/global\";\n\nexport function useEnsoUserTokensWithBalances(\n { chainId }: { chainId?: number } = {},\n options?: DefaultHookOptions,\n) {\n const { address: fromAddress } = useBeraWallet();\n const wagmiConfig = useConfig();\n const isEnabled = !!fromAddress && (options?.opts?.isEnabled ?? true);\n\n const QUERY_KEY =\n isEnabled && wagmiConfig\n ? ([\"useEnsoUserTokensWithBalances\", fromAddress, chainId] as const)\n : null;\n\n const swrResponse = useSWR(\n QUERY_KEY,\n async ([, fromAddress, chainId]): Promise<BalanceToken[]> =>\n getEnsoUserTokensWithBalances({\n account: fromAddress,\n wagmiConfig,\n chainId: chainId ?? \"all\",\n ensoClient: getEnsoClient(),\n }),\n {\n refreshInterval: POLLING.NORMAL,\n isEnabled,\n ...options?.opts,\n },\n );\n return {\n ...swrResponse,\n refresh: () => swrResponse.mutate(),\n };\n}\n","import type { EnsoClient } from \"@ensofinance/sdk\";\nimport { type Config, getChains, multicall } from \"@wagmi/core\";\nimport { type Address, formatUnits } from \"viem\";\n\nimport { BeraMonitoring } from \"../../errors/BeraMonitoring\";\nimport { InvalidArgumentError } from \"../../errors/InvalidArgumentError\";\nimport { initBeraError } from \"../../errors/initBeraError\";\nimport type { BalanceToken } from \"../../types/dex\";\nimport { beraToken, isToken } from \"../../utils/tokens\";\nimport { getBalanceCall } from \"../tokens/getWalletBalances\";\n\n/**\n * Get user balances for each supported chain.\n *\n * This uses enso's balance endpoint to get the balances and RPC to get fresh balances.\n */\nexport async function getEnsoUserTokensWithBalances({\n account,\n wagmiConfig,\n chainId,\n ensoClient,\n}: {\n account: Address;\n wagmiConfig: Config;\n chainId: number | \"all\";\n ensoClient: EnsoClient;\n}): Promise<BalanceToken[]> {\n const ensoBalances = await ensoClient.getBalances({\n useEoa: true,\n chainId: chainId ?? \"all\",\n eoaAddress: account,\n });\n\n const tokens: BalanceToken[] = ensoBalances.map(\n (balance) =>\n ({\n name: balance.name,\n symbol: balance.symbol,\n decimals: balance.decimals,\n address: isToken(balance.token, \"ETH\")\n ? beraToken.address\n : balance.token,\n logoURI: balance.logoUri,\n balance: {\n raw: balance.amount.toString(),\n formatted: formatUnits(BigInt(balance.amount), balance.decimals),\n },\n\n chainId: Number(\n // @ts-expect-error - balance.chainId is defined just not typed by enso\n balance.chainId,\n ),\n price: Number(balance.price),\n }) as const satisfies BalanceToken,\n );\n\n const tokenByChainId = Object.groupBy(tokens, (a) => a.chainId ?? 0);\n\n const balances = await Promise.allSettled(\n Object.entries(tokenByChainId).map(async ([chainId, chainTokens]) => {\n if (!chainTokens) return undefined;\n const chainConfig = getChains(wagmiConfig).find(\n (chain) => chain.id === Number(chainId),\n );\n\n if (!chainConfig) {\n // if we've queried a chain that is not supported, we need to return undefined\n return undefined;\n }\n\n const multicall3 = chainConfig.contracts?.multicall3;\n\n const multicallAddress = multicall3?.address;\n\n if (!multicallAddress) {\n // if multicall is not supported on this chain, we need to use the enso balance\n // first let's report the error, as this is likely unexpected\n BeraMonitoring.captureException(\n new InvalidArgumentError({\n property: \"multicallAddress\",\n value: multicallAddress,\n expected: \"Address\",\n chainId: Number(chainId),\n }),\n );\n\n // we can return the tokens as is, as the balance is already set from the enso client\n return chainTokens;\n }\n\n const balances = await multicall(wagmiConfig, {\n chainId: Number(chainId),\n contracts: chainTokens.map((token) =>\n getBalanceCall({\n token,\n account,\n multicallAddress,\n }),\n ),\n allowFailure: true,\n });\n\n const tokensWithBalances: BalanceToken[] = [];\n\n for (let index = 0; index < chainTokens.length; index++) {\n const token = chainTokens[index];\n if (balances[index].status === \"success\") {\n const balance = balances[index].result;\n\n tokensWithBalances.push({\n ...token,\n balance: {\n raw: balance?.toString() ?? \"0\",\n formatted: formatUnits(balance ?? 0n, token.decimals),\n },\n });\n } else {\n console.error(\"error getting balance\", balances[index].error);\n BeraMonitoring.captureException(\n initBeraError({ cause: balances[index].error }),\n );\n // uses enso balance as fallback\n tokensWithBalances.push(token);\n }\n }\n\n return tokensWithBalances;\n }),\n );\n\n const flattenedBalances: BalanceToken[] = [];\n for (const result of balances) {\n if (result.status === \"fulfilled\") {\n flattenedBalances.push(...(result.value ?? []));\n } else {\n BeraMonitoring.captureException(initBeraError({ cause: result.reason }));\n }\n }\n\n return flattenedBalances.sort((a, b) => {\n const aValue = Number(a.balance.formatted) * (a.price ?? 0);\n const bValue = Number(b.balance.formatted) * (b.price ?? 0);\n return bValue - aValue;\n });\n}\n","import { createContext, type PropsWithChildren, useMemo } from \"react\";\n\nimport {\n type EdgeConfigSchema,\n isFlagEnabled,\n} from \"@berachain/config/internal/edge-config\";\n\nimport { useEnsoUserTokensWithBalances } from \"../hooks/enso/useEnsoUserTokensWithBalances\";\nimport type { BalanceToken, Token, TokenWithMetadata } from \"../types/dex\";\nimport { formatTokenList } from \"../utils/formatTokenList\";\n\nexport interface TokensProviderContext {\n tokenList: TokenWithMetadata[];\n userTokens: Token[];\n featuredTokens: TokenWithMetadata[];\n onRemoveToken: (token: Token) => void;\n onAddToken: (token: Token) => void;\n refresh: () => void;\n ensoTokens: BalanceToken[] | undefined;\n}\n\nexport const TokenContext = createContext<TokensProviderContext | undefined>(\n undefined,\n);\n\nexport interface TokensProviderProps\n extends Omit<\n TokensProviderContext,\n \"tokenList\" | \"onAddToken\" | \"featuredTokens\" | \"ensoTokens\"\n > {\n onAddToken: (\n token: Token,\n context: {\n defaultTokens: TokenWithMetadata[];\n userTokens: Token[];\n tokenList: TokenWithMetadata[];\n },\n ) => void;\n defaultTokens: TokenWithMetadata[];\n edgeConfigTokenList: EdgeConfigSchema[\"tokens\"];\n}\n\nexport function TokensProvider({\n children,\n defaultTokens,\n edgeConfigTokenList,\n userTokens,\n onAddToken,\n onRemoveToken,\n}: PropsWithChildren<Omit<TokensProviderProps, \"refresh\">>) {\n const { data: ensoTokens, refresh } = useEnsoUserTokensWithBalances();\n\n const { tokenList = [], featuredTokenList = [] } = useMemo(\n () =>\n formatTokenList({\n defaultTokenList: [\n ...defaultTokens,\n ...(edgeConfigTokenList?.filter((token) =>\n isFlagEnabled(token.enabled),\n ) as TokenWithMetadata[]),\n ],\n externalList: [\n ...userTokens,\n ...(ensoTokens ?? []).map((t) => ({\n ...t,\n balance: undefined,\n price: undefined,\n })),\n ],\n }),\n [defaultTokens, userTokens, edgeConfigTokenList, ensoTokens],\n );\n\n return (\n <TokenContext.Provider\n value={{\n tokenList,\n userTokens,\n featuredTokens: featuredTokenList,\n ensoTokens,\n onAddToken(tk) {\n onAddToken(tk, { defaultTokens, userTokens, tokenList });\n },\n onRemoveToken,\n refresh: () => {\n refresh();\n },\n }}\n >\n {children}\n </TokenContext.Provider>\n );\n}\n","import type { Token, TokenWithMetadata } from \"../types/dex\";\nimport { isToken } from \"./tokens\";\n\nexport interface FormatTokenListReturnType {\n /**\n * Token list including custom tokens\n */\n tokenList: Token[];\n /**\n * Custom token list (added by the user)\n */\n customTokenList?: Token[];\n /**\n * Featured token list\n */\n featuredTokenList?: Token[];\n}\n\nfunction formatTokenList({\n defaultTokenList = [],\n externalList = [],\n}: {\n defaultTokenList: TokenWithMetadata[];\n externalList?: Token[];\n}): FormatTokenListReturnType {\n if (defaultTokenList.length === 0) {\n return {\n tokenList: externalList,\n customTokenList: externalList,\n featuredTokenList: [],\n };\n }\n\n const defaultList = defaultTokenList.map((token) => {\n return { ...token, default: true };\n });\n\n const featuredTokenList = defaultList.filter((token) => {\n return token.tags?.some((tag) => tag === \"featured\");\n });\n\n const mergedList = [...defaultList, ...externalList];\n\n const uniqueList = mergedList.filter(\n (item, index) => mergedList.findIndex((i) => isToken(i, item)) === index,\n );\n\n return {\n tokenList: uniqueList,\n customTokenList: externalList,\n featuredTokenList,\n };\n}\n\nexport { formatTokenList };\n"]}
|
|
File without changes
|
|
File without changes
|