@gibs/bridge-sdk 1.13.1 → 1.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (228) hide show
  1. package/README.md +295 -18
  2. package/abis/package.json +6 -0
  3. package/bridge-limits/package.json +6 -0
  4. package/chain-info/package.json +6 -0
  5. package/chain-names/package.json +6 -0
  6. package/chains/package.json +6 -0
  7. package/claims/package.json +6 -0
  8. package/config/package.json +6 -0
  9. package/consolidated-quote/package.json +6 -0
  10. package/destination-calldata/package.json +6 -0
  11. package/dist/chain-info.d.ts +1 -1
  12. package/dist/chain-info.js +11 -12
  13. package/dist/chains.d.ts +25 -0
  14. package/dist/chains.js +55 -20
  15. package/dist/cjs/abis.d.ts +1 -0
  16. package/dist/cjs/abis.js +19 -0
  17. package/dist/cjs/bridge-limits.d.ts +103 -0
  18. package/dist/cjs/bridge-limits.js +89 -0
  19. package/dist/cjs/chain-info.d.ts +169 -0
  20. package/dist/cjs/chain-info.js +452 -0
  21. package/dist/cjs/chain-names.d.ts +160 -0
  22. package/dist/cjs/chain-names.js +207 -0
  23. package/dist/cjs/chains.d.ts +90 -0
  24. package/dist/cjs/chains.js +357 -0
  25. package/dist/cjs/claims.d.ts +198 -0
  26. package/dist/cjs/claims.js +182 -0
  27. package/dist/cjs/config.d.ts +255 -0
  28. package/dist/cjs/config.js +569 -0
  29. package/dist/cjs/consolidated-quote.d.ts +648 -0
  30. package/dist/cjs/consolidated-quote.js +1048 -0
  31. package/dist/cjs/destination-calldata.d.ts +118 -0
  32. package/dist/cjs/destination-calldata.js +156 -0
  33. package/dist/cjs/ecosystems.d.ts +217 -0
  34. package/dist/cjs/ecosystems.js +298 -0
  35. package/dist/cjs/execution.d.ts +359 -0
  36. package/dist/cjs/execution.js +495 -0
  37. package/dist/cjs/fee-type.d.ts +10 -0
  38. package/dist/cjs/fee-type.js +10 -0
  39. package/dist/cjs/hyperliquid-execution.d.ts +152 -0
  40. package/dist/cjs/hyperliquid-execution.js +175 -0
  41. package/dist/cjs/image-links.d.ts +117 -0
  42. package/dist/cjs/image-links.js +153 -0
  43. package/dist/cjs/index.d.ts +24 -0
  44. package/dist/cjs/index.js +40 -0
  45. package/dist/cjs/lifi-execution-guard.d.ts +210 -0
  46. package/dist/cjs/lifi-execution-guard.js +409 -0
  47. package/dist/cjs/near-intents-conformance.d.ts +85 -0
  48. package/dist/cjs/near-intents-conformance.js +337 -0
  49. package/dist/cjs/near-intents-route.d.ts +47 -0
  50. package/dist/cjs/near-intents-route.js +303 -0
  51. package/dist/cjs/near-intents.d.ts +524 -0
  52. package/dist/cjs/near-intents.js +1071 -0
  53. package/dist/cjs/origin-deposit.d.ts +326 -0
  54. package/dist/cjs/origin-deposit.js +82 -0
  55. package/dist/cjs/package.json +3 -0
  56. package/dist/cjs/pre-quote.d.ts +198 -0
  57. package/dist/cjs/pre-quote.js +180 -0
  58. package/dist/cjs/prices.d.ts +117 -0
  59. package/dist/cjs/prices.js +224 -0
  60. package/dist/cjs/providers.d.ts +238 -0
  61. package/dist/cjs/providers.js +171 -0
  62. package/dist/cjs/quote-fees.d.ts +102 -0
  63. package/dist/cjs/quote-fees.js +201 -0
  64. package/dist/cjs/referral.d.ts +85 -0
  65. package/dist/cjs/referral.js +85 -0
  66. package/dist/cjs/relay-currencies.d.ts +47 -0
  67. package/dist/cjs/relay-currencies.js +95 -0
  68. package/dist/cjs/relay-depository.d.ts +2 -0
  69. package/dist/cjs/relay-depository.js +85 -0
  70. package/dist/cjs/relay-quote.d.ts +301 -0
  71. package/dist/cjs/relay-quote.js +996 -0
  72. package/dist/cjs/route-steps.d.ts +138 -0
  73. package/dist/cjs/route-steps.js +310 -0
  74. package/dist/cjs/routing/amounts.d.ts +80 -0
  75. package/dist/cjs/routing/amounts.js +126 -0
  76. package/dist/cjs/routing/candidate-route.d.ts +43 -0
  77. package/dist/cjs/routing/candidate-route.js +50 -0
  78. package/dist/cjs/routing/candidate.d.ts +237 -0
  79. package/dist/cjs/routing/candidate.js +100 -0
  80. package/dist/cjs/routing/carrier-provider-key.d.ts +31 -0
  81. package/dist/cjs/routing/carrier-provider-key.js +42 -0
  82. package/dist/cjs/routing/carriers/ask-answer.d.ts +77 -0
  83. package/dist/cjs/routing/carriers/ask-answer.js +2 -0
  84. package/dist/cjs/routing/carriers/omnibridge.d.ts +137 -0
  85. package/dist/cjs/routing/carriers/omnibridge.js +459 -0
  86. package/dist/cjs/routing/carriers/pulsex-paths.d.ts +80 -0
  87. package/dist/cjs/routing/carriers/pulsex-paths.js +97 -0
  88. package/dist/cjs/routing/carriers/pulsex-split.d.ts +175 -0
  89. package/dist/cjs/routing/carriers/pulsex-split.js +193 -0
  90. package/dist/cjs/routing/carriers/pulsex.d.ts +184 -0
  91. package/dist/cjs/routing/carriers/pulsex.js +615 -0
  92. package/dist/cjs/routing/carriers/wrap.d.ts +25 -0
  93. package/dist/cjs/routing/carriers/wrap.js +119 -0
  94. package/dist/cjs/routing/composed-route-quality.d.ts +125 -0
  95. package/dist/cjs/routing/composed-route-quality.js +144 -0
  96. package/dist/cjs/routing/entry-chain-anchor.d.ts +88 -0
  97. package/dist/cjs/routing/entry-chain-anchor.js +59 -0
  98. package/dist/cjs/routing/format.d.ts +31 -0
  99. package/dist/cjs/routing/format.js +64 -0
  100. package/dist/cjs/routing/index.d.ts +42 -0
  101. package/dist/cjs/routing/index.js +142 -0
  102. package/dist/cjs/routing/producers.d.ts +770 -0
  103. package/dist/cjs/routing/producers.js +1617 -0
  104. package/dist/cjs/routing/providers.d.ts +31 -0
  105. package/dist/cjs/routing/providers.js +48 -0
  106. package/dist/cjs/routing/route-data.d.ts +397 -0
  107. package/dist/cjs/routing/route-data.js +2 -0
  108. package/dist/cjs/routing/search/compose.d.ts +168 -0
  109. package/dist/cjs/routing/search/compose.js +104 -0
  110. package/dist/cjs/routing/search/graph.d.ts +668 -0
  111. package/dist/cjs/routing/search/graph.js +461 -0
  112. package/dist/cjs/routing/search/plan-route-data.d.ts +285 -0
  113. package/dist/cjs/routing/search/plan-route-data.js +871 -0
  114. package/dist/cjs/routing/search/score.d.ts +356 -0
  115. package/dist/cjs/routing/search/score.js +445 -0
  116. package/dist/cjs/routing/swap-transactions.d.ts +95 -0
  117. package/dist/cjs/routing/swap-transactions.js +133 -0
  118. package/dist/cjs/routing/usd-value.d.ts +17 -0
  119. package/dist/cjs/routing/usd-value.js +29 -0
  120. package/dist/cjs/settings.d.ts +785 -0
  121. package/dist/cjs/settings.js +1074 -0
  122. package/dist/cjs/swap-venues.d.ts +43 -0
  123. package/dist/cjs/swap-venues.js +29 -0
  124. package/dist/cjs/ton-connect.d.ts +98 -0
  125. package/dist/cjs/ton-connect.js +206 -0
  126. package/dist/cjs/ton-execution.d.ts +7 -0
  127. package/dist/cjs/ton-execution.js +23 -0
  128. package/dist/cjs/ton.d.ts +37 -0
  129. package/dist/cjs/ton.js +83 -0
  130. package/dist/cjs/tron-execution.d.ts +146 -0
  131. package/dist/cjs/tron-execution.js +248 -0
  132. package/dist/cjs/types.d.ts +51 -0
  133. package/dist/cjs/types.js +2 -0
  134. package/dist/claims.d.ts +198 -0
  135. package/dist/claims.js +140 -0
  136. package/dist/config.d.ts +42 -3
  137. package/dist/config.js +87 -21
  138. package/dist/consolidated-quote.d.ts +109 -15
  139. package/dist/consolidated-quote.js +310 -52
  140. package/dist/execution.d.ts +359 -0
  141. package/dist/execution.js +455 -0
  142. package/dist/hyperliquid-execution.js +2 -3
  143. package/dist/index.d.ts +4 -0
  144. package/dist/index.js +4 -0
  145. package/dist/lifi-execution-guard.d.ts +13 -2
  146. package/dist/lifi-execution-guard.js +4 -0
  147. package/dist/near-intents.js +2 -3
  148. package/dist/pre-quote.d.ts +6 -6
  149. package/dist/pre-quote.js +10 -14
  150. package/dist/prices.d.ts +10 -0
  151. package/dist/prices.js +52 -1
  152. package/dist/providers.d.ts +17 -0
  153. package/dist/providers.js +6 -0
  154. package/dist/referral.d.ts +12 -4
  155. package/dist/referral.js +12 -4
  156. package/dist/relay-depository.d.ts +2 -0
  157. package/dist/relay-depository.js +82 -0
  158. package/dist/relay-quote.js +2 -3
  159. package/dist/routing/candidate.d.ts +3 -3
  160. package/dist/routing/candidate.js +3 -3
  161. package/dist/routing/carrier-provider-key.d.ts +31 -0
  162. package/dist/routing/carrier-provider-key.js +37 -0
  163. package/dist/routing/carriers/ask-answer.d.ts +17 -0
  164. package/dist/routing/carriers/omnibridge.js +23 -21
  165. package/dist/routing/carriers/pulsex-paths.d.ts +80 -0
  166. package/dist/routing/carriers/pulsex-paths.js +92 -0
  167. package/dist/routing/carriers/pulsex-split.d.ts +175 -0
  168. package/dist/routing/carriers/pulsex-split.js +185 -0
  169. package/dist/routing/carriers/pulsex.d.ts +81 -46
  170. package/dist/routing/carriers/pulsex.js +267 -148
  171. package/dist/routing/composed-route-quality.d.ts +28 -6
  172. package/dist/routing/composed-route-quality.js +36 -5
  173. package/dist/routing/entry-chain-anchor.d.ts +1 -1
  174. package/dist/routing/entry-chain-anchor.js +1 -1
  175. package/dist/routing/index.d.ts +11 -3
  176. package/dist/routing/index.js +8 -2
  177. package/dist/routing/producers.js +1 -1
  178. package/dist/routing/providers.d.ts +5 -0
  179. package/dist/routing/providers.js +5 -0
  180. package/dist/routing/route-data.d.ts +47 -5
  181. package/dist/routing/search/graph.d.ts +15 -0
  182. package/dist/routing/search/plan-route-data.d.ts +42 -1
  183. package/dist/routing/search/plan-route-data.js +68 -9
  184. package/dist/routing/search/score.d.ts +3 -0
  185. package/dist/routing/search/score.js +11 -3
  186. package/dist/routing/swap-transactions.d.ts +95 -0
  187. package/dist/routing/swap-transactions.js +127 -0
  188. package/dist/settings.d.ts +94 -1
  189. package/dist/settings.js +95 -3
  190. package/dist/swap-venues.d.ts +43 -0
  191. package/dist/swap-venues.js +24 -0
  192. package/dist/ton-connect.d.ts +98 -0
  193. package/dist/ton-connect.js +200 -0
  194. package/dist/ton-execution.d.ts +4 -114
  195. package/dist/ton-execution.js +4 -244
  196. package/dist/ton.d.ts +37 -0
  197. package/dist/ton.js +65 -0
  198. package/docs/examples/example-a-ether-to-pulse.ts +300 -0
  199. package/docs/examples/example-b-token-pulsechain-to-ethereum.ts +270 -0
  200. package/docs/examples/shared.ts +261 -0
  201. package/docs/examples/tsconfig.json +18 -0
  202. package/docs/integration-guide.md +617 -0
  203. package/ecosystems/package.json +6 -0
  204. package/execution/package.json +6 -0
  205. package/fee-type/package.json +6 -0
  206. package/hyperliquid-execution/package.json +6 -0
  207. package/image-links/package.json +6 -0
  208. package/lifi-execution-guard/package.json +6 -0
  209. package/llms.txt +75 -10
  210. package/near-intents/package.json +6 -0
  211. package/near-intents-route/package.json +6 -0
  212. package/origin-deposit/package.json +6 -0
  213. package/package.json +817 -10
  214. package/pre-quote/package.json +6 -0
  215. package/prices/package.json +6 -0
  216. package/providers/package.json +6 -0
  217. package/quote-fees/package.json +6 -0
  218. package/referral/package.json +6 -0
  219. package/relay-currencies/package.json +6 -0
  220. package/relay-quote/package.json +6 -0
  221. package/route-steps/package.json +6 -0
  222. package/routing/package.json +6 -0
  223. package/settings/package.json +6 -0
  224. package/ton/package.json +6 -0
  225. package/ton-connect/package.json +6 -0
  226. package/ton-execution/package.json +6 -0
  227. package/tron-execution/package.json +6 -0
  228. package/types/package.json +6 -0
@@ -0,0 +1,175 @@
1
+ import type { Hex } from 'viem';
2
+ /**
3
+ * PRICING ONLY. NOTHING SIGNS A SPLIT, SO NOTHING SERVES ONE.
4
+ *
5
+ * A split swap sends part of one trade along one PulseX path and the rest
6
+ * along others, often on both venues (V1 and V2). That lowers price impact on
7
+ * a large trade. But a split is several router calls, and on PulseChain no
8
+ * contract this application deploys or calls can run several router calls
9
+ * from the reader's tokens in one transaction:
10
+ *
11
+ * - The PulseX routers have no split call. Each call trades one path on one
12
+ * factory.
13
+ * - The Gibs destination routers (`TokenOmnibridgeRouter`) only unwrap and pay
14
+ * delivery fees in `onTokenBridged`. They make no arbitrary call.
15
+ * - Multicall3 forwards native value, but it cannot pull the reader's tokens
16
+ * safely: an allowance to Multicall3 is open to anyone who calls it.
17
+ * - PulseChain has no EIP-7702, so an ordinary wallet cannot batch calls
18
+ * atomically through `wallet_sendCalls`.
19
+ *
20
+ * So this module stays out of the package index and out of the carrier's
21
+ * `exact`. It exists so the figures can be measured and compared. Wiring it
22
+ * into the engine needs an execution path first: see the design note in the
23
+ * report that introduced this file.
24
+ */
25
+ /** One pool a split leg crosses, read in the direction of travel, with the identity shared pools are matched by. */
26
+ export type PulseXSplitStep = {
27
+ /** The pool's identity: its venue and token pair. Two legs that name the same `pool` trade against the same reserves. */
28
+ readonly pool: string;
29
+ /** The token flowing into the pool. */
30
+ readonly tokenIn: Hex;
31
+ /** The token flowing out of the pool. */
32
+ readonly tokenOut: Hex;
33
+ /** The pool's reserve of `tokenIn` before any leg of the split trades. */
34
+ readonly reserveIn: bigint;
35
+ /** The pool's reserve of `tokenOut` before any leg of the split trades. */
36
+ readonly reserveOut: bigint;
37
+ };
38
+ /** One path a split may send part of the trade along. */
39
+ export type PulseXSplitCandidate = {
40
+ /** The router the leg would be signed on. */
41
+ readonly venue: Hex;
42
+ /** The tokens the leg passes through, in order. */
43
+ readonly path: readonly Hex[];
44
+ /** The pools the leg crosses, in order. */
45
+ readonly steps: readonly PulseXSplitStep[];
46
+ };
47
+ /** One leg of a priced split, in execution order. */
48
+ export type PulseXSplitLeg = {
49
+ readonly venue: Hex;
50
+ readonly path: readonly Hex[];
51
+ /** The part of the trade this leg spends. The legs' inputs sum to the whole trade. */
52
+ readonly amountIn: bigint;
53
+ /** What this leg delivers, after every earlier leg has moved the pools it shares. */
54
+ readonly deliveredAmount: bigint;
55
+ };
56
+ /** A priced split: the legs, in the order they must execute, and the combined figures. */
57
+ export type PulseXSplitQuote = {
58
+ readonly legs: readonly PulseXSplitLeg[];
59
+ /** What all legs deliver together. */
60
+ readonly deliveredAmount: bigint;
61
+ /** What the best single path delivers for the same trade, for comparison. */
62
+ readonly singlePathDeliveredAmount: bigint;
63
+ /**
64
+ * Price impact of the COMBINED trade, in percent, against the best marginal
65
+ * rate any candidate offers (see {@link splitPriceImpact}). Null when the
66
+ * reference trade rounds away.
67
+ */
68
+ readonly priceImpactPercent: number | null;
69
+ };
70
+ /**
71
+ * How many equal chunks the search divides the trade into: 20, so legs move
72
+ * in 5% steps. Finer steps buy a little output for proportionally more work.
73
+ */
74
+ export declare const PULSEX_SPLIT_CHUNKS = 20;
75
+ /** The most legs one split may have. Each leg is one more router call to sign or batch, and one more swap's gas. */
76
+ export declare const PULSEX_SPLIT_MAX_LEGS = 3;
77
+ /** How many candidate paths, best single-path output first, the search may spread the trade over. */
78
+ export declare const PULSEX_SPLIT_CANDIDATE_LIMIT = 4;
79
+ /**
80
+ * The gain a split must show over the best single path before it is chosen,
81
+ * in basis points of the single path's output: 25, or 0.25%.
82
+ *
83
+ * GAS IS REAL. Each extra leg costs roughly one more swap's gas, and a
84
+ * batching contract adds its own overhead. A split that wins by a rounding
85
+ * margin buys the reader nothing but a larger fee. The figure is a judgement,
86
+ * not a measurement; revisit it once an execution path has a real gas cost.
87
+ */
88
+ export declare const PULSEX_SPLIT_MINIMUM_GAIN_BASIS_POINTS = 25n;
89
+ /**
90
+ * Executes legs one after another against shared pool state, exactly as
91
+ * sequential router calls would. A leg that crosses a pool an earlier leg
92
+ * already traded sees that pool's moved reserves, in whichever direction the
93
+ * earlier leg traded it.
94
+ *
95
+ * Each trade adds its full input to the pool and removes its output, the
96
+ * Uniswap-V2 accounting. See the open risk in the report: if PulseX moves
97
+ * part of its fee out of the pool during a swap, a shared pool is a few
98
+ * hundredths of a percent shallower here than on chain.
99
+ *
100
+ * @param legs - each candidate with the amount it spends, in execution order
101
+ * @returns what each leg delivers, in the same order
102
+ */
103
+ export declare const executePulseXSplitInOrder: (legs: readonly {
104
+ readonly candidate: PulseXSplitCandidate;
105
+ readonly amountIn: bigint;
106
+ }[]) => readonly bigint[];
107
+ /**
108
+ * The candidates a split may use: the {@link PULSEX_SPLIT_CANDIDATE_LIMIT}
109
+ * best by single-path output for the whole trade. A candidate that delivers
110
+ * nothing is dropped. Ties go to the shorter path, then the earlier
111
+ * candidate, so the ranking is deterministic.
112
+ *
113
+ * @param candidates - every priced path, on every venue
114
+ * @param amountIn - the whole trade
115
+ * @returns the ranked candidates, best first, each with its single-path output
116
+ */
117
+ export declare const rankPulseXSplitCandidates: (candidates: readonly PulseXSplitCandidate[], amountIn: bigint) => readonly {
118
+ readonly candidate: PulseXSplitCandidate;
119
+ readonly deliveredAmount: bigint;
120
+ }[];
121
+ /**
122
+ * Spreads a trade over ranked candidates, one chunk at a time. Each chunk goes
123
+ * to the candidate whose share, once raised by that chunk, makes the WHOLE
124
+ * split deliver the most — the split is re-executed in full each time
125
+ * ({@link executePulseXSplitInOrder}), so a shared pool is always priced with
126
+ * the reserves every leg leaves behind. A candidate not yet used is skipped
127
+ * once {@link PULSEX_SPLIT_MAX_LEGS} legs exist. Ties go to the earlier
128
+ * candidate.
129
+ *
130
+ * BOUNDED AND DETERMINISTIC. Work per quote is at most
131
+ * `PULSEX_SPLIT_CHUNKS × PULSEX_SPLIT_CANDIDATE_LIMIT` full executions (80),
132
+ * each of at most `PULSEX_SPLIT_MAX_LEGS` legs of at most three pools: under
133
+ * 750 constant-product evaluations, no network call.
134
+ *
135
+ * On pools that share nothing, each candidate's output is concave in its
136
+ * share, so this greedy fill reaches the best allocation on the chunk grid.
137
+ * Shared pools break that guarantee; {@link bestPulseXSplitQuote} still never
138
+ * returns a split worse than the best single path.
139
+ *
140
+ * @param candidates - ranked candidates, best first
141
+ * @param amountIn - the whole trade
142
+ * @returns the share of the trade each candidate spends, in candidate order
143
+ */
144
+ export declare const allocatePulseXSplit: (candidates: readonly PulseXSplitCandidate[], amountIn: bigint) => readonly bigint[];
145
+ /**
146
+ * Price impact of a combined trade, in percent, measured with the same
147
+ * reference size the single-path figure uses
148
+ * (`amountIn / PULSEX_MARGINAL_REFERENCE_DIVISOR`).
149
+ *
150
+ * THE REFERENCE IS THE BEST MARGINAL RATE OF ANY CANDIDATE, not a blend of
151
+ * the legs' own rates. A split that leans on a path with a worse spot price
152
+ * pays for that, and the figure shows it. A blend would hide it.
153
+ *
154
+ * @param options.candidates - every ranked candidate
155
+ * @param options.amountIn - the whole trade
156
+ * @param options.deliveredAmount - what the combined trade delivers
157
+ * @returns the impact in percent, or null when the reference trade rounds away
158
+ */
159
+ export declare const splitPriceImpact: (options: {
160
+ readonly candidates: readonly PulseXSplitCandidate[];
161
+ readonly amountIn: bigint;
162
+ readonly deliveredAmount: bigint;
163
+ }) => number | null;
164
+ /**
165
+ * The best split of a PulseX trade, or null when no split beats the best
166
+ * single path by {@link PULSEX_SPLIT_MINIMUM_GAIN_BASIS_POINTS}.
167
+ *
168
+ * NEVER WORSE THAN ONE PATH. A null answer means "take the best single path";
169
+ * this never returns a split that delivers less than that path.
170
+ *
171
+ * @param candidates - every priced path, on every venue
172
+ * @param amountIn - the whole trade
173
+ * @returns the split with its legs in execution order, or null
174
+ */
175
+ export declare const bestPulseXSplitQuote: (candidates: readonly PulseXSplitCandidate[], amountIn: bigint) => PulseXSplitQuote | null;
@@ -0,0 +1,185 @@
1
+ import { PULSEX_MARGINAL_REFERENCE_DIVISOR } from '../producers.js';
2
+ import { amountOutAlongPath, priceImpactAgainstMarginal } from './pulsex.js';
3
+ /**
4
+ * How many equal chunks the search divides the trade into: 20, so legs move
5
+ * in 5% steps. Finer steps buy a little output for proportionally more work.
6
+ */
7
+ export const PULSEX_SPLIT_CHUNKS = 20;
8
+ /** The most legs one split may have. Each leg is one more router call to sign or batch, and one more swap's gas. */
9
+ export const PULSEX_SPLIT_MAX_LEGS = 3;
10
+ /** How many candidate paths, best single-path output first, the search may spread the trade over. */
11
+ export const PULSEX_SPLIT_CANDIDATE_LIMIT = 4;
12
+ /**
13
+ * The gain a split must show over the best single path before it is chosen,
14
+ * in basis points of the single path's output: 25, or 0.25%.
15
+ *
16
+ * GAS IS REAL. Each extra leg costs roughly one more swap's gas, and a
17
+ * batching contract adds its own overhead. A split that wins by a rounding
18
+ * margin buys the reader nothing but a larger fee. The figure is a judgement,
19
+ * not a measurement; revisit it once an execution path has a real gas cost.
20
+ */
21
+ export const PULSEX_SPLIT_MINIMUM_GAIN_BASIS_POINTS = 25n;
22
+ const BASIS_POINTS = 10000n;
23
+ /** The key one token's reserve in one pool is held under while a split executes. */
24
+ const reserveKey = (pool, token) => `${pool}|${token.toLowerCase()}`;
25
+ /**
26
+ * Executes legs one after another against shared pool state, exactly as
27
+ * sequential router calls would. A leg that crosses a pool an earlier leg
28
+ * already traded sees that pool's moved reserves, in whichever direction the
29
+ * earlier leg traded it.
30
+ *
31
+ * Each trade adds its full input to the pool and removes its output, the
32
+ * Uniswap-V2 accounting. See the open risk in the report: if PulseX moves
33
+ * part of its fee out of the pool during a swap, a shared pool is a few
34
+ * hundredths of a percent shallower here than on chain.
35
+ *
36
+ * @param legs - each candidate with the amount it spends, in execution order
37
+ * @returns what each leg delivers, in the same order
38
+ */
39
+ export const executePulseXSplitInOrder = (legs) => {
40
+ const reserves = new Map();
41
+ const reserveOf = (pool, token, initial) => reserves.get(reserveKey(pool, token)) ?? initial;
42
+ return legs.map(({ candidate, amountIn }) => candidate.steps.reduce((runningAmount, step) => {
43
+ const reserveIn = reserveOf(step.pool, step.tokenIn, step.reserveIn);
44
+ const reserveOut = reserveOf(step.pool, step.tokenOut, step.reserveOut);
45
+ const amountOut = amountOutAlongPath(runningAmount, [{ reserveIn, reserveOut }]);
46
+ reserves.set(reserveKey(step.pool, step.tokenIn), reserveIn + runningAmount);
47
+ reserves.set(reserveKey(step.pool, step.tokenOut), reserveOut - amountOut);
48
+ return amountOut;
49
+ }, amountIn));
50
+ };
51
+ /** What one candidate alone delivers for the whole trade. */
52
+ const singlePathOutput = (candidate, amountIn) => executePulseXSplitInOrder([{ candidate, amountIn }])[0] ?? 0n;
53
+ /**
54
+ * The candidates a split may use: the {@link PULSEX_SPLIT_CANDIDATE_LIMIT}
55
+ * best by single-path output for the whole trade. A candidate that delivers
56
+ * nothing is dropped. Ties go to the shorter path, then the earlier
57
+ * candidate, so the ranking is deterministic.
58
+ *
59
+ * @param candidates - every priced path, on every venue
60
+ * @param amountIn - the whole trade
61
+ * @returns the ranked candidates, best first, each with its single-path output
62
+ */
63
+ export const rankPulseXSplitCandidates = (candidates, amountIn) => candidates
64
+ .map((candidate, index) => ({ candidate, index, deliveredAmount: singlePathOutput(candidate, amountIn) }))
65
+ .filter((ranked) => ranked.deliveredAmount > 0n)
66
+ .sort((left, right) => {
67
+ if (left.deliveredAmount !== right.deliveredAmount)
68
+ return left.deliveredAmount > right.deliveredAmount ? -1 : 1;
69
+ if (left.candidate.path.length !== right.candidate.path.length)
70
+ return left.candidate.path.length - right.candidate.path.length;
71
+ return left.index - right.index;
72
+ })
73
+ .slice(0, PULSEX_SPLIT_CANDIDATE_LIMIT)
74
+ .map(({ candidate, deliveredAmount }) => ({ candidate, deliveredAmount }));
75
+ /** The trade divided into {@link PULSEX_SPLIT_CHUNKS} chunks; the last one takes the remainder, so the chunks sum to the trade exactly. */
76
+ const chunksOf = (amountIn) => {
77
+ const count = BigInt(PULSEX_SPLIT_CHUNKS);
78
+ const chunk = amountIn / count;
79
+ return Array.from({ length: PULSEX_SPLIT_CHUNKS }, (_, index) => index === PULSEX_SPLIT_CHUNKS - 1 ? amountIn - chunk * (count - 1n) : chunk);
80
+ };
81
+ /** Each candidate with a positive allocation, in candidate order — the order the legs execute in. */
82
+ const legsOf = (candidates, allocation) => candidates.flatMap((candidate, index) => {
83
+ const amountIn = allocation[index] ?? 0n;
84
+ return amountIn > 0n ? [{ candidate, amountIn }] : [];
85
+ });
86
+ /** What an allocation delivers in total, executed in candidate order. */
87
+ const allocationOutput = (candidates, allocation) => executePulseXSplitInOrder(legsOf(candidates, allocation)).reduce((total, amount) => total + amount, 0n);
88
+ /**
89
+ * Spreads a trade over ranked candidates, one chunk at a time. Each chunk goes
90
+ * to the candidate whose share, once raised by that chunk, makes the WHOLE
91
+ * split deliver the most — the split is re-executed in full each time
92
+ * ({@link executePulseXSplitInOrder}), so a shared pool is always priced with
93
+ * the reserves every leg leaves behind. A candidate not yet used is skipped
94
+ * once {@link PULSEX_SPLIT_MAX_LEGS} legs exist. Ties go to the earlier
95
+ * candidate.
96
+ *
97
+ * BOUNDED AND DETERMINISTIC. Work per quote is at most
98
+ * `PULSEX_SPLIT_CHUNKS × PULSEX_SPLIT_CANDIDATE_LIMIT` full executions (80),
99
+ * each of at most `PULSEX_SPLIT_MAX_LEGS` legs of at most three pools: under
100
+ * 750 constant-product evaluations, no network call.
101
+ *
102
+ * On pools that share nothing, each candidate's output is concave in its
103
+ * share, so this greedy fill reaches the best allocation on the chunk grid.
104
+ * Shared pools break that guarantee; {@link bestPulseXSplitQuote} still never
105
+ * returns a split worse than the best single path.
106
+ *
107
+ * @param candidates - ranked candidates, best first
108
+ * @param amountIn - the whole trade
109
+ * @returns the share of the trade each candidate spends, in candidate order
110
+ */
111
+ export const allocatePulseXSplit = (candidates, amountIn) => chunksOf(amountIn).reduce((allocation, chunk) => {
112
+ const usedLegs = allocation.filter((amount) => amount > 0n).length;
113
+ const trials = candidates.flatMap((_, index) => {
114
+ const unused = (allocation[index] ?? 0n) === 0n;
115
+ if (unused && usedLegs >= PULSEX_SPLIT_MAX_LEGS)
116
+ return [];
117
+ const trial = allocation.map((amount, trialIndex) => (trialIndex === index ? amount + chunk : amount));
118
+ return [{ trial, output: allocationOutput(candidates, trial) }];
119
+ });
120
+ const best = trials.reduce((leader, entry) => (leader === null || entry.output > leader.output ? entry : leader), null);
121
+ return best === null ? allocation : best.trial;
122
+ }, candidates.map(() => 0n));
123
+ /**
124
+ * Price impact of a combined trade, in percent, measured with the same
125
+ * reference size the single-path figure uses
126
+ * (`amountIn / PULSEX_MARGINAL_REFERENCE_DIVISOR`).
127
+ *
128
+ * THE REFERENCE IS THE BEST MARGINAL RATE OF ANY CANDIDATE, not a blend of
129
+ * the legs' own rates. A split that leans on a path with a worse spot price
130
+ * pays for that, and the figure shows it. A blend would hide it.
131
+ *
132
+ * @param options.candidates - every ranked candidate
133
+ * @param options.amountIn - the whole trade
134
+ * @param options.deliveredAmount - what the combined trade delivers
135
+ * @returns the impact in percent, or null when the reference trade rounds away
136
+ */
137
+ export const splitPriceImpact = (options) => {
138
+ const { candidates, amountIn, deliveredAmount } = options;
139
+ const referenceAmountIn = amountIn / PULSEX_MARGINAL_REFERENCE_DIVISOR;
140
+ const referenceAmountOut = candidates.reduce((best, candidate) => {
141
+ const output = singlePathOutput(candidate, referenceAmountIn);
142
+ return output > best ? output : best;
143
+ }, 0n);
144
+ return priceImpactAgainstMarginal({ amountIn, amountOut: deliveredAmount, referenceAmountIn, referenceAmountOut });
145
+ };
146
+ /**
147
+ * The best split of a PulseX trade, or null when no split beats the best
148
+ * single path by {@link PULSEX_SPLIT_MINIMUM_GAIN_BASIS_POINTS}.
149
+ *
150
+ * NEVER WORSE THAN ONE PATH. A null answer means "take the best single path";
151
+ * this never returns a split that delivers less than that path.
152
+ *
153
+ * @param candidates - every priced path, on every venue
154
+ * @param amountIn - the whole trade
155
+ * @returns the split with its legs in execution order, or null
156
+ */
157
+ export const bestPulseXSplitQuote = (candidates, amountIn) => {
158
+ if (amountIn <= 0n)
159
+ return null;
160
+ const ranked = rankPulseXSplitCandidates(candidates, amountIn);
161
+ const singlePathDeliveredAmount = ranked[0]?.deliveredAmount;
162
+ if (singlePathDeliveredAmount === undefined)
163
+ return null;
164
+ const rankedCandidates = ranked.map(({ candidate }) => candidate);
165
+ const allocation = allocatePulseXSplit(rankedCandidates, amountIn);
166
+ const legs = legsOf(rankedCandidates, allocation);
167
+ if (legs.length < 2)
168
+ return null;
169
+ const legOutputs = executePulseXSplitInOrder(legs);
170
+ const deliveredAmount = legOutputs.reduce((total, amount) => total + amount, 0n);
171
+ const requiredAmount = singlePathDeliveredAmount + (singlePathDeliveredAmount * PULSEX_SPLIT_MINIMUM_GAIN_BASIS_POINTS) / BASIS_POINTS;
172
+ if (deliveredAmount < requiredAmount)
173
+ return null;
174
+ return {
175
+ legs: legs.map(({ candidate, amountIn: legAmountIn }, index) => ({
176
+ venue: candidate.venue,
177
+ path: candidate.path,
178
+ amountIn: legAmountIn,
179
+ deliveredAmount: legOutputs[index] ?? 0n,
180
+ })),
181
+ deliveredAmount,
182
+ singlePathDeliveredAmount,
183
+ priceImpactPercent: splitPriceImpact({ candidates: rankedCandidates, amountIn, deliveredAmount }),
184
+ };
185
+ };
@@ -1,60 +1,86 @@
1
1
  import { type Hex } from 'viem';
2
2
  import type { PublicClient } from 'viem';
3
- import { type AssetNode, type HopEdge } from '../search/graph.js';
3
+ import { type SwapVenue, type SwapVenues } from '../../swap-venues.js';
4
+ import { type AssetNode, type HopEdge, type PlannedHop } from '../search/graph.js';
4
5
  import type { CarrierAskAnswer, CarrierExactResult } from './ask-answer.js';
5
6
  /**
6
- * One PulseX deployment a swap can execute on: the router the reader signs
7
- * and the factory whose pools that router trades against. A Uniswap-V2-style
7
+ * One swap deployment a swap can execute on: the router the reader signs and
8
+ * the factory whose pools that router trades against. A Uniswap-V2-style
8
9
  * router resolves every pool through its OWN factory, so one router call can
9
10
  * only ever touch that one deployment's pools — a path can never mix them.
11
+ *
12
+ * Same type as {@link SwapVenue}; the old name stays for existing callers.
10
13
  */
11
- export type PulseXVenue = {
12
- readonly router: Hex;
13
- readonly factory: Hex;
14
- };
14
+ export type PulseXVenue = SwapVenue;
15
15
  /**
16
- * Every PulseX deployment on PulseChain, V1 first: `uniV2Routers` paired with
17
- * `uniV2Factories` by index. Each factory is the router's own
18
- * `router.factory()` read on chain — see `uniV2Factories`'s own doc in
19
- * `config.ts`. A router with no recorded factory is left out, because its
20
- * pools cannot be read.
16
+ * Every PulseX deployment on PulseChain, V1 first: the PulseChain entry of
17
+ * {@link defaultSwapVenues}. Frozen. It lists the DEFAULTS only — a carrier
18
+ * built with its own `venues` offers those instead.
21
19
  */
22
20
  export declare const pulseXVenues: readonly PulseXVenue[];
23
21
  /**
24
- * The router a PulseX edge must be signed on — the one its figure was quoted
25
- * against. Reads the edge's own {@link HopEdge.venue}; an edge with none is a
26
- * V1 edge (see {@link defaultPulseXVenue}).
22
+ * The {@link SwapVenue} a swap edge runs on: the one its figure was quoted
23
+ * against. Reads the edge's own {@link HopEdge.venue}; an edge with none runs
24
+ * on the FIRST venue of its chain (V1 for PulseX) — every swap edge built
25
+ * before venues existed was quoted and signed there, and the same-chain swap
26
+ * sender's own hand-built edge still is.
27
+ *
28
+ * NEVER FALLS BACK TO ANOTHER CHAIN OR ANOTHER ROUTER. An edge that names a
29
+ * router `venues` does not list gets null, so the caller can refuse it.
30
+ *
31
+ * @param venues - the venues the caller allows
32
+ * @param edge - the edge to sign; `from` names the chain, and defaults to PulseChain when absent
33
+ * @returns the venue, or null when the edge is not a swap edge or names a router that is not in `venues`
34
+ */
35
+ export declare const venueForEdge: (venues: SwapVenues, edge: Pick<HopEdge, "carrier" | "venue"> & {
36
+ readonly from?: Pick<AssetNode, "chainId">;
37
+ }) => SwapVenue | null;
38
+ /**
39
+ * The router a PulseX edge must be signed on, judged against the DEFAULT
40
+ * venues only. Prefer {@link venueForEdge} with the venues your host passes.
27
41
  *
28
42
  * @param edge - the edge to sign
29
- * @returns the router, or null when the edge is not a PulseX edge or names a venue that is not a known PulseX router
43
+ * @returns the router, or null when the edge is not a swap edge or names a router that is not a default
30
44
  */
31
- export declare const pulseXRouterForEdge: (edge: Pick<HopEdge, "carrier" | "venue">) => Hex | null;
45
+ export declare const pulseXRouterForEdge: (edge: Pick<HopEdge, "carrier" | "venue"> & {
46
+ readonly from?: Pick<AssetNode, "chainId">;
47
+ }) => Hex | null;
32
48
  /**
33
- * The router swap path a PulseX hop from `from` to `to` prices and signs
34
- * along, or null when there is no swap for PulseX to do — including when
35
- * both ends resolve to the SAME pool token, which is true of PLS<->WPLS
36
- * (native PLS resolves to {@link wplsAddress} via {@link poolTokenAddress},
37
- * same as Wrapped PLS itself): that pair is the wrap carrier's job, never a
38
- * PulseX hop, so this returns null rather than a zero-length or self-paired
39
- * path.
49
+ * The fixed Wrapped-PLS path from `from` to `to` — `[from, WPLS, to]`, or
50
+ * `[from, to]` when one side is WPLS — or null when both ends resolve to the
51
+ * same pool token (PLS<->WPLS is the wrap carrier's job).
52
+ *
53
+ * NOT THE PATH A HOP IS SIGNED ALONG. The carrier's own `exact` picks the
54
+ * best of many paths ({@link candidatePulseXPaths}) and records the winner on
55
+ * the hop's outcome; the signer reads it back with {@link pulseXSwapPathForHop}.
56
+ * This fixed path serves only the carrier's asynchronous `ask` — the
57
+ * interface's `getAmountsOut` read, which the route search never calls for a
58
+ * PulseX hop, because the search only asks aggregators live.
40
59
  *
41
- * EVERY PULSEX QUOTE AND SIGNATURE IN THIS FILE MUST GO THROUGH THIS ONE
42
- * FUNCTION — `pulseXCarries`, `prepare`'s pool discovery, and `exact`'s hop
43
- * pricing all call it, so native PLS resolves the same way in every one of
44
- * them. Before this existed, `pulseXCarries` and `prepare`/`exact` called
45
- * `pulseXConversionSwapPath` directly on the raw node address: a native PLS
46
- * node produced a path that LITERALLY STARTED WITH THE ZERO ADDRESS
47
- * (`[zeroAddress, wplsAddress, ...]`), which `pulseXCarries` accepted (its
48
- * length is still >= 2) but for which `prepare` could never find a pool —
49
- * the factory has no pair for the zero address — so `exact` always answered
50
- * `null` for a direct native-PLS PulseX hop, and `enumerate.ts` pruned it,
51
- * leaving only the two-signature wrap-then-swap path.
60
+ * Native PLS resolves to WPLS first ({@link poolTokenAddress}), so a path
61
+ * never starts or ends on the zero address, which has no pool.
52
62
  *
53
63
  * @param from - the hop's origin node
54
64
  * @param to - the hop's destination node
55
- * @returns the swap path, or null when there is nothing for PulseX to swap
65
+ * @returns the fixed path, or null when there is nothing for PulseX to swap
56
66
  */
57
- export declare const pulseXPoolPath: (from: AssetNode, to: AssetNode) => readonly Hex[] | null;
67
+ export declare const pulseXWrappedNativePath: (from: AssetNode, to: AssetNode) => readonly Hex[] | null;
68
+ /**
69
+ * The swap path a planned PulseX hop must be signed along: the path its
70
+ * outcome records ({@link HopOutcome.swapPath}), which is the path the
71
+ * carrier's `exact` priced the figure on. NEVER REBUILT HERE — rebuilding a
72
+ * path at signing time is how a quote on one path becomes a signature on
73
+ * another.
74
+ *
75
+ * The recorded path is checked against the hop's own edge before it is
76
+ * returned: it must start at the edge's input pool token, end at its output
77
+ * pool token, hold only addresses, and name no token twice. A path that fails
78
+ * any check is refused (null) rather than signed.
79
+ *
80
+ * @param hop - the planned hop to sign
81
+ * @returns the path to sign, or null when the hop is not a PulseX hop, records no path, or records one that does not fit its edge
82
+ */
83
+ export declare const pulseXSwapPathForHop: (hop: Pick<PlannedHop, "edge" | "outcome">) => readonly Hex[] | null;
58
84
  /** One pool a swap path crosses, read in the direction of travel. */
59
85
  export type PulseXPathStep = {
60
86
  /** The pool's reserve of the token flowing in. */
@@ -68,9 +94,10 @@ export type PulseXPathStep = {
68
94
  *
69
95
  * @param amountIn - the amount entering the first pool
70
96
  * @param steps - the pools in order of travel
97
+ * @param feeBasisPoints - the venue's swap fee in basis points; PulseX's 29 when omitted
71
98
  * @returns the amount leaving the last pool; 0 when any pool cannot pay out
72
99
  */
73
- export declare const amountOutAlongPath: (amountIn: bigint, steps: readonly PulseXPathStep[]) => bigint;
100
+ export declare const amountOutAlongPath: (amountIn: bigint, steps: readonly PulseXPathStep[], feeBasisPoints?: number) => bigint;
74
101
  /**
75
102
  * How far a trade's executed rate falls below the marginal (near-spot) rate,
76
103
  * in percent. The marginal rate is a tiny reference trade through the same
@@ -100,12 +127,12 @@ export type CreatePulseXCarrierOptions = {
100
127
  * in the edge's `to` token's base units. Returns null when the path has no
101
128
  * liquidity.
102
129
  *
103
- * MUST READ THE EDGE'S OWN ROUTER ({@link pulseXRouterForEdge}). A V2 edge
130
+ * MUST READ THE EDGE'S OWN ROUTER ({@link venueForEdge}). A V2 edge
104
131
  * answered from V1 would carry V1's figure into a V2 signature.
105
132
  */
106
133
  readonly readAmountOut: (edge: HopEdge, inputAmount: bigint) => Promise<bigint | null>;
107
134
  /**
108
- * Returns a PulseChain client, for {@link Carrier.prepare}'s own batched
135
+ * Returns a client for a chain, for {@link Carrier.prepare}'s own batched
109
136
  * reserve reads — never called by `ask`, which keeps using
110
137
  * {@link readAmountOut} unchanged.
111
138
  *
@@ -113,17 +140,25 @@ export type CreatePulseXCarrierOptions = {
113
140
  * field for why: a host that has not wired this yet gets the carrier's
114
141
  * original behavior, `prepare` a no-op and `exact` always `null`.
115
142
  *
116
- * @param chainId - always {@link pulsechainChainId} — PulseX runs nowhere else
143
+ * @param chainId - a chain that has swap venues
117
144
  * @returns a client, or null when this host has none
118
145
  */
119
146
  readonly clientForChain?: (chainId: number) => PublicClient | null;
120
147
  /**
121
- * The PulseX routers this host can SIGN on. The carrier offers an edge on
122
- * each, and only on these: an edge is always signed on the router it was
123
- * quoted against ({@link pulseXRouterForEdge}), so a router the host cannot
124
- * sign on must never be quoted either.
148
+ * The swap venues to offer. Merged over {@link defaultSwapVenues} by
149
+ * {@link resolveSwapVenues}: a chain named here REPLACES that chain's
150
+ * default list, a chain left out keeps its defaults, and an empty list
151
+ * switches swaps off on that chain. A venue on ANY chain builds swap edges
152
+ * there.
153
+ */
154
+ readonly venues?: SwapVenues;
155
+ /**
156
+ * Narrows the offered venues to these routers. An edge is always signed on
157
+ * the router it was quoted against ({@link venueForEdge}), so a router the
158
+ * host cannot sign on must never be quoted either. A router that is in no
159
+ * offered venue is a configuration error and throws at construction.
125
160
  *
126
- * Defaults to every known venue ({@link pulseXVenues}: V1 and V2).
161
+ * Defaults to every offered venue.
127
162
  */
128
163
  readonly routers?: readonly Hex[];
129
164
  };