@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,1071 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.parseNearIntentsStatus = exports.parseNearIntentsQuoteRefusal = exports.parseNearIntentsQuote = exports.parseNearIntentsPriceQuote = exports.parseNearIntentsPreQuote = exports.buildNearIntentsQuoteRequest = exports.buildNearIntentsPreQuoteRequest = exports.isBelowWorkingFloor = exports.workingFloorFor = exports.zcashWorkingFloorBaseUnits = exports.slippageToNearIntentsBasisPoints = exports.findNearIntentsAsset = exports.parseNearIntentsTokens = exports.chainIdByNearIntentsChain = exports.nearIntentsRequestHeaders = exports.nearIntentsUserAgent = exports.nearIntentsStatusUrl = exports.nearIntentsAuthenticatedStablecoinFeeBasisPoints = exports.nearIntentsAuthenticatedFeeBasisPoints = exports.nearIntentsUnauthenticatedFeeBasisPoints = exports.nearIntentsDepositSubmitUrl = exports.nearIntentsTokensUrl = exports.nearIntentsQuoteUrl = exports.nearIntentsApiBaseUrl = void 0;
4
+ const url_1 = require("@gibs/common/url");
5
+ const chains_1 = require("viem/chains");
6
+ const viem_1 = require("viem");
7
+ const chain_names_js_1 = require("./chain-names.js");
8
+ const ecosystems_js_1 = require("./ecosystems.js");
9
+ const relay_quote_js_1 = require("./relay-quote.js");
10
+ const referral_js_1 = require("./referral.js");
11
+ /**
12
+ * NEAR Intents, through its "one click" quoting service.
13
+ *
14
+ * THIS PROVIDER CANNOT EXECUTE ON THE DESTINATION CHAIN, AND IS REGISTERED
15
+ * ANYWAY. Read both halves of that before changing anything here.
16
+ *
17
+ * The service validates its request body against a closed property list and
18
+ * answers `property destinationCall should not exist` for every name a call
19
+ * could travel under — `destinationCall`, `calldata`, `msg`, `txs`, `hook`,
20
+ * `action`, `postSwapAction`. The only thing nameable on the destination side
21
+ * is an address: `recipient`, with a `recipientType` of `DESTINATION_CHAIN`,
22
+ * `INTENTS` or `CONFIDENTIAL_INTENTS`. That is measured, not inferred from
23
+ * silence. `docs/near-intents-capability-survey.md` holds the evidence.
24
+ *
25
+ * DELIVERING TO THE MEDIATOR INSTEAD IS NOT A WAY AROUND IT, and the reason is
26
+ * structural rather than a matter of configuration. The service will happily
27
+ * deliver to a contract — a quote naming a well-known router as `recipient` is
28
+ * accepted. But every omnibridge entry point learns WHO THE READER IS from a
29
+ * data field: `transferAndCall` carries the recipient in its third argument,
30
+ * `relayTokens` in its second, `wrapAndRelayTokens` in its first. A plain
31
+ * token transfer has no data field. So a bare arrival cannot name a recipient,
32
+ * which means it can only ever credit the sender — the solver — or nobody at
33
+ * all. Do not attempt it.
34
+ *
35
+ * SO THE ROUTE TAKES TWO SIGNATURES, and the interface says so on the route
36
+ * strip rather than in a tooltip. The reader signs the origin transfer; NEAR
37
+ * Intents lands the anchor token in THEIR OWN WALLET on the entry chain; then
38
+ * they sign the ordinary bridge leg themselves. `near-intents-route.ts` builds
39
+ * that shape, and `executesDestinationCalls: false` on the descriptor is what
40
+ * keeps this provider out of the single-signature machinery, including the
41
+ * entry-anchor pre-quote — that phase feeds an exact-output target to the
42
+ * providers that DO execute, and a target only a non-executing provider can
43
+ * reach is a target nobody can fill.
44
+ *
45
+ * TWO SIZE FLOORS MAKE THIS A ROUTING RULE, NOT A FOOTNOTE. Binance Smart
46
+ * Chain — one of the two omnibridge entry chains — refuses any transfer worth
47
+ * one thousand United States dollars or less, in either direction, and Polygon
48
+ * and Tron carry floors of their own. The service imposed these on 2026-09-09
49
+ * and calls them temporary. Only asking reveals them, so a route has to be
50
+ * WITHDRAWN on a refusal rather than left to fail: see
51
+ * {@link NearIntentsQuoteRefusal} and `near-intents-route.ts`.
52
+ */
53
+ /** Base address for the NEAR Intents one-click service. */
54
+ exports.nearIntentsApiBaseUrl = 'https://1click.chaindefuser.com';
55
+ /** Quote endpoint. Verified live: no key required, and a key-less request is answered in full. */
56
+ exports.nearIntentsQuoteUrl = `${exports.nearIntentsApiBaseUrl}/v0/quote`;
57
+ /** The list of assets the service can carry, keyed by its own asset identifiers. */
58
+ exports.nearIntentsTokensUrl = `${exports.nearIntentsApiBaseUrl}/v0/tokens`;
59
+ /**
60
+ * Optional notification that the reader's deposit has been sent. The service
61
+ * detects the deposit on its own; telling it the transaction hash only makes
62
+ * the detection faster. Takes `{ txHash, depositAddress }`.
63
+ */
64
+ exports.nearIntentsDepositSubmitUrl = `${exports.nearIntentsApiBaseUrl}/v0/deposit/submit`;
65
+ /**
66
+ * What a key-less request costs, in basis points of the input amount.
67
+ *
68
+ * NOT A FEE THIS CODE CHARGES OR CAN DECLINE. The service inserts it into the
69
+ * echoed request as an `appFees` entry payable to its own account whenever no
70
+ * key is presented, so a reader on a key-less route pays a quarter of a percent
71
+ * that no part of this repository asked for. It is named here so the parser can
72
+ * surface it as a charge rather than let it disappear into the delivered
73
+ * amount. A partner key reduces it; obtaining one is an owner decision.
74
+ */
75
+ exports.nearIntentsUnauthenticatedFeeBasisPoints = 25;
76
+ /**
77
+ * What a partner-key request costs instead, in basis points of the input
78
+ * amount, for an ordinary (non-stablecoin) pair.
79
+ *
80
+ * Read from the service's own current documentation on 2026-09-18:
81
+ * `docs.near-intents.org/integration/distribution-channels/1click-api/authentication`.
82
+ * See `docs/near-intents-partner-key.md` for the full process of obtaining a
83
+ * key and what else changes once one is configured.
84
+ */
85
+ exports.nearIntentsAuthenticatedFeeBasisPoints = 20;
86
+ /**
87
+ * What a partner-key request costs on a stablecoin pair or a same-asset
88
+ * multi-chain route, in basis points of the input amount.
89
+ *
90
+ * Read from the same page as {@link nearIntentsAuthenticatedFeeBasisPoints} on
91
+ * 2026-09-18. Kept as its own constant rather than a special case of the other
92
+ * one because the service documents it as a distinct figure for a distinct
93
+ * class of route, not a discount computed from the ordinary rate.
94
+ */
95
+ exports.nearIntentsAuthenticatedStablecoinFeeBasisPoints = 1;
96
+ /**
97
+ * Builds the status-poll address for one quote.
98
+ *
99
+ * The deposit address IS the lookup key here, unlike every other provider in
100
+ * this repository, which key by a request identifier. Each quote is issued its
101
+ * own deposit address, so the two are one and the same fact — see
102
+ * {@link parseNearIntentsQuote}, which puts the deposit address in `quoteId`
103
+ * for exactly this reason.
104
+ *
105
+ * @param options.quoteId - the quote's deposit address
106
+ * @returns the fully-formed status address
107
+ */
108
+ const nearIntentsStatusUrl = ({ quoteId }) => {
109
+ return (0, url_1.buildUrl)(`${exports.nearIntentsApiBaseUrl}/v0/status`, { depositAddress: quoteId });
110
+ };
111
+ exports.nearIntentsStatusUrl = nearIntentsStatusUrl;
112
+ /**
113
+ * What this repository calls itself when it asks the one-click service.
114
+ *
115
+ * SENT BECAUSE THE SERVICE REFUSES SOME CALLERS BY NAME, and until now the
116
+ * name was whatever the runtime happened to supply. The service sits behind
117
+ * Cloudflare, which answers a refused caller with HTTP 403 and a body reading
118
+ * `error code: 1010` — a page, not a quote, so a parser sees a shape it cannot
119
+ * read and the whole provider looks like an outage.
120
+ *
121
+ * MEASURED against the live quote endpoint on 2026-09-21, one identical body,
122
+ * one header changed:
123
+ *
124
+ * | user agent | answer |
125
+ * | ------------------------- | ------ |
126
+ * | none (Node 26 default) | 201 |
127
+ * | `undici` | 201 |
128
+ * | `node` | 201 |
129
+ * | `curl/8.7.1` | 201 |
130
+ * | `python-requests/2.32` | 201 |
131
+ * | `Python-urllib/3.14` | 403 |
132
+ * | this value | 201 |
133
+ *
134
+ * So nothing is blocked today. The point is that whether we are blocked was
135
+ * being decided by a list we do not control, matched against a string we never
136
+ * chose — and a runtime upgrade could change that string without anyone here
137
+ * touching a line. Naming ourselves fixes the input to that decision.
138
+ *
139
+ * A BROWSER IGNORES THIS, and that is fine. `User-Agent` is a forbidden header
140
+ * name for `fetch`, so the browser drops it silently and sends its own. The
141
+ * value therefore governs Node alone: the live test harness, the deposit
142
+ * poller, and any script written later.
143
+ */
144
+ exports.nearIntentsUserAgent = 'gibs-bridge/1.0 (+https://gibs.finance)';
145
+ /**
146
+ * Request headers for the one-click service.
147
+ *
148
+ * THE KEY IS A JSON WEB TOKEN, NOT A PLAIN IDENTIFIER LIKE RELAY'S. The
149
+ * service's own documentation accepts it as `Authorization: Bearer` as well as
150
+ * `X-API-Key`, calls it a "JWT token" throughout, and tells an integrator to
151
+ * "store your JWT token securely and never commit it to version control. Use
152
+ * environment variables or secure secret management systems." Relay's
153
+ * documentation says none of that about its key. `X-API-Key` is the form sent
154
+ * here because the service accepts it and it matches the header name Relay
155
+ * already uses, so one code path serves both — but the caller of this
156
+ * function decides where the value comes from, and that decision is where the
157
+ * secrecy question has to be answered. See `packages/ui/src/lib/config.ts`
158
+ * and `docs/near-intents-partner-key.md`.
159
+ *
160
+ * THE DEFAULT `User-Agent` NAMES GIBS FINANCE, AND THAT COSTS A CALLER
161
+ * NOTHING: it carries no key and no rate-limit budget, and a browser drops it.
162
+ * Pass `options.userAgent` to name yourself instead, or `null` to send none and
163
+ * let the runtime use its own.
164
+ *
165
+ * @param apiKey - a partner key, when one is configured
166
+ * @param options - `userAgent`: your own value, or `null` for none (defaults to {@link nearIntentsUserAgent})
167
+ * @returns the headers, carrying the key only when there is one to carry
168
+ */
169
+ const nearIntentsRequestHeaders = (apiKey, options = {}) => {
170
+ const userAgent = (0, referral_js_1.resolveAttribution)(options.userAgent, exports.nearIntentsUserAgent);
171
+ return {
172
+ 'Content-Type': 'application/json',
173
+ ...(userAgent === undefined ? {} : { 'User-Agent': userAgent }),
174
+ ...(apiKey ? { 'X-API-Key': apiKey } : {}),
175
+ };
176
+ };
177
+ exports.nearIntentsRequestHeaders = nearIntentsRequestHeaders;
178
+ /**
179
+ * This repository's chain identifiers, keyed by the service's short chain name.
180
+ *
181
+ * The Ethereum-virtual-machine entries are read from viem rather than written
182
+ * down, because a chain identifier typed from memory is a hypothesis that every
183
+ * later reader will trust — and a wrong one here does not fail loudly, it
184
+ * simply quotes a different chain's token.
185
+ *
186
+ * The non-Ethereum entries are this repository's own identifiers for those
187
+ * families, which are Relay's numbers (see {@link relayChainIds}); the service
188
+ * uses short names and has no numeric identifier of its own to reconcile with.
189
+ *
190
+ * DELIBERATELY SHORTER THAN THE SERVICE'S CHAIN LIST. The service names about
191
+ * thirty-five chains. Only the ones this bridge can actually originate from or
192
+ * enter are listed, because an unlisted chain resolves to no asset and
193
+ * therefore to no route, which is the honest outcome, whereas a guessed
194
+ * identifier resolves to a route on the wrong chain.
195
+ */
196
+ exports.chainIdByNearIntentsChain = new Map([
197
+ ['eth', chains_1.mainnet.id],
198
+ ['bsc', chains_1.bsc.id],
199
+ ['base', chains_1.base.id],
200
+ ['arb', chains_1.arbitrum.id],
201
+ ['op', chains_1.optimism.id],
202
+ ['pol', chains_1.polygon.id],
203
+ ['avax', chains_1.avalanche.id],
204
+ ['gnosis', chains_1.gnosis.id],
205
+ ['scroll', chains_1.scroll.id],
206
+ ['sol', chain_names_js_1.relayChainIds.solana],
207
+ ['btc', chain_names_js_1.relayChainIds.bitcoin],
208
+ ['tron', chain_names_js_1.relayChainIds.tron],
209
+ ['ton', chain_names_js_1.relayChainIds.ton],
210
+ ['hypercore', chain_names_js_1.relayChainIds.hyperliquid],
211
+ // THE ONE ENTRY WITH NO WALLET BEHIND IT. Zcash is not a Relay chain and not
212
+ // a LI.FI chain; this repository names it itself, in `chain-names.ts`, so
213
+ // that a route from it can be priced and drawn. The reader pays the address
214
+ // this service issues, by hand, from wherever they hold the coin.
215
+ ['zec', chain_names_js_1.depositAddressChainIds.zcash],
216
+ ]);
217
+ const asRecord = (value) => {
218
+ if (typeof value !== 'object' || value === null) {
219
+ return null;
220
+ }
221
+ return value;
222
+ };
223
+ /**
224
+ * Reads `GET /v0/tokens` into the asset records the identifier lookup needs.
225
+ *
226
+ * An entry missing any field the lookup reads is dropped rather than patched
227
+ * with a default: an asset whose decimals were invented would price every
228
+ * amount wrong by orders of magnitude, and an asset whose identifier is
229
+ * missing cannot be quoted at all.
230
+ *
231
+ * @param payload - the raw JSON body from `GET /v0/tokens`
232
+ * @returns every readable asset, in the order the service listed them
233
+ */
234
+ const parseNearIntentsTokens = (payload) => {
235
+ if (!Array.isArray(payload)) {
236
+ return [];
237
+ }
238
+ const assets = [];
239
+ for (const entry of payload) {
240
+ const record = asRecord(entry);
241
+ if (!record) {
242
+ continue;
243
+ }
244
+ const { assetId, blockchain, symbol, decimals, contractAddress, price, priceUpdatedAt } = record;
245
+ if (typeof assetId !== 'string' || typeof blockchain !== 'string') {
246
+ continue;
247
+ }
248
+ if (typeof symbol !== 'string' || typeof decimals !== 'number') {
249
+ continue;
250
+ }
251
+ assets.push({
252
+ assetId,
253
+ blockchain,
254
+ symbol,
255
+ decimals,
256
+ contractAddress: typeof contractAddress === 'string' ? contractAddress : null,
257
+ price: typeof price === 'number' && Number.isFinite(price) ? price : null,
258
+ priceUpdatedAt: typeof priceUpdatedAt === 'string' ? priceUpdatedAt : null,
259
+ });
260
+ }
261
+ return assets;
262
+ };
263
+ exports.parseNearIntentsTokens = parseNearIntentsTokens;
264
+ /**
265
+ * Finds the service's identifier for one token on one chain.
266
+ *
267
+ * THE IDENTIFIER CANNOT BE CONSTRUCTED, ONLY LOOKED UP. It reads like a
268
+ * pattern — a chain name, the token's address, a fixed suffix — and for an
269
+ * Ethereum-virtual-machine token it currently is one. It is not one for the
270
+ * other families: Solana's USD Coin carries a hexadecimal handle that is
271
+ * nothing like its base58 mint. Building the string from its parts therefore
272
+ * produces an identifier that is well-formed and refers to nothing, so the
273
+ * asset list is the only source.
274
+ *
275
+ * @param options.assets - the parsed asset list
276
+ * @param options.chainId - this repository's identifier for the chain
277
+ * @param options.tokenAddress - the token's address on that chain
278
+ * @param options.ecosystem - the chain's virtual-machine family, which decides
279
+ * whether the native-coin test and the address comparison are meaningful
280
+ * @returns the matching asset, or null when the service does not carry it
281
+ */
282
+ const findNearIntentsAsset = ({ assets, chainId, tokenAddress, ecosystem, }) => {
283
+ const onChain = assets.filter((asset) => exports.chainIdByNearIntentsChain.get(asset.blockchain) === chainId);
284
+ if (onChain.length === 0) {
285
+ return null;
286
+ }
287
+ if ((0, ecosystems_js_1.isNativeAsset)(tokenAddress, ecosystem)) {
288
+ return onChain.find((asset) => asset.contractAddress === null) ?? null;
289
+ }
290
+ // Only an Ethereum-virtual-machine chain reports a token's real address here,
291
+ // so a match on any other family would be a coincidence of hexadecimal.
292
+ if (ecosystem !== 'evm') {
293
+ return null;
294
+ }
295
+ const match = onChain.find((asset) => asset.contractAddress !== null && (0, ecosystems_js_1.sameAddress)(asset.contractAddress, tokenAddress, 'evm'));
296
+ return match ?? null;
297
+ };
298
+ exports.findNearIntentsAsset = findNearIntentsAsset;
299
+ /**
300
+ * How far ahead the requested refund deadline is set, in milliseconds.
301
+ *
302
+ * WHAT IS SENT, NOT WHAT COMES BACK. The service does not honour this value: it
303
+ * returns a `deadline` of exactly three days after the one asked for, and
304
+ * returns `timeWhenInactive` equal to that same instant rather than to the
305
+ * earlier moment the documentation describes. Both are visible in the checked-in
306
+ * capture — asked 2026-09-17T23:49:52.805Z, answered 2026-09-20T23:49:52.805Z.
307
+ *
308
+ * So anything that needs the real clock must read `quote.deadline` off the
309
+ * answer. Reading `quoteRequest.deadline` back gives this number, which is the
310
+ * request echoed, not a commitment; and treating `deadline` and
311
+ * `timeWhenInactive` as two milestones reads a distinction the service is not
312
+ * currently making.
313
+ */
314
+ const defaultDeadlineMilliseconds = 30 * 60 * 1000;
315
+ /**
316
+ * Slippage THIS MODULE sends when the caller states none, in basis points.
317
+ *
318
+ * Not a default the service holds. `slippageTolerance` is a required property —
319
+ * the service rejects a request without it — so there is no "leave it to them"
320
+ * option here as there is with the other providers, and one percent is a value
321
+ * chosen on this side.
322
+ */
323
+ const defaultSlippageBasisPoints = 100;
324
+ /**
325
+ * Converts a slippage fraction into the basis points the service expects.
326
+ *
327
+ * @param slippage - tolerance as a fraction (0.005 means half a percent)
328
+ * @returns basis points (0.005 becomes 50)
329
+ */
330
+ const slippageToNearIntentsBasisPoints = (slippage) => Math.round(slippage * 10_000);
331
+ exports.slippageToNearIntentsBasisPoints = slippageToNearIntentsBasisPoints;
332
+ /**
333
+ * Reads the build inputs out of the shared provider context.
334
+ *
335
+ * Returns null when the asset list is absent, and that is not a defensive
336
+ * check — without the list no asset identifier can be resolved, so there is no
337
+ * request to form. Answering null leaves the route to the providers that can
338
+ * express it, which is the same thing every other builder here does when it
339
+ * cannot express a request.
340
+ */
341
+ const buildOptionsFrom = (context, { dry }) => {
342
+ const assets = context?.nearIntentsAssets;
343
+ if (assets === undefined || assets.length === 0) {
344
+ return null;
345
+ }
346
+ return { assets, now: context?.now ?? new Date(), referral: context?.referral, dry };
347
+ };
348
+ /**
349
+ * Where a refund goes, and it is a different answer for a chain the reader
350
+ * cannot sign on.
351
+ *
352
+ * THE ORDINARY CASE. A refund lands back on the ORIGIN chain, at the reader's
353
+ * own origin-chain address — never the delivery address, which could not
354
+ * receive one there.
355
+ *
356
+ * THE PAY-BY-HAND CASE, WHICH IS THE WHOLE REASON THIS FLOW IS POSSIBLE. A
357
+ * reader with no Zcash wallet has no Zcash address to refund to, and
358
+ * `refundType` offers no destination-chain option: the three values are
359
+ * `ORIGIN_CHAIN`, `INTENTS` and `CONFIDENTIAL_INTENTS`. `INTENTS` credits the
360
+ * refund to a ledger row inside the settlement contract `intents.near`, and the
361
+ * row may be named for the reader's own Ethereum address, which the same
362
+ * Ethereum key controls. So the reader types nothing, and the refund fee falls
363
+ * from 32,000 base units to zero: crediting a balance inside a contract needs
364
+ * no Zcash transaction. `docs/near-implicit-account-refunds.md` checks the
365
+ * claim at the protocol level.
366
+ *
367
+ * TWO TRAPS, BOTH MEASURED, BOTH CAPABLE OF COSTING SOMEBODY THEIR MONEY.
368
+ *
369
+ * FIRST, LOWER CASE IS NOT COSMETIC. The account name must be lower case. The
370
+ * same address in its checksummed spelling is refused outright with `refundTo
371
+ * is not valid` — the capture is
372
+ * `__fixtures__/near-intents/quote-error-zcash-refund-mixed-case.json`.
373
+ *
374
+ * SECOND, ACCEPTANCE PROVES NOTHING. On the intents path the service checks
375
+ * only that the string looks like a NEAR account name — the literal
376
+ * `not-an-address-at-all` quotes happily. A wrong value therefore passes
377
+ * quoting and is discovered only when a swap is refunded to nobody. That is
378
+ * why this reads `connectedEthereumAccount`, whose contract is that it comes
379
+ * from the wallet connection, and why it builds nothing when that is absent
380
+ * or is not an Ethereum address.
381
+ *
382
+ * @param options.fromChainId - the origin chain
383
+ * @param options.fromAddress - the reader's address on the origin chain
384
+ * @param options.connectedEthereumAccount - the reader's connected Ethereum account
385
+ * @returns the two refund properties, or null when a pay-by-hand route has no
386
+ * connected Ethereum account to name
387
+ */
388
+ const refundFields = ({ fromChainId, fromAddress, connectedEthereumAccount, }) => {
389
+ if (!(0, chain_names_js_1.isDepositAddressChain)(fromChainId)) {
390
+ return { refundTo: fromAddress, refundType: 'ORIGIN_CHAIN' };
391
+ }
392
+ if (connectedEthereumAccount === undefined || !(0, viem_1.isAddress)(connectedEthereumAccount)) {
393
+ return null;
394
+ }
395
+ return { refundTo: connectedEthereumAccount.toLowerCase(), refundType: 'INTENTS' };
396
+ };
397
+ /**
398
+ * The smallest Zcash deposit that can actually be credited, in base units:
399
+ * 0.01 Zcash.
400
+ *
401
+ * THE LARGER OF TWO FIGURES THAT DISAGREE. The quoting service prices a Zcash
402
+ * input down to about two cents — the smaller floor, read live from its
403
+ * refusal by {@link parseNearIntentsQuoteRefusal}. But Zcash crosses on the
404
+ * Proof of Authority bridge, not the Omni Bridge, and that bridge publishes
405
+ * `min_deposit_amount: 1000000` for native Zcash. A quote between the two is
406
+ * priced by one surface and below the other's floor, so it takes the money and
407
+ * stalls — and the published stuck-deposit recovery flow is written for the
408
+ * Omni Bridge, so it does not cover Zcash. Measured 2026-09-21; see
409
+ * `docs/near-intents-capability-survey.md`.
410
+ */
411
+ exports.zcashWorkingFloorBaseUnits = 1000000n;
412
+ /**
413
+ * The working floor for each chain a reader pays by hand, in base units of
414
+ * that chain's native asset, one entry per member of {@link DepositAddressChain}.
415
+ * Typed on the union rather than on `number` so a pay-by-hand chain added to
416
+ * {@link depositAddressChainIds} without a floor here is a compile error.
417
+ */
418
+ const workingFloorBaseUnitsByChain = {
419
+ zcash: exports.zcashWorkingFloorBaseUnits,
420
+ };
421
+ /** {@link workingFloorBaseUnitsByChain}, keyed by chain id for lookup. */
422
+ const workingFloorByChainId = new Map(Object.keys(chain_names_js_1.depositAddressChainIds).map((chain) => [
423
+ chain_names_js_1.depositAddressChainIds[chain],
424
+ workingFloorBaseUnitsByChain[chain],
425
+ ]));
426
+ /**
427
+ * The working floor for a pay-by-hand chain, in base units, or null when the
428
+ * chain has none registered.
429
+ *
430
+ * EXPORTED SO A SCREEN NEVER KEEPS ITS OWN COPY. {@link isBelowWorkingFloor} is
431
+ * the decision this library enforces when quoting; this is the SAME table,
432
+ * exposed so a payment screen can PRINT the figure it refuses under instead of
433
+ * hand-copying the table — a copy that would silently disagree with quoting
434
+ * the moment a second pay-by-hand chain gets a floor here and not there.
435
+ *
436
+ * @param chainId - the origin chain
437
+ * @returns the floor in base units, or null when the chain has none
438
+ */
439
+ const workingFloorFor = (chainId) => workingFloorByChainId.get(chainId) ?? null;
440
+ exports.workingFloorFor = workingFloorFor;
441
+ /**
442
+ * Whether an amount is below the floor a deposit on this chain can actually
443
+ * be credited at.
444
+ *
445
+ * ASK IT BEFORE ASKING FOR A LIVE QUOTE. The quote request builder already
446
+ * declines such an amount, so no deposit address is ever issued for money that
447
+ * would stall. This predicate lets a surface say WHY there is no route, and
448
+ * what size would work.
449
+ *
450
+ * @param options.chainId - the origin chain
451
+ * @param options.amount - the input, in base units of the origin asset
452
+ * @returns whether the amount is below that chain's working floor
453
+ */
454
+ const isBelowWorkingFloor = ({ chainId, amount, }) => {
455
+ const floor = workingFloorByChainId.get(chainId);
456
+ return floor !== undefined && amount < floor;
457
+ };
458
+ exports.isBelowWorkingFloor = isBelowWorkingFloor;
459
+ /**
460
+ * Builds the request body every quote and pre-quote shares.
461
+ *
462
+ * THE ORIGIN ECOSYSTEM IS DERIVED FROM THE CHAIN ID, NOT ACCEPTED AS AN
463
+ * ARGUMENT. It used to be read off the request's own `originVmType` while the
464
+ * pay-by-hand `swapType` decision two lines below read `fromChainId` through
465
+ * {@link isDepositAddressChain} — two signals that a caller could set to
466
+ * disagree, most easily by simply leaving `originVmType` unset on a
467
+ * deposit-address request. `near-intents.test.ts` certified exactly that
468
+ * contradiction as a valid Zcash request before this was fixed. Deriving both
469
+ * decisions from the same chain id, in the same function, makes the
470
+ * disagreement impossible to construct rather than merely unlikely.
471
+ */
472
+ const buildBody = ({ fromChainId, fromTokenAddress, fromAddress, connectedEthereumAccount, toChainId, toTokenAddress, recipient, amount, swapType, slippage, options, }) => {
473
+ if (amount <= 0n) {
474
+ return null;
475
+ }
476
+ if ((0, exports.isBelowWorkingFloor)({ chainId: fromChainId, amount })) {
477
+ return null;
478
+ }
479
+ const originAsset = (0, exports.findNearIntentsAsset)({
480
+ assets: options.assets,
481
+ chainId: fromChainId,
482
+ tokenAddress: fromTokenAddress,
483
+ ecosystem: (0, relay_quote_js_1.ecosystemByChainId)(fromChainId),
484
+ });
485
+ if (originAsset === null) {
486
+ return null;
487
+ }
488
+ // The delivered side of every route this module can express lands on an
489
+ // entry chain, which is always an Ethereum Virtual Machine chain.
490
+ const destinationAsset = (0, exports.findNearIntentsAsset)({
491
+ assets: options.assets,
492
+ chainId: toChainId,
493
+ tokenAddress: toTokenAddress,
494
+ ecosystem: 'evm',
495
+ });
496
+ if (destinationAsset === null) {
497
+ return null;
498
+ }
499
+ const refund = refundFields({ fromChainId, fromAddress, connectedEthereumAccount });
500
+ if (refund === null) {
501
+ return null;
502
+ }
503
+ return {
504
+ dry: options.dry,
505
+ // A reader paying by hand gets the flexible band; a reader whose wallet
506
+ // composes the transfer to the exact base unit does not need one.
507
+ swapType: (0, chain_names_js_1.isDepositAddressChain)(fromChainId) ? 'FLEX_INPUT' : swapType,
508
+ slippageTolerance: slippage === undefined
509
+ ? defaultSlippageBasisPoints
510
+ : (0, exports.slippageToNearIntentsBasisPoints)(slippage),
511
+ originAsset: originAsset.assetId,
512
+ depositType: 'ORIGIN_CHAIN',
513
+ destinationAsset: destinationAsset.assetId,
514
+ amount: amount.toString(),
515
+ ...refund,
516
+ recipient,
517
+ recipientType: 'DESTINATION_CHAIN',
518
+ deadline: new Date(options.now.getTime() + defaultDeadlineMilliseconds).toISOString(),
519
+ ...(options.referral === undefined ? {} : { referral: options.referral }),
520
+ };
521
+ };
522
+ /**
523
+ * Builds the forward-solving origin-to-anchor pre-quote body.
524
+ *
525
+ * READ THE HEAD OF THIS MODULE BEFORE CALLING THIS FROM THE ROUTER. The
526
+ * entry-anchor pre-quote takes the largest delivered amount across providers
527
+ * and hands it to the providers that execute, so a pre-quote from a provider
528
+ * that cannot execute raises a target nobody can reach. This builder exists
529
+ * because the request shape is real and testable, not because that wiring is
530
+ * wanted.
531
+ *
532
+ * @param request - the provider-agnostic pre-quote request
533
+ * @param options - the asset list, the clock, and the referral tag
534
+ * @returns the request body, or null when the service carries neither asset or
535
+ * the amount is not positive
536
+ */
537
+ const buildNearIntentsPreQuoteRequest = (request, context) => {
538
+ // A pre-quote prices a route it will never execute, so it must not reserve a
539
+ // deposit address; asking dry also keeps it out of the service's records.
540
+ const options = buildOptionsFrom(context, { dry: true });
541
+ if (options === null) {
542
+ return null;
543
+ }
544
+ const recipient = request.recipient ?? request.fromAddress;
545
+ return buildBody({
546
+ fromChainId: request.fromChainId,
547
+ fromTokenAddress: request.fromTokenAddress,
548
+ fromAddress: request.fromAddress,
549
+ // A pre-quote carries no connected account, so a pay-by-hand origin builds
550
+ // no pre-quote. None is wanted: this provider never bids in the pre-quote.
551
+ connectedEthereumAccount: undefined,
552
+ toChainId: request.toChainId,
553
+ toTokenAddress: request.toTokenAddress,
554
+ recipient,
555
+ amount: request.amount,
556
+ swapType: 'EXACT_INPUT',
557
+ slippage: request.slippage,
558
+ options: { ...options, dry: true },
559
+ });
560
+ };
561
+ exports.buildNearIntentsPreQuoteRequest = buildNearIntentsPreQuoteRequest;
562
+ /**
563
+ * Builds the execution quote body for a crossing with nothing to run on arrival.
564
+ *
565
+ * REFUSES ANY REQUEST CARRYING A DESTINATION CALL, and that refusal is the
566
+ * whole point of it. The service has no field a call can travel in, so a
567
+ * request built without the call would look like a valid quote for the same
568
+ * route and would deliver the reader's funds to an address instead of into the
569
+ * omnibridge — a silent, funds-affecting difference. Returning null leaves that
570
+ * route to the providers that execute.
571
+ *
572
+ * @param request - the provider-agnostic consolidated request
573
+ * @param context - carries the asset list, the clock and the referral tag
574
+ * @param options.dry - price only, reserving nothing. What a route ON DISPLAY
575
+ * must ask; a live quote reserves a deposit address for three days, so it is
576
+ * asked only when the reader commits. See `UnreservedDeposit`.
577
+ * @returns the request body, or null when the route needs a destination call,
578
+ * names no input amount, or the service carries neither asset
579
+ */
580
+ const buildNearIntentsQuoteRequest = (request, context, { dry = false } = {}) => {
581
+ if (request.destinationCall !== undefined) {
582
+ return null;
583
+ }
584
+ const { fromAmount, toChainId } = request;
585
+ if (fromAmount === undefined || toChainId === undefined) {
586
+ return null;
587
+ }
588
+ const options = buildOptionsFrom(context, { dry });
589
+ if (options === null) {
590
+ return null;
591
+ }
592
+ return buildBody({
593
+ fromChainId: request.fromChainId,
594
+ fromTokenAddress: request.fromTokenAddress,
595
+ fromAddress: request.fromAddress,
596
+ connectedEthereumAccount: request.connectedEthereumAccount,
597
+ toChainId,
598
+ toTokenAddress: request.toTokenAddress,
599
+ recipient: request.recipient,
600
+ amount: fromAmount,
601
+ swapType: 'EXACT_INPUT',
602
+ slippage: request.slippage,
603
+ options: { ...options, dry },
604
+ });
605
+ };
606
+ exports.buildNearIntentsQuoteRequest = buildNearIntentsQuoteRequest;
607
+ const parseAmount = (value) => {
608
+ if (typeof value !== 'string' || value === '') {
609
+ return null;
610
+ }
611
+ try {
612
+ return BigInt(value);
613
+ }
614
+ catch {
615
+ return null;
616
+ }
617
+ };
618
+ /**
619
+ * Parses a quote response into the delivered amounts a pre-quote reports.
620
+ *
621
+ * `amountOut` is the expected delivery and `minAmountOut` the guaranteed floor
622
+ * after slippage, which is the same pair the other providers' pre-quote parsers
623
+ * produce, so the three rank on like figures.
624
+ *
625
+ * @param payload - the raw JSON body from `POST /v0/quote`
626
+ * @returns the delivered amounts, or null when the payload is an error or
627
+ * otherwise not a quote
628
+ */
629
+ const parseNearIntentsPreQuote = (payload) => {
630
+ const quote = asRecord(asRecord(payload)?.quote);
631
+ if (!quote) {
632
+ return null;
633
+ }
634
+ const expectedAmount = parseAmount(quote.amountOut);
635
+ if (expectedAmount === null) {
636
+ return null;
637
+ }
638
+ const minimumAmount = parseAmount(quote.minAmountOut);
639
+ return { expectedAmount, minimumAmount: minimumAmount ?? expectedAmount };
640
+ };
641
+ exports.parseNearIntentsPreQuote = parseNearIntentsPreQuote;
642
+ /**
643
+ * Builds the transfer the reader signs to fund a quote.
644
+ *
645
+ * THE SERVICE RETURNS NO TRANSACTION, ONLY AN ADDRESS. Every other provider in
646
+ * this repository hands back a signable payload; this one hands back a deposit
647
+ * address and watches the chain for an ordinary transfer into it. So the origin
648
+ * deposit is CONSTRUCTED here from the request, not read off the response, and
649
+ * the response alone is not enough to produce one.
650
+ *
651
+ * There is never an approval. Nothing pulls from the reader's account — they
652
+ * send — so a spender allowance has nothing to authorize.
653
+ *
654
+ * @param options.depositAddress - the address the quote reserved
655
+ * @param options.amount - the input amount, in the origin token's base units
656
+ * @param options.request - the request the quote answered
657
+ * @returns the Ethereum deposit, or null for an origin family this cannot build
658
+ */
659
+ const nearIntentsOriginDeposit = ({ depositAddress, amount, request, }) => {
660
+ // Only Ethereum-virtual-machine origins are built. The other families need a
661
+ // transfer composed in that family's own encoding — a Solana instruction, a
662
+ // Bitcoin transaction — and no signer in this repository accepts a transfer
663
+ // this module composed. Returning null declines the route rather than
664
+ // handing a wallet a payload meant for a different chain.
665
+ //
666
+ // Derived from the chain id, never from the request's own `originVmType` —
667
+ // see the note on {@link buildBody}, which fixes the same signal for the
668
+ // same reason.
669
+ if ((0, relay_quote_js_1.ecosystemByChainId)(request.fromChainId) !== 'evm') {
670
+ return null;
671
+ }
672
+ if (!depositAddress.startsWith('0x')) {
673
+ return null;
674
+ }
675
+ const chainId = request.fromChainId;
676
+ if ((0, ecosystems_js_1.isNativeAsset)(request.fromTokenAddress, 'evm')) {
677
+ return {
678
+ ecosystem: 'evm',
679
+ to: depositAddress,
680
+ data: '0x',
681
+ value: amount,
682
+ chainId,
683
+ gasLimit: null,
684
+ };
685
+ }
686
+ return {
687
+ ecosystem: 'evm',
688
+ to: request.fromTokenAddress,
689
+ data: (0, viem_1.encodeFunctionData)({
690
+ abi: viem_1.erc20Abi,
691
+ functionName: 'transfer',
692
+ args: [depositAddress, amount],
693
+ }),
694
+ value: 0n,
695
+ chainId,
696
+ gasLimit: null,
697
+ };
698
+ };
699
+ /**
700
+ * Builds the deposit for a chain the reader pays by hand: an address, an
701
+ * amount, a tolerance and a clock, and nothing to sign.
702
+ *
703
+ * EVERY FIELD IS READ OFF THE LIVE ANSWER, and each one refuses rather than
704
+ * defaults, because a wrong figure here is shown to a person who then sends
705
+ * money by hand:
706
+ *
707
+ * - the address must be a well-formed address ON THE ORIGIN CHAIN. An answer
708
+ * that issued an Ethereum-shaped address for a Zcash route is not a Zcash
709
+ * deposit, whatever else it says.
710
+ * - the displayed minimum is the LARGER of two floors, never `minAmountIn`
711
+ * alone. `minAmountIn` is the service's flexible-input floor, priced about
712
+ * one percent under the quoted amount; {@link isBelowWorkingFloor} is the
713
+ * bridge's own floor, which does not move with the quote and can sit above
714
+ * `minAmountIn` for a small Zcash amount. A reader told to send the smaller
715
+ * figure sends a deposit the bridge will not credit, and it stalls with no
716
+ * published recovery — see {@link zcashWorkingFloorBaseUnits}. The combined
717
+ * minimum still may not exceed the quoted amount; one that did would tell
718
+ * the reader to send more than asked, so that is refused rather than shown.
719
+ * - `deadline` is the answer's own. The request's echoed deadline is ignored
720
+ * by the service, which substitutes one three days out — see
721
+ * {@link defaultDeadlineMilliseconds}.
722
+ *
723
+ * @param options.quote - the `quote` record of a live answer
724
+ * @param options.depositAddress - the address that answer issued
725
+ * @param options.amount - the quoted input, in base units of the origin asset
726
+ * @param options.chainId - the origin chain
727
+ * @param options.decimals - the origin asset's decimal places
728
+ * @returns the deposit, or null when any field is missing or malformed
729
+ */
730
+ const depositAddressOriginDeposit = ({ quote, depositAddress, amount, chainId, decimals, }) => {
731
+ if (!(0, ecosystems_js_1.isValidAddressIn)(depositAddress, (0, relay_quote_js_1.ecosystemByChainId)(chainId))) {
732
+ return null;
733
+ }
734
+ const flexibleInputFloor = parseAmount(quote.minAmountIn);
735
+ if (flexibleInputFloor === null || flexibleInputFloor <= 0n) {
736
+ return null;
737
+ }
738
+ const bridgeWorkingFloor = workingFloorByChainId.get(chainId) ?? 0n;
739
+ const minimumAmount = flexibleInputFloor > bridgeWorkingFloor ? flexibleInputFloor : bridgeWorkingFloor;
740
+ if (minimumAmount > amount) {
741
+ return null;
742
+ }
743
+ const expiresAtMs = typeof quote.deadline === 'string' ? Date.parse(quote.deadline) : Number.NaN;
744
+ if (Number.isNaN(expiresAtMs)) {
745
+ return null;
746
+ }
747
+ return {
748
+ kind: 'deposit-address',
749
+ chainId,
750
+ depositAddress,
751
+ amount,
752
+ minimumAmount,
753
+ decimals,
754
+ expiresAtMs,
755
+ };
756
+ };
757
+ /**
758
+ * Reads what the route charges.
759
+ *
760
+ * TWO OF THE THREE NUMBERS THE SERVICE REPORTS ARE COSTS, AND ONE IS NOT.
761
+ * `withdrawFee` is taken out of the delivered amount on every successful route,
762
+ * and the key-less surcharge in the echoed `appFees` is taken out of the input,
763
+ * so both are real. `refundFee` is charged ONLY when a swap is refunded — it is
764
+ * the price of a route that did not happen — so counting it would overstate
765
+ * what a completed crossing costs, and it is deliberately left out.
766
+ */
767
+ const nearIntentsQuoteFees = ({ quote, quoteRequest, originToken, destinationToken, }) => {
768
+ const fees = [];
769
+ const withdrawFee = parseAmount(quote.withdrawFee);
770
+ if (withdrawFee !== null && withdrawFee > 0n) {
771
+ fees.push({
772
+ kind: 'service',
773
+ label: 'Withdrawal fee',
774
+ amount: withdrawFee,
775
+ token: destinationToken,
776
+ amountUsd: null,
777
+ // Taken out of what is delivered rather than added to what is sent, so
778
+ // the reader never pays it on top.
779
+ includedInFromAmount: true,
780
+ });
781
+ }
782
+ const amountIn = parseAmount(quote.amountIn);
783
+ const appFees = quoteRequest?.appFees;
784
+ if (amountIn === null || !Array.isArray(appFees)) {
785
+ return fees;
786
+ }
787
+ for (const entry of appFees) {
788
+ const basisPoints = asRecord(entry)?.fee;
789
+ if (typeof basisPoints !== 'number' || basisPoints <= 0) {
790
+ continue;
791
+ }
792
+ fees.push({
793
+ kind: 'service',
794
+ label: 'NEAR Intents platform fee',
795
+ amount: (amountIn * BigInt(Math.round(basisPoints))) / 10000n,
796
+ token: originToken,
797
+ amountUsd: null,
798
+ includedInFromAmount: true,
799
+ });
800
+ }
801
+ return fees;
802
+ };
803
+ /**
804
+ * Normalizes a quote response into the shared consolidated quote shape.
805
+ *
806
+ * READS THE REQUEST AS WELL AS THE RESPONSE, unlike every other parser here,
807
+ * and it has to: the response names a deposit address and no transaction, so
808
+ * the origin chain, the origin token and the ecosystem — everything needed to
809
+ * build the transfer the reader signs — exist only on the request. That is why
810
+ * {@link ProviderQuoteContext} carries a request at all.
811
+ *
812
+ * A DRY QUOTE IS REFUSED. It carries prices and no deposit address, so it can
813
+ * never be executed, and a quote that cannot be executed must not be returned
814
+ * as one.
815
+ *
816
+ * @param payload - the raw JSON body from `POST /v0/quote`
817
+ * @param context - carries the request this answers and both tokens' metadata
818
+ * @returns the normalized quote, or null when the payload cannot produce one
819
+ */
820
+ /**
821
+ * The parts of an answer every NEAR Intents quote needs, reserved or not.
822
+ *
823
+ * @returns the pieces, or null when the context or the body is unusable
824
+ */
825
+ const quoteEssentials = (payload, context) => {
826
+ const request = context?.request;
827
+ const originToken = context?.originToken;
828
+ const destinationToken = context?.destinationToken;
829
+ // Without the request there is no chain and no token to compose a transfer
830
+ // from, so there is no quote to return — the same answer as a malformed body.
831
+ if (request === undefined || originToken === undefined || destinationToken === undefined) {
832
+ return null;
833
+ }
834
+ const body = asRecord(payload);
835
+ const quote = asRecord(body?.quote);
836
+ if (!quote) {
837
+ return null;
838
+ }
839
+ const fromAmount = parseAmount(quote.amountIn);
840
+ if (fromAmount === null) {
841
+ return null;
842
+ }
843
+ if (typeof quote.timeEstimate !== 'number') {
844
+ return null;
845
+ }
846
+ return { request, originToken, destinationToken, body, quote, fromAmount, timeEstimate: quote.timeEstimate };
847
+ };
848
+ /**
849
+ * Assembles the shared quote shape around a deposit.
850
+ *
851
+ * @returns the normalized quote
852
+ */
853
+ const nearIntentsQuoteShape = ({ essentials: { body, quote, fromAmount, timeEstimate, originToken, destinationToken }, quoteId, originDeposit, }) => {
854
+ const toAmount = parseAmount(quote.amountOut);
855
+ return {
856
+ provider: 'near-intents',
857
+ quoteId,
858
+ tool: 'near-intents',
859
+ toolName: 'NEAR Intents',
860
+ fromAmount,
861
+ ...(toAmount === null ? {} : { toAmount }),
862
+ fromAmountUsd: typeof quote.amountInUsd === 'string' ? quote.amountInUsd : null,
863
+ ...(typeof quote.amountOutUsd === 'string' ? { toAmountUsd: quote.amountOutUsd } : {}),
864
+ // Nothing pulls from the reader's account, so no spender is ever approved.
865
+ approvalAddress: null,
866
+ executionDurationSeconds: timeEstimate,
867
+ // The service reports no per-leg breakdown, only the two ends of the trade.
868
+ steps: [],
869
+ originDeposit,
870
+ fees: nearIntentsQuoteFees({
871
+ quote,
872
+ quoteRequest: asRecord(body?.quoteRequest),
873
+ originToken,
874
+ destinationToken,
875
+ }),
876
+ };
877
+ };
878
+ /**
879
+ * Normalizes a DRY answer into a quote that can be drawn and not paid.
880
+ *
881
+ * Same figures, fees and timing as a live quote; its deposit is
882
+ * {@link UnreservedDeposit} and its `quoteId` is empty, because a dry answer
883
+ * reserves no address and the address is a quote's identity. A caller that
884
+ * reaches the commit asks live with `buildNearIntentsQuoteRequest(…, { dry:
885
+ * false })` and pays that answer instead.
886
+ *
887
+ * @param payload - the raw JSON body of a `dry: true` quote
888
+ * @param context - the same context the live parser reads
889
+ * @returns the priced quote, or null when the body is not a quote
890
+ */
891
+ const parseNearIntentsPriceQuote = (payload, context) => {
892
+ const essentials = quoteEssentials(payload, context);
893
+ if (essentials === null) {
894
+ return null;
895
+ }
896
+ return nearIntentsQuoteShape({
897
+ essentials,
898
+ quoteId: '',
899
+ originDeposit: { kind: 'unreserved', chainId: essentials.request.fromChainId },
900
+ });
901
+ };
902
+ exports.parseNearIntentsPriceQuote = parseNearIntentsPriceQuote;
903
+ const parseNearIntentsQuote = (payload, context) => {
904
+ const essentials = quoteEssentials(payload, context);
905
+ if (essentials === null) {
906
+ return null;
907
+ }
908
+ const { request, originToken, quote, fromAmount } = essentials;
909
+ const depositAddress = quote.depositAddress;
910
+ if (typeof depositAddress !== 'string' || depositAddress === '') {
911
+ return null;
912
+ }
913
+ const originDeposit = (0, chain_names_js_1.isDepositAddressChain)(request.fromChainId)
914
+ ? depositAddressOriginDeposit({
915
+ quote,
916
+ depositAddress,
917
+ amount: fromAmount,
918
+ chainId: request.fromChainId,
919
+ decimals: originToken.decimals,
920
+ })
921
+ : nearIntentsOriginDeposit({ depositAddress, amount: fromAmount, request });
922
+ if (originDeposit === null) {
923
+ return null;
924
+ }
925
+ // The deposit address is this quote's identity: the service issues a fresh
926
+ // one per quote and the status endpoint is keyed by it. See
927
+ // {@link nearIntentsStatusUrl}.
928
+ return nearIntentsQuoteShape({ essentials, quoteId: depositAddress, originDeposit });
929
+ };
930
+ exports.parseNearIntentsQuote = parseNearIntentsQuote;
931
+ // "Temporary swap limits: minimum swap amount is $1,000" — thousands separators
932
+ // and all. Captured live against Binance Smart Chain, Polygon and Tron.
933
+ const chainMinimumPattern = /minimum swap amount is \$([\d,]+(?:\.\d+)?)/;
934
+ // "Amount is too low for bridge, try at least 303824" — base units of the
935
+ // origin asset, quoted live and different on consecutive requests.
936
+ const bridgeMinimumPattern = /try at least (\d+)/;
937
+ /**
938
+ * Reads why a quote request was declined.
939
+ *
940
+ * WORTH READING RATHER THAN TREATING AS A FAILURE. A route below one of these
941
+ * floors is not a fault to retry — it is a route this provider will never
942
+ * carry at that size, so a router can drop the provider from the competition
943
+ * and a surface can say what size would work. Left as a bare rejection, the
944
+ * same route simply produces a slower answer with one fewer bidder and nothing
945
+ * on screen to explain it.
946
+ *
947
+ * @param payload - the raw JSON body of a declined `POST /v0/quote`
948
+ * @returns the refusal, or null when the body carries no message to read
949
+ */
950
+ const parseNearIntentsQuoteRefusal = (payload) => {
951
+ const message = asRecord(payload)?.message;
952
+ if (typeof message !== 'string') {
953
+ return null;
954
+ }
955
+ const chainMinimum = chainMinimumPattern.exec(message);
956
+ if (chainMinimum?.[1] !== undefined) {
957
+ return { reason: 'belowChainMinimum', minimumUsd: Number(chainMinimum[1].replaceAll(',', '')) };
958
+ }
959
+ const bridgeMinimum = bridgeMinimumPattern.exec(message);
960
+ if (bridgeMinimum?.[1] !== undefined) {
961
+ return { reason: 'belowBridgeMinimum', minimumAmount: BigInt(bridgeMinimum[1]) };
962
+ }
963
+ if (message.includes('No liquidity available')) {
964
+ return { reason: 'noLiquidity' };
965
+ }
966
+ return { reason: 'other' };
967
+ };
968
+ exports.parseNearIntentsQuoteRefusal = parseNearIntentsQuoteRefusal;
969
+ /**
970
+ * The lifecycle states the status endpoint reports. `SUCCESS`, `REFUNDED` and
971
+ * `FAILED` are terminal; the rest are still in flight.
972
+ */
973
+ const nearIntentsInFlightStatuses = [
974
+ 'KNOWN_DEPOSIT_TX',
975
+ 'PENDING_DEPOSIT',
976
+ 'INCOMPLETE_DEPOSIT',
977
+ 'PROCESSING',
978
+ ];
979
+ const isEthereumTransactionHash = (value) => typeof value === 'string' && /^0x[0-9a-fA-F]{64}$/.test(value);
980
+ /**
981
+ * Finds the destination-chain transaction hash, which is what hands a route
982
+ * over from provider polling to the omnibridge indexer.
983
+ *
984
+ * The hashes arrive as records carrying a `hash` and an explorer address, and
985
+ * the destination chain may not be an Ethereum one, so anything that is not a
986
+ * full thirty-two-byte hash collapses to null rather than being passed on as
987
+ * though it were a transaction.
988
+ */
989
+ const destinationTransactionHash = (swapDetails) => {
990
+ const hashes = swapDetails?.destinationChainTxHashes;
991
+ if (!Array.isArray(hashes)) {
992
+ return null;
993
+ }
994
+ for (const entry of hashes) {
995
+ const hash = asRecord(entry)?.hash;
996
+ if (isEthereumTransactionHash(hash)) {
997
+ return hash;
998
+ }
999
+ }
1000
+ return null;
1001
+ };
1002
+ /**
1003
+ * Where a refund was credited, when it went into an account inside NEAR
1004
+ * Intents rather than back to the origin chain.
1005
+ *
1006
+ * READ FROM THE PROVIDER'S OWN ECHO OF THE REQUEST. The status response carries
1007
+ * the quote request it answered, so the refund's account, type and asset come
1008
+ * from what the provider says it did — not from a guess on our side about
1009
+ * which asset a chain's refund would be in. The amount is the provider's own
1010
+ * `refundedAmount`.
1011
+ *
1012
+ * NULL FOR AN `ORIGIN_CHAIN` REFUND, which lands back in the reader's own
1013
+ * origin wallet and needs nothing from them, and null whenever any field is
1014
+ * missing: a refund step that names the wrong account or asset would send the
1015
+ * reader looking in the wrong place.
1016
+ *
1017
+ * @param body - the whole status response
1018
+ * @param swapDetails - its `swapDetails` record
1019
+ * @returns the account refund, or null
1020
+ */
1021
+ const intentsAccountRefund = (body, swapDetails) => {
1022
+ const request = asRecord(asRecord(body?.quoteResponse)?.quoteRequest);
1023
+ if (request?.refundType !== 'INTENTS') {
1024
+ return null;
1025
+ }
1026
+ const { refundTo, originAsset } = request;
1027
+ const refundedAmount = swapDetails?.refundedAmount;
1028
+ if (typeof refundTo !== 'string' || typeof originAsset !== 'string') {
1029
+ return null;
1030
+ }
1031
+ if (typeof refundedAmount !== 'string' || !/^\d+$/.test(refundedAmount)) {
1032
+ return null;
1033
+ }
1034
+ return { account: refundTo.toLowerCase(), assetId: originAsset, baseUnits: refundedAmount };
1035
+ };
1036
+ /**
1037
+ * Normalizes a `GET /v0/status` response.
1038
+ *
1039
+ * @param payload - the raw JSON body
1040
+ * @returns the normalized status, or null when the payload names no status
1041
+ */
1042
+ const parseNearIntentsStatus = (payload) => {
1043
+ const body = asRecord(payload);
1044
+ const status = body?.status;
1045
+ if (typeof status !== 'string') {
1046
+ return null;
1047
+ }
1048
+ const swapDetails = asRecord(body?.swapDetails);
1049
+ const receivingTxHash = destinationTransactionHash(swapDetails);
1050
+ if (status === 'SUCCESS') {
1051
+ return { status: 'DONE', substatus: 'COMPLETED', receivingTxHash };
1052
+ }
1053
+ if (status === 'REFUNDED') {
1054
+ return {
1055
+ status: 'DONE',
1056
+ substatus: 'REFUNDED',
1057
+ receivingTxHash: null,
1058
+ refund: intentsAccountRefund(body, swapDetails),
1059
+ };
1060
+ }
1061
+ if (status === 'FAILED') {
1062
+ return { status: 'FAILED', substatus: status, receivingTxHash: null };
1063
+ }
1064
+ if (nearIntentsInFlightStatuses.some((inFlight) => inFlight === status)) {
1065
+ return { status: 'PENDING', substatus: status, receivingTxHash };
1066
+ }
1067
+ // An unrecognized state is treated as still settling rather than terminal, so
1068
+ // a new state the service adds never reads as a completed transfer.
1069
+ return { status: 'NOT_FOUND', substatus: status, receivingTxHash };
1070
+ };
1071
+ exports.parseNearIntentsStatus = parseNearIntentsStatus;