@clawnch/clawncher-sdk 0.1.3 → 0.3.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 (63) hide show
  1. package/README.md +190 -0
  2. package/dist/analytics.d.ts +157 -0
  3. package/dist/analytics.d.ts.map +1 -0
  4. package/dist/analytics.js +468 -0
  5. package/dist/analytics.js.map +1 -0
  6. package/dist/api-deployer.d.ts.map +1 -1
  7. package/dist/api-deployer.js +38 -35
  8. package/dist/api-deployer.js.map +1 -1
  9. package/dist/claimer.d.ts.map +1 -1
  10. package/dist/claimer.js +9 -7
  11. package/dist/claimer.js.map +1 -1
  12. package/dist/errors.d.ts +13 -0
  13. package/dist/errors.d.ts.map +1 -1
  14. package/dist/errors.js +50 -0
  15. package/dist/errors.js.map +1 -1
  16. package/dist/index.d.ts +8 -0
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +16 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/liquidity.d.ts +13 -7
  21. package/dist/liquidity.d.ts.map +1 -1
  22. package/dist/liquidity.js +143 -46
  23. package/dist/liquidity.js.map +1 -1
  24. package/dist/orders.d.ts +338 -0
  25. package/dist/orders.d.ts.map +1 -0
  26. package/dist/orders.js +611 -0
  27. package/dist/orders.js.map +1 -0
  28. package/dist/permit2.d.ts +258 -0
  29. package/dist/permit2.d.ts.map +1 -0
  30. package/dist/permit2.js +520 -0
  31. package/dist/permit2.js.map +1 -0
  32. package/dist/price.d.ts +95 -0
  33. package/dist/price.d.ts.map +1 -0
  34. package/dist/price.js +207 -0
  35. package/dist/price.js.map +1 -0
  36. package/dist/swap.d.ts.map +1 -1
  37. package/dist/swap.js +21 -19
  38. package/dist/swap.js.map +1 -1
  39. package/dist/trader.d.ts +188 -0
  40. package/dist/trader.d.ts.map +1 -0
  41. package/dist/trader.js +277 -0
  42. package/dist/trader.js.map +1 -0
  43. package/dist/uniswap-abis.d.ts +525 -0
  44. package/dist/uniswap-abis.d.ts.map +1 -1
  45. package/dist/uniswap-abis.js +432 -1
  46. package/dist/uniswap-abis.js.map +1 -1
  47. package/dist/uniswap-chains.d.ts +77 -0
  48. package/dist/uniswap-chains.d.ts.map +1 -0
  49. package/dist/uniswap-chains.js +362 -0
  50. package/dist/uniswap-chains.js.map +1 -0
  51. package/dist/uniswap-quoter.d.ts +178 -0
  52. package/dist/uniswap-quoter.d.ts.map +1 -0
  53. package/dist/uniswap-quoter.js +432 -0
  54. package/dist/uniswap-quoter.js.map +1 -0
  55. package/dist/uniswap-trading.d.ts +203 -0
  56. package/dist/uniswap-trading.d.ts.map +1 -0
  57. package/dist/uniswap-trading.js +380 -0
  58. package/dist/uniswap-trading.js.map +1 -0
  59. package/dist/watcher.d.ts +117 -2
  60. package/dist/watcher.d.ts.map +1 -1
  61. package/dist/watcher.js +147 -2
  62. package/dist/watcher.js.map +1 -1
  63. package/package.json +3 -1
package/README.md CHANGED
@@ -319,6 +319,174 @@ import {
319
319
  } from '@clawnch/clawncher-sdk';
320
320
  ```
321
321
 
322
+ ## Uniswap V4 Trading API
323
+
324
+ Execute swaps via the Uniswap Trading API with automatic Permit2 approval handling. Supports all 15 Uniswap chains.
325
+
326
+ ```typescript
327
+ import { UniswapTradingApi } from '@clawnch/clawncher-sdk';
328
+
329
+ const trading = new UniswapTradingApi({
330
+ wallet,
331
+ publicClient,
332
+ chainId: 8453,
333
+ apiKey: process.env.UNISWAP_API_KEY,
334
+ slippageBps: 50, // 0.5%
335
+ });
336
+
337
+ // Full swap: check_approval → quote → swap (handles Permit2 automatically)
338
+ const result = await trading.swap({
339
+ tokenIn: NATIVE_TOKEN_ADDRESS,
340
+ tokenOut: '0xTokenAddress...',
341
+ amount: parseEther('0.01'),
342
+ });
343
+ console.log('Tx:', result.txHash);
344
+
345
+ // Quote only (no execution)
346
+ const quote = await trading.getQuote({
347
+ tokenIn: NATIVE_TOKEN_ADDRESS,
348
+ tokenOut: '0xTokenAddress...',
349
+ amount: parseEther('0.01'),
350
+ });
351
+ console.log('Output:', quote.quoteAmount, 'Impact:', quote.priceImpact);
352
+
353
+ // Generate Uniswap app deep link
354
+ const link = trading.getSwapDeepLink({
355
+ tokenIn: NATIVE_TOKEN_ADDRESS,
356
+ tokenOut: '0xTokenAddress...',
357
+ amount: parseEther('0.1'),
358
+ });
359
+ ```
360
+
361
+ The Trading API uses a 3-step flow: `POST /check_approval` → `POST /quote` → `POST /swap`. The `swap()` method handles all three steps including Permit2 approvals. Sign up for an API key at [hub.uniswap.org](https://hub.uniswap.org).
362
+
363
+ ## On-Chain V4 Quoter
364
+
365
+ Simulate swaps directly against V4 pools without an API key. Includes Clawnch-native pool discovery via the LP locker contract.
366
+
367
+ ```typescript
368
+ import { UniswapQuoter } from '@clawnch/clawncher-sdk';
369
+
370
+ const quoter = new UniswapQuoter({
371
+ publicClient,
372
+ chainId: 8453,
373
+ });
374
+
375
+ // One-call quote for any Clawnch token (auto-discovers pool key from LP locker)
376
+ const quote = await quoter.quoteClawnchToken(
377
+ '0xTokenAddress...',
378
+ parseEther('0.01'),
379
+ 'buy', // 'buy' = ETH→Token, 'sell' = Token→ETH
380
+ );
381
+ console.log('Output:', quote.quotedAmount);
382
+ console.log('Impact:', quote.priceImpact);
383
+ console.log('Hook:', quote.poolKey.hooks); // correct MEV hook, not zero address
384
+
385
+ // Build pool key from LP locker (includes hook address, fee, tick spacing)
386
+ const poolKey = await quoter.buildPoolKeyFromToken('0xTokenAddress...');
387
+
388
+ // Read pool state (sqrtPriceX96, tick, liquidity)
389
+ const state = await quoter.getPoolState(poolKey);
390
+
391
+ // Manual quote with explicit pool key
392
+ const manualQuote = await quoter.quoteExactInput({
393
+ poolKey,
394
+ zeroForOne: true,
395
+ amount: parseEther('0.01'),
396
+ });
397
+
398
+ // Estimate price impact without a full quote
399
+ const impact = await quoter.estimatePriceImpact(poolKey, parseEther('1'));
400
+ ```
401
+
402
+ `buildPoolKeyFromToken()` reads the LP locker via `ClawnchReader.getTokenRewards()` to auto-discover the correct pool key — including the MEV hook address. This is critical because defaulting the hook to the zero address targets the wrong pool for Clawnch tokens.
403
+
404
+ ## Permit2 Client
405
+
406
+ Manage token approvals for Uniswap V4 via the Permit2 contract. Supports both AllowanceTransfer (PositionManager) and SignatureTransfer (UniversalRouter).
407
+
408
+ ```typescript
409
+ import { Permit2Client, PERMIT2_ADDRESS } from '@clawnch/clawncher-sdk';
410
+
411
+ const permit2 = new Permit2Client({
412
+ wallet,
413
+ publicClient,
414
+ chainId: 8453,
415
+ });
416
+
417
+ // Full approval flow: ERC20→Permit2 + Permit2→spender
418
+ const { approvalTxHash, permitTxHash } = await permit2.ensurePermit2Allowance(
419
+ tokenAddress,
420
+ spenderAddress, // e.g. UniversalRouter
421
+ amount,
422
+ );
423
+
424
+ // Two-token approval for LP operations
425
+ await permit2.ensurePermit2AllowancePair(
426
+ token0, token1, positionManagerAddress, amount0, amount1,
427
+ );
428
+
429
+ // Check allowance state
430
+ const allowance = await permit2.getAllowance(tokenAddress, spenderAddress);
431
+ console.log('Amount:', allowance.amount, 'Expires:', allowance.expiration);
432
+
433
+ // Emergency lockdown — revoke all access
434
+ await permit2.lockdown([
435
+ { token: tokenA, spender: routerAddress },
436
+ { token: tokenB, spender: routerAddress },
437
+ ]);
438
+
439
+ // Sign off-chain permits (AllowanceTransfer)
440
+ const signed = await permit2.signPermitSingle({
441
+ token: tokenAddress,
442
+ spender: routerAddress,
443
+ });
444
+
445
+ // Sign off-chain permits (SignatureTransfer — bitmap nonces)
446
+ const nonce = await permit2.findUnusedNonce(0n);
447
+ const transfer = await permit2.signPermitTransferFrom({
448
+ token: tokenAddress,
449
+ amount: parseEther('1'),
450
+ spender: routerAddress,
451
+ nonce,
452
+ });
453
+ ```
454
+
455
+ Permit2 is deployed at `0x000000000022D473030F116dDEE9F6B43aC78BA3` on all chains.
456
+
457
+ ## Multi-Chain Uniswap Registry
458
+
459
+ Address registry for all 15 Uniswap-supported chains.
460
+
461
+ ```typescript
462
+ import {
463
+ getUniswapChain,
464
+ getAllUniswapChains,
465
+ getTradingApiChains,
466
+ getV4Chains,
467
+ chainIdFromSlug,
468
+ FEE_TIERS,
469
+ } from '@clawnch/clawncher-sdk';
470
+
471
+ // Get config for a specific chain
472
+ const base = getUniswapChain(8453);
473
+ console.log(base.v4UniversalRouter, base.weth, base.permit2);
474
+
475
+ // All chains with Trading API support
476
+ const tradingChains = getTradingApiChains(); // 15 chains
477
+
478
+ // All chains with V4 deployed
479
+ const v4Chains = getV4Chains();
480
+
481
+ // Resolve slug to chain ID
482
+ const chainId = chainIdFromSlug('arbitrum'); // 42161
483
+
484
+ // Fee tiers with tick spacing
485
+ FEE_TIERS.forEach(t => console.log(t.label, t.fee, t.tickSpacing));
486
+ ```
487
+
488
+ Supported chains: Ethereum, Base, Arbitrum, Optimism, Polygon, BNB Chain, Unichain, Avalanche, Celo, Blast, Zora, World Chain, Soneium, zkSync, Monad.
489
+
322
490
  ## Liquidity Management
323
491
 
324
492
  Manage Uniswap V3 and V4 liquidity positions on Base.
@@ -514,6 +682,28 @@ import type {
514
682
  UniswapV4Addresses,
515
683
  UniswapV3Addresses,
516
684
  CommonAddresses,
685
+ // Uniswap Trading API types
686
+ UniswapTradingConfig,
687
+ TradingSwapParams,
688
+ TradingQuote,
689
+ TradingSwapResult,
690
+ ApprovalCheckResult,
691
+ // Uniswap Quoter types
692
+ QuoterConfig,
693
+ PoolKey,
694
+ QuoteParams,
695
+ QuoteResult,
696
+ PoolState,
697
+ // Permit2 types
698
+ Permit2Config,
699
+ Permit2Allowance,
700
+ PermitSingleParams,
701
+ PermitBatchParams,
702
+ SignedPermitSingle,
703
+ SignedPermitBatch,
704
+ // Multi-chain registry types
705
+ UniswapChainConfig,
706
+ FeeTier,
517
707
  // Verified agent launch types
518
708
  ClawnchApiDeployer,
519
709
  ApiDeployerConfig,
@@ -0,0 +1,157 @@
1
+ /**
2
+ * ClawnchAnalytics — Price history aggregation and technical indicators.
3
+ *
4
+ * Builds OHLCV candles from on-chain swap events and computes basic
5
+ * technical indicators the agent can use for trading decisions.
6
+ *
7
+ * Indicators:
8
+ * - SMA (Simple Moving Average) — trend direction
9
+ * - EMA (Exponential Moving Average) — responsive trend
10
+ * - RSI (Relative Strength Index) — overbought/oversold
11
+ * - Bollinger Bands — volatility + mean reversion
12
+ * - VWAP (Volume-Weighted Average Price) — fair price
13
+ * - Volatility (annualized, from returns)
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const analytics = new ClawnchAnalytics();
18
+ *
19
+ * // Build candles from swap events
20
+ * const swaps = await watcher.getRecentSwaps(poolId, { fromBlock: 1000n });
21
+ * const candles = analytics.buildCandles(swaps, wethSide, '1h');
22
+ *
23
+ * // Compute indicators
24
+ * const sma20 = analytics.sma(candles, 20);
25
+ * const rsi14 = analytics.rsi(candles, 14);
26
+ * const bb = analytics.bollingerBands(candles, 20, 2);
27
+ *
28
+ * // Get a full analysis
29
+ * const analysis = analytics.analyze(candles);
30
+ * console.log(analysis.signal); // 'bullish' | 'bearish' | 'neutral'
31
+ * ```
32
+ */
33
+ import type { PoolSwapEvent } from './watcher.js';
34
+ export interface Candle {
35
+ /** Period start timestamp (ms) */
36
+ timestamp: number;
37
+ /** Opening price in ETH */
38
+ open: number;
39
+ /** Highest price in period */
40
+ high: number;
41
+ /** Lowest price in period */
42
+ low: number;
43
+ /** Closing price in ETH */
44
+ close: number;
45
+ /** Volume in ETH (absolute value of WETH side) */
46
+ volume: number;
47
+ /** Number of swaps in this candle */
48
+ swapCount: number;
49
+ }
50
+ export type CandleInterval = '5m' | '15m' | '1h' | '4h' | '1d';
51
+ export interface BollingerBand {
52
+ upper: number;
53
+ middle: number;
54
+ lower: number;
55
+ bandwidth: number;
56
+ }
57
+ export type Signal = 'strong_buy' | 'buy' | 'neutral' | 'sell' | 'strong_sell';
58
+ export interface MarketAnalysis {
59
+ /** Overall signal */
60
+ signal: Signal;
61
+ /** Signal strength 0-100 */
62
+ strength: number;
63
+ /** Individual indicator signals */
64
+ indicators: {
65
+ sma20: {
66
+ value: number;
67
+ signal: Signal;
68
+ };
69
+ sma50: {
70
+ value: number;
71
+ signal: Signal;
72
+ };
73
+ rsi14: {
74
+ value: number;
75
+ signal: Signal;
76
+ };
77
+ bollinger: {
78
+ band: BollingerBand;
79
+ signal: Signal;
80
+ };
81
+ vwap: {
82
+ value: number;
83
+ signal: Signal;
84
+ };
85
+ volatility: {
86
+ annualized: number;
87
+ signal: Signal;
88
+ };
89
+ };
90
+ /** Current price */
91
+ currentPrice: number;
92
+ /** Volume trend */
93
+ volumeTrend: 'increasing' | 'decreasing' | 'stable';
94
+ /** Human-readable summary for agent prompt */
95
+ summary: string;
96
+ }
97
+ export declare class ClawnchAnalytics {
98
+ /**
99
+ * Build OHLCV candles from raw swap events.
100
+ *
101
+ * @param swaps - Pool swap events (from ClawnchWatcher.getRecentSwaps)
102
+ * @param wethSide - Which side WETH is on in the pool (0 or 1)
103
+ * @param interval - Candle interval
104
+ * @param tokenDecimals - Token decimals (default 18)
105
+ * @returns Sorted candles (oldest first)
106
+ */
107
+ buildCandles(swaps: PoolSwapEvent[], wethSide: 0 | 1, interval?: CandleInterval, tokenDecimals?: number): Candle[];
108
+ /**
109
+ * Build candles from pre-priced data (e.g. from a price feed or manual entries).
110
+ * Useful when you already have timestamp + price data rather than raw swap events.
111
+ */
112
+ buildCandlesFromPrices(data: Array<{
113
+ timestamp: number;
114
+ price: number;
115
+ volume?: number;
116
+ }>, interval?: CandleInterval): Candle[];
117
+ /**
118
+ * Simple Moving Average over closing prices.
119
+ */
120
+ sma(candles: Candle[], period: number): number[];
121
+ /**
122
+ * Exponential Moving Average over closing prices.
123
+ */
124
+ ema(candles: Candle[], period: number): number[];
125
+ /**
126
+ * Relative Strength Index.
127
+ * RSI < 30 → oversold, RSI > 70 → overbought.
128
+ */
129
+ rsi(candles: Candle[], period?: number): number[];
130
+ /**
131
+ * Bollinger Bands (SMA ± k standard deviations).
132
+ */
133
+ bollingerBands(candles: Candle[], period?: number, k?: number): BollingerBand[];
134
+ /**
135
+ * Volume-Weighted Average Price.
136
+ */
137
+ vwap(candles: Candle[]): number;
138
+ /**
139
+ * Annualized volatility from closing prices.
140
+ * Uses log returns and scales to annual (assuming 24h candles for daily vol,
141
+ * or scaled by intervals per year).
142
+ */
143
+ volatility(candles: Candle[], interval?: CandleInterval): number;
144
+ /**
145
+ * Run all indicators and produce a combined signal + human summary.
146
+ */
147
+ analyze(candles: Candle[], interval?: CandleInterval): MarketAnalysis | null;
148
+ private smaFromValues;
149
+ private emaFromValues;
150
+ private signalFromSMA;
151
+ private signalFromRSI;
152
+ private signalFromBB;
153
+ private signalFromVWAP;
154
+ private signalFromVolatility;
155
+ private compositeSignal;
156
+ }
157
+ //# sourceMappingURL=analytics.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"analytics.d.ts","sourceRoot":"","sources":["../src/analytics.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAMlD,MAAM,WAAW,MAAM;IACrB,kCAAkC;IAClC,SAAS,EAAE,MAAM,CAAC;IAClB,2BAA2B;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,8BAA8B;IAC9B,IAAI,EAAE,MAAM,CAAC;IACb,6BAA6B;IAC7B,GAAG,EAAE,MAAM,CAAC;IACZ,2BAA2B;IAC3B,KAAK,EAAE,MAAM,CAAC;IACd,kDAAkD;IAClD,MAAM,EAAE,MAAM,CAAC;IACf,qCAAqC;IACrC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,MAAM,cAAc,GAAG,IAAI,GAAG,KAAK,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,CAAC;AAE/D,MAAM,WAAW,aAAa;IAC5B,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,EAAE,MAAM,CAAC;IACf,KAAK,EAAE,MAAM,CAAC;IACd,SAAS,EAAE,MAAM,CAAC;CACnB;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