@berachain/berajs 0.2.9 → 0.2.11

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 (182) hide show
  1. package/dist/{HoneyConfigProvider-Dkj-_a5x.d.ts → HoneyConfigProvider-COOuDNra.d.ts} +1 -1
  2. package/dist/actions/clients/exports.d.ts +77 -1
  3. package/dist/actions/clients/exports.mjs +13 -4
  4. package/dist/actions/exports.d.ts +121 -39
  5. package/dist/actions/exports.mjs +75 -34
  6. package/dist/actions/governance/exports.d.ts +3 -11
  7. package/dist/actions/governance/exports.mjs +3 -3
  8. package/dist/actions/server/exports.mjs +4 -4
  9. package/dist/{chunk-4Z4AK6SH.mjs → chunk-3JJLQ2JX.mjs} +3 -3
  10. package/dist/{chunk-EXIUPSFN.mjs → chunk-7YVNSDXG.mjs} +2 -2
  11. package/dist/{chunk-WXXOISTU.mjs → chunk-AUOPN6NK.mjs} +1 -1
  12. package/dist/{chunk-75M6TF7M.mjs → chunk-DQRH5VE3.mjs} +1 -1
  13. package/dist/{chunk-CDFWPU2R.mjs → chunk-E7YFXBBQ.mjs} +0 -124
  14. package/dist/{chunk-AFN4CVD3.mjs → chunk-GUURQAME.mjs} +1 -1
  15. package/dist/{chunk-KQUMKB66.mjs → chunk-GY6B3PD5.mjs} +1 -1
  16. package/dist/{chunk-HSSJKHZ4.mjs → chunk-HYDP32P6.mjs} +3 -3
  17. package/dist/{chunk-NPBQLVL3.mjs → chunk-IXIBY5FP.mjs} +2 -2
  18. package/dist/{chunk-J5I45WGQ.mjs → chunk-KHXJDYA4.mjs} +7 -0
  19. package/dist/chunk-MRQGHXAN.mjs +54 -0
  20. package/dist/{chunk-FFB5LFDW.mjs → chunk-QVHEM4BG.mjs} +2 -2
  21. package/dist/{chunk-3EARVV7K.mjs → chunk-SXUNCX5E.mjs} +22 -9
  22. package/dist/chunk-UD5IUNCW.mjs +34 -0
  23. package/dist/{chunk-QJIXTYTZ.mjs → chunk-VAA2FVPP.mjs} +162 -41
  24. package/dist/chunk-Y6THHG77.mjs +126 -0
  25. package/dist/{chunk-XIYN6AL6.mjs → chunk-ZLTMIFCZ.mjs} +10 -5
  26. package/dist/contexts/exports.d.ts +2 -2
  27. package/dist/contexts/exports.mjs +11 -9
  28. package/dist/enum/exports.d.ts +8 -2
  29. package/dist/errors/exports.mjs +5 -5
  30. package/dist/getProposalVotes-DAUrdX2n.d.ts +12 -0
  31. package/dist/{getValidatorQueuedOperatorAddress-Dw5KN5sh.d.ts → getValidatorQueuedOperatorAddress-Cxt-DlL_.d.ts} +2 -2
  32. package/dist/{global.d-BuGDKh4k.d.ts → global.d-q_LQWQqs.d.ts} +2 -4
  33. package/dist/hooks/exports.d.ts +114 -164
  34. package/dist/hooks/exports.mjs +535 -522
  35. package/dist/hooks/governance/exports.d.ts +20 -15
  36. package/dist/hooks/governance/exports.mjs +43 -41
  37. package/dist/{pol.d-CqPA9K6m.d.ts → pol.d-CeRgXBL8.d.ts} +33 -8
  38. package/dist/types/exports.d.ts +5 -5
  39. package/dist/{useHoneySwapState-vFmuFF0g.d.ts → useHoneySwapState-twi7NTaO.d.ts} +1 -1
  40. package/dist/utils/exports.d.ts +2 -2
  41. package/dist/utils/exports.mjs +15 -9
  42. package/package.json +9 -8
  43. package/src/actions/bend/getMaxDeposit.ts +28 -2
  44. package/src/actions/clients/exports.ts +3 -0
  45. package/src/actions/clients/fetchBeep.ts +34 -0
  46. package/src/actions/clients/fetchOpenApi.ts +97 -0
  47. package/src/actions/clients/fetchOpenApi.unit.test.ts +245 -0
  48. package/src/actions/clients/fetchRailwayBackend.ts +34 -0
  49. package/src/actions/enso/getEnsoUserTokensWithBalances.ts +18 -0
  50. package/src/actions/exports.ts +2 -0
  51. package/src/actions/honey/getChartData.ts +53 -12
  52. package/src/actions/honey/getHoney24hVolume.ts +34 -6
  53. package/src/actions/honey/getHoneyTxns.ts +93 -0
  54. package/src/actions/honey/getPythLatestPrices.ts +7 -0
  55. package/src/actions/pol/__tests__/rewardVaults.integration.test.ts +1 -1
  56. package/src/actions/pol/getAutoclaimedIncentives.ts +21 -10
  57. package/src/actions/pol/getAutoclaimedIncentivesTxHash.ts +41 -0
  58. package/src/actions/pol/getBgtIncentiveDistributorPaused.ts +5 -12
  59. package/src/actions/pol/getEarnedStakedBeraVault.ts +20 -16
  60. package/src/actions/pol/getRewardVaults.ts +4 -4
  61. package/src/actions/pol/getStakingDailyAssets.ts +18 -14
  62. package/src/actions/validators/getValidatorIncentiveDistribution.ts +64 -12
  63. package/src/actions/validators/utils/getValidatorBoostApy.ts +1 -1
  64. package/src/contexts/SwrFallback.tsx +2 -1
  65. package/src/data/contracts.ts +4 -0
  66. package/src/errors/RequestError.ts +12 -3
  67. package/src/errors/RequestError.unit.test.ts +55 -0
  68. package/src/errors/errorMap.ts +8 -0
  69. package/src/errors/getRevertReason.integration.test.ts +5 -1
  70. package/src/hooks/bend/useGetConvertToAssets.ts +2 -3
  71. package/src/hooks/dex/useAggregatorsQuotes.ts +10 -10
  72. package/src/hooks/dex/useAggregatorsRouterFeeBps.ts +1 -1
  73. package/src/hooks/dex/useAllUserPools.ts +7 -5
  74. package/src/hooks/dex/useApiPool.ts +1 -1
  75. package/src/hooks/dex/useGlobalLiquidityAndSwapVolume.ts +1 -1
  76. package/src/hooks/dex/useOnChainPoolData.ts +1 -1
  77. package/src/hooks/dex/usePollPoolCreationRelayerApproval.ts +2 -2
  78. package/src/hooks/dex/usePoolEvents.ts +1 -2
  79. package/src/hooks/dex/usePoolHistoricalData.ts +2 -3
  80. package/src/hooks/dex/usePools.ts +4 -2
  81. package/src/hooks/dex/useSingleAggregatorQuote.ts +6 -18
  82. package/src/hooks/enso/useBendDemultiply.ts +3 -4
  83. package/src/hooks/enso/useBendMultiply.ts +3 -4
  84. package/src/hooks/enso/useBendZapSupply.ts +3 -4
  85. package/src/hooks/enso/useEnsoSwapBundle.ts +1 -1
  86. package/src/hooks/enso/useEnsoUserTokensWithBalances.ts +3 -5
  87. package/src/hooks/enso/useEnsoWalletV2Address.ts +1 -1
  88. package/src/hooks/enso/useIsBendAuthorized.ts +1 -1
  89. package/src/hooks/enso/useZapStakeBera.ts +2 -2
  90. package/src/hooks/exports.ts +2 -0
  91. package/src/hooks/governance/useGetPastVotes.ts +1 -1
  92. package/src/hooks/governance/useHasVoted.ts +1 -1
  93. package/src/hooks/governance/useIsCanceller.ts +1 -1
  94. package/src/hooks/governance/usePollAllProposals.ts +13 -12
  95. package/src/hooks/governance/usePollProposal.ts +3 -3
  96. package/src/hooks/governance/usePollProposalThreshold.ts +1 -1
  97. package/src/hooks/governance/usePollProposalVotes.ts +23 -5
  98. package/src/hooks/governance/usePollUserDelegates.ts +3 -3
  99. package/src/hooks/governance/useProposalFromTx.ts +2 -1
  100. package/src/hooks/governance/useProposalSnapshot.ts +2 -3
  101. package/src/hooks/governance/useProposalState.ts +2 -2
  102. package/src/hooks/governance/useProposalTimelockState.ts +2 -1
  103. package/src/hooks/governance/useQuorum.ts +1 -2
  104. package/src/hooks/honey/useCappedGlobally.ts +3 -6
  105. package/src/hooks/honey/useCappedRelatively.ts +2 -2
  106. package/src/hooks/honey/useCollateralWeights.ts +3 -3
  107. package/src/hooks/honey/useHoney24hVolume.ts +1 -1
  108. package/src/hooks/honey/useHoneyBalances.ts +1 -1
  109. package/src/hooks/honey/useHoneyChartData.ts +1 -1
  110. package/src/hooks/honey/useHoneyVaultsBalance.ts +2 -3
  111. package/src/hooks/honey/useIsBadCollateralAsset.ts +4 -7
  112. package/src/hooks/honey/useIsBasketModeEnabled.ts +4 -7
  113. package/src/hooks/honey/usePythLatestPrices.ts +13 -9
  114. package/src/hooks/perps/usePythUpdateFee.ts +13 -11
  115. package/src/hooks/pol/useAutoclaimedIncentives.ts +2 -12
  116. package/src/hooks/pol/useAutoclaimedIncentivesTxHash.ts +44 -0
  117. package/src/hooks/pol/useBgtIncentiveDistributorPaused.ts +39 -0
  118. package/src/hooks/pol/useBgtUnstakedBalance.ts +2 -2
  119. package/src/hooks/pol/useClaimableFees.ts +1 -1
  120. package/src/hooks/pol/useHighestVaultsAPR.ts +4 -6
  121. package/src/hooks/pol/useOnChainRewardVault.ts +77 -72
  122. package/src/hooks/pol/usePollGlobalData.ts +2 -3
  123. package/src/hooks/pol/usePollMarkets.ts +2 -2
  124. package/src/hooks/pol/useQueuedBeraUnlock.ts +2 -2
  125. package/src/hooks/pol/useRewardTokenToBeraRate.ts +2 -2
  126. package/src/hooks/pol/useRewardVault.ts +7 -6
  127. package/src/hooks/pol/useRewardVaultBalanceFromStakingToken.ts +4 -4
  128. package/src/hooks/pol/useRewardVaultFromToken.ts +1 -1
  129. package/src/hooks/pol/useRewardVaultIncentives.ts +1 -1
  130. package/src/hooks/pol/useRewardVaultRewards.ts +2 -2
  131. package/src/hooks/pol/useRewardVaults.ts +3 -6
  132. package/src/hooks/pol/useStakedAPR.ts +1 -2
  133. package/src/hooks/pol/useStakedData.ts +90 -41
  134. package/src/hooks/pol/useStakedSnapshots.ts +1 -1
  135. package/src/hooks/pol/useStakingVaultsMetadata.ts +1 -1
  136. package/src/hooks/pol/useTotalStakedAmount.ts +1 -2
  137. package/src/hooks/pol/useUserVaultInfo.ts +2 -2
  138. package/src/hooks/pol/useUserVaults.ts +2 -3
  139. package/src/hooks/pol/useVaultAddress.ts +1 -1
  140. package/src/hooks/pol/useVaultHistory.ts +1 -2
  141. package/src/hooks/pol/useVaultValidators.ts +2 -2
  142. package/src/hooks/tokens/useMultipleTokenInformation.ts +2 -2
  143. package/src/hooks/tokens/usePollAllowances.ts +3 -4
  144. package/src/hooks/tokens/usePollBalance.ts +2 -2
  145. package/src/hooks/tokens/usePollWalletBalances.ts +2 -2
  146. package/src/hooks/tokens/useStakingTokenInformation.ts +2 -2
  147. package/src/hooks/tokens/useTokenCurrentPrices.ts +11 -13
  148. package/src/hooks/tokens/useTokenInformation.ts +2 -2
  149. package/src/hooks/tokens/useTokenPrice.ts +2 -1
  150. package/src/hooks/tokens/useTokenPrices.ts +3 -4
  151. package/src/hooks/tokens/useTotalSupply.ts +1 -1
  152. package/src/hooks/tokens/useUnderlyingAsset.ts +1 -2
  153. package/src/hooks/useBlockToTimestamp.ts +1 -2
  154. package/src/hooks/useGetVerifiedAbi.ts +2 -1
  155. package/src/hooks/validators/useAllValidators.ts +2 -3
  156. package/src/hooks/validators/useApiEnrichedAllocation.ts +1 -1
  157. package/src/hooks/validators/useApiValidator.ts +3 -6
  158. package/src/hooks/validators/useBaselineRewardAllocation.ts +1 -2
  159. package/src/hooks/validators/useDailyValidatorBlockStats.ts +1 -1
  160. package/src/hooks/validators/useDefaultRewardAllocation.ts +2 -3
  161. package/src/hooks/validators/useManagedValidatorRole.ts +2 -2
  162. package/src/hooks/validators/useOnChainValidator.ts +3 -3
  163. package/src/hooks/validators/useStakingPoolBatch.ts +3 -4
  164. package/src/hooks/validators/useUserActiveValidators.ts +2 -3
  165. package/src/hooks/validators/useUserBoostsOnValidator.ts +1 -1
  166. package/src/hooks/validators/useUserClaimableIncentives.ts +1 -1
  167. package/src/hooks/validators/useUserStakingPositions.ts +2 -1
  168. package/src/hooks/validators/useValidator.ts +4 -8
  169. package/src/hooks/validators/useValidatorAnalytics.ts +1 -1
  170. package/src/hooks/validators/useValidatorCommission.ts +2 -2
  171. package/src/hooks/validators/useValidatorIncentiveDistribution.ts +3 -3
  172. package/src/hooks/validators/useValidatorQueuedCommission.ts +2 -2
  173. package/src/hooks/validators/useValidatorQueuedOperatorAddress.ts +2 -2
  174. package/src/hooks/validators/useValidatorQueuedRewardAllocation.ts +2 -2
  175. package/src/hooks/validators/useValidatorRewardAllocation.ts +2 -2
  176. package/src/types/bribe-boost.d.ts +14 -3
  177. package/src/types/global.d.ts +3 -4
  178. package/src/types/pol.d.ts +17 -3
  179. package/src/utils/polyfillAbortSignalAny.ts +53 -0
  180. package/src/utils/polyfillAbortSignalAny.unit.test.ts +81 -0
  181. package/dist/polling-BKnyavLI.d.ts +0 -8
  182. /package/dist/{exports-BcUTGFUb.d.ts → getApolloClient-BcUTGFUb.d.ts} +0 -0
@@ -0,0 +1,34 @@
1
+ import type { paths } from "@berachain/graphql/beep";
2
+
3
+ import { parseBaseArgs } from "../../utils/parseBaseArgs";
4
+ import {
5
+ type DefinedParams,
6
+ fetchOpenApi,
7
+ type GetPath,
8
+ type GetResponse,
9
+ } from "./fetchOpenApi";
10
+
11
+ /**
12
+ * Typed GET against the next-gen "beep" backend.
13
+ *
14
+ * The `path`, its path/query params and the response are all type-checked
15
+ * against the beep schema (`@berachain/graphql/beep`), so route shapes (e.g.
16
+ * the `/v0/stake/*` namespace) can never drift out of sync with the backend.
17
+ * The base URL is resolved from `config.beep`.
18
+ *
19
+ * @throws if `config.beep` is not set for the active chain. Callers should only
20
+ * reach for beep when `config.beep` is non-null.
21
+ */
22
+ export function fetchBeep<P extends GetPath<paths>>(
23
+ path: P,
24
+ params: DefinedParams<paths, P>,
25
+ args: BeraJS.BaseFunctionArgs = {},
26
+ ): Promise<GetResponse<paths, P>> {
27
+ const { config } = parseBaseArgs(args);
28
+
29
+ if (!config.beep) {
30
+ throw new Error("fetchBeep: `beep` backend is not configured.");
31
+ }
32
+
33
+ return fetchOpenApi<paths, P>(config.beep, path, params, "beep");
34
+ }
@@ -0,0 +1,97 @@
1
+ import type { HttpLink } from "@berachain/config";
2
+ import { getUriFromLink } from "@berachain/config";
3
+
4
+ import { beraFetchJson } from "../../utils/beraFetch";
5
+
6
+ /**
7
+ * A minimal, fully-typed GET helper for our `openapi-typescript`-generated
8
+ * backends. Both backends serve only GETs, so rather than a full OpenAPI client
9
+ * we type a single `fetchOpenApi` against a schema's `paths` and wrap it per
10
+ * backend (`fetchBeep`, `fetchRailwayBackend`).
11
+ *
12
+ * The `path`, its path/query params and the response body are all type-checked
13
+ * against the schema, so route shapes can never drift out of sync with the
14
+ * backend. Requests go through {@link beraFetchJson} so they keep the same
15
+ * Sentry tracing, `RequestError` handling and URL sanitization as the rest of
16
+ * the codebase.
17
+ */
18
+
19
+ /** Any `openapi-typescript` `paths` object. */
20
+ // biome-ignore lint/suspicious/noExplicitAny: schema `paths` are structurally diverse; constrained at call sites by the concrete schema.
21
+ type AnyPaths = Record<string, any>;
22
+
23
+ /** Paths in a schema that expose a JSON GET response. */
24
+ export type GetPath<Paths extends AnyPaths> = {
25
+ [P in keyof Paths]: Paths[P] extends {
26
+ get: { responses: { 200: { content: { "application/json": unknown } } } };
27
+ }
28
+ ? P
29
+ : never;
30
+ }[keyof Paths];
31
+
32
+ type GetParams<
33
+ Paths extends AnyPaths,
34
+ P extends GetPath<Paths>,
35
+ > = Paths[P]["get"] extends { parameters: infer Params } ? Params : never;
36
+
37
+ export type GetResponse<
38
+ Paths extends AnyPaths,
39
+ P extends GetPath<Paths>,
40
+ > = Paths[P]["get"]["responses"][200]["content"]["application/json"];
41
+
42
+ // Drop the params keys that are `never` (e.g. an endpoint with no query) so
43
+ // callers only pass what an endpoint actually accepts.
44
+ export type DefinedParams<Paths extends AnyPaths, P extends GetPath<Paths>> = {
45
+ [K in keyof GetParams<Paths, P> as GetParams<Paths, P>[K] extends never
46
+ ? never
47
+ : K]: GetParams<Paths, P>[K];
48
+ };
49
+
50
+ /**
51
+ * Perform a typed GET against an OpenAPI backend.
52
+ *
53
+ * @param link The backend `HttpLink`. The base URL and monitoring name are
54
+ * read from it.
55
+ * @param path An OpenAPI path template, e.g. `/v0/stake/{vault}/stats-by-day`.
56
+ * @param params Path and query params, typed from the schema for `path`.
57
+ * @param fallbackName Monitoring name to use when `link` is a bare string.
58
+ */
59
+ // biome-ignore lint/complexity/useMaxParams: internal helper; the wrappers (fetchBeep / fetchRailwayBackend) are the public surface.
60
+ export function fetchOpenApi<Paths extends AnyPaths, P extends GetPath<Paths>>(
61
+ link: HttpLink,
62
+ path: P,
63
+ params: DefinedParams<Paths, P>,
64
+ fallbackName: string,
65
+ ): Promise<GetResponse<Paths, P>> {
66
+ const { path: pathParams, query } = params as {
67
+ path?: Record<string, string | number>;
68
+ query?: Record<string, string | number | undefined>;
69
+ };
70
+
71
+ // Substitute `{param}` placeholders from the typed path params.
72
+ const pathStr = path as string;
73
+ const resolvedPath = pathStr.replace(/\{([^}]+)\}/g, (_, key) => {
74
+ const value = pathParams?.[key];
75
+ if (value === undefined) {
76
+ throw new Error(
77
+ `fetchOpenApi: missing path param "${key}" for "${pathStr}"`,
78
+ );
79
+ }
80
+ return encodeURIComponent(String(value));
81
+ });
82
+
83
+ // Omit params whose value is `undefined` rather than serializing them as the
84
+ // literal string "undefined" (e.g. optional filters left unset by callers).
85
+ const search = query
86
+ ? new URLSearchParams(
87
+ Object.entries(query)
88
+ .filter(([, v]) => v !== undefined)
89
+ .map(([k, v]) => [k, String(v)]),
90
+ ).toString()
91
+ : "";
92
+
93
+ const url = `${getUriFromLink(link)}${resolvedPath}${search ? `?${search}` : ""}`;
94
+ const name = typeof link === "string" ? fallbackName : link.name;
95
+
96
+ return beraFetchJson<GetResponse<Paths, P>>({ url, name, type: "rest" });
97
+ }
@@ -0,0 +1,245 @@
1
+ import {
2
+ assert,
3
+ beforeEach,
4
+ describe,
5
+ expect,
6
+ expectTypeOf,
7
+ it,
8
+ vi,
9
+ } from "vitest";
10
+
11
+ import type { HttpLink } from "@berachain/config";
12
+ import { bepolia } from "@berachain/config/bepolia";
13
+ import { mainnet } from "@berachain/config/mainnet";
14
+
15
+ import type {
16
+ paths as beepPaths,
17
+ StakeEarningResponse,
18
+ StakeStatsByDayResponse,
19
+ ValidatorsResponse,
20
+ } from "@berachain/graphql/beep";
21
+
22
+ import { fetchBeep } from "./fetchBeep";
23
+ import { fetchOpenApi } from "./fetchOpenApi";
24
+
25
+ // Mock the network layer so we can assert exactly what the helpers build and
26
+ // pass through, without hitting a backend.
27
+ const beraFetchJson = vi.fn();
28
+ vi.mock("../../utils/beraFetch", () => ({
29
+ beraFetchJson: (...args: unknown[]) => beraFetchJson(...args),
30
+ }));
31
+
32
+ const BASE = "https://beep.testnet.berachain.com";
33
+ const NAMED_LINK: HttpLink = { name: "Berachain Beep", uri: BASE };
34
+
35
+ const VAULT = "0x1111111111111111111111111111111111111111" as const;
36
+ const OWNER = "0x2222222222222222222222222222222222222222" as const;
37
+
38
+ describe("fetchOpenApi", () => {
39
+ beforeEach(() => {
40
+ beraFetchJson.mockReset();
41
+ beraFetchJson.mockResolvedValue(undefined);
42
+ });
43
+
44
+ it("substitutes path params and serializes the query", async () => {
45
+ await fetchOpenApi<beepPaths, "/v0/stake/{vault}/stats-by-day">(
46
+ NAMED_LINK,
47
+ "/v0/stake/{vault}/stats-by-day",
48
+ { path: { vault: VAULT }, query: { days: "30" } },
49
+ "beep",
50
+ );
51
+
52
+ expect(beraFetchJson).toHaveBeenCalledTimes(1);
53
+ expect(beraFetchJson).toHaveBeenCalledWith({
54
+ url: `${BASE}/v0/stake/${VAULT}/stats-by-day?days=30`,
55
+ name: "Berachain Beep",
56
+ type: "rest",
57
+ });
58
+ });
59
+
60
+ it("substitutes multiple path params and omits the query when absent", async () => {
61
+ await fetchOpenApi<beepPaths, "/v0/stake/{vault}/earnings/{owner}">(
62
+ NAMED_LINK,
63
+ "/v0/stake/{vault}/earnings/{owner}",
64
+ { path: { vault: VAULT, owner: OWNER } },
65
+ "beep",
66
+ );
67
+
68
+ expect(beraFetchJson).toHaveBeenCalledWith({
69
+ url: `${BASE}/v0/stake/${VAULT}/earnings/${OWNER}`,
70
+ name: "Berachain Beep",
71
+ type: "rest",
72
+ });
73
+ });
74
+
75
+ it("omits query params whose value is undefined", async () => {
76
+ await fetchOpenApi<beepPaths, "/v0/honey/transactions/latest">(
77
+ NAMED_LINK,
78
+ "/v0/honey/transactions/latest",
79
+ // `perPage` is set; `page` is left undefined and must not be serialized
80
+ // as the literal string "undefined".
81
+ { query: { page: undefined, perPage: "10" } },
82
+ "beep",
83
+ );
84
+
85
+ expect(beraFetchJson).toHaveBeenCalledWith(
86
+ expect.objectContaining({
87
+ url: `${BASE}/v0/honey/transactions/latest?perPage=10`,
88
+ }),
89
+ );
90
+ });
91
+
92
+ it("url-encodes path param values", async () => {
93
+ // `pubkey` is a free-form string segment; reserved chars must be encoded.
94
+ await fetchOpenApi<beepPaths, "/v0/validators/{pubkey}/incentives">(
95
+ NAMED_LINK,
96
+ "/v0/validators/{pubkey}/incentives",
97
+ { path: { pubkey: "a/b c" } },
98
+ "beep",
99
+ );
100
+
101
+ expect(beraFetchJson).toHaveBeenCalledWith(
102
+ expect.objectContaining({
103
+ url: `${BASE}/v0/validators/a%2Fb%20c/incentives`,
104
+ }),
105
+ );
106
+ });
107
+
108
+ it("falls back to the provided name for a string link", async () => {
109
+ await fetchOpenApi<beepPaths, "/v0/validators">(
110
+ BASE,
111
+ "/v0/validators",
112
+ {},
113
+ "beep",
114
+ );
115
+
116
+ expect(beraFetchJson).toHaveBeenCalledWith(
117
+ expect.objectContaining({ name: "beep" }),
118
+ );
119
+ });
120
+
121
+ it("throws when a required path param is missing", () => {
122
+ expect(() =>
123
+ fetchOpenApi<beepPaths, "/v0/stake/{vault}/earnings/{owner}">(
124
+ NAMED_LINK,
125
+ "/v0/stake/{vault}/earnings/{owner}",
126
+ // @ts-expect-error — `vault` is required by the schema for this path.
127
+ { path: { owner: OWNER } },
128
+ "beep",
129
+ ),
130
+ ).toThrow(/missing path param "vault"/);
131
+ });
132
+
133
+ it("returns the response from beraFetchJson", async () => {
134
+ const response = [{ total_assets: "1", total_supply: "2", timestamp: 3 }];
135
+ beraFetchJson.mockResolvedValue(response);
136
+
137
+ const result = await fetchOpenApi<
138
+ beepPaths,
139
+ "/v0/stake/{vault}/stats-by-day"
140
+ >(
141
+ NAMED_LINK,
142
+ "/v0/stake/{vault}/stats-by-day",
143
+ { path: { vault: VAULT }, query: { days: "30" } },
144
+ "beep",
145
+ );
146
+
147
+ expect(result).toBe(response);
148
+ });
149
+ });
150
+
151
+ describe("fetchBeep", () => {
152
+ beforeEach(() => {
153
+ beraFetchJson.mockReset();
154
+ beraFetchJson.mockResolvedValue(undefined);
155
+ });
156
+
157
+ it("resolves the base URL from config.beep", async () => {
158
+ await fetchBeep(
159
+ "/v0/stake/{vault}/stats-by-day",
160
+ { path: { vault: VAULT }, query: { days: "30" } },
161
+ { config: bepolia },
162
+ );
163
+
164
+ expect(beraFetchJson).toHaveBeenCalledWith(
165
+ expect.objectContaining({
166
+ url: `${BASE}/v0/stake/${VAULT}/stats-by-day?days=30`,
167
+ name: "Berachain Beep",
168
+ type: "rest",
169
+ }),
170
+ );
171
+ });
172
+
173
+ it("throws when config.beep is not set (e.g. a chain not yet migrated)", () => {
174
+ // Construct the no-beep case explicitly rather than relying on a real
175
+ // chain config: `mainnet.beep` is env-gated, so it may be set in some
176
+ // environments.
177
+ const configWithoutBeep = { ...mainnet, beep: null };
178
+
179
+ expect(() =>
180
+ fetchBeep(
181
+ "/v0/stake/{vault}/earnings/{owner}",
182
+ { path: { vault: VAULT, owner: OWNER } },
183
+ { config: configWithoutBeep },
184
+ ),
185
+ ).toThrow(/`beep` backend is not configured/);
186
+ });
187
+ });
188
+
189
+ // Type-only assertions. The bodies are never executed at runtime (they would
190
+ // hit the `beep` not-configured throw); they exist so `tsc` validates inference
191
+ // and the `@ts-expect-error` lines. `expectTypeOf` is purely compile-time.
192
+ describe("fetchBeep types", () => {
193
+ it("infers the response type per path", () => {
194
+ const _assert = () => {
195
+ expectTypeOf(
196
+ fetchBeep("/v0/stake/{vault}/stats-by-day", {
197
+ path: { vault: VAULT },
198
+ query: { days: "30" },
199
+ }),
200
+ ).resolves.toEqualTypeOf<StakeStatsByDayResponse>();
201
+
202
+ expectTypeOf(
203
+ fetchBeep("/v0/stake/{vault}/earnings/{owner}", {
204
+ path: { vault: VAULT, owner: OWNER },
205
+ }),
206
+ ).resolves.toEqualTypeOf<StakeEarningResponse>();
207
+
208
+ expectTypeOf(
209
+ fetchBeep("/v0/validators", {}),
210
+ ).resolves.toEqualTypeOf<ValidatorsResponse>();
211
+ };
212
+ assert.ok(_assert);
213
+ });
214
+
215
+ it("rejects unknown paths", () => {
216
+ const _assert = () => {
217
+ // @ts-expect-error — not a path in the beep schema.
218
+ fetchBeep("/v0/not/a/real/path", { path: {} });
219
+ };
220
+ assert.ok(_assert);
221
+ });
222
+
223
+ it("rejects unknown path params", () => {
224
+ const _assert = () => {
225
+ fetchBeep("/v0/stake/{vault}/stats-by-day", {
226
+ // @ts-expect-error — `owner` is not a param of stats-by-day.
227
+ path: { vault: VAULT, owner: OWNER },
228
+ query: { days: "30" },
229
+ });
230
+ };
231
+ assert.ok(_assert);
232
+ });
233
+
234
+ it("constrains query values to the schema enum", () => {
235
+ const _assert = () => {
236
+ fetchBeep("/v0/stake/{vault}/stats-by-day", {
237
+ path: { vault: VAULT },
238
+ // @ts-expect-error — `7` is not an allowed `days` value.
239
+ query: { days: "7" },
240
+ });
241
+ };
242
+
243
+ assert.ok(_assert);
244
+ });
245
+ });
@@ -0,0 +1,34 @@
1
+ import type { paths } from "@berachain/graphql/api";
2
+
3
+ import { parseBaseArgs } from "../../utils/parseBaseArgs";
4
+ import {
5
+ type DefinedParams,
6
+ fetchOpenApi,
7
+ type GetPath,
8
+ type GetResponse,
9
+ } from "./fetchOpenApi";
10
+
11
+ /**
12
+ * Typed GET against the legacy Railway backend.
13
+ *
14
+ * The `path`, its path/query params and the response are all type-checked
15
+ * against the Railway schema (`@berachain/graphql/api`). The base URL is
16
+ * resolved from `config.backend`.
17
+ *
18
+ * @deprecated The Railway backend is being replaced by beep; prefer
19
+ * {@link fetchBeep} where `config.beep` is available.
20
+ */
21
+ export function fetchRailwayBackend<P extends GetPath<paths>>(
22
+ path: P,
23
+ params: DefinedParams<paths, P>,
24
+ args: BeraJS.BaseFunctionArgs = {},
25
+ ): Promise<GetResponse<paths, P>> {
26
+ const { config } = parseBaseArgs(args);
27
+
28
+ return fetchOpenApi<paths, P>(
29
+ config.backend,
30
+ path,
31
+ params,
32
+ "backend-railway",
33
+ );
34
+ }
@@ -31,6 +31,24 @@ export async function getEnsoUserTokensWithBalances({
31
31
  eoaAddress: account,
32
32
  });
33
33
 
34
+ // The Enso SDK can return a non-array (e.g. an error object) on a malformed
35
+ // or empty response. Guard before mapping to avoid the unactionable minified
36
+ // "(...).map is not a function" crash — but still report it as a typed,
37
+ // stably-grouped warning so we don't silently swallow an Enso API problem
38
+ // (an empty portfolio would otherwise look like "user has no tokens").
39
+ if (!Array.isArray(ensoBalances)) {
40
+ BeraMonitoring.captureException(
41
+ new InvalidArgumentError({
42
+ property: "ensoBalances",
43
+ value: ensoBalances,
44
+ expected: "BalanceToken[]",
45
+ chainId: typeof chainId === "number" ? chainId : undefined,
46
+ extra: { account, chainId },
47
+ }),
48
+ );
49
+ return [];
50
+ }
51
+
34
52
  const tokens: BalanceToken[] = ensoBalances.map(
35
53
  (balance) =>
36
54
  ({
@@ -35,6 +35,7 @@ export * from "./honey/getHoneyPausedState";
35
35
  export * from "./honey/getHoneyPreview";
36
36
  export * from "./honey/getHoneyPythPriceOracle";
37
37
  export * from "./honey/getHoneyRootPriceOracle";
38
+ export * from "./honey/getHoneyTxns";
38
39
  export * from "./honey/getHoneyVaultsBalance";
39
40
  export * from "./honey/getPythLatestPrices";
40
41
  export * from "./honey/getRelativeCapLimit";
@@ -43,6 +44,7 @@ export * from "./honey/isBadCollateralAsset";
43
44
  export * from "./honey/isBasketModeEnabled";
44
45
  export * from "./misc/getBlockTimestamp";
45
46
  export * from "./pol/getAutoclaimedIncentives";
47
+ export * from "./pol/getAutoclaimedIncentivesTxHash";
46
48
  export * from "./pol/getBeraTokenTotalSupply";
47
49
  export * from "./pol/getBgtAprSimulation";
48
50
  export * from "./pol/getBgtIncentiveDistributorPaused";
@@ -1,18 +1,26 @@
1
+ import type { HoneySnapshotResponse } from "@berachain/graphql/beep";
1
2
  import type { GetSnapshotsQuery } from "@berachain/graphql/honey";
2
3
 
3
4
  import { BeraError } from "../../errors/BeraError";
4
5
  import { beraFetchJson } from "../../utils/beraFetch";
6
+ import { parseBaseArgs } from "../../utils/parseBaseArgs";
7
+ import { fetchBeep } from "../clients/fetchBeep";
5
8
 
6
9
  /**
7
- * Browser-only. Hits the typed `/api/honey/snapshots` endpoint.
8
- * Server callers must compose the upstream query directly (this action is
9
- * not server-safe — `fetch` against a relative URL has no origin off-browser).
10
+ * Browser-only. Returns daily honey snapshots in the `beep` response shape
11
+ * (`HoneySnapshotResponse`) the chart consumes.
12
+ *
13
+ * Reads from the `beep` backend (`fetchBeep`) when configured, falling back to
14
+ * the legacy honey subgraph proxied through `/api/honey/snapshots` (whose
15
+ * GraphQL result is adapted into the beep shape) otherwise. Server callers must
16
+ * compose the upstream query directly (this action is not server-safe — `fetch`
17
+ * against a relative URL has no origin off-browser).
10
18
  */
11
19
  export async function getChartData({
12
20
  days,
13
21
  }: {
14
22
  days: number;
15
- }): Promise<GetSnapshotsQuery> {
23
+ }): Promise<HoneySnapshotResponse> {
16
24
  if (typeof window === "undefined") {
17
25
  throw new BeraError({
18
26
  message:
@@ -21,13 +29,46 @@ export async function getChartData({
21
29
  });
22
30
  }
23
31
 
24
- const params = new URLSearchParams({ interval: "day", first: String(days) });
25
- const honeySnapshots = await beraFetchJson<
26
- GetSnapshotsQuery["honeySnapshots"]
27
- >({
28
- url: `/api/honey/snapshots?${params}`,
29
- name: "honey-snapshots",
30
- type: "rest",
32
+ const { config } = parseBaseArgs({});
33
+
34
+ // TODO(beep): remove this entire block once `beep` is deployed on every
35
+ // chain. It is the only legacy honey-subgraph code left here; deleting it
36
+ // leaves the `beep` path below as the sole implementation.
37
+ if (!config.beep) {
38
+ const params = new URLSearchParams({
39
+ interval: "day",
40
+ first: String(days),
41
+ });
42
+ const snapshots = await beraFetchJson<GetSnapshotsQuery["honeySnapshots"]>({
43
+ url: `/api/honey/snapshots?${params}`,
44
+ name: "honey-snapshots",
45
+ type: "rest",
46
+ });
47
+ return snapshots.map(fromHoneySnapshot);
48
+ }
49
+
50
+ // beep backend (next-gen), typed against `@berachain/graphql/beep`. Queried
51
+ // directly from the browser — no Vercel proxy.
52
+ return fetchBeep("/v0/honey/snapshots/{interval}", {
53
+ path: { interval: "day" },
54
+ query: { perPage: String(days) },
31
55
  });
32
- return { honeySnapshots };
56
+ }
57
+
58
+ /**
59
+ * Adapt a legacy subgraph snapshot into the beep `HoneySnapshotResponse` shape.
60
+ *
61
+ * The subgraph reports `timestamp` in microseconds; beep (and every consumer)
62
+ * expects seconds, so scale microseconds → seconds.
63
+ */
64
+ function fromHoneySnapshot(
65
+ snapshot: GetSnapshotsQuery["honeySnapshots"][number],
66
+ ): HoneySnapshotResponse[number] {
67
+ return {
68
+ timestamp: Math.floor(Number(snapshot.timestamp) / 1_000_000),
69
+ mintVolume: snapshot.mintVolume,
70
+ redeemVolume: snapshot.redeemVolume,
71
+ totalVolume: snapshot.totalVolume,
72
+ totalSupply: snapshot.totalSupply,
73
+ };
33
74
  }
@@ -3,8 +3,16 @@ import BigNumber from "@berachain/utils/pkg/bignumber.js";
3
3
 
4
4
  import { BeraError } from "../../errors/BeraError";
5
5
  import { beraFetchJson } from "../../utils/beraFetch";
6
+ import { parseBaseArgs } from "../../utils/parseBaseArgs";
7
+ import { fetchBeep } from "../clients/fetchBeep";
6
8
 
7
- /** Browser-only. Hits `/api/honey/snapshots?interval=hour&first=24` and reduces. */
9
+ /**
10
+ * Browser-only. Sums the last 24 hourly honey snapshots into a 24h volume.
11
+ *
12
+ * Reads from the `beep` backend (`fetchBeep`) when configured, falling back to
13
+ * the legacy honey subgraph proxied through `/api/honey/snapshots` otherwise.
14
+ * Both backends expose `totalVolume` per snapshot, so the sum is shape-agnostic.
15
+ */
8
16
  export async function getHoney24hVolume(): Promise<BigNumber | undefined> {
9
17
  if (typeof window === "undefined") {
10
18
  throw new BeraError({
@@ -14,12 +22,32 @@ export async function getHoney24hVolume(): Promise<BigNumber | undefined> {
14
22
  });
15
23
  }
16
24
 
17
- const params = new URLSearchParams({ interval: "hour", first: "24" });
18
- const snapshots = await beraFetchJson<GetSnapshotsQuery["honeySnapshots"]>({
19
- url: `/api/honey/snapshots?${params}`,
20
- name: "honey-snapshots",
21
- type: "rest",
25
+ const { config } = parseBaseArgs({});
26
+
27
+ // TODO(beep): remove this entire block once `beep` is deployed on every
28
+ // chain. It is the only legacy honey-subgraph code left here; deleting it
29
+ // leaves the `beep` path below as the sole implementation.
30
+ if (!config.beep) {
31
+ const params = new URLSearchParams({ interval: "hour", first: "24" });
32
+ const snapshots = await beraFetchJson<GetSnapshotsQuery["honeySnapshots"]>({
33
+ url: `/api/honey/snapshots?${params}`,
34
+ name: "honey-snapshots",
35
+ type: "rest",
36
+ });
37
+ return sumTotalVolume(snapshots);
38
+ }
39
+
40
+ // beep backend (next-gen), typed against `@berachain/graphql/beep`. Queried
41
+ // directly from the browser — no Vercel proxy.
42
+ const snapshots = await fetchBeep("/v0/honey/snapshots/{interval}", {
43
+ path: { interval: "hour" },
44
+ query: { perPage: "24" },
22
45
  });
46
+
47
+ return sumTotalVolume(snapshots);
48
+ }
49
+
50
+ function sumTotalVolume(snapshots: { totalVolume: string }[]): BigNumber {
23
51
  return snapshots.reduce(
24
52
  (acc, curr) => new BigNumber(curr.totalVolume).plus(acc),
25
53
  new BigNumber(0),