@t402/smart-router 1.0.0-beta.1

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.
package/README.md ADDED
@@ -0,0 +1,388 @@
1
+ # @t402-internal/smart-router
2
+
3
+ Smart Payment Routing Engine for T402 Protocol.
4
+
5
+ ## Overview
6
+
7
+ This package provides intelligent multi-chain payment routing with optimal path finding, real-time pricing, liquidity aggregation, and MEV protection. It enables finding the most cost-effective or fastest route for cross-chain payments.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pnpm add @t402-internal/smart-router
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```typescript
18
+ import {
19
+ RoutingEngine,
20
+ GasOracle,
21
+ FeeEstimator,
22
+ LiquidityAggregator,
23
+ TransactionBuilder,
24
+ MevProtection,
25
+ } from '@t402-internal/smart-router';
26
+
27
+ // Set up routing engine
28
+ const router = new RoutingEngine();
29
+
30
+ // Add network graph edges (liquidity sources)
31
+ router.updateGraph([
32
+ {
33
+ from: 'eip155:1',
34
+ to: 'eip155:8453',
35
+ fromAsset: '0xUSDT',
36
+ toAsset: '0xUSDT',
37
+ protocol: 'layerzero',
38
+ type: 'bridge',
39
+ cost: 50000,
40
+ liquidity: '50000000000',
41
+ maxAmount: '10000000000',
42
+ minAmount: '10000000',
43
+ estimatedTime: 120,
44
+ },
45
+ // ... more edges
46
+ ]);
47
+
48
+ // Find best route
49
+ const routes = await router.findRoutes({
50
+ sourceChain: 'eip155:1',
51
+ sourceAsset: '0xUSDT',
52
+ sourceAmount: '1000000000', // 1000 USDT
53
+ destinationChain: 'eip155:8453',
54
+ destinationAsset: '0xUSDT',
55
+ recipient: '0xRecipient',
56
+ sender: '0xSender',
57
+ optimization: 'balanced',
58
+ });
59
+
60
+ console.log(routes[0].totalCost);
61
+ console.log(routes[0].estimatedTime);
62
+ ```
63
+
64
+ ## Modules
65
+
66
+ ### Routing
67
+
68
+ The routing module provides path-finding algorithms and route optimization.
69
+
70
+ ```typescript
71
+ import {
72
+ RoutingEngine,
73
+ dijkstra,
74
+ astar,
75
+ kShortestPaths,
76
+ paretoOptimalPaths,
77
+ } from '@t402-internal/smart-router/routing';
78
+
79
+ // Create engine with configuration
80
+ const router = new RoutingEngine({
81
+ maxRoutes: 5,
82
+ cacheTtl: 30000,
83
+ minConfidence: 50,
84
+ });
85
+
86
+ // Find routes with different optimization strategies
87
+ const costOptimized = await router.findRoutes({
88
+ ...request,
89
+ optimization: 'cost',
90
+ });
91
+
92
+ const speedOptimized = await router.findRoutes({
93
+ ...request,
94
+ optimization: 'speed',
95
+ });
96
+
97
+ // Get best single route
98
+ const best = await router.getBestRoute(request);
99
+
100
+ // Validate route before execution
101
+ const validation = await router.validateRoute(route);
102
+ if (!validation.valid) {
103
+ console.log(validation.errors);
104
+ }
105
+ ```
106
+
107
+ ### Optimization Strategies
108
+
109
+ | Strategy | Description |
110
+ |----------|-------------|
111
+ | `cost` | Minimize total fees and gas costs |
112
+ | `speed` | Minimize execution time |
113
+ | `balanced` | Balance cost, speed, and reliability |
114
+ | `slippage` | Minimize price impact |
115
+ | `privacy` | Prefer privacy-preserving routes |
116
+
117
+ ### Pricing
118
+
119
+ Real-time gas and fee estimation with predictive modeling.
120
+
121
+ ```typescript
122
+ import {
123
+ GasOracle,
124
+ FeeEstimator,
125
+ MockGasProvider,
126
+ } from '@t402-internal/smart-router/pricing';
127
+
128
+ // Gas oracle for multi-chain gas tracking
129
+ const gasOracle = new GasOracle({
130
+ cacheTtl: 15000,
131
+ enablePrediction: true,
132
+ });
133
+
134
+ // Get gas prices
135
+ const gasPrice = await gasOracle.getGasPrice('eip155:8453');
136
+ console.log(gasPrice.standard); // Standard gas price in wei
137
+
138
+ // Calculate gas cost in USD
139
+ const { costUsd } = await gasOracle.calculateGasCostUsd(
140
+ 'eip155:8453',
141
+ '150000', // gas units
142
+ 'fast',
143
+ );
144
+
145
+ // Get gas price prediction
146
+ const prediction = gasOracle.predictGasPrice('eip155:8453', 5);
147
+
148
+ // Fee estimator
149
+ const feeEstimator = new FeeEstimator(gasOracle);
150
+
151
+ const estimate = await feeEstimator.estimateFees({
152
+ chain: 'eip155:8453',
153
+ operation: 'swap',
154
+ protocol: 'uniswap',
155
+ inputAsset: '0xUSDT',
156
+ outputAsset: '0xUSDC',
157
+ amount: '1000000000',
158
+ gasSpeed: 'standard',
159
+ });
160
+
161
+ console.log(estimate.totalFeeUsd);
162
+ ```
163
+
164
+ ### Liquidity
165
+
166
+ Aggregate liquidity across multiple DEXs and bridges.
167
+
168
+ ```typescript
169
+ import {
170
+ LiquidityAggregator,
171
+ MockLiquidityProvider,
172
+ MockBridgeProvider,
173
+ } from '@t402-internal/smart-router/liquidity';
174
+
175
+ const aggregator = new LiquidityAggregator({
176
+ cacheTtl: 30000,
177
+ minLiquidity: '1000',
178
+ });
179
+
180
+ // Register providers
181
+ aggregator.registerProvider(new MockLiquidityProvider('eip155:8453', 'uniswap'));
182
+ aggregator.registerBridgeProvider(new MockBridgeProvider('layerzero'));
183
+
184
+ // Get aggregated liquidity
185
+ const liquidity = await aggregator.getLiquidity(
186
+ 'eip155:8453',
187
+ '0xUSDT',
188
+ '0xUSDC',
189
+ );
190
+
191
+ console.log(liquidity.totalLiquidity);
192
+ console.log(liquidity.bestPrice);
193
+
194
+ // Calculate slippage
195
+ const slippage = aggregator.calculateSlippage(
196
+ liquidity,
197
+ '100000000', // 100 USDT
198
+ '0.5', // 0.5% tolerance
199
+ );
200
+
201
+ console.log(slippage.priceImpact);
202
+ console.log(slippage.minOutputAmount);
203
+
204
+ // Get cross-chain liquidity
205
+ const crossChain = await aggregator.getCrossChainLiquidity(
206
+ 'eip155:1',
207
+ 'eip155:8453',
208
+ '0xUSDT',
209
+ );
210
+
211
+ console.log(crossChain.bestBridge);
212
+ ```
213
+
214
+ ### Execution
215
+
216
+ Build and execute transactions with MEV protection.
217
+
218
+ ```typescript
219
+ import {
220
+ TransactionBuilder,
221
+ MevProtection,
222
+ createMevProtectedOptions,
223
+ } from '@t402-internal/smart-router/execution';
224
+
225
+ // Build transactions from route
226
+ const builder = new TransactionBuilder(gasOracle);
227
+
228
+ const transactions = await builder.buildRoute(route, '0xSender', {
229
+ gasSpeed: 'fast',
230
+ mevProtection: 'flashbots',
231
+ autoApprove: true,
232
+ });
233
+
234
+ // Get required approvals
235
+ const approvals = builder.getRequiredApprovals(route, '0xSender');
236
+
237
+ // MEV protection
238
+ const mev = new MevProtection({
239
+ flashbotsRelay: 'https://relay.flashbots.net',
240
+ });
241
+
242
+ // Estimate MEV risk
243
+ const risk = mev.estimateMevRisk(transaction, 'eip155:1');
244
+ console.log(risk.riskLevel);
245
+ console.log(risk.recommendations);
246
+
247
+ // Submit with protection
248
+ const result = await mev.protect(
249
+ transaction,
250
+ signedTransaction,
251
+ 'flashbots',
252
+ 'eip155:1',
253
+ );
254
+ ```
255
+
256
+ ## Route Types
257
+
258
+ | Type | Description |
259
+ |------|-------------|
260
+ | `transfer` | Simple token transfer |
261
+ | `swap` | DEX swap |
262
+ | `bridge` | Cross-chain bridge |
263
+ | `wrap` | Wrap native token (ETH -> WETH) |
264
+ | `unwrap` | Unwrap to native (WETH -> ETH) |
265
+ | `approve` | Token approval |
266
+
267
+ ## Path Finding Algorithms
268
+
269
+ The package includes several path-finding algorithms:
270
+
271
+ ```typescript
272
+ import {
273
+ dijkstra,
274
+ astar,
275
+ kShortestPaths,
276
+ paretoOptimalPaths,
277
+ COST_CONFIGS,
278
+ } from '@t402-internal/smart-router/routing';
279
+
280
+ // Dijkstra's algorithm
281
+ const path = dijkstra(
282
+ edges,
283
+ 'eip155:1', '0xUSDT',
284
+ 'eip155:8453', '0xUSDT',
285
+ COST_CONFIGS.balanced,
286
+ 5, // max hops
287
+ );
288
+
289
+ // A* with heuristic
290
+ const fastPath = astar(
291
+ edges,
292
+ 'eip155:1', '0xUSDT',
293
+ 'eip155:8453', '0xUSDT',
294
+ COST_CONFIGS.speed,
295
+ 5,
296
+ );
297
+
298
+ // K-shortest paths (Yen's algorithm)
299
+ const topPaths = kShortestPaths(
300
+ edges,
301
+ 'eip155:1', '0xUSDT',
302
+ 'eip155:8453', '0xUSDT',
303
+ COST_CONFIGS.balanced,
304
+ 5, // k paths
305
+ );
306
+
307
+ // Pareto-optimal paths (multi-objective)
308
+ const pareto = paretoOptimalPaths(
309
+ edges,
310
+ 'eip155:1', '0xUSDT',
311
+ 'eip155:8453', '0xUSDT',
312
+ );
313
+ ```
314
+
315
+ ## Supported Chains
316
+
317
+ The router uses CAIP-2 chain identifiers:
318
+
319
+ | Chain | ID |
320
+ |-------|-----|
321
+ | Ethereum | `eip155:1` |
322
+ | Base | `eip155:8453` |
323
+ | Arbitrum | `eip155:42161` |
324
+ | Optimism | `eip155:10` |
325
+ | Polygon | `eip155:137` |
326
+ | BSC | `eip155:56` |
327
+ | Solana | `solana:mainnet` |
328
+
329
+ ## MEV Protection Strategies
330
+
331
+ | Strategy | Description |
332
+ |----------|-------------|
333
+ | `none` | No protection (public mempool) |
334
+ | `flashbots` | Use Flashbots bundle (Ethereum) |
335
+ | `private_mempool` | Use private RPC endpoints |
336
+ | `timing` | Submit at optimal time |
337
+ | `splitting` | Split into smaller transactions |
338
+
339
+ ## API Reference
340
+
341
+ ### RoutingEngine
342
+
343
+ - `findRoutes(request)` - Find all routes matching request
344
+ - `getBestRoute(request)` - Get single best route
345
+ - `validateRoute(route)` - Validate route is still executable
346
+ - `updateGraph(edges)` - Update network graph
347
+ - `addEdge(edge)` - Add single edge to graph
348
+
349
+ ### GasOracle
350
+
351
+ - `getGasPrice(chain)` - Get current gas prices
352
+ - `getMultiChainGasPrices(chains)` - Get prices for multiple chains
353
+ - `calculateGasCostUsd(chain, gas, speed)` - Calculate cost in USD
354
+ - `predictGasPrice(chain, horizon)` - Predict future prices
355
+ - `getRecommendedGasPrice(chain, urgency)` - Get recommended price
356
+
357
+ ### FeeEstimator
358
+
359
+ - `estimateFees(request)` - Estimate fees for operation
360
+ - `estimateRouteFees(steps)` - Estimate total route fees
361
+ - `getSwapQuote(...)` - Get swap quote
362
+ - `getBridgeQuote(...)` - Get bridge quote
363
+
364
+ ### LiquidityAggregator
365
+
366
+ - `getLiquidity(chain, input, output)` - Get aggregated liquidity
367
+ - `getCrossChainLiquidity(from, to, asset)` - Get bridge liquidity
368
+ - `calculateSlippage(source, amount, tolerance)` - Calculate slippage
369
+ - `getLiquidityDepth(...)` - Get liquidity at price levels
370
+ - `findBestRoute(source, amount)` - Find best execution route
371
+
372
+ ### TransactionBuilder
373
+
374
+ - `buildRoute(route, sender, options)` - Build all transactions
375
+ - `buildStep(step, sender, options)` - Build single transaction
376
+ - `buildApproval(...)` - Build approval transaction
377
+ - `getRequiredApprovals(route, sender)` - Get required approvals
378
+
379
+ ### MevProtection
380
+
381
+ - `protect(tx, signed, strategy, chain)` - Apply MEV protection
382
+ - `submitBundle(txs, block, chain)` - Submit Flashbots bundle
383
+ - `simulate(tx, chain)` - Simulate transaction
384
+ - `estimateMevRisk(tx, chain)` - Estimate MEV risk
385
+
386
+ ## License
387
+
388
+ Internal use only - T402 Protocol