@gibs/bridge-sdk 1.13.0 → 1.17.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 (217) hide show
  1. package/README.md +244 -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 +240 -0
  28. package/dist/cjs/config.js +537 -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 +346 -0
  36. package/dist/cjs/execution.js +468 -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 +23 -0
  44. package/dist/cjs/index.js +39 -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 +107 -0
  59. package/dist/cjs/prices.js +172 -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/carriers/ask-answer.d.ts +77 -0
  81. package/dist/cjs/routing/carriers/ask-answer.js +2 -0
  82. package/dist/cjs/routing/carriers/omnibridge.d.ts +137 -0
  83. package/dist/cjs/routing/carriers/omnibridge.js +459 -0
  84. package/dist/cjs/routing/carriers/pulsex-paths.d.ts +80 -0
  85. package/dist/cjs/routing/carriers/pulsex-paths.js +97 -0
  86. package/dist/cjs/routing/carriers/pulsex-split.d.ts +175 -0
  87. package/dist/cjs/routing/carriers/pulsex-split.js +193 -0
  88. package/dist/cjs/routing/carriers/pulsex.d.ts +159 -0
  89. package/dist/cjs/routing/carriers/pulsex.js +565 -0
  90. package/dist/cjs/routing/carriers/wrap.d.ts +25 -0
  91. package/dist/cjs/routing/carriers/wrap.js +119 -0
  92. package/dist/cjs/routing/composed-route-quality.d.ts +125 -0
  93. package/dist/cjs/routing/composed-route-quality.js +144 -0
  94. package/dist/cjs/routing/entry-chain-anchor.d.ts +88 -0
  95. package/dist/cjs/routing/entry-chain-anchor.js +59 -0
  96. package/dist/cjs/routing/format.d.ts +31 -0
  97. package/dist/cjs/routing/format.js +64 -0
  98. package/dist/cjs/routing/index.d.ts +38 -0
  99. package/dist/cjs/routing/index.js +134 -0
  100. package/dist/cjs/routing/producers.d.ts +770 -0
  101. package/dist/cjs/routing/producers.js +1617 -0
  102. package/dist/cjs/routing/providers.d.ts +31 -0
  103. package/dist/cjs/routing/providers.js +48 -0
  104. package/dist/cjs/routing/route-data.d.ts +355 -0
  105. package/dist/cjs/routing/route-data.js +2 -0
  106. package/dist/cjs/routing/search/compose.d.ts +168 -0
  107. package/dist/cjs/routing/search/compose.js +104 -0
  108. package/dist/cjs/routing/search/graph.d.ts +668 -0
  109. package/dist/cjs/routing/search/graph.js +461 -0
  110. package/dist/cjs/routing/search/plan-route-data.d.ts +269 -0
  111. package/dist/cjs/routing/search/plan-route-data.js +848 -0
  112. package/dist/cjs/routing/search/score.d.ts +356 -0
  113. package/dist/cjs/routing/search/score.js +445 -0
  114. package/dist/cjs/routing/swap-transactions.d.ts +91 -0
  115. package/dist/cjs/routing/swap-transactions.js +131 -0
  116. package/dist/cjs/routing/usd-value.d.ts +17 -0
  117. package/dist/cjs/routing/usd-value.js +29 -0
  118. package/dist/cjs/settings.d.ts +785 -0
  119. package/dist/cjs/settings.js +1074 -0
  120. package/dist/cjs/ton-connect.d.ts +98 -0
  121. package/dist/cjs/ton-connect.js +206 -0
  122. package/dist/cjs/ton-execution.d.ts +7 -0
  123. package/dist/cjs/ton-execution.js +23 -0
  124. package/dist/cjs/ton.d.ts +37 -0
  125. package/dist/cjs/ton.js +83 -0
  126. package/dist/cjs/tron-execution.d.ts +146 -0
  127. package/dist/cjs/tron-execution.js +248 -0
  128. package/dist/cjs/types.d.ts +51 -0
  129. package/dist/cjs/types.js +2 -0
  130. package/dist/claims.d.ts +198 -0
  131. package/dist/claims.js +140 -0
  132. package/dist/config.d.ts +24 -0
  133. package/dist/config.js +39 -5
  134. package/dist/consolidated-quote.d.ts +109 -15
  135. package/dist/consolidated-quote.js +310 -52
  136. package/dist/execution.d.ts +346 -0
  137. package/dist/execution.js +428 -0
  138. package/dist/hyperliquid-execution.js +2 -3
  139. package/dist/index.d.ts +3 -0
  140. package/dist/index.js +3 -0
  141. package/dist/lifi-execution-guard.d.ts +13 -2
  142. package/dist/lifi-execution-guard.js +4 -0
  143. package/dist/near-intents.js +2 -3
  144. package/dist/pre-quote.d.ts +6 -6
  145. package/dist/pre-quote.js +10 -14
  146. package/dist/providers.d.ts +17 -0
  147. package/dist/providers.js +6 -0
  148. package/dist/referral.d.ts +12 -4
  149. package/dist/referral.js +12 -4
  150. package/dist/relay-depository.d.ts +2 -0
  151. package/dist/relay-depository.js +82 -0
  152. package/dist/relay-quote.js +2 -3
  153. package/dist/routing/candidate.d.ts +3 -3
  154. package/dist/routing/candidate.js +3 -3
  155. package/dist/routing/carriers/ask-answer.d.ts +19 -0
  156. package/dist/routing/carriers/omnibridge.js +23 -21
  157. package/dist/routing/carriers/pulsex-paths.d.ts +80 -0
  158. package/dist/routing/carriers/pulsex-paths.js +92 -0
  159. package/dist/routing/carriers/pulsex-split.d.ts +175 -0
  160. package/dist/routing/carriers/pulsex-split.js +185 -0
  161. package/dist/routing/carriers/pulsex.d.ts +69 -21
  162. package/dist/routing/carriers/pulsex.js +184 -65
  163. package/dist/routing/composed-route-quality.d.ts +28 -6
  164. package/dist/routing/composed-route-quality.js +36 -5
  165. package/dist/routing/entry-chain-anchor.d.ts +1 -1
  166. package/dist/routing/entry-chain-anchor.js +1 -1
  167. package/dist/routing/index.d.ts +7 -3
  168. package/dist/routing/index.js +7 -3
  169. package/dist/routing/producers.js +1 -1
  170. package/dist/routing/providers.d.ts +5 -0
  171. package/dist/routing/providers.js +5 -0
  172. package/dist/routing/search/graph.d.ts +29 -0
  173. package/dist/routing/search/plan-route-data.d.ts +25 -0
  174. package/dist/routing/search/plan-route-data.js +43 -7
  175. package/dist/routing/search/score.d.ts +33 -1
  176. package/dist/routing/search/score.js +41 -6
  177. package/dist/routing/swap-transactions.d.ts +91 -0
  178. package/dist/routing/swap-transactions.js +125 -0
  179. package/dist/settings.d.ts +94 -1
  180. package/dist/settings.js +95 -3
  181. package/dist/ton-connect.d.ts +98 -0
  182. package/dist/ton-connect.js +200 -0
  183. package/dist/ton-execution.d.ts +4 -114
  184. package/dist/ton-execution.js +4 -244
  185. package/dist/ton.d.ts +37 -0
  186. package/dist/ton.js +65 -0
  187. package/docs/examples/example-a-ether-to-pulse.ts +300 -0
  188. package/docs/examples/example-b-token-pulsechain-to-ethereum.ts +270 -0
  189. package/docs/examples/shared.ts +261 -0
  190. package/docs/examples/tsconfig.json +18 -0
  191. package/docs/integration-guide.md +617 -0
  192. package/ecosystems/package.json +6 -0
  193. package/execution/package.json +6 -0
  194. package/fee-type/package.json +6 -0
  195. package/hyperliquid-execution/package.json +6 -0
  196. package/image-links/package.json +6 -0
  197. package/lifi-execution-guard/package.json +6 -0
  198. package/llms.txt +234 -0
  199. package/near-intents/package.json +6 -0
  200. package/near-intents-route/package.json +6 -0
  201. package/origin-deposit/package.json +6 -0
  202. package/package.json +818 -10
  203. package/pre-quote/package.json +6 -0
  204. package/prices/package.json +6 -0
  205. package/providers/package.json +6 -0
  206. package/quote-fees/package.json +6 -0
  207. package/referral/package.json +6 -0
  208. package/relay-currencies/package.json +6 -0
  209. package/relay-quote/package.json +6 -0
  210. package/route-steps/package.json +6 -0
  211. package/routing/package.json +6 -0
  212. package/settings/package.json +6 -0
  213. package/ton/package.json +6 -0
  214. package/ton-connect/package.json +6 -0
  215. package/ton-execution/package.json +6 -0
  216. package/tron-execution/package.json +6 -0
  217. package/types/package.json +6 -0
@@ -0,0 +1,848 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.buildRouteScoreInputsFromPlan = exports.buildRouteCandidateFromPlan = exports.buildRouteDataFromPlan = exports.deriveDeferredCrossingFromPlan = exports.deriveHeadlineProviderKeyFromPlan = exports.derivePlanKind = exports.deriveViaChainIdsFromPlan = exports.deriveEntryChainIdFromPlan = exports.deriveOmnibridgeProviderFromPlan = void 0;
37
+ const imageLinks = __importStar(require("../../image-links.js"));
38
+ const chain_names_js_1 = require("../../chain-names.js");
39
+ const providers_js_1 = require("../../providers.js");
40
+ const near_intents_route_js_1 = require("../../near-intents-route.js");
41
+ const producers_js_1 = require("../producers.js");
42
+ const graph_js_1 = require("./graph.js");
43
+ /**
44
+ * PHASE 1 — turns a priced {@link RoutePlan} into the SAME `RouteData` /
45
+ * `RouteCandidate` / `RouteScoreInputs` shapes today's four hand-written
46
+ * producers emit: {@link buildNearIntentsTwoStepRouteData} (`../../near-intents-route.js`),
47
+ * {@link buildConversionRouteData}, {@link buildOutboundRouteData} and
48
+ * {@link buildDirectCrossingCandidate} (paired with `buildCandidateRouteData`)
49
+ * — all in `../producers.js` and `../candidate.js`. See the route-search
50
+ * design's section 6, "what it absorbs," and this module's own tests
51
+ * (`plan-route-data.test.ts`) for the parity checks against each of the four.
52
+ *
53
+ * WHAT THIS MODULE DOES NOT DO: PRICE A PLAN. Every existing builder prices
54
+ * a section from carrier-specific knowledge this module has no access to — a
55
+ * bridge's own fee-manager rate (`crossingCost` in `../producers.js`), a
56
+ * PulseX swap's estimate (`buildPulseXSwapEstimateData`), or an aggregator's
57
+ * own paid/delivered spread (`candidatePaidUsd` / `candidateDeliveredUsd`,
58
+ * both reused here rather than restated). A `RoutePlan` (`./graph.js`) names
59
+ * the STRUCTURE of a path and a base-unit delivered amount per hop; it
60
+ * carries no United States dollar figure at all. So every dollar figure this
61
+ * module places on a `RouteData` — a section's fee, a section's landing
62
+ * value, the route's total cost — is a CALLER-SUPPLIED input
63
+ * ({@link PlanSectionPricing}), never a formula computed here. This mirrors
64
+ * `RouteScoreInputs`' own doc in `score.ts`: "the caller is responsible for
65
+ * turning a priced RoutePlan into these fields."
66
+ *
67
+ * WHAT THIS MODULE DOES DO: compose the STRUCTURE — which section a hop
68
+ * belongs to, whether that section is deferred, what it is labelled, what
69
+ * its hops are titled, and what its token flow is — directly from the
70
+ * plan's graph shape, using exactly the same conventions today's four
71
+ * builders use. Where those four builders DISAGREE with each other (and two
72
+ * of them genuinely do — see `hopIsAutomatic` below), this module picks ONE
73
+ * rule and documents which existing convention it follows and which it
74
+ * knowingly departs from, per this project's "surface conflicts, don't
75
+ * average them" rule. Every departure is named in this module's tests.
76
+ */
77
+ // ---------------------------------------------------------------------------
78
+ // Carrier classification
79
+ // ---------------------------------------------------------------------------
80
+ /**
81
+ * Whether `carrier` is an omnibridge crossing (`'pulsechain'` or
82
+ * `'tokensex'`) — a genuine type predicate, not a plain boolean, so every
83
+ * call site narrows `carrier` from the wide {@link HopCarrier} union down to
84
+ * {@link Provider}. `providerDisplayName` (`../producers.js`) is total only
85
+ * over `Provider`'s two keys and falls back to the generic string
86
+ * "Omnibridge" for anything else; a plain-boolean guard left the call sites
87
+ * below typed as `HopCarrier` and accepting a bare `string`, which is the
88
+ * SAME shape of fault that let a NEAR Intents leg display as "Omnibridge"
89
+ * (see `plan-route-data.test.ts`'s now-fixed "documented divergence" case).
90
+ * Narrowing here makes that class of mistake fail to compile instead of
91
+ * silently mis-naming a hop.
92
+ */
93
+ const isBridgeCarrier = (carrier) => carrier === 'pulsechain' || carrier === 'tokensex';
94
+ /** Whether `carrier` is a consolidated-route aggregator (LI.FI, Relay, NEAR Intents). */
95
+ const isAggregatorCarrier = (carrier) => carrier === 'lifi' || carrier === 'relay' || carrier === 'near-intents';
96
+ /** Whether a hop lands on PulseChain — the signal every label/title rule below keys on. */
97
+ const hopLandsOnPulsechain = (hop) => hop.edge.to.chainId === producers_js_1.pulsechainChainId;
98
+ /** Whether `hopIndex` is the plan's LAST hop overall — a completing leg, not a starting one. */
99
+ const isFinalHopOfPlan = (hopIndex, plan) => hopIndex === plan.hops.length - 1;
100
+ /**
101
+ * Resolves a node's display token and asserts its `decimals` agree with the
102
+ * NODE's own `decimals` — the field `graph.ts` added specifically so a hop
103
+ * touching two independently-resolved mentions of the same token can be
104
+ * checked against each other without a second lookup (see `AssetNode`'s own
105
+ * doc). A name is a hypothesis, not evidence: `resolveToken` is a caller
106
+ * hook this module does not control, and trusting its `decimals` blind would
107
+ * silently misplace a decimal point in a real amount exactly the way
108
+ * `compose.ts`'s `decimals-mismatch` refusal exists to prevent one hop
109
+ * downstream. The NODE's decimals wins as the returned, asserted value.
110
+ *
111
+ * @param node - the graph node to resolve
112
+ * @param resolveToken - resolves the node to its full display token
113
+ * @returns the resolved token and the node's own, asserted decimals
114
+ */
115
+ const resolveNodeWithAssertedDecimals = (node, resolveToken) => {
116
+ const token = resolveToken(node);
117
+ if (token.decimals !== node.decimals) {
118
+ throw new Error(`resolveToken disagrees with the graph node about ${(0, graph_js_1.assetNodeKey)(node)}'s decimals: ` +
119
+ `node says ${node.decimals}, the resolved token says ${token.decimals}`);
120
+ }
121
+ return { token, decimals: node.decimals };
122
+ };
123
+ /**
124
+ * Builds the raw `RouteTokenRef` for one graph node, resolving its logo the
125
+ * same way every existing builder's own token-node helper does
126
+ * (`tokenNode` in `../../near-intents-route.js`, the inline node literals in
127
+ * `buildCandidateRouteData`): the token's own image first, the chain badge
128
+ * from `imageLinks.networkOrPseudo` second — which is what makes a
129
+ * pay-by-hand origin's invented chain id resolve to a real badge instead of
130
+ * a 404ing numeric lookup.
131
+ *
132
+ * @param node - the graph node to render
133
+ * @param resolveToken - resolves the node to its full display token
134
+ * @returns the raw token reference
135
+ */
136
+ const toRouteTokenRef = (node, resolveToken) => {
137
+ const { token, decimals } = resolveNodeWithAssertedDecimals(node, resolveToken);
138
+ return {
139
+ symbol: token.symbol,
140
+ address: token.address,
141
+ chainId: node.chainId,
142
+ decimals,
143
+ // NOT `image`, which checksums the address as an Ethereum one and throws
144
+ // for anything else. A plan can start on a pay-by-hand chain (Zcash's
145
+ // native sentinel is `t1Hsc…`), and that throw blanked the whole bridge
146
+ // form the moment such a route was served. A token's own logo still wins;
147
+ // an address no picture can be asked for draws its chain's mark.
148
+ logoUri: token.logoURI ? token.logoURI : imageLinks.tokenImageOrChainFallback(token),
149
+ chainLogoUri: imageLinks.networkOrPseudo(node.chainId),
150
+ };
151
+ };
152
+ /**
153
+ * The distinct stops a signature group's hops walk: the origin, then every
154
+ * node a hop lands on, collapsing a hop that lands back on the node the
155
+ * flow already holds — generalizing `deriveTokenFlow` in `../producers.js`
156
+ * from RAW ADDRESS-STRING comparison (`isSameTokenRef`) to
157
+ * {@link assetNodeKey}, which is already the collision-free, casing-normalized
158
+ * identity every other part of the graph model uses.
159
+ *
160
+ * THIS IS WHERE THE RECENTLY-FIXED BUG STAYS FIXED. `deriveTokenFlow` used to
161
+ * leave a route showing only its origin when a candidate itemized no hops at
162
+ * all — see `../producers.js`'s own note on the defect. A `RoutePlan` always
163
+ * carries at least one hop for a real crossing, and this walk always ends on
164
+ * that hop's `to` node, so the flow can never stop short of the plan's own
165
+ * declared destination for its group.
166
+ *
167
+ * @param hops - one signature group's hops, first to last
168
+ * @param resolveToken - resolves a graph node to its full display token
169
+ * @returns the group's token flow, origin first
170
+ */
171
+ const buildGroupTokenFlow = (hops, resolveToken) => {
172
+ const originNode = hops[0].edge.from;
173
+ const nodeFlow = hops.reduce((flow, hop) => {
174
+ const produced = hop.edge.to;
175
+ const held = flow[flow.length - 1];
176
+ if ((0, graph_js_1.assetNodeKey)(held) === (0, graph_js_1.assetNodeKey)(produced))
177
+ return flow;
178
+ return [...flow, produced];
179
+ }, [originNode]);
180
+ return nodeFlow.map((node) => toRouteTokenRef(node, resolveToken));
181
+ };
182
+ // ---------------------------------------------------------------------------
183
+ // Section-level labelling
184
+ // ---------------------------------------------------------------------------
185
+ /**
186
+ * A signature group's own hop-index list, resolved to its hops.
187
+ *
188
+ * @param group - one entry of `plan.signatures` — hop indices into `plan.hops`
189
+ * @param plan - the plan those indices are drawn from
190
+ * @returns the group's hops, first to last
191
+ */
192
+ const groupHops = (group, plan) => group.map((hopIndex) => plan.hops[hopIndex]);
193
+ /**
194
+ * Whether every hop of a group is carried by PulseX — the standalone-swap
195
+ * shape `buildPulseXSwapSectionData` draws, labelled "Swap on PulseX"
196
+ * regardless of the group's position in the plan.
197
+ */
198
+ const isPulseXOnlyGroup = (hops) => hops.every((hop) => hop.edge.carrier === 'PulseX');
199
+ /** Whether a group's LAST hop is the omnibridge crossing — the fact that decides "Bridge to X". */
200
+ const groupEndsWithBridgeHop = (hops) => isBridgeCarrier(hops[hops.length - 1].edge.carrier);
201
+ /**
202
+ * A signature section's label, generalizing the four distinct conventions
203
+ * found across today's producers into one rule:
204
+ *
205
+ * - **"Swap on PulseX"** — every hop in the group is carried by PulseX.
206
+ * Matches `buildPulseXSwapSectionData`'s hard-coded label.
207
+ * - **"Bridge to {X}"** — the WHOLE plan is one signature (matches
208
+ * `buildCandidateRouteData`, which always uses this label for its one
209
+ * section, omnibridge leg or not), OR the group's last hop IS the
210
+ * omnibridge crossing (matches `buildNearIntentsTwoStepRouteData`'s
211
+ * second section AND `buildOutboundRouteData`'s first section).
212
+ * - **"Complete at {X}"** — the group is the plan's LAST signature and does
213
+ * NOT end on a bridge hop. Matches `buildOutboundRouteData`'s second
214
+ * section, in BOTH its shapes (the entry-chain swap and the onward
215
+ * aggregator hop) — the section label names where the journey finishes
216
+ * regardless of which service carries the last leg.
217
+ * - **"Send to {X}"** — every other case: a non-final, non-bridge-ending
218
+ * group. Matches `buildNearIntentsTwoStepRouteData`'s first section.
219
+ *
220
+ * @param group - the group's hop indices
221
+ * @param groupIndex - the group's position in `plan.signatures`
222
+ * @param plan - the plan the group belongs to
223
+ * @returns the section's label
224
+ */
225
+ const sectionLabel = (group, groupIndex, plan) => {
226
+ const hops = groupHops(group, plan);
227
+ if (isPulseXOnlyGroup(hops))
228
+ return 'Swap on PulseX';
229
+ const destinationChainId = hops[hops.length - 1].edge.to.chainId;
230
+ const isOnlyGroup = plan.signatures.length === 1;
231
+ if (isOnlyGroup || groupEndsWithBridgeHop(hops)) {
232
+ return `Bridge to ${(0, chain_names_js_1.chainDisplayName)(destinationChainId)}`;
233
+ }
234
+ const isFinalGroup = groupIndex === plan.signatures.length - 1;
235
+ if (isFinalGroup) {
236
+ return `Complete at ${(0, chain_names_js_1.chainDisplayName)(destinationChainId)}`;
237
+ }
238
+ return `Send to ${(0, chain_names_js_1.chainDisplayName)(destinationChainId)}`;
239
+ };
240
+ // ---------------------------------------------------------------------------
241
+ // Hop-level rendering
242
+ // ---------------------------------------------------------------------------
243
+ /**
244
+ * A hop's display provider name.
245
+ *
246
+ * A bridge carrier resolves through {@link providerDisplayName} (the same
247
+ * "PulseChain Bridge" / "Tokens Express Bridge" table every builder reads).
248
+ * PulseX is named directly. An aggregator carrier resolves through the
249
+ * PROVIDER REGISTRY's own label (`providerById(id).label`) — DELIBERATELY,
250
+ * not through `providerDisplayName`, because that function's table only
251
+ * ever held the two omnibridge providers. `buildNearIntentsTwoStepRouteData`
252
+ * calls `providerDisplayName(candidate.quote.provider)` for its aggregator
253
+ * hop today, and `'near-intents'` is not a key in that table, so it silently
254
+ * falls back to the generic string `'Omnibridge'` — naming NEAR Intents
255
+ * after the bridge it is not. That reads as an unintentional defect in the
256
+ * existing code, not a convention worth reproducing; this function returns
257
+ * `'NEAR Intents'` instead. See this module's test file and the report back
258
+ * to the owner for the specific call-out.
259
+ *
260
+ * @param carrier - the hop's carrier
261
+ * @returns the display name for that carrier
262
+ */
263
+ const hopProviderName = (carrier) => {
264
+ if (isBridgeCarrier(carrier))
265
+ return (0, producers_js_1.providerDisplayName)(carrier);
266
+ if (carrier === 'PulseX')
267
+ return 'PulseX';
268
+ // TOTAL OVER EVERY CARRIER. The engine plans hops for carriers the provider
269
+ // registry does not hold (a local wrap, a host's own plug-in). Casting such
270
+ // an id to a provider id and asking the throwing lookup crashed the whole
271
+ // bridge form the first time a plan began with a wrap. A carrier with no
272
+ // registered label is named by its own id.
273
+ return (0, providers_js_1.findProviderById)(carrier)?.label ?? carrier;
274
+ };
275
+ /**
276
+ * A hop's title, generalizing the title conventions of every existing
277
+ * builder:
278
+ *
279
+ * - a bridge hop landing on PulseChain → `"Bridge to PulseChain"` (matches
280
+ * `buildCandidateRouteData`'s omnibridge hop and
281
+ * `buildNearIntentsTwoStepRouteData`'s crossing hop);
282
+ * - a bridge hop landing elsewhere (leaving PulseChain) →
283
+ * `providerDisplayName(carrier)`, e.g. `"PulseChain Bridge"` (matches
284
+ * `buildOutboundRouteData`'s bridge hop exactly);
285
+ * - a PulseX hop → `"Swap to {toSymbol}"` (matches `buildPulseXSwapSectionData`);
286
+ * - an aggregator hop that is the plan's FINAL hop (nothing follows it,
287
+ * so this signature is the one that COMPLETES the journey) →
288
+ * `"Bridge to {toChainName}"` (matches `buildOutboundRouteData`'s onward
289
+ * hop, which names the chain it finishes on even though an aggregator,
290
+ * not the omnibridge, carries it);
291
+ * - any other aggregator hop (something follows it) → `"Send to {toChainName}"`
292
+ * (matches `buildNearIntentsTwoStepRouteData`'s aggregator hop).
293
+ *
294
+ * @param hop - the hop to title
295
+ * @param hopIndex - the hop's index into `plan.hops`
296
+ * @param plan - the plan the hop belongs to
297
+ * @param resolveToken - resolves a graph node to its full display token
298
+ * @returns the hop's title
299
+ */
300
+ const hopTitle = (hop, hopIndex, plan, resolveToken) => {
301
+ const carrier = hop.edge.carrier;
302
+ if (isBridgeCarrier(carrier)) {
303
+ return hopLandsOnPulsechain(hop)
304
+ ? `Bridge to ${(0, chain_names_js_1.chainDisplayName)(producers_js_1.pulsechainChainId)}`
305
+ : (0, producers_js_1.providerDisplayName)(carrier);
306
+ }
307
+ if (carrier === 'PulseX') {
308
+ return `Swap to ${resolveToken(hop.edge.to).symbol}`;
309
+ }
310
+ const destinationChainName = (0, chain_names_js_1.chainDisplayName)(hop.edge.to.chainId);
311
+ return isFinalHopOfPlan(hopIndex, plan)
312
+ ? `Bridge to ${destinationChainName}`
313
+ : `Send to ${destinationChainName}`;
314
+ };
315
+ /**
316
+ * A hop's conversion subtitle.
317
+ *
318
+ * The source data has two conventions for this string: the candidate-based
319
+ * builders (`buildCandidateRouteData`'s omnibridge hop,
320
+ * `buildNearIntentsTwoStepRouteData`'s both hops) write an ARROW-ONLY clause
321
+ * (`"→ USDC"`), leaving the origin side implicit; the settings-based
322
+ * builders (`buildOutboundRouteData`, `buildPulseXSwapSectionData`) write
323
+ * the FULL two-sided clause (`"PLS → USDC"`). Both are correct prose for
324
+ * their own hop; this function reproduces BOTH conventions rather than
325
+ * picking one, keyed on the exact same signal {@link hopTitle} already uses
326
+ * to distinguish a starting/intermediate leg from a completing one: arrow-only
327
+ * for a bridge hop landing on PulseChain or an aggregator hop that is NOT the
328
+ * plan's final hop (there is more journey to draw, so the origin side is
329
+ * already on screen from the previous hop); full two-sided otherwise.
330
+ *
331
+ * @param hop - the hop to describe
332
+ * @param hopIndex - the hop's index into `plan.hops`
333
+ * @param plan - the plan the hop belongs to
334
+ * @param resolveToken - resolves a graph node to its full display token
335
+ * @returns the hop's conversion subtitle
336
+ */
337
+ const hopConversion = (hop, hopIndex, plan, resolveToken) => {
338
+ const carrier = hop.edge.carrier;
339
+ const toSymbol = resolveToken(hop.edge.to).symbol;
340
+ const usesArrowOnly = (isBridgeCarrier(carrier) && hopLandsOnPulsechain(hop)) ||
341
+ (isAggregatorCarrier(carrier) && !isFinalHopOfPlan(hopIndex, plan));
342
+ if (usesArrowOnly)
343
+ return `→ ${toSymbol}`;
344
+ const fromSymbol = resolveToken(hop.edge.from).symbol;
345
+ return `${fromSymbol} → ${toSymbol}`;
346
+ };
347
+ /**
348
+ * Whether a hop runs AUTOMATICALLY inside a signature a PRECEDING hop
349
+ * already signed — true exactly when the hop is not the first hop of its
350
+ * own signature group, per `RouteHopData.automatic`'s own doc ("runs
351
+ * automatically inside the SECTION's single signature").
352
+ *
353
+ * THIS MATCHES THREE OF THE FOUR TARGET SHAPES EXACTLY —
354
+ * `buildCandidateRouteData` (an aggregator hop with index > 0 inside its
355
+ * section, and the omnibridge hop only when an aggregator hop preceded it),
356
+ * `buildNearIntentsTwoStepRouteData` (both of its hops are their own
357
+ * section's first and only hop, so both are `false`), and
358
+ * `buildPulseXSwapSectionData` (its one hop is always `false`, hard-coded
359
+ * for the same reason).
360
+ *
361
+ * IT DOES NOT MATCH `buildOutboundRouteData`'s BRIDGE HOP, which hard-codes
362
+ * `true` even though it is that section's own first and only hop — a SECOND,
363
+ * DIFFERENT reading of "automatic" that describes the omnibridge's own
364
+ * far-side auto-completion (no reader signature needed to FINISH the
365
+ * crossing once signed) rather than whether the hop itself needed no
366
+ * signature to START. `buildDirectRouteData` (a separate, non-plan family
367
+ * this module does not otherwise touch) hard-codes the same reading. This
368
+ * function follows the field's own documented meaning and the majority
369
+ * convention (three of four builders) rather than that reading — see this
370
+ * module's test file for the specific, deliberate divergence this produces
371
+ * against `buildOutboundRouteData`'s bridge hop.
372
+ *
373
+ * @param hopIndex - the hop's index into `plan.hops`
374
+ * @param plan - the plan the hop belongs to
375
+ * @returns whether the hop is automatic
376
+ */
377
+ const hopIsAutomatic = (hopIndex, plan) => {
378
+ const group = plan.signatures.find((candidateGroup) => candidateGroup.includes(hopIndex));
379
+ return group !== undefined && group[0] !== hopIndex;
380
+ };
381
+ /**
382
+ * Builds the raw `RouteHopData` for one planned hop.
383
+ *
384
+ * @param hop - the hop to render
385
+ * @param hopIndex - the hop's index into `plan.hops`
386
+ * @param plan - the plan the hop belongs to
387
+ * @param resolveToken - resolves a graph node to its full display token
388
+ * @param feeUsdValue - the hop's own share of its section's cost, or null
389
+ * @returns the raw hop data
390
+ */
391
+ const toRouteHopData = (hop, hopIndex, plan, resolveToken, feeUsdValue) => ({
392
+ providerName: hopProviderName(hop.edge.carrier),
393
+ providerKey: hop.edge.carrier,
394
+ title: hopTitle(hop, hopIndex, plan, resolveToken),
395
+ conversion: hopConversion(hop, hopIndex, plan, resolveToken),
396
+ fromToken: toRouteTokenRef(hop.edge.from, resolveToken),
397
+ toToken: toRouteTokenRef(hop.edge.to, resolveToken),
398
+ // The per-hop dollar figure is a caller-supplied input (see this module's
399
+ // head doc); the caller passes it in, never derived here.
400
+ feeUsdValue,
401
+ automatic: hopIsAutomatic(hopIndex, plan),
402
+ });
403
+ /**
404
+ * The per-hop shares a section's pricing names, checked against the group
405
+ * they describe.
406
+ *
407
+ * @param pricing - the section's caller-supplied pricing
408
+ * @param group - the signature group's hop indices
409
+ * @param groupIndex - the group's index, for the error message
410
+ * @returns one share per hop, null where none was given
411
+ * @throws when the caller passed a share list of the wrong length — a share
412
+ * matched to the wrong hop is a figure on the wrong leg
413
+ */
414
+ const groupHopFeeUsdValues = (pricing, group, groupIndex) => {
415
+ const shares = pricing.hopFeeUsdValues;
416
+ if (shares === undefined)
417
+ return group.map(() => null);
418
+ if (shares.length !== group.length) {
419
+ throw new Error(`buildRouteDataFromPlan: section ${groupIndex + 1} has ${group.length} hop(s) but ${shares.length} hop fee(s)`);
420
+ }
421
+ return shares;
422
+ };
423
+ // ---------------------------------------------------------------------------
424
+ // Route-level derivations — candidate.ts's promised derivation, made real
425
+ // ---------------------------------------------------------------------------
426
+ /**
427
+ * The plan's omnibridge provider, or null when the plan crosses no bridge
428
+ * hop at all — exactly the derivation `RouteCandidate.plan`'s own TSDoc
429
+ * (`../candidate.ts`) promises: "that same hop's `carrier`... the `to` node's
430
+ * `chainId` of the plan's LAST hop whose carrier is `'pulsechain'` or
431
+ * `'tokensex'`." Reading the LAST such hop, not the first, matters for a
432
+ * plan with two bridge crossings (an outbound leg out of PulseChain followed
433
+ * later by a separate inbound one) — not a shape any of today's four
434
+ * builders draws, but one the general search can.
435
+ *
436
+ * @param plan - the plan to derive from
437
+ * @returns the omnibridge provider, or null
438
+ */
439
+ const deriveOmnibridgeProviderFromPlan = (plan) => {
440
+ const bridgeHop = [...plan.hops].reverse().find((hop) => isBridgeCarrier(hop.edge.carrier));
441
+ if (bridgeHop === undefined)
442
+ return null;
443
+ // `Array.prototype.find`'s own predicate narrowing does not flow back out
444
+ // of the callback into the found element's type — only `isBridgeCarrier`
445
+ // called again, directly on the plain `carrier` binding, narrows it here.
446
+ // Re-declaring the return type as the real `Provider | null` (rather than
447
+ // the wide `string | null` this used to widen to) is what surfaces a
448
+ // mismatch at the source the moment a caller narrows further downstream,
449
+ // instead of a silent `string` riding all the way to `providerDisplayName`.
450
+ const { carrier } = bridgeHop.edge;
451
+ return isBridgeCarrier(carrier) ? carrier : null;
452
+ };
453
+ exports.deriveOmnibridgeProviderFromPlan = deriveOmnibridgeProviderFromPlan;
454
+ /**
455
+ * The plan's entry chain id — the chain the plan's FIRST hop lands on, when
456
+ * that hop is carried by an aggregator (LI.FI, Relay or NEAR Intents); null
457
+ * when the plan's first hop IS the omnibridge itself (a direct, same-chain
458
+ * crossing — `buildDirectCrossingCandidate`'s shape) or is a PulseX swap.
459
+ *
460
+ * MATCHES `RouteCandidate.entryChainId`'S EXISTING MEANING throughout the
461
+ * candidate-based builders — "the chain the omnibridge leg starts on" — for
462
+ * every candidate that carries one, including a candidate whose aggregator
463
+ * reaches its OWN destination with no further bridge hop at all (today's
464
+ * `makeCandidate` test fixtures set `entryChainId` to the destination chain
465
+ * in exactly that case, because it is still where the aggregator's own leg
466
+ * lands).
467
+ *
468
+ * @param plan - the plan to derive from
469
+ * @returns the entry chain id, or null for a direct crossing or a swap-only plan
470
+ */
471
+ const deriveEntryChainIdFromPlan = (plan) => {
472
+ const firstHop = plan.hops[0];
473
+ if (!firstHop)
474
+ return null;
475
+ return isAggregatorCarrier(firstHop.edge.carrier) ? firstHop.edge.to.chainId : null;
476
+ };
477
+ exports.deriveEntryChainIdFromPlan = deriveEntryChainIdFromPlan;
478
+ /**
479
+ * The decimal chain ids every INTERMEDIATE hop of the plan passes through,
480
+ * origin and destination excluded — `RouteData.viaChainIds`'s own contract.
481
+ * Undefined (never an empty array) when the plan has nothing to report, per
482
+ * that field's own "ABSENT... on any route with no intermediate chain" doc.
483
+ *
484
+ * @param plan - the plan to derive from
485
+ * @returns the via chain ids in hop order, or undefined
486
+ */
487
+ const deriveViaChainIdsFromPlan = (plan) => {
488
+ const intermediateChainIds = plan.hops.slice(0, -1).map((hop) => hop.edge.to.chainId);
489
+ return intermediateChainIds.length > 0 ? intermediateChainIds : undefined;
490
+ };
491
+ exports.deriveViaChainIdsFromPlan = deriveViaChainIdsFromPlan;
492
+ /**
493
+ * The plan's `RouteKind`, per the route-search design's section 1: `'direct'`
494
+ * when signature 1 IS the omnibridge crossing itself (no aggregator prefix —
495
+ * `buildDirectCrossingCandidate`'s shape, and `buildOutboundRouteData`'s
496
+ * shape), `'conversion'` when the LAST hop is a PulseX swap
497
+ * (`buildConversionRouteData`'s shape), `'aggregated'` otherwise (an
498
+ * aggregator carries signature 1, fused with a bridge hop or not —
499
+ * `buildNearIntentsTwoStepRouteData`'s shape, and the general
500
+ * aggregator-fused shape).
501
+ *
502
+ * DIVERGES FROM TODAY'S LITERAL OUTPUT FOR ONE CASE, DELIBERATELY: a
503
+ * same-chain candidate built by `buildDirectCrossingCandidate` and rendered
504
+ * through `buildCandidateRouteData` today always comes back `kind:
505
+ * 'aggregated'`, because that builder hard-codes `'aggregated'`
506
+ * unconditionally — an artifact of `RouteCandidate.entryChainId` being
507
+ * non-nullable, so `buildCandidateRouteData` always assumes an
508
+ * aggregator-entry shape even for a candidate with no aggregator leg at all.
509
+ * This function instead answers `'direct'` for that exact plan, matching how
510
+ * `buildDirectRouteData` (the OTHER, non-candidate 'direct' family) already
511
+ * represents the identical real-world same-chain crossing. See this
512
+ * module's test file for the specific case.
513
+ *
514
+ * @param plan - the plan to derive from
515
+ * @returns the route's kind
516
+ */
517
+ const derivePlanKind = (plan) => {
518
+ const lastHop = plan.hops[plan.hops.length - 1];
519
+ if (lastHop && lastHop.edge.carrier === 'PulseX')
520
+ return 'conversion';
521
+ const firstHop = plan.hops[0];
522
+ if (firstHop && isBridgeCarrier(firstHop.edge.carrier))
523
+ return 'direct';
524
+ return 'aggregated';
525
+ };
526
+ exports.derivePlanKind = derivePlanKind;
527
+ /**
528
+ * Narrows a plan's {@link HopCarrier} (a plain string, since `HopEdge.carrier`
529
+ * moved off the closed `ProviderKey` union) down to `RouteData.headlineProviderKey`'s
530
+ * own closed {@link ProviderKey} type, for the display/logo lookup tables that
531
+ * type exists to protect (`resolveProviderLogoUri` / `resolveProviderDisplayName`
532
+ * — see `ProviderKey`'s own doc in `../../providers.js`).
533
+ *
534
+ * A GIBS PLAN NEVER CARRIES ANYTHING ELSE. Every carrier a `RoutePlan` this
535
+ * module renders can name is one gibs itself registered — the three built-in
536
+ * aggregators, the omnibridge, PulseX, or a wrap step, which
537
+ * {@link deriveHeadlineProviderKeyFromPlan} skips (`routing/carriers/`,
538
+ * `packages/ui/src/lib/state/useRouteSearch.ts`) — so this throws rather than
539
+ * guessing when it sees anything else: a plan naming an unrecognized carrier
540
+ * is a bug in whatever built it, not a display gap to paper over silently.
541
+ *
542
+ * @param carrier - the plan's headline carrier
543
+ * @returns the same value, typed as `ProviderKey`
544
+ */
545
+ /** The carrier id of the native-coin wrap step (`routing/carriers/wrap.ts`). */
546
+ const WRAP_CARRIER = 'wrap';
547
+ const toHeadlineProviderKey = (carrier) => {
548
+ if (isBridgeCarrier(carrier))
549
+ return carrier;
550
+ if (isAggregatorCarrier(carrier))
551
+ return carrier;
552
+ if (carrier === 'PulseX')
553
+ return carrier;
554
+ throw new Error(`toHeadlineProviderKey: unrecognized carrier "${carrier}"`);
555
+ };
556
+ /**
557
+ * The plan's headline provider — the omnibridge crossing it out when it
558
+ * crosses one, or whichever carrier performs signature 1 when it does not.
559
+ * Matches every existing builder's own headline choice: the omnibridge when
560
+ * present (`buildCandidateRouteData`, `buildNearIntentsTwoStepRouteData`,
561
+ * `buildOutboundRouteData`), the aggregator's own key as the fallback
562
+ * (`buildCandidateRouteData`'s no-omnibridge branch).
563
+ *
564
+ * @param plan - the plan to derive from
565
+ * @returns the headline provider key
566
+ */
567
+ const deriveHeadlineProviderKeyFromPlan = (plan) => toHeadlineProviderKey((0, exports.deriveOmnibridgeProviderFromPlan)(plan) ?? firstHeadlineCarrier(plan));
568
+ exports.deriveHeadlineProviderKeyFromPlan = deriveHeadlineProviderKeyFromPlan;
569
+ /**
570
+ * The carrier of the first hop that can headline a route. A `wrap` hop
571
+ * (native coin to its wrapped token, or back) is a step inside a route, never
572
+ * the route itself, so it is skipped. A plan made only of wraps headlines as
573
+ * PulseX, the same key the same-chain swap builder gives that route
574
+ * (`buildSameChainSwapRouteData`).
575
+ *
576
+ * @param plan - the plan to read
577
+ * @returns the carrier to headline
578
+ */
579
+ const firstHeadlineCarrier = (plan) => plan.hops.find((hop) => hop.edge.carrier !== WRAP_CARRIER)?.edge.carrier ?? 'PulseX';
580
+ /**
581
+ * The anchor a two-signature plan leaves the reader holding between its
582
+ * first and second groups — `RouteCandidate.plan`'s own TSDoc: "the anchor
583
+ * the reader is left holding between signatures... taken from the first hop
584
+ * of the second group." Reuses `describeDeferredCrossing`
585
+ * (`../../near-intents-route.js`) rather than re-validating the same
586
+ * "positive amount, resolved token" rule a second time.
587
+ *
588
+ * Null when the plan has only one signature group (there is no deferred
589
+ * crossing to describe) or the plan is malformed (a signature group naming
590
+ * hop indices the plan does not have).
591
+ *
592
+ * @param plan - the plan to derive from
593
+ * @param resolveToken - resolves a graph node to its full display token
594
+ * @param anchorUsdValue - the anchor's own carrier's valuation of the
595
+ * landing, exactly as `DeferredCrossing.anchorUsdValue` expects — supplied
596
+ * by the caller, since a plan carries no United States dollar figures.
597
+ * @returns the deferred crossing, or null
598
+ */
599
+ const deriveDeferredCrossingFromPlan = (plan, resolveToken, anchorUsdValue) => {
600
+ const secondGroup = plan.signatures[1];
601
+ const firstGroup = plan.signatures[0];
602
+ if (!secondGroup || !firstGroup)
603
+ return null;
604
+ const anchorHopIndex = secondGroup[0];
605
+ const landingHopIndex = firstGroup[firstGroup.length - 1];
606
+ if (anchorHopIndex === undefined || landingHopIndex === undefined)
607
+ return null;
608
+ const anchorHop = plan.hops[anchorHopIndex];
609
+ const landingHop = plan.hops[landingHopIndex];
610
+ if (!anchorHop || !landingHop)
611
+ return null;
612
+ return (0, near_intents_route_js_1.describeDeferredCrossing)({
613
+ anchorToken: resolveToken(anchorHop.edge.from),
614
+ anchorAmount: landingHop.outcome.deliveredAmount,
615
+ anchorUsdValue,
616
+ });
617
+ };
618
+ exports.deriveDeferredCrossingFromPlan = deriveDeferredCrossingFromPlan;
619
+ /**
620
+ * Whether `hop`'s own figure carries no value at all — an `EstimateBasis`
621
+ * (`graph.ts`) of `'unpriced'`: a bare decimal rescale with nothing behind
622
+ * it (see that type's own doc). {@link sectionLandingAmount} is what a
623
+ * `true` result means for the section's (and the route's) headline figure:
624
+ * it is left OUT of `amount` entirely, never shown at all.
625
+ */
626
+ const hopOutcomeIsUnpriced = (hop) => hop.outcome.kind === 'estimate' && hop.outcome.basis === 'unpriced';
627
+ /**
628
+ * What `hop` reports for `RouteLandingData.estimateBasis` /
629
+ * `RouteOutputData.estimateBasis` (`../route-data.ts`): the hop's own
630
+ * `EstimateBasis` string when it is a composed/probed figure, `null` for a
631
+ * bound quote — and `null` for `'unpriced'` too, per that field's own doc
632
+ * ("'unpriced' never reaches here"), since {@link sectionLandingAmount}
633
+ * already leaves an unpriced hop's `amount` out entirely rather than
634
+ * labelling it.
635
+ *
636
+ * @param hop - the hop to read
637
+ * @returns the estimate basis to report, or null
638
+ */
639
+ const hopEstimateBasis = (hop) => {
640
+ if (hop.outcome.kind !== 'estimate')
641
+ return null;
642
+ if (hop.outcome.basis === 'unpriced')
643
+ return null;
644
+ return hop.outcome.basis;
645
+ };
646
+ /**
647
+ * A section's landing amount: the caller's explicit override when given
648
+ * ({@link PlanSectionPricing.landingAmountOverride}'s own doc), else `null`
649
+ * when the section's last hop is `'unpriced'` (see {@link hopOutcomeIsUnpriced}
650
+ * — a figure with no value behind it is never shown, marked or not), else
651
+ * the hop's own composed delivered amount.
652
+ *
653
+ * @param pricing - the section's caller-supplied pricing
654
+ * @param lastHop - the section's last hop
655
+ * @returns the amount to land the section on, or null
656
+ */
657
+ const sectionLandingAmount = (pricing, lastHop) => {
658
+ if ('landingAmountOverride' in pricing)
659
+ return pricing.landingAmountOverride ?? null;
660
+ if (hopOutcomeIsUnpriced(lastHop))
661
+ return null;
662
+ return lastHop.outcome.deliveredAmount;
663
+ };
664
+ /**
665
+ * Turns a priced {@link RoutePlan} into a raw {@link RouteData} — one section
666
+ * per signature group, `deferred` on every group after the first, each
667
+ * section's hops and token flow drawn structurally from the plan, and the
668
+ * dollar figures overlaid from `inputs.sections`. See this module's head doc
669
+ * for why the dollar figures are caller-supplied rather than derived here.
670
+ *
671
+ * NEVER SHOWS AN UNPRICED HEADLINE FIGURE, AND MARKS EVERY OTHER ESTIMATE AS
672
+ * ONE — PHASE 3. A section (and the route's own `output`) whose last hop is
673
+ * grounded on `EstimateBasis` `'unpriced'` lands on `amount: null`, whatever
674
+ * the caller's own pricing says, per {@link sectionLandingAmount}'s own doc.
675
+ * Every OTHER estimate (`'probe-rate'`, `'priced-conversion'`) still shows
676
+ * its figure, with `estimateBasis` set to that basis so a reader is never
677
+ * shown a composed/probed number as if it were a confirmed quote — see
678
+ * `RouteOutputData.estimateBasis`'s own doc (`../route-data.ts`) for the
679
+ * full rule this reads off {@link hopEstimateBasis}.
680
+ *
681
+ * @param inputs - the plan, a token resolver, an id, and per-section pricing
682
+ * @returns the raw route data
683
+ */
684
+ const buildRouteDataFromPlan = (inputs) => {
685
+ const { plan, resolveToken, routeId, sections, totalCostUsdValue, netValueUsd, etaMinutes } = inputs;
686
+ if (plan.hops.length === 0) {
687
+ throw new Error('buildRouteDataFromPlan: a plan needs at least one hop');
688
+ }
689
+ if (sections.length !== plan.signatures.length) {
690
+ throw new Error(`buildRouteDataFromPlan: expected ${plan.signatures.length} section(s) of pricing, got ${sections.length}`);
691
+ }
692
+ const routeSections = plan.signatures.map((group, groupIndex) => {
693
+ const hops = groupHops(group, plan);
694
+ const pricing = sections[groupIndex];
695
+ const lastHop = hops[hops.length - 1];
696
+ const landing = resolveNodeWithAssertedDecimals(lastHop.edge.to, resolveToken);
697
+ const landingIsUnpriced = hopOutcomeIsUnpriced(lastHop);
698
+ const hopFeeUsdValues = groupHopFeeUsdValues(pricing, group, groupIndex);
699
+ return {
700
+ id: `${routeId}-signature-${groupIndex + 1}`,
701
+ label: sectionLabel(group, groupIndex, plan),
702
+ providerKey: hops[0].edge.carrier,
703
+ tokenFlow: buildGroupTokenFlow(hops, resolveToken),
704
+ landing: {
705
+ amount: sectionLandingAmount(pricing, lastHop),
706
+ decimals: landing.decimals,
707
+ symbol: landing.token.symbol,
708
+ usdValue: landingIsUnpriced ? null : pricing.landingUsdValue,
709
+ estimateBasis: hopEstimateBasis(lastHop),
710
+ },
711
+ feeUsdValue: pricing.feeUsdValue,
712
+ fees: pricing.fees ? [...pricing.fees] : undefined,
713
+ etaMinutes: pricing.etaMinutes,
714
+ etaSeconds: pricing.etaSeconds,
715
+ hops: group.map((hopIndex, positionInGroup) => toRouteHopData(plan.hops[hopIndex], hopIndex, plan, resolveToken, hopFeeUsdValues[positionInGroup] ?? null)),
716
+ deferred: groupIndex > 0 ? true : undefined,
717
+ deferredNote: pricing.deferredNote,
718
+ };
719
+ });
720
+ const lastSection = routeSections[routeSections.length - 1];
721
+ return {
722
+ kind: (0, exports.derivePlanKind)(plan),
723
+ entryChainId: (0, exports.deriveEntryChainIdFromPlan)(plan),
724
+ headlineProviderKey: (0, exports.deriveHeadlineProviderKeyFromPlan)(plan),
725
+ sections: routeSections,
726
+ output: {
727
+ amount: lastSection.landing?.amount ?? null,
728
+ decimals: lastSection.landing?.decimals ?? 0,
729
+ symbol: lastSection.landing?.symbol ?? '',
730
+ usdValue: lastSection.landing?.usdValue ?? null,
731
+ estimateBasis: lastSection.landing?.estimateBasis ?? null,
732
+ },
733
+ totalCostUsdValue,
734
+ netValueUsd,
735
+ etaMinutes,
736
+ // The single legacy `viaChainId` a not-yet-migrated consumer may still
737
+ // read (`RouteOption`, `journeyPlan.ts`'s current `pathKeyFor` — see the
738
+ // route-search design's section 1) — the first intermediate chain, when
739
+ // there is one. `buildOutboundRouteData` sets this to the chain its one
740
+ // bridge hop lands on, which is exactly this plan's first via chain.
741
+ viaChainId: (0, exports.deriveViaChainIdsFromPlan)(plan)?.[0],
742
+ pathKey: plan.pathKey,
743
+ viaChainIds: (0, exports.deriveViaChainIdsFromPlan)(plan),
744
+ };
745
+ };
746
+ exports.buildRouteDataFromPlan = buildRouteDataFromPlan;
747
+ /**
748
+ * Turns a priced {@link RoutePlan} into a {@link RouteCandidate}, filling
749
+ * `plan` and deriving `deferredCrossing`, `entryChainId` and
750
+ * `omnibridgeProvider` from it exactly as `RouteCandidate.plan`'s own TSDoc
751
+ * (`../candidate.ts`) promises.
752
+ *
753
+ * @param inputs - the plan, a token resolver, an id, and the caller's pricing
754
+ * @returns the route candidate
755
+ */
756
+ const buildRouteCandidateFromPlan = (inputs) => {
757
+ const { plan, resolveToken, id, inputAmount, paidUsdValue, lastHopDeliveredUsdValue, destinationUsdPrice, omnibridgeFeeAmount = 0n, anchorUsdValue = null, requestedAmount, fees = [], executionDurationSeconds = 0, } = inputs;
758
+ const firstHop = plan.hops[0];
759
+ const lastHop = plan.hops[plan.hops.length - 1];
760
+ if (!firstHop || !lastHop) {
761
+ throw new Error('buildRouteCandidateFromPlan: a plan needs at least one hop');
762
+ }
763
+ const omnibridgeProvider = (0, exports.deriveOmnibridgeProviderFromPlan)(plan);
764
+ const entryChainId = (0, exports.deriveEntryChainIdFromPlan)(plan) ?? lastHop.edge.to.chainId;
765
+ const originToken = resolveNodeWithAssertedDecimals(firstHop.edge.from, resolveToken).token;
766
+ const destinationToken = resolveNodeWithAssertedDecimals(lastHop.edge.to, resolveToken).token;
767
+ const deferredCrossing = (0, exports.deriveDeferredCrossingFromPlan)(plan, resolveToken, anchorUsdValue);
768
+ const carrier = firstHop.edge.carrier;
769
+ const quote = {
770
+ provider: carrier,
771
+ quoteId: id,
772
+ tool: carrier,
773
+ toolName: hopProviderName(carrier),
774
+ fromAmount: inputAmount,
775
+ fromAmountUsd: paidUsdValue,
776
+ ...(omnibridgeProvider === null && lastHopDeliveredUsdValue !== null
777
+ ? { toAmount: lastHop.outcome.deliveredAmount, toAmountUsd: lastHopDeliveredUsdValue }
778
+ : {}),
779
+ approvalAddress: null,
780
+ executionDurationSeconds,
781
+ steps: [],
782
+ fees: [...fees],
783
+ // A PRICED-BUT-NOT-RESERVED deposit (`UnreservedDeposit`,
784
+ // `../../origin-deposit.js`) — the variant that EXISTS for exactly this
785
+ // case: "a route on display... priced with a dry quote, which carries
786
+ // figures and no address" (that type's own doc). This candidate exists
787
+ // for scoring and for `RouteData`/`RouteCandidate` shape assembly, never
788
+ // for a real signature, so it has nothing to reserve.
789
+ //
790
+ // THIS IS NOT A STAND-IN FOR THE ORIGIN'S REAL ECOSYSTEM. An earlier
791
+ // version of this line hard-coded `{ ecosystem: 'evm', ... }`
792
+ // unconditionally, which is wrong for any non-Ethereum-Virtual-Machine
793
+ // origin a general-search plan can now represent (a Zcash or Solana
794
+ // first hop, for example) — a deposit's ecosystem must come from the
795
+ // chain, never asserted past it. `UnreservedDeposit` sidesteps the
796
+ // question honestly instead of answering it wrongly: it is
797
+ // discriminated by `kind`, not by `ecosystem`, and carries no
798
+ // ecosystem-specific fields at all, so there is no wrong shape to pick
799
+ // regardless of which ecosystem `firstHop.edge.from` names.
800
+ originDeposit: { kind: 'unreserved', chainId: firstHop.edge.from.chainId },
801
+ };
802
+ return {
803
+ id,
804
+ quote,
805
+ omnibridgeProvider,
806
+ entryChainId,
807
+ originToken,
808
+ destinationToken,
809
+ deliveredAmount: lastHop.outcome.deliveredAmount,
810
+ omnibridgeFeeAmount,
811
+ destinationUsdPrice,
812
+ requestedAmount,
813
+ deferredCrossing,
814
+ plan,
815
+ };
816
+ };
817
+ exports.buildRouteCandidateFromPlan = buildRouteCandidateFromPlan;
818
+ /**
819
+ * Turns a priced {@link RoutePlan} into {@link RouteScoreInputs} — reusing
820
+ * `candidateDeliveredUsd`, `candidatePaidUsd` and `candidateOutsideFeesUsd`
821
+ * (`../producers.js`) against the SAME candidate
822
+ * {@link buildRouteCandidateFromPlan} builds, exactly as `RouteScoreInputs`'
823
+ * own doc in `score.ts` asks: "generalized to the plan's LAST hop and FIRST
824
+ * hop respectively... import and reuse them; do not write a second
825
+ * valuation."
826
+ *
827
+ * @param valuation - the plan, a token resolver, an id, and the caller's pricing
828
+ * @param gaslessIntermediateChainCount - intermediate chains the connected
829
+ * account holds no gas on — supplied by the caller, never computed here
830
+ * @returns the plan's score inputs
831
+ */
832
+ const buildRouteScoreInputsFromPlan = (valuation, gaslessIntermediateChainCount) => {
833
+ const candidate = (0, exports.buildRouteCandidateFromPlan)(valuation);
834
+ return {
835
+ deliveredUsd: (0, producers_js_1.candidateDeliveredUsd)(candidate) ?? 0,
836
+ paidUsd: (0, producers_js_1.candidatePaidUsd)(candidate) ?? 0,
837
+ outsideFeesUsd: (0, producers_js_1.candidateOutsideFeesUsd)(candidate),
838
+ legClaimedDurationsSeconds: valuation.legClaimedDurationsSeconds,
839
+ readerActionCount: valuation.plan.signatures.length,
840
+ gaslessIntermediateChainCount,
841
+ // PHASE 3 — read directly off the plan's own hops, never re-derived: see
842
+ // `planComposedBasis`'s own doc (`graph.ts`) for why this always agrees
843
+ // with `planIsRankable`, and `RouteScoreInputs.basis`'s own doc for what
844
+ // `scoreRoutePlan` does with it.
845
+ basis: (0, graph_js_1.planComposedBasis)(valuation.plan.hops),
846
+ };
847
+ };
848
+ exports.buildRouteScoreInputsFromPlan = buildRouteScoreInputsFromPlan;