@gibs/bridge-sdk 1.13.1 → 1.18.0

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 (228) hide show
  1. package/README.md +295 -18
  2. package/abis/package.json +6 -0
  3. package/bridge-limits/package.json +6 -0
  4. package/chain-info/package.json +6 -0
  5. package/chain-names/package.json +6 -0
  6. package/chains/package.json +6 -0
  7. package/claims/package.json +6 -0
  8. package/config/package.json +6 -0
  9. package/consolidated-quote/package.json +6 -0
  10. package/destination-calldata/package.json +6 -0
  11. package/dist/chain-info.d.ts +1 -1
  12. package/dist/chain-info.js +11 -12
  13. package/dist/chains.d.ts +25 -0
  14. package/dist/chains.js +55 -20
  15. package/dist/cjs/abis.d.ts +1 -0
  16. package/dist/cjs/abis.js +19 -0
  17. package/dist/cjs/bridge-limits.d.ts +103 -0
  18. package/dist/cjs/bridge-limits.js +89 -0
  19. package/dist/cjs/chain-info.d.ts +169 -0
  20. package/dist/cjs/chain-info.js +452 -0
  21. package/dist/cjs/chain-names.d.ts +160 -0
  22. package/dist/cjs/chain-names.js +207 -0
  23. package/dist/cjs/chains.d.ts +90 -0
  24. package/dist/cjs/chains.js +357 -0
  25. package/dist/cjs/claims.d.ts +198 -0
  26. package/dist/cjs/claims.js +182 -0
  27. package/dist/cjs/config.d.ts +255 -0
  28. package/dist/cjs/config.js +569 -0
  29. package/dist/cjs/consolidated-quote.d.ts +648 -0
  30. package/dist/cjs/consolidated-quote.js +1048 -0
  31. package/dist/cjs/destination-calldata.d.ts +118 -0
  32. package/dist/cjs/destination-calldata.js +156 -0
  33. package/dist/cjs/ecosystems.d.ts +217 -0
  34. package/dist/cjs/ecosystems.js +298 -0
  35. package/dist/cjs/execution.d.ts +359 -0
  36. package/dist/cjs/execution.js +495 -0
  37. package/dist/cjs/fee-type.d.ts +10 -0
  38. package/dist/cjs/fee-type.js +10 -0
  39. package/dist/cjs/hyperliquid-execution.d.ts +152 -0
  40. package/dist/cjs/hyperliquid-execution.js +175 -0
  41. package/dist/cjs/image-links.d.ts +117 -0
  42. package/dist/cjs/image-links.js +153 -0
  43. package/dist/cjs/index.d.ts +24 -0
  44. package/dist/cjs/index.js +40 -0
  45. package/dist/cjs/lifi-execution-guard.d.ts +210 -0
  46. package/dist/cjs/lifi-execution-guard.js +409 -0
  47. package/dist/cjs/near-intents-conformance.d.ts +85 -0
  48. package/dist/cjs/near-intents-conformance.js +337 -0
  49. package/dist/cjs/near-intents-route.d.ts +47 -0
  50. package/dist/cjs/near-intents-route.js +303 -0
  51. package/dist/cjs/near-intents.d.ts +524 -0
  52. package/dist/cjs/near-intents.js +1071 -0
  53. package/dist/cjs/origin-deposit.d.ts +326 -0
  54. package/dist/cjs/origin-deposit.js +82 -0
  55. package/dist/cjs/package.json +3 -0
  56. package/dist/cjs/pre-quote.d.ts +198 -0
  57. package/dist/cjs/pre-quote.js +180 -0
  58. package/dist/cjs/prices.d.ts +117 -0
  59. package/dist/cjs/prices.js +224 -0
  60. package/dist/cjs/providers.d.ts +238 -0
  61. package/dist/cjs/providers.js +171 -0
  62. package/dist/cjs/quote-fees.d.ts +102 -0
  63. package/dist/cjs/quote-fees.js +201 -0
  64. package/dist/cjs/referral.d.ts +85 -0
  65. package/dist/cjs/referral.js +85 -0
  66. package/dist/cjs/relay-currencies.d.ts +47 -0
  67. package/dist/cjs/relay-currencies.js +95 -0
  68. package/dist/cjs/relay-depository.d.ts +2 -0
  69. package/dist/cjs/relay-depository.js +85 -0
  70. package/dist/cjs/relay-quote.d.ts +301 -0
  71. package/dist/cjs/relay-quote.js +996 -0
  72. package/dist/cjs/route-steps.d.ts +138 -0
  73. package/dist/cjs/route-steps.js +310 -0
  74. package/dist/cjs/routing/amounts.d.ts +80 -0
  75. package/dist/cjs/routing/amounts.js +126 -0
  76. package/dist/cjs/routing/candidate-route.d.ts +43 -0
  77. package/dist/cjs/routing/candidate-route.js +50 -0
  78. package/dist/cjs/routing/candidate.d.ts +237 -0
  79. package/dist/cjs/routing/candidate.js +100 -0
  80. package/dist/cjs/routing/carrier-provider-key.d.ts +31 -0
  81. package/dist/cjs/routing/carrier-provider-key.js +42 -0
  82. package/dist/cjs/routing/carriers/ask-answer.d.ts +77 -0
  83. package/dist/cjs/routing/carriers/ask-answer.js +2 -0
  84. package/dist/cjs/routing/carriers/omnibridge.d.ts +137 -0
  85. package/dist/cjs/routing/carriers/omnibridge.js +459 -0
  86. package/dist/cjs/routing/carriers/pulsex-paths.d.ts +80 -0
  87. package/dist/cjs/routing/carriers/pulsex-paths.js +97 -0
  88. package/dist/cjs/routing/carriers/pulsex-split.d.ts +175 -0
  89. package/dist/cjs/routing/carriers/pulsex-split.js +193 -0
  90. package/dist/cjs/routing/carriers/pulsex.d.ts +184 -0
  91. package/dist/cjs/routing/carriers/pulsex.js +615 -0
  92. package/dist/cjs/routing/carriers/wrap.d.ts +25 -0
  93. package/dist/cjs/routing/carriers/wrap.js +119 -0
  94. package/dist/cjs/routing/composed-route-quality.d.ts +125 -0
  95. package/dist/cjs/routing/composed-route-quality.js +144 -0
  96. package/dist/cjs/routing/entry-chain-anchor.d.ts +88 -0
  97. package/dist/cjs/routing/entry-chain-anchor.js +59 -0
  98. package/dist/cjs/routing/format.d.ts +31 -0
  99. package/dist/cjs/routing/format.js +64 -0
  100. package/dist/cjs/routing/index.d.ts +42 -0
  101. package/dist/cjs/routing/index.js +142 -0
  102. package/dist/cjs/routing/producers.d.ts +770 -0
  103. package/dist/cjs/routing/producers.js +1617 -0
  104. package/dist/cjs/routing/providers.d.ts +31 -0
  105. package/dist/cjs/routing/providers.js +48 -0
  106. package/dist/cjs/routing/route-data.d.ts +397 -0
  107. package/dist/cjs/routing/route-data.js +2 -0
  108. package/dist/cjs/routing/search/compose.d.ts +168 -0
  109. package/dist/cjs/routing/search/compose.js +104 -0
  110. package/dist/cjs/routing/search/graph.d.ts +668 -0
  111. package/dist/cjs/routing/search/graph.js +461 -0
  112. package/dist/cjs/routing/search/plan-route-data.d.ts +285 -0
  113. package/dist/cjs/routing/search/plan-route-data.js +871 -0
  114. package/dist/cjs/routing/search/score.d.ts +356 -0
  115. package/dist/cjs/routing/search/score.js +445 -0
  116. package/dist/cjs/routing/swap-transactions.d.ts +95 -0
  117. package/dist/cjs/routing/swap-transactions.js +133 -0
  118. package/dist/cjs/routing/usd-value.d.ts +17 -0
  119. package/dist/cjs/routing/usd-value.js +29 -0
  120. package/dist/cjs/settings.d.ts +785 -0
  121. package/dist/cjs/settings.js +1074 -0
  122. package/dist/cjs/swap-venues.d.ts +43 -0
  123. package/dist/cjs/swap-venues.js +29 -0
  124. package/dist/cjs/ton-connect.d.ts +98 -0
  125. package/dist/cjs/ton-connect.js +206 -0
  126. package/dist/cjs/ton-execution.d.ts +7 -0
  127. package/dist/cjs/ton-execution.js +23 -0
  128. package/dist/cjs/ton.d.ts +37 -0
  129. package/dist/cjs/ton.js +83 -0
  130. package/dist/cjs/tron-execution.d.ts +146 -0
  131. package/dist/cjs/tron-execution.js +248 -0
  132. package/dist/cjs/types.d.ts +51 -0
  133. package/dist/cjs/types.js +2 -0
  134. package/dist/claims.d.ts +198 -0
  135. package/dist/claims.js +140 -0
  136. package/dist/config.d.ts +42 -3
  137. package/dist/config.js +87 -21
  138. package/dist/consolidated-quote.d.ts +109 -15
  139. package/dist/consolidated-quote.js +310 -52
  140. package/dist/execution.d.ts +359 -0
  141. package/dist/execution.js +455 -0
  142. package/dist/hyperliquid-execution.js +2 -3
  143. package/dist/index.d.ts +4 -0
  144. package/dist/index.js +4 -0
  145. package/dist/lifi-execution-guard.d.ts +13 -2
  146. package/dist/lifi-execution-guard.js +4 -0
  147. package/dist/near-intents.js +2 -3
  148. package/dist/pre-quote.d.ts +6 -6
  149. package/dist/pre-quote.js +10 -14
  150. package/dist/prices.d.ts +10 -0
  151. package/dist/prices.js +52 -1
  152. package/dist/providers.d.ts +17 -0
  153. package/dist/providers.js +6 -0
  154. package/dist/referral.d.ts +12 -4
  155. package/dist/referral.js +12 -4
  156. package/dist/relay-depository.d.ts +2 -0
  157. package/dist/relay-depository.js +82 -0
  158. package/dist/relay-quote.js +2 -3
  159. package/dist/routing/candidate.d.ts +3 -3
  160. package/dist/routing/candidate.js +3 -3
  161. package/dist/routing/carrier-provider-key.d.ts +31 -0
  162. package/dist/routing/carrier-provider-key.js +37 -0
  163. package/dist/routing/carriers/ask-answer.d.ts +17 -0
  164. package/dist/routing/carriers/omnibridge.js +23 -21
  165. package/dist/routing/carriers/pulsex-paths.d.ts +80 -0
  166. package/dist/routing/carriers/pulsex-paths.js +92 -0
  167. package/dist/routing/carriers/pulsex-split.d.ts +175 -0
  168. package/dist/routing/carriers/pulsex-split.js +185 -0
  169. package/dist/routing/carriers/pulsex.d.ts +81 -46
  170. package/dist/routing/carriers/pulsex.js +267 -148
  171. package/dist/routing/composed-route-quality.d.ts +28 -6
  172. package/dist/routing/composed-route-quality.js +36 -5
  173. package/dist/routing/entry-chain-anchor.d.ts +1 -1
  174. package/dist/routing/entry-chain-anchor.js +1 -1
  175. package/dist/routing/index.d.ts +11 -3
  176. package/dist/routing/index.js +8 -2
  177. package/dist/routing/producers.js +1 -1
  178. package/dist/routing/providers.d.ts +5 -0
  179. package/dist/routing/providers.js +5 -0
  180. package/dist/routing/route-data.d.ts +47 -5
  181. package/dist/routing/search/graph.d.ts +15 -0
  182. package/dist/routing/search/plan-route-data.d.ts +42 -1
  183. package/dist/routing/search/plan-route-data.js +68 -9
  184. package/dist/routing/search/score.d.ts +3 -0
  185. package/dist/routing/search/score.js +11 -3
  186. package/dist/routing/swap-transactions.d.ts +95 -0
  187. package/dist/routing/swap-transactions.js +127 -0
  188. package/dist/settings.d.ts +94 -1
  189. package/dist/settings.js +95 -3
  190. package/dist/swap-venues.d.ts +43 -0
  191. package/dist/swap-venues.js +24 -0
  192. package/dist/ton-connect.d.ts +98 -0
  193. package/dist/ton-connect.js +200 -0
  194. package/dist/ton-execution.d.ts +4 -114
  195. package/dist/ton-execution.js +4 -244
  196. package/dist/ton.d.ts +37 -0
  197. package/dist/ton.js +65 -0
  198. package/docs/examples/example-a-ether-to-pulse.ts +300 -0
  199. package/docs/examples/example-b-token-pulsechain-to-ethereum.ts +270 -0
  200. package/docs/examples/shared.ts +261 -0
  201. package/docs/examples/tsconfig.json +18 -0
  202. package/docs/integration-guide.md +617 -0
  203. package/ecosystems/package.json +6 -0
  204. package/execution/package.json +6 -0
  205. package/fee-type/package.json +6 -0
  206. package/hyperliquid-execution/package.json +6 -0
  207. package/image-links/package.json +6 -0
  208. package/lifi-execution-guard/package.json +6 -0
  209. package/llms.txt +75 -10
  210. package/near-intents/package.json +6 -0
  211. package/near-intents-route/package.json +6 -0
  212. package/origin-deposit/package.json +6 -0
  213. package/package.json +817 -10
  214. package/pre-quote/package.json +6 -0
  215. package/prices/package.json +6 -0
  216. package/providers/package.json +6 -0
  217. package/quote-fees/package.json +6 -0
  218. package/referral/package.json +6 -0
  219. package/relay-currencies/package.json +6 -0
  220. package/relay-quote/package.json +6 -0
  221. package/route-steps/package.json +6 -0
  222. package/routing/package.json +6 -0
  223. package/settings/package.json +6 -0
  224. package/ton/package.json +6 -0
  225. package/ton-connect/package.json +6 -0
  226. package/ton-execution/package.json +6 -0
  227. package/tron-execution/package.json +6 -0
  228. package/types/package.json +6 -0
@@ -0,0 +1,996 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseRelayStatus = exports.relayStatusUrl = exports.parseRelayQuote = exports.buildRelayQuoteRequest = exports.relayReferrerField = exports.slippageToBasisPoints = exports.relayNativeCurrencyAddresses = exports.ecosystemByChainId = exports.relayChainNames = exports.relayChainIds = exports.relayApprovalGasBuffer = exports.relayReferralRecipient = exports.relayReferralFeeBasisPoints = exports.relayReferrer = exports.relayRequestHeaders = exports.relayRequestsUrl = exports.relayQuoteUrl = exports.relayApiBaseUrl = void 0;
4
+ const url_1 = require("@gibs/common/url");
5
+ const viem_1 = require("viem");
6
+ const config_js_1 = require("./config.js");
7
+ const consolidated_quote_js_1 = require("./consolidated-quote.js");
8
+ const referral_js_1 = require("./referral.js");
9
+ const chain_names_js_1 = require("./chain-names.js");
10
+ const route_steps_js_1 = require("./route-steps.js");
11
+ const quote_fees_js_1 = require("./quote-fees.js");
12
+ /**
13
+ * Relay (relay.link) as a second consolidated-route quote provider, competing
14
+ * with LI.FI on price. Relay quotes the same backwards-from-destination route:
15
+ * deliver exactly `toAmount` of the Ethereum-side token, then run our omnibridge
16
+ * entry call against it.
17
+ *
18
+ * One semantic differs from LI.FI and the difference is load-bearing. Relay has
19
+ * NO destination-chain fallback address. When the destination call cannot fill,
20
+ * Relay refunds on the ORIGIN chain to `refundTo`, in the origin currency — the
21
+ * user ends up back where they started, not holding the Ethereum-side token at
22
+ * a fallback. We therefore map our `fallbackAddress` onto `refundTo`; a failed
23
+ * Relay route is recovered on the origin chain, never stranded on Ethereum.
24
+ */
25
+ /**
26
+ * Relay's API root. Steps carry RELATIVE post endpoints (`/authorize`), so a
27
+ * caller completing one has to resolve it against this.
28
+ */
29
+ exports.relayApiBaseUrl = 'https://api.relay.link';
30
+ /** Relay quote endpoint. Anonymous access works at a 50-requests-per-minute tier. */
31
+ exports.relayQuoteUrl = `${exports.relayApiBaseUrl}/quote/v2`;
32
+ /** Relay requests endpoint; filters by origin or destination transaction hash. */
33
+ /**
34
+ * The request-lookup endpoint, used to poll a route's progress.
35
+ *
36
+ * v3 RATHER THAN v2 BECAUSE v2 IS GOING AWAY. Relay began staged rate limiting
37
+ * of `/requests/v2` on 2026-09-01 and retires it on 2026-11-24, saying so in a
38
+ * `deprecation` block on every v2 response. v3 REQUIRES `x-api-key` - it
39
+ * answers 400 without one, where v2 served anonymous callers from a shared
40
+ * pool - so a caller must send `relayRequestHeaders(yourRelayApiKey)`.
41
+ */
42
+ exports.relayRequestsUrl = 'https://api.relay.link/requests/v3';
43
+ /**
44
+ * Builds the headers for a Relay request. `apiKey` is Relay's `x-api-key`
45
+ * value. This package ships no key: the caller supplies its own (the Gibs
46
+ * interface keeps its key in `packages/ui/src/lib/config.ts`).
47
+ * Relay raises the account's rate limit and attributes traffic to it when the
48
+ * header is present.
49
+ *
50
+ * When `apiKey` is absent or an empty string, the returned headers carry NO
51
+ * `x-api-key` entry at all — not an empty one.
52
+ *
53
+ * WHETHER THAT IS SURVIVABLE DEPENDS ENTIRELY ON WHICH ENDPOINT IS BEING CALLED,
54
+ * and this note used to say only the reassuring half. Measured against the live
55
+ * service:
56
+ *
57
+ * POST /quote no key -> 200 routing works anonymously
58
+ * GET /requests/v3 no key -> 400 "headers must have required
59
+ * property 'x-api-key'"
60
+ *
61
+ * So a missing key is a normal operating state for ROUTING — a reader on a
62
+ * local build or the anonymous InterPlanetary File System deployment still gets
63
+ * real quotes, and clearing the key disables attribution rather than the
64
+ * product. It is NOT survivable for STATUS. Every status poll from a keyless
65
+ * build fails, which means a consolidated record never learns its provider
66
+ * finished, never records the entry-chain transaction, and never releases from
67
+ * the pending list. That is not a degraded rate limit; it is the feature not
68
+ * working at all, silently.
69
+ */
70
+ const relayRequestHeaders = (apiKey) => {
71
+ const headers = { 'Content-Type': 'application/json' };
72
+ if (apiKey) {
73
+ headers['x-api-key'] = apiKey;
74
+ }
75
+ return headers;
76
+ };
77
+ exports.relayRequestHeaders = relayRequestHeaders;
78
+ /**
79
+ * Gibs Finance's own Relay `referrer`, for callers that want to attribute to
80
+ * Gibs Finance. The request builders do NOT default to it: pass it, or your
81
+ * own, as `relayReferrer` on the request. Relay reads any `referrer` as "a
82
+ * referrer was supplied" and then requires an API key, so a default would
83
+ * break every caller without one.
84
+ */
85
+ exports.relayReferrer = referral_js_1.referralIntegrator;
86
+ /**
87
+ * Application fee in basis points charged on Relay routes. Ten basis points is
88
+ * one tenth of a percent. Sent as `appFees[0].fee` when a payout recipient is
89
+ * configured; absent entirely when the recipient is missing.
90
+ */
91
+ exports.relayReferralFeeBasisPoints = referral_js_1.defaultReferralFeeBasisPoints;
92
+ var referral_js_2 = require("./referral.js");
93
+ Object.defineProperty(exports, "relayReferralRecipient", { enumerable: true, get: function () { return referral_js_2.relayReferralRecipient; } });
94
+ /** Extra gas added to the destination budget to cover a prepended approval call. */
95
+ exports.relayApprovalGasBuffer = 60000n;
96
+ /**
97
+ * Relay's chain identifiers and their display names live in `chain-names.ts`
98
+ * so the route-step normalizer can name a Relay chain without importing this
99
+ * module, which imports it. Re-exported here because callers reach for them
100
+ * alongside the rest of the Relay surface.
101
+ */
102
+ var chain_names_js_2 = require("./chain-names.js");
103
+ Object.defineProperty(exports, "relayChainIds", { enumerable: true, get: function () { return chain_names_js_2.relayChainIds; } });
104
+ Object.defineProperty(exports, "relayChainNames", { enumerable: true, get: function () { return chain_names_js_2.relayChainNames; } });
105
+ /**
106
+ * Relay's pseudo chain identifiers, mapped to the ecosystem each belongs to.
107
+ * Data rather than a branch chain, so registering another Relay origin is one
108
+ * entry here instead of another conditional.
109
+ */
110
+ const ecosystemByRelayChainId = new Map([
111
+ [chain_names_js_1.relayChainIds.solana, 'svm'],
112
+ // two chain ids, one ecosystem: the mapping is many-to-one by design
113
+ [chain_names_js_1.relayChainIds.eclipse, 'svm'],
114
+ [chain_names_js_1.relayChainIds.bitcoin, 'bvm'],
115
+ [chain_names_js_1.relayChainIds.tron, 'tvm'],
116
+ [chain_names_js_1.relayChainIds.ton, 'tonvm'],
117
+ [chain_names_js_1.relayChainIds.hyperliquid, 'hypevm'],
118
+ ]);
119
+ /**
120
+ * The chains a reader pays by hand, mapped to the ecosystem each belongs to.
121
+ *
122
+ * KEPT APART FROM THE RELAY MAP ABOVE, because none of these is a Relay chain
123
+ * and a map named for Relay should not claim one. They are here at all because
124
+ * {@link ecosystemByChainId} answers `evm` for every identifier it does not
125
+ * know. An unregistered Zcash identifier would therefore read as an Ethereum
126
+ * chain — which has a wallet, a signer and a transaction — and the reader would
127
+ * be asked to sign on a chain they do not hold.
128
+ *
129
+ * Typed `Record<DepositAddressChain, Ecosystem>` rather than `Map<number, …>`
130
+ * so a chain added to {@link depositAddressChainIds} without an ecosystem
131
+ * here is a compile error. This is the table finding this danger is about: a
132
+ * silent miss is exactly the "reads as Ethereum" failure the comment above
133
+ * warns against, and a compile error is the only guard that cannot be
134
+ * forgotten.
135
+ */
136
+ const ecosystemByDepositAddressChain = {
137
+ zcash: 'zcash',
138
+ };
139
+ /** {@link ecosystemByDepositAddressChain}, keyed by chain id for lookup. */
140
+ const ecosystemByDepositAddressChainId = new Map(Object.keys(chain_names_js_1.depositAddressChainIds).map((chain) => [
141
+ chain_names_js_1.depositAddressChainIds[chain],
142
+ ecosystemByDepositAddressChain[chain],
143
+ ]));
144
+ /**
145
+ * Maps a chain identifier to its virtual-machine ecosystem. Relay's non-Ethereum
146
+ * pseudo chain identifiers map to their own ecosystem; every other identifier
147
+ * (every Ethereum Virtual Machine chain) maps to `evm`. Total — never throws.
148
+ *
149
+ * Lives here rather than in `ecosystems.ts` because it depends on
150
+ * `relayChainIds` (defined in this file); the `Ecosystem` import is type-only,
151
+ * so `ecosystems.ts` stays a dependency-free leaf and no import cycle is formed.
152
+ *
153
+ * @param chainId - a chain identifier (an Ethereum chain id, or a Relay pseudo id)
154
+ * @returns the ecosystem that chain belongs to
155
+ */
156
+ const ecosystemByChainId = (chainId) => ecosystemByRelayChainId.get(chainId) ?? ecosystemByDepositAddressChainId.get(chainId) ?? 'evm';
157
+ exports.ecosystemByChainId = ecosystemByChainId;
158
+ /**
159
+ * Relay's native-currency address strings, used verbatim as `originCurrency`
160
+ * when the origin pays in the chain's native asset.
161
+ *
162
+ * Source: https://api.relay.link/chains.
163
+ */
164
+ exports.relayNativeCurrencyAddresses = {
165
+ /**
166
+ * Ethereum Virtual Machine native currency (Ether, native gas tokens). The
167
+ * all-zero address Relay uses across every Ethereum Virtual Machine chain.
168
+ */
169
+ ethereumVirtualMachine: '0x0000000000000000000000000000000000000000',
170
+ /**
171
+ * Solana native currency (SOL), addressed by the System Program. Nine
172
+ * decimals.
173
+ */
174
+ solana: '11111111111111111111111111111111',
175
+ /** Bitcoin native currency (BTC). Eight decimals. */
176
+ bitcoin: 'bc1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqmql8k8',
177
+ /** Tron native currency (TRX). Six decimals. */
178
+ tron: 'T9yD14Nj9j7xAB4dbGeiX9h8unkKHxuWwb',
179
+ /**
180
+ * The Open Network's native currency as Relay reports it: Gram, NOT the
181
+ * Toncoin gas asset. Nine decimals.
182
+ */
183
+ ton: 'EQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAM9c',
184
+ /**
185
+ * Hyperliquid's native currency as Relay reports it: USD Coin, NOT the Hype
186
+ * gas asset, addressed by a sixteen-byte HyperCore token identifier. Eight
187
+ * decimals. Deliberately NOT the twenty-byte all-zero Ethereum address.
188
+ */
189
+ hyperliquid: '0x00000000000000000000000000000000',
190
+ };
191
+ /**
192
+ * Converts a slippage fraction into the basis-point string Relay expects.
193
+ *
194
+ * @param slippage - tolerance as a fraction (0.005 means half a percent)
195
+ * @returns basis points as a string (0.005 becomes "50")
196
+ */
197
+ const slippageToBasisPoints = (slippage) => Math.round(slippage * 10_000).toString();
198
+ exports.slippageToBasisPoints = slippageToBasisPoints;
199
+ /**
200
+ * The `referrer` field of a Relay request body, present only when the caller
201
+ * named one. Relay reads any `referrer`, an empty one included, as "a referrer
202
+ * was supplied" and then requires an API key, so absence is the safe default.
203
+ *
204
+ * @param request - carries the caller's `relayReferrer`, if any
205
+ * @returns `{ referrer }`, or an empty object
206
+ */
207
+ const relayReferrerField = (request) => {
208
+ const referrer = (0, referral_js_1.resolveAttribution)(request.relayReferrer, undefined);
209
+ return referrer === undefined ? {} : { referrer };
210
+ };
211
+ exports.relayReferrerField = relayReferrerField;
212
+ /**
213
+ * Builds the Relay contract-call quote request from a provider-agnostic
214
+ * consolidated request. The omnibridge entry call becomes the final `txs`
215
+ * entry; when it needs an ERC20 allowance (the relayTokens shape, where
216
+ * `approvalTarget` is set) an `approve` call is prepended so Relay's executor
217
+ * grants it before relaying.
218
+ *
219
+ * @returns the request body, or null when the inputs cannot form a valid call
220
+ */
221
+ const buildRelayQuoteRequest = (request) => {
222
+ const { destinationCall, toAmount } = request;
223
+ // A DIRECT ROUTE — no omnibridge leg, so nothing to call on arrival.
224
+ //
225
+ // Solved FORWARDS rather than backwards, which is the whole difference. A
226
+ // route into the omnibridge must deliver an exact amount to the entry call,
227
+ // so it asks Relay for an exact OUTPUT. Here the reader says what they are
228
+ // spending and the delivered amount is whatever the market gives, so it asks
229
+ // for an exact INPUT and names a `recipient` instead of a transaction to run.
230
+ if (destinationCall === undefined) {
231
+ const fromAmount = request.fromAmount;
232
+ if (fromAmount === undefined || fromAmount <= 0n) {
233
+ return null;
234
+ }
235
+ const nonEthereumOriginDirect = (0, consolidated_quote_js_1.isNonEthereumVirtualMachineOrigin)(request);
236
+ return {
237
+ user: request.fromAddress,
238
+ originChainId: request.fromChainId,
239
+ originCurrency: request.fromTokenAddress,
240
+ destinationChainId: request.toChainId ?? Number(config_js_1.Chains.ETH),
241
+ destinationCurrency: request.toTokenAddress,
242
+ amount: fromAmount.toString(),
243
+ tradeType: 'EXACT_INPUT',
244
+ // Where the funds land. On a route through the omnibridge this is encoded
245
+ // inside the entry call; with no call to carry it, Relay is told directly.
246
+ recipient: request.recipient,
247
+ // Same rule as the omnibridge path below: Relay refunds on the ORIGIN
248
+ // chain, so a non-Ethereum origin cannot be refunded to an Ethereum
249
+ // fallback address and must name its own.
250
+ refundTo: nonEthereumOriginDirect ? request.fromAddress : request.fallbackAddress,
251
+ ...(0, exports.relayReferrerField)(request),
252
+ ...(request.slippage === undefined
253
+ ? {}
254
+ : { slippageTolerance: (0, exports.slippageToBasisPoints)(request.slippage) }),
255
+ ...(request.originVmType === 'svm' && request.solanaFeePayer !== undefined
256
+ ? { depositFeePayer: request.solanaFeePayer }
257
+ : {}),
258
+ ...(request.originVmType === 'bvm' && request.bitcoinPublicKey !== undefined
259
+ ? { additionalData: { userPublicKey: request.bitcoinPublicKey } }
260
+ : {}),
261
+ ...(request.relayAppFee &&
262
+ request.relayAppFee.basisPoints > 0n &&
263
+ request.relayAppFee.recipient
264
+ ? {
265
+ appFees: [
266
+ {
267
+ recipient: request.relayAppFee.recipient,
268
+ fee: request.relayAppFee.basisPoints.toString(),
269
+ },
270
+ ],
271
+ }
272
+ : {}),
273
+ };
274
+ }
275
+ if (toAmount <= 0n) {
276
+ return null;
277
+ }
278
+ // A NATIVE ENTRY (`wrapAndRelayTokens`) CARRIES VALUE, and Relay's solver
279
+ // attaches it: a dry quote with this exact call simulates it on the entry
280
+ // chain (see `providers.ts`'s `destinationCallCarriesNativeValue` for the
281
+ // measurement). Relay delivers the native coin itself, so no approval is
282
+ // prepended — the call's own `approvalTarget` is null for this shape.
283
+ const entryCall = {
284
+ to: destinationCall.to,
285
+ value: destinationCall.value.toString(),
286
+ data: destinationCall.data,
287
+ };
288
+ const needsApproval = destinationCall.approvalTarget !== null;
289
+ // grant an unbounded allowance, the standard executor pattern: Relay's
290
+ // Multicaller holds the bridged tokens only transiently during the call
291
+ // sequence, and an exact allowance would strand funds if the entry call ever
292
+ // pulls a balance rather than the fixed amount encoded in its calldata
293
+ const approvalCall = needsApproval
294
+ ? {
295
+ to: request.toTokenAddress,
296
+ value: '0',
297
+ data: (0, viem_1.encodeFunctionData)({
298
+ abi: viem_1.erc20Abi,
299
+ functionName: 'approve',
300
+ args: [destinationCall.approvalTarget, viem_1.maxUint256],
301
+ }),
302
+ }
303
+ : null;
304
+ const txs = approvalCall ? [approvalCall, entryCall] : [entryCall];
305
+ const txsGasLimit = destinationCall.gasLimit + (needsApproval ? exports.relayApprovalGasBuffer : 0n);
306
+ // The omnibridge has two entry points: Ethereum and Binance Smart Chain. The
307
+ // destination chain MUST track the entry chain the request targets, because
308
+ // `destinationCurrency` is the entry-chain token address — pairing a
309
+ // Binance-side token with a hardcoded Ethereum destination makes Relay reject
310
+ // the quote with "Invalid input or output currency" (that token does not exist
311
+ // on Ethereum). Defaults to Ethereum, preserving the original single-entry
312
+ // behavior when `toChainId` is omitted.
313
+ const destinationChainId = request.toChainId ?? Number(config_js_1.Chains.ETH);
314
+ const nonEthereumOrigin = (0, consolidated_quote_js_1.isNonEthereumVirtualMachineOrigin)(request);
315
+ // Relay always refunds a failed route on the ORIGIN chain. For an Ethereum
316
+ // Virtual Machine origin the user's Ethereum-side fallback address doubles as
317
+ // that origin refund target (unchanged behavior). For a non-Ethereum origin
318
+ // the fallback address is an Ethereum address Relay cannot refund to on the
319
+ // origin chain, so the refund must go to the user's own origin-chain address.
320
+ const refundTo = nonEthereumOrigin ? request.fromAddress : request.fallbackAddress;
321
+ // Relay's Solana fee sponsorship; only included for a Solana origin that names a payer.
322
+ const includeDepositFeePayer = request.originVmType === 'svm' && request.solanaFeePayer !== undefined;
323
+ // Relay's Bitcoin pay-to-script-hash public key; only for a Bitcoin origin that supplies one.
324
+ const includeBitcoinPublicKey = request.originVmType === 'bvm' && request.bitcoinPublicKey !== undefined;
325
+ return {
326
+ user: request.fromAddress,
327
+ originChainId: request.fromChainId,
328
+ originCurrency: request.fromTokenAddress,
329
+ destinationChainId,
330
+ destinationCurrency: request.toTokenAddress,
331
+ amount: toAmount.toString(),
332
+ tradeType: 'EXACT_OUTPUT',
333
+ // origin-chain refund target — Relay's only failure remedy for this route
334
+ refundTo,
335
+ ...(0, exports.relayReferrerField)(request),
336
+ txs,
337
+ txsGasLimit: Number(txsGasLimit),
338
+ ...(request.slippage === undefined
339
+ ? {}
340
+ : { slippageTolerance: (0, exports.slippageToBasisPoints)(request.slippage) }),
341
+ ...(includeDepositFeePayer ? { depositFeePayer: request.solanaFeePayer } : {}),
342
+ ...(includeBitcoinPublicKey
343
+ ? { additionalData: { userPublicKey: request.bitcoinPublicKey } }
344
+ : {}),
345
+ ...(request.relayAppFee && request.relayAppFee.basisPoints > 0n && request.relayAppFee.recipient
346
+ ? { appFees: [{ recipient: request.relayAppFee.recipient, fee: request.relayAppFee.basisPoints.toString() }] }
347
+ : {}),
348
+ };
349
+ };
350
+ exports.buildRelayQuoteRequest = buildRelayQuoteRequest;
351
+ const isHexString = (value) => typeof value === 'string' && value.startsWith('0x');
352
+ /**
353
+ * Parses a quantity Relay may report as a hex string, a decimal string, or a
354
+ * number into a bigint.
355
+ *
356
+ * @returns the bigint value, or null when the input is not a parseable quantity
357
+ */
358
+ const parseQuantity = (value) => {
359
+ if (typeof value === 'number' && Number.isInteger(value)) {
360
+ return BigInt(value);
361
+ }
362
+ if (typeof value !== 'string' || value === '') {
363
+ return null;
364
+ }
365
+ try {
366
+ return BigInt(value);
367
+ }
368
+ catch {
369
+ return null;
370
+ }
371
+ };
372
+ const asRecord = (value) => {
373
+ if (typeof value !== 'object' || value === null) {
374
+ return null;
375
+ }
376
+ return value;
377
+ };
378
+ /**
379
+ * Pulls the signable transaction out of a Relay step item.
380
+ *
381
+ * @returns the transaction data, or null when the item has no usable transaction
382
+ */
383
+ const stepItemTransaction = (item) => {
384
+ const record = asRecord(item);
385
+ const data = asRecord(record?.data);
386
+ if (!data) {
387
+ return null;
388
+ }
389
+ if (!isHexString(data.to) || !isHexString(data.data)) {
390
+ return null;
391
+ }
392
+ return data;
393
+ };
394
+ /**
395
+ * Pulls a Solana instruction set out of a Relay deposit step item. A Solana
396
+ * deposit carries `data.instructions[]` plus the address-lookup-table addresses
397
+ * to compile a versioned transaction, and no `to`/`data` hex fields.
398
+ *
399
+ * @returns the instruction set, or null when the item is not a Solana deposit
400
+ */
401
+ const stepItemSolanaInstructions = (item) => {
402
+ const data = asRecord(asRecord(item)?.data);
403
+ if (!data || !Array.isArray(data.instructions)) {
404
+ return null;
405
+ }
406
+ const instructions = data.instructions.filter((instruction) => {
407
+ const value = asRecord(instruction);
408
+ return (Array.isArray(value?.keys) &&
409
+ typeof value?.programId === 'string' &&
410
+ typeof value?.data === 'string');
411
+ });
412
+ if (instructions.length === 0) {
413
+ return null;
414
+ }
415
+ const lookupTables = Array.isArray(data.addressLookupTableAddresses)
416
+ ? data.addressLookupTableAddresses.filter((address) => typeof address === 'string')
417
+ : [];
418
+ return { instructions, addressLookupTableAddresses: lookupTables };
419
+ };
420
+ /**
421
+ * Pulls a Bitcoin partially-signed transaction out of a Relay deposit step
422
+ * item. Relay hex-encodes it (the "psbt\xff" magic, `70736274ff…`) and it is not
423
+ * `0x`-prefixed, so the Ethereum hex gate does not match it.
424
+ *
425
+ * @returns the partially-signed transaction, or null when the item is not a Bitcoin deposit
426
+ */
427
+ const stepItemBitcoinPsbt = (item) => {
428
+ const data = asRecord(asRecord(item)?.data);
429
+ if (!data || typeof data.psbt !== 'string' || data.psbt === '') {
430
+ return null;
431
+ }
432
+ return { psbt: data.psbt };
433
+ };
434
+ /**
435
+ * Normalizes a typed-data type table, keeping only well-formed `{name, type}`
436
+ * fields. Shared by the Hyperliquid action and its authorization, which carry
437
+ * the same table shape under different keys.
438
+ *
439
+ * @returns the type table; empty when the payload carries none
440
+ */
441
+ const typedDataTypes = (value) => {
442
+ const record = asRecord(value);
443
+ if (!record) {
444
+ return {};
445
+ }
446
+ const entries = Object.entries(record).flatMap(([name, fields]) => {
447
+ if (!Array.isArray(fields)) {
448
+ return [];
449
+ }
450
+ const parsed = fields.flatMap((field) => {
451
+ const candidate = asRecord(field);
452
+ return typeof candidate?.name === 'string' && typeof candidate?.type === 'string'
453
+ ? [{ name: candidate.name, type: candidate.type }]
454
+ : [];
455
+ });
456
+ return [[name, parsed]];
457
+ });
458
+ return Object.fromEntries(entries);
459
+ };
460
+ /**
461
+ * Pulls a Tron contract call out of a Relay deposit step item. Tron's wire shape
462
+ * nests snake_case fields under `parameter` and names the contract kind in
463
+ * `type`; its `data` is bare hex with no `0x` prefix, so the Ethereum hex gate
464
+ * never claims it.
465
+ *
466
+ * @returns the contract call, or null when the item is not a Tron deposit
467
+ */
468
+ const stepItemTronContract = (item) => {
469
+ const data = asRecord(asRecord(item)?.data);
470
+ if (!data || typeof data.type !== 'string') {
471
+ return null;
472
+ }
473
+ const parameter = asRecord(data.parameter);
474
+ if (!parameter) {
475
+ return null;
476
+ }
477
+ const ownerAddress = parameter.owner_address;
478
+ const contractAddress = parameter.contract_address;
479
+ const callData = parameter.data;
480
+ // require every field we map, so a wire-shape change fails closed rather than
481
+ // producing a deposit with silently empty addresses
482
+ if (typeof ownerAddress !== 'string' ||
483
+ typeof contractAddress !== 'string' ||
484
+ typeof callData !== 'string') {
485
+ return null;
486
+ }
487
+ return {
488
+ contractType: data.type,
489
+ ownerAddress,
490
+ contractAddress,
491
+ // a call that sends no TRX omits the field rather than sending zero
492
+ callValue: parseQuantity(parameter.call_value) ?? 0n,
493
+ data: callData,
494
+ };
495
+ };
496
+ /**
497
+ * Pulls a TON message list out of a Relay deposit step item. TON wallets send a
498
+ * list of messages rather than one transaction, and each payload is a base64
499
+ * bag-of-cells rather than hex.
500
+ *
501
+ * @returns the message list, or null when the item is not a TON deposit
502
+ */
503
+ const stepItemTonMessages = (item) => {
504
+ const data = asRecord(asRecord(item)?.data);
505
+ if (!data || !Array.isArray(data.messages)) {
506
+ return null;
507
+ }
508
+ const messages = data.messages.flatMap((entry) => {
509
+ const record = asRecord(entry);
510
+ if (!record || typeof record.to !== 'string' || typeof record.body !== 'string') {
511
+ return [];
512
+ }
513
+ const value = parseQuantity(record.value);
514
+ if (value === null) {
515
+ return [];
516
+ }
517
+ return [
518
+ {
519
+ to: record.to,
520
+ value,
521
+ body: record.body,
522
+ // mode 0 sends with no special flags, TON's own default
523
+ mode: typeof record.mode === 'number' ? record.mode : 0,
524
+ // absent means non-bouncing; only an explicit true bounces
525
+ bounce: record.bounce === true,
526
+ from: typeof record.from === 'string' ? record.from : null,
527
+ },
528
+ ];
529
+ });
530
+ if (messages.length === 0) {
531
+ return null;
532
+ }
533
+ return { messages };
534
+ };
535
+ /**
536
+ * Pulls the typed-data action out of a Relay Hyperliquid deposit step item.
537
+ * Nothing here is broadcast: the action is signed and posted to Hyperliquid's
538
+ * API, so there is no `to`, no calldata, and no gas for the Ethereum hex gate to
539
+ * match.
540
+ *
541
+ * @returns the action, or null when the item is not a Hyperliquid deposit
542
+ */
543
+ const stepItemHyperliquidAction = (item) => {
544
+ const data = asRecord(asRecord(item)?.data);
545
+ if (!data || typeof data.eip712PrimaryType !== 'string') {
546
+ return null;
547
+ }
548
+ const action = asRecord(data.action);
549
+ if (!action || typeof action.type !== 'string') {
550
+ return null;
551
+ }
552
+ return {
553
+ action: { type: action.type, parameters: asRecord(action.parameters) ?? {} },
554
+ eip712Types: typedDataTypes(data.eip712Types),
555
+ eip712PrimaryType: data.eip712PrimaryType,
556
+ nonce: parseQuantity(data.nonce) ?? 0n,
557
+ };
558
+ };
559
+ /**
560
+ * Finds the authorization a Hyperliquid deposit must complete before its action
561
+ * can be submitted. It arrives as its own `signature` step ahead of the deposit,
562
+ * which the deposit scan skips because it carries no deposit shape — so it is
563
+ * collected separately and attached to the deposit, rather than lost.
564
+ *
565
+ * @param steps - every step on the quote
566
+ * @returns the authorization, or null when the quote carries none
567
+ */
568
+ const stepAuthorization = (steps) => {
569
+ for (const step of steps) {
570
+ if (step.kind !== 'signature' || !Array.isArray(step.items)) {
571
+ continue;
572
+ }
573
+ for (const item of step.items) {
574
+ const data = asRecord(asRecord(item)?.data);
575
+ const sign = asRecord(data?.sign);
576
+ const post = asRecord(data?.post);
577
+ if (!sign || !post || typeof sign.primaryType !== 'string') {
578
+ continue;
579
+ }
580
+ if (typeof post.endpoint !== 'string' || typeof post.method !== 'string') {
581
+ continue;
582
+ }
583
+ return {
584
+ sign: {
585
+ signatureKind: typeof sign.signatureKind === 'string' ? sign.signatureKind : '',
586
+ domain: asRecord(sign.domain) ?? {},
587
+ types: typedDataTypes(sign.types),
588
+ value: asRecord(sign.value) ?? {},
589
+ primaryType: sign.primaryType,
590
+ },
591
+ post: {
592
+ endpoint: post.endpoint,
593
+ method: post.method,
594
+ body: asRecord(post.body) ?? {},
595
+ },
596
+ };
597
+ }
598
+ }
599
+ return null;
600
+ };
601
+ /**
602
+ * Recognizes the one deposit shape a Relay step item carries, trying the
603
+ * Ethereum transaction shape first (the only one gated on hex `to`/`data`), then
604
+ * each non-Ethereum shape in turn. Every shape is keyed on a field the others do
605
+ * not carry, so the recognizers are mutually exclusive and the order is a
606
+ * cheapest-check-first convenience rather than a correctness requirement — a
607
+ * property the tests pin, because a future overlap would silently mis-route a
608
+ * deposit to the wrong ecosystem's signer.
609
+ *
610
+ * @returns the discriminated deposit, or null when the item carries none
611
+ */
612
+ const stepItemDeposit = (item) => {
613
+ const transaction = stepItemTransaction(item);
614
+ if (transaction) {
615
+ return { kind: 'evm', transaction };
616
+ }
617
+ const solana = stepItemSolanaInstructions(item);
618
+ if (solana) {
619
+ return { kind: 'svm', ...solana };
620
+ }
621
+ const bitcoin = stepItemBitcoinPsbt(item);
622
+ if (bitcoin) {
623
+ return { kind: 'bvm', psbt: bitcoin.psbt };
624
+ }
625
+ const tron = stepItemTronContract(item);
626
+ if (tron) {
627
+ return { kind: 'tvm', contract: tron };
628
+ }
629
+ const ton = stepItemTonMessages(item);
630
+ if (ton) {
631
+ return { kind: 'tonvm', messages: ton.messages };
632
+ }
633
+ const hyperliquid = stepItemHyperliquidAction(item);
634
+ if (hyperliquid) {
635
+ return { kind: 'hypevm', action: hyperliquid };
636
+ }
637
+ return null;
638
+ };
639
+ /**
640
+ * Extracts the ERC20 spender from a Relay `approve` step so our own approval
641
+ * machinery can grant it. The origin token, not Relay, decides the spender, so
642
+ * we decode it from the ready-made approval calldata rather than guessing.
643
+ *
644
+ * @returns the spender address, or null when the step is absent or undecodable
645
+ */
646
+ const approvalSpender = (steps) => {
647
+ const approveStep = steps.find((step) => step.id === 'approve');
648
+ if (!approveStep) {
649
+ return null;
650
+ }
651
+ const items = approveStep.items;
652
+ if (!Array.isArray(items)) {
653
+ return null;
654
+ }
655
+ for (const item of items) {
656
+ const transaction = stepItemTransaction(item);
657
+ if (!transaction) {
658
+ continue;
659
+ }
660
+ try {
661
+ const decoded = (0, viem_1.decodeFunctionData)({ abi: viem_1.erc20Abi, data: transaction.data });
662
+ if (decoded.functionName === 'approve') {
663
+ return decoded.args[0];
664
+ }
665
+ }
666
+ catch {
667
+ // not an approve call we recognize; keep scanning
668
+ }
669
+ }
670
+ return null;
671
+ };
672
+ /**
673
+ * Finds the deposit the user signs after any approval — the first
674
+ * deposit-bearing item on a step that is not the `approve` step — and reports
675
+ * which source ecosystem's shape it carries.
676
+ *
677
+ * @returns the step and its discriminated deposit, or null when none is present
678
+ */
679
+ const depositStep = (steps) => {
680
+ for (const step of steps) {
681
+ if (step.id === 'approve') {
682
+ continue;
683
+ }
684
+ const items = step.items;
685
+ if (!Array.isArray(items)) {
686
+ continue;
687
+ }
688
+ for (const item of items) {
689
+ const deposit = stepItemDeposit(item);
690
+ if (deposit) {
691
+ return { step, deposit };
692
+ }
693
+ }
694
+ }
695
+ return null;
696
+ };
697
+ /**
698
+ * Maps a discriminated Relay deposit onto the shared `OriginDeposit` union.
699
+ * Ethereum reads its chain id from the deposit transaction; the non-Ethereum
700
+ * variants have no chain id on the deposit payload, so they read it from the
701
+ * quote's origin currency (`details.currencyIn.currency.chainId`).
702
+ *
703
+ * The non-Ethereum variants are matched by an EXHAUSTIVE switch rather than a
704
+ * trailing fallback: an unhandled variant must be a compile error, because
705
+ * quietly treating one ecosystem's deposit as another's would hand a payload to
706
+ * the wrong signer.
707
+ *
708
+ * @param found - the deposit and the step it was found on
709
+ * @param currencyIn - the quote's `details.currencyIn`, the only source of an
710
+ * origin chain id for a non-Ethereum deposit
711
+ * @param steps - every step on the quote, needed to collect the Hyperliquid
712
+ * authorization that arrives as its own step
713
+ * @returns the origin deposit, or null when a required field is unparseable
714
+ */
715
+ const relayOriginDeposit = (found, currencyIn, steps) => {
716
+ const { step, deposit } = found;
717
+ if (deposit.kind === 'evm') {
718
+ const chainId = parseQuantity(deposit.transaction.chainId);
719
+ if (chainId === null) {
720
+ return null;
721
+ }
722
+ return {
723
+ ecosystem: 'evm',
724
+ to: deposit.transaction.to,
725
+ data: deposit.transaction.data,
726
+ value: parseQuantity(deposit.transaction.value) ?? 0n,
727
+ chainId: Number(chainId),
728
+ gasLimit: parseQuantity(deposit.transaction.gas),
729
+ };
730
+ }
731
+ const originCurrency = asRecord(currencyIn.currency);
732
+ if (typeof originCurrency?.chainId !== 'number') {
733
+ return null;
734
+ }
735
+ const chainId = originCurrency.chainId;
736
+ switch (deposit.kind) {
737
+ case 'svm':
738
+ return {
739
+ ecosystem: 'svm',
740
+ form: 'instructions',
741
+ instructions: deposit.instructions,
742
+ addressLookupTableAddresses: deposit.addressLookupTableAddresses,
743
+ chainId,
744
+ };
745
+ case 'tvm':
746
+ return { ecosystem: 'tvm', ...deposit.contract, chainId };
747
+ case 'tonvm':
748
+ return { ecosystem: 'tonvm', messages: deposit.messages, chainId };
749
+ case 'hypevm':
750
+ return {
751
+ ecosystem: 'hypevm',
752
+ ...deposit.action,
753
+ authorization: stepAuthorization(steps),
754
+ chainId,
755
+ };
756
+ case 'bvm': {
757
+ const amountSats = parseQuantity(currencyIn.amount);
758
+ if (amountSats === null) {
759
+ return null;
760
+ }
761
+ return {
762
+ ecosystem: 'bvm',
763
+ psbt: deposit.psbt,
764
+ depositAddress: typeof step.depositAddress === 'string' ? step.depositAddress : '',
765
+ amountSats,
766
+ chainId,
767
+ };
768
+ }
769
+ }
770
+ };
771
+ /**
772
+ * Normalizes a Relay `/quote/v2` response into the shared consolidated quote
773
+ * shape. The origin approval Relay returns as its own step is folded back into
774
+ * `approvalAddress` so the executor raises it through the same path as LI.FI;
775
+ * the deposit step becomes the single `originDeposit`.
776
+ *
777
+ * @returns the normalized quote, or null when the payload shape is unexpected
778
+ */
779
+ const parseRelayQuote = (payload) => {
780
+ const quote = asRecord(payload);
781
+ if (!quote) {
782
+ return null;
783
+ }
784
+ const steps = Array.isArray(quote.steps)
785
+ ? quote.steps.filter((step) => asRecord(step) !== null)
786
+ : null;
787
+ if (!steps || steps.length === 0) {
788
+ return null;
789
+ }
790
+ const details = asRecord(quote.details);
791
+ const currencyIn = asRecord(details?.currencyIn);
792
+ if (!currencyIn) {
793
+ return null;
794
+ }
795
+ const fromAmount = parseQuantity(currencyIn.amount);
796
+ if (fromAmount === null) {
797
+ return null;
798
+ }
799
+ if (typeof details?.timeEstimate !== 'number') {
800
+ return null;
801
+ }
802
+ const found = depositStep(steps);
803
+ if (!found) {
804
+ return null;
805
+ }
806
+ // the identifier lives on the steps in the verified response shape; fall back
807
+ // through a top-level field so a future nesting change does not reject quotes
808
+ const requestId = typeof quote.requestId === 'string'
809
+ ? quote.requestId
810
+ : steps.map((step) => step.requestId).find((id) => typeof id === 'string');
811
+ if (typeof requestId !== 'string') {
812
+ return null;
813
+ }
814
+ const originDeposit = relayOriginDeposit(found, currencyIn, steps);
815
+ if (originDeposit === null) {
816
+ return null;
817
+ }
818
+ const spender = approvalSpender(steps);
819
+ return {
820
+ provider: 'relay',
821
+ quoteId: requestId,
822
+ tool: 'relay',
823
+ toolName: 'Relay',
824
+ fromAmount,
825
+ // WHAT THE ROUTE DELIVERS, WHEN ONLY RELAY KNOWS. An omnibridge route names
826
+ // its own delivered amount in the request and asks for an exact output, so
827
+ // this repeats what the caller already said. A direct route asks for an
828
+ // exact input, and the delivered amount exists nowhere until this answer.
829
+ // Undefined rather than zero when the field is missing: zero is a real
830
+ // quantity and would read as "this route delivers nothing".
831
+ ...(() => {
832
+ const out = parseQuantity(asRecord(details?.currencyOut)?.amount);
833
+ return out === null ? {} : { toAmount: out };
834
+ })(),
835
+ fromAmountUsd: typeof currencyIn.amountUsd === 'string' ? currencyIn.amountUsd : null,
836
+ // The delivered side valued by the same answer that valued the paid side —
837
+ // see `ConsolidatedQuote.toAmountUsd` for why it may not come from anywhere
838
+ // else. Omitted rather than nulled when Relay leaves it out.
839
+ ...(() => {
840
+ const outUsd = asRecord(details?.currencyOut)?.amountUsd;
841
+ return typeof outUsd === 'string' ? { toAmountUsd: outUsd } : {};
842
+ })(),
843
+ // a native origin token is pulled with no allowance, so no spender applies
844
+ approvalAddress: spender !== null && spender !== viem_1.zeroAddress ? spender : null,
845
+ executionDurationSeconds: details.timeEstimate,
846
+ // Relay's `steps` are operational (approve + deposit); the per-leg route
847
+ // lives in `details.route`, so the whole quote is normalized, not `steps`.
848
+ steps: (0, route_steps_js_1.normalizeRelaySteps)(quote),
849
+ originDeposit,
850
+ fees: (0, quote_fees_js_1.relayQuoteFees)(payload),
851
+ };
852
+ };
853
+ exports.parseRelayQuote = parseRelayQuote;
854
+ /**
855
+ * Builds the requests-lookup address for a Relay route BY ITS QUOTE
856
+ * IDENTIFIER.
857
+ *
858
+ * IT USED TO ASK BY ORIGIN TRANSACTION HASH, AND THAT RETURNED OTHER PEOPLE'S
859
+ * TRANSFERS. `/requests/v3` does not accept a `hash` filter: it ignores the
860
+ * parameter entirely and answers with the twenty most recent requests ACROSS
861
+ * ALL USERS. Measured, with two different origin hashes a minute apart:
862
+ *
863
+ * ?hash=0x447149ed… -> 20 requests, first is 8453:0x7d7c3de2… -> 4663:…
864
+ * ?hash=0xa650d2d7… -> the SAME 20 requests, same first entry
865
+ *
866
+ * `parseRelayStatus` reads `requests[0]`, so both of this account's transfers
867
+ * were updated from a stranger's — they took the same entry-chain transaction
868
+ * hash, and neither was their own. A transfer was reported finished because
869
+ * somebody else's had finished.
870
+ *
871
+ * `id` is the filter v3 actually honours. The same lookup by quote identifier
872
+ * returns exactly ONE request, and its `inTxs` name the origin transaction the
873
+ * reader really signed. The caller should assert that correspondence rather
874
+ * than trust it — see `checkConsolidatedRecord`.
875
+ */
876
+ const relayStatusUrl = ({ quoteId }) => {
877
+ return (0, url_1.buildUrl)(exports.relayRequestsUrl, { id: quoteId });
878
+ };
879
+ exports.relayStatusUrl = relayStatusUrl;
880
+ /**
881
+ * Relay's request lifecycle states. Terminal states are `success` (the
882
+ * destination call filled), `failure`, and `refund` (made whole on the origin
883
+ * chain). Every other state is still in flight.
884
+ */
885
+ const relayInFlightStatuses = ['waiting', 'depositing', 'pending', 'submitted', 'delayed'];
886
+ const isEthereumTransactionHash = (value) => typeof value === 'string' && /^0x[0-9a-fA-F]{64}$/.test(value);
887
+ /**
888
+ * Finds the destination-chain transaction hash among a Relay request's output
889
+ * transactions — the hash that gates the handover to the omnibridge indexer.
890
+ * The destination chain is the omnibridge entry chain the route targeted
891
+ * (Ethereum or Binance Smart Chain), so it is supplied by the caller rather
892
+ * than assumed.
893
+ *
894
+ * @param request - a Relay request record
895
+ * @param destinationChainId - the omnibridge entry chain the route targeted
896
+ * @returns the destination-chain transaction hash, or null when none recorded
897
+ */
898
+ const outputTransactions = (request) => {
899
+ // RELAY NESTS THESE UNDER `data`. An earlier version read `request.outTxs`,
900
+ // which no response has ever carried: measured 2026-09-01 across a hundred
901
+ // live records, `request.outTxs` was present on ZERO and `request.data.outTxs`
902
+ // on every one. So this returned null for every completed route, and the
903
+ // interface reported DONE while linking nothing. The unit tests missed it
904
+ // because they were written to the same wrong shape as the parser.
905
+ const data = asRecord(request.data);
906
+ if (Array.isArray(data?.outTxs)) {
907
+ return data.outTxs;
908
+ }
909
+ // Kept as a fallback rather than deleted: it costs one array check, and a
910
+ // response that does flatten them still reads correctly.
911
+ if (Array.isArray(request.outTxs)) {
912
+ return request.outTxs;
913
+ }
914
+ return [];
915
+ };
916
+ /**
917
+ * The transaction hash on one output entry. `/requests/v2` names the field
918
+ * `hash` and `/requests/v3` names it `txHash`; both appear in the wild, so both
919
+ * are read rather than choosing by endpoint version.
920
+ */
921
+ const outputHashOf = (entry) => {
922
+ const record = asRecord(entry);
923
+ if (isEthereumTransactionHash(record?.txHash)) {
924
+ return record.txHash;
925
+ }
926
+ if (isEthereumTransactionHash(record?.hash)) {
927
+ return record.hash;
928
+ }
929
+ return null;
930
+ };
931
+ const destinationOutputHash = (request, destinationChainId) => {
932
+ for (const entry of outputTransactions(request)) {
933
+ if (Number(asRecord(entry)?.chainId) !== destinationChainId) {
934
+ continue;
935
+ }
936
+ const hash = outputHashOf(entry);
937
+ if (hash) {
938
+ return hash;
939
+ }
940
+ }
941
+ const txHashes = request.txHashes;
942
+ if (Array.isArray(txHashes)) {
943
+ const hash = txHashes.find((entry) => isEthereumTransactionHash(entry));
944
+ if (isEthereumTransactionHash(hash)) {
945
+ return hash;
946
+ }
947
+ }
948
+ return null;
949
+ };
950
+ /**
951
+ * Maps a Relay request status onto the provider-agnostic consolidated status.
952
+ * `success` reports `DONE`/`COMPLETED` because for this route the destination
953
+ * fill IS our omnibridge entry call; `refund` reports `DONE`/`REFUNDED` because
954
+ * the user was made whole on the origin chain. Relay never strands funds on
955
+ * Ethereum, so the partial/stranded status LI.FI can return has no analogue.
956
+ *
957
+ * @param payload - a `/requests/v2?hash=` response body
958
+ * @param options.destinationChainId - the omnibridge entry chain the route
959
+ * targeted (Ethereum or Binance Smart Chain); defaults to Ethereum,
960
+ * preserving the original single-entry behavior
961
+ * @returns the normalized status, or null when no matching request is present
962
+ */
963
+ const parseRelayStatus = (payload, { destinationChainId = Number(config_js_1.Chains.ETH) } = {}) => {
964
+ const data = asRecord(payload);
965
+ if (!data) {
966
+ return null;
967
+ }
968
+ const requests = data.requests;
969
+ if (!Array.isArray(requests) || requests.length === 0) {
970
+ return { status: 'NOT_FOUND', substatus: null, receivingTxHash: null };
971
+ }
972
+ const request = asRecord(requests[0]);
973
+ if (!request) {
974
+ return null;
975
+ }
976
+ const status = request.status;
977
+ if (typeof status !== 'string') {
978
+ return null;
979
+ }
980
+ const receivingTxHash = destinationOutputHash(request, destinationChainId);
981
+ if (status === 'success') {
982
+ return { status: 'DONE', substatus: 'COMPLETED', receivingTxHash };
983
+ }
984
+ if (status === 'refund') {
985
+ return { status: 'DONE', substatus: 'REFUNDED', receivingTxHash: null };
986
+ }
987
+ if (status === 'failure') {
988
+ return { status: 'FAILED', substatus: status, receivingTxHash: null };
989
+ }
990
+ if (relayInFlightStatuses.some((inFlight) => inFlight === status)) {
991
+ return { status: 'PENDING', substatus: status, receivingTxHash };
992
+ }
993
+ // an unrecognized status is treated as still indexing rather than terminal
994
+ return { status: 'NOT_FOUND', substatus: status, receivingTxHash };
995
+ };
996
+ exports.parseRelayStatus = parseRelayStatus;