sol-trade-sdk 0.1.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 (87) hide show
  1. package/README.md +390 -0
  2. package/dist/chunk-MMQAMIKR.mjs +3735 -0
  3. package/dist/chunk-NEZDFAYA.mjs +7744 -0
  4. package/dist/clients-VITWK7B6.mjs +1370 -0
  5. package/dist/index-1BK_FXsW.d.mts +2327 -0
  6. package/dist/index-1BK_FXsW.d.ts +2327 -0
  7. package/dist/index.d.mts +2659 -0
  8. package/dist/index.d.ts +2659 -0
  9. package/dist/index.js +13265 -0
  10. package/dist/index.mjs +562 -0
  11. package/dist/perf/index.d.mts +2 -0
  12. package/dist/perf/index.d.ts +2 -0
  13. package/dist/perf/index.js +3742 -0
  14. package/dist/perf/index.mjs +214 -0
  15. package/package.json +101 -0
  16. package/src/__tests__/complete_sdk.test.ts +354 -0
  17. package/src/__tests__/hotpath.test.ts +486 -0
  18. package/src/__tests__/nonce.test.ts +45 -0
  19. package/src/__tests__/sdk.test.ts +425 -0
  20. package/src/address-lookup/index.ts +197 -0
  21. package/src/cache/cache.ts +308 -0
  22. package/src/calc/index.ts +1058 -0
  23. package/src/calc/pumpfun.ts +124 -0
  24. package/src/common/bonding_curve.ts +272 -0
  25. package/src/common/compute-budget.ts +148 -0
  26. package/src/common/confirm-any-signature.ts +184 -0
  27. package/src/common/fast-timing.ts +481 -0
  28. package/src/common/fast_fn.ts +150 -0
  29. package/src/common/gas-fee-strategy.ts +253 -0
  30. package/src/common/map-pool.ts +23 -0
  31. package/src/common/nonce.ts +40 -0
  32. package/src/common/sdk-log.ts +460 -0
  33. package/src/common/seed.ts +381 -0
  34. package/src/common/spl-token.ts +578 -0
  35. package/src/common/subscription-handle.ts +644 -0
  36. package/src/common/trading-utils.ts +239 -0
  37. package/src/common/wsol-manager.ts +325 -0
  38. package/src/compute/compute_budget_manager.ts +187 -0
  39. package/src/compute/index.ts +21 -0
  40. package/src/constants/index.ts +96 -0
  41. package/src/execution/execution.ts +532 -0
  42. package/src/execution/index.ts +42 -0
  43. package/src/hotpath/executor.ts +464 -0
  44. package/src/hotpath/index.ts +64 -0
  45. package/src/hotpath/state.ts +435 -0
  46. package/src/index.ts +2117 -0
  47. package/src/instruction/bonk_builder.ts +730 -0
  48. package/src/instruction/index.ts +24 -0
  49. package/src/instruction/meteora_damm_v2_builder.ts +509 -0
  50. package/src/instruction/pumpfun_builder.ts +1183 -0
  51. package/src/instruction/pumpswap.ts +1123 -0
  52. package/src/instruction/raydium_amm_v4_builder.ts +692 -0
  53. package/src/instruction/raydium_cpmm_builder.ts +795 -0
  54. package/src/middleware/traits.ts +407 -0
  55. package/src/params/index.ts +483 -0
  56. package/src/perf/compiler-optimization.ts +529 -0
  57. package/src/perf/hardware.ts +631 -0
  58. package/src/perf/index.ts +9 -0
  59. package/src/perf/kernel-bypass.ts +656 -0
  60. package/src/perf/protocol.ts +682 -0
  61. package/src/perf/realtime.ts +592 -0
  62. package/src/perf/simd.ts +668 -0
  63. package/src/perf/syscall-bypass.ts +331 -0
  64. package/src/perf/ultra-low-latency.ts +505 -0
  65. package/src/perf/zero-copy.ts +589 -0
  66. package/src/pool/pool.ts +294 -0
  67. package/src/rpc/client.ts +345 -0
  68. package/src/sdk-errors.ts +13 -0
  69. package/src/security/index.ts +26 -0
  70. package/src/security/secure-key.ts +303 -0
  71. package/src/security/validators.ts +281 -0
  72. package/src/seed/pda.ts +262 -0
  73. package/src/serialization/index.ts +28 -0
  74. package/src/serialization/serialization.ts +288 -0
  75. package/src/swqos/clients.ts +1754 -0
  76. package/src/swqos/index.ts +50 -0
  77. package/src/swqos/providers.ts +1707 -0
  78. package/src/trading/core/async-executor.ts +702 -0
  79. package/src/trading/core/confirmation-monitor.ts +711 -0
  80. package/src/trading/core/index.ts +82 -0
  81. package/src/trading/core/retry-handler.ts +683 -0
  82. package/src/trading/core/transaction-pool.ts +780 -0
  83. package/src/trading/executor.ts +385 -0
  84. package/src/trading/factory.ts +282 -0
  85. package/src/trading/index.ts +30 -0
  86. package/src/types.ts +8 -0
  87. package/src/utils/index.ts +155 -0
@@ -0,0 +1,214 @@
1
+ import {
2
+ AlignedBuffer,
3
+ AsyncSocket,
4
+ BranchOptimizer,
5
+ BufferPool,
6
+ CACHE_LINE_SIZE,
7
+ CPUAffinity,
8
+ CacheOptimizer,
9
+ ComputeBudgetOptimizer,
10
+ CryptoSIMD,
11
+ DirectIOFile,
12
+ FastTimeProvider,
13
+ FixedBufferView,
14
+ Float32x4,
15
+ FuncCache,
16
+ HardwareMonitor,
17
+ IOBatchProcessor,
18
+ IOOperation,
19
+ InstructionBatcher,
20
+ KernelBypassManager,
21
+ LatencyMonitor,
22
+ LatencyOptimizer,
23
+ LockFreeQueue,
24
+ LoopOptimizer,
25
+ MPMCQueue,
26
+ MemoryMappedFile,
27
+ MemoryOps,
28
+ MemoryPool,
29
+ NUMAOptimizer,
30
+ OptimizedMath,
31
+ PerformanceGovernor,
32
+ ProfileGuidedOptimizer,
33
+ RealtimeTuner,
34
+ SIMDDetector,
35
+ SchedulerPolicy,
36
+ SpinLock,
37
+ SyscallBypassManager,
38
+ ThreadPriority,
39
+ ThreadPriorityLevel,
40
+ TransactionBuilder,
41
+ TransactionOptimizer,
42
+ VectorizedMath,
43
+ ZeroCopyBuffer,
44
+ ZeroCopySerializer,
45
+ busySpin,
46
+ busyWait,
47
+ calculateOptimalPrice,
48
+ coldPath,
49
+ copyBytes,
50
+ createBufferPool,
51
+ createCPUAffinity,
52
+ createCacheOptimizer,
53
+ createComputeBudgetOptimizer,
54
+ createCryptoSIMD,
55
+ createHardwareMonitor,
56
+ createInstructionBatcher,
57
+ createLatencyMonitor,
58
+ createLockFreeQueue,
59
+ createMPMCQueue,
60
+ createMemoryPool,
61
+ createNUMAOptimizer,
62
+ createPerformanceGovernor,
63
+ createRealtimeTuner,
64
+ createSIMDDetector,
65
+ createSerializer,
66
+ createSyscallBypassManager,
67
+ createThreadPriority,
68
+ createTimer,
69
+ createTransactionBuilder,
70
+ createTransactionOptimizer,
71
+ createVectorizedMath,
72
+ createView,
73
+ createZeroCopyBuffer,
74
+ defaultAffinityConfig,
75
+ defaultBufferPoolConfig,
76
+ defaultIOUringConfig,
77
+ defaultJITConfig,
78
+ defaultNUMAConfig,
79
+ defaultRealtimeConfig,
80
+ defaultSIMDConfig,
81
+ defaultSyscallBypassConfig,
82
+ defaultTransactionConfig,
83
+ defaultUltraLowLatencyConfig,
84
+ detectCPUFeatures,
85
+ estimateCompute,
86
+ fastInvSqrt,
87
+ fastNowMs,
88
+ fastNowNs,
89
+ fastNowUs,
90
+ getGlobalTimeProvider,
91
+ getKernelBypassManager,
92
+ getOptimalSIMDWidth,
93
+ getProfileOptimizer,
94
+ getSystemCPUInfo,
95
+ getSystemMemoryInfo,
96
+ hotPath,
97
+ isSIMDAvailable,
98
+ likely,
99
+ measureTime,
100
+ prefetch,
101
+ prefetchArray,
102
+ prefetchHint,
103
+ profile,
104
+ spinLock,
105
+ unlikely,
106
+ yieldToEventLoop
107
+ } from "../chunk-MMQAMIKR.mjs";
108
+ export {
109
+ AlignedBuffer,
110
+ AsyncSocket,
111
+ BranchOptimizer,
112
+ BufferPool,
113
+ CACHE_LINE_SIZE,
114
+ CPUAffinity,
115
+ CacheOptimizer,
116
+ ComputeBudgetOptimizer,
117
+ CryptoSIMD,
118
+ DirectIOFile,
119
+ FastTimeProvider,
120
+ FixedBufferView,
121
+ Float32x4,
122
+ FuncCache,
123
+ HardwareMonitor,
124
+ IOBatchProcessor,
125
+ IOOperation,
126
+ InstructionBatcher,
127
+ KernelBypassManager,
128
+ LatencyMonitor,
129
+ LatencyOptimizer,
130
+ LockFreeQueue,
131
+ LoopOptimizer,
132
+ MPMCQueue,
133
+ MemoryMappedFile,
134
+ MemoryOps,
135
+ MemoryPool,
136
+ NUMAOptimizer,
137
+ OptimizedMath,
138
+ PerformanceGovernor,
139
+ ProfileGuidedOptimizer,
140
+ RealtimeTuner,
141
+ SIMDDetector,
142
+ SchedulerPolicy,
143
+ SpinLock,
144
+ SyscallBypassManager,
145
+ ThreadPriority,
146
+ ThreadPriorityLevel,
147
+ TransactionBuilder,
148
+ TransactionOptimizer,
149
+ VectorizedMath,
150
+ ZeroCopyBuffer,
151
+ ZeroCopySerializer,
152
+ busySpin,
153
+ busyWait,
154
+ calculateOptimalPrice,
155
+ coldPath,
156
+ copyBytes,
157
+ createBufferPool,
158
+ createCPUAffinity,
159
+ createCacheOptimizer,
160
+ createComputeBudgetOptimizer,
161
+ createCryptoSIMD,
162
+ createHardwareMonitor,
163
+ createInstructionBatcher,
164
+ createLatencyMonitor,
165
+ createLockFreeQueue,
166
+ createMPMCQueue,
167
+ createMemoryPool,
168
+ createNUMAOptimizer,
169
+ createPerformanceGovernor,
170
+ createRealtimeTuner,
171
+ createSIMDDetector,
172
+ createSerializer,
173
+ createSyscallBypassManager,
174
+ createThreadPriority,
175
+ createTimer,
176
+ createTransactionBuilder,
177
+ createTransactionOptimizer,
178
+ createVectorizedMath,
179
+ createView,
180
+ createZeroCopyBuffer,
181
+ defaultAffinityConfig,
182
+ defaultBufferPoolConfig,
183
+ defaultIOUringConfig,
184
+ defaultJITConfig,
185
+ defaultNUMAConfig,
186
+ defaultRealtimeConfig,
187
+ defaultSIMDConfig,
188
+ defaultSyscallBypassConfig,
189
+ defaultTransactionConfig,
190
+ defaultUltraLowLatencyConfig,
191
+ detectCPUFeatures,
192
+ estimateCompute,
193
+ fastInvSqrt,
194
+ fastNowMs,
195
+ fastNowNs,
196
+ fastNowUs,
197
+ getGlobalTimeProvider,
198
+ getKernelBypassManager,
199
+ getOptimalSIMDWidth,
200
+ getProfileOptimizer,
201
+ getSystemCPUInfo,
202
+ getSystemMemoryInfo,
203
+ hotPath,
204
+ isSIMDAvailable,
205
+ likely,
206
+ measureTime,
207
+ prefetch,
208
+ prefetchArray,
209
+ prefetchHint,
210
+ profile,
211
+ spinLock,
212
+ unlikely,
213
+ yieldToEventLoop
214
+ };
package/package.json ADDED
@@ -0,0 +1,101 @@
1
+ {
2
+ "name": "sol-trade-sdk",
3
+ "version": "0.1.0",
4
+ "description": "High-performance Solana trading SDK with multi-protocol support",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ },
14
+ "./cache": {
15
+ "types": "./dist/cache/index.d.ts",
16
+ "import": "./dist/cache/index.mjs",
17
+ "require": "./dist/cache/index.js"
18
+ },
19
+ "./pool": {
20
+ "types": "./dist/pool/index.d.ts",
21
+ "import": "./dist/pool/index.mjs",
22
+ "require": "./dist/pool/index.js"
23
+ },
24
+ "./rpc": {
25
+ "types": "./dist/rpc/index.d.ts",
26
+ "import": "./dist/rpc/index.mjs",
27
+ "require": "./dist/rpc/index.js"
28
+ },
29
+ "./swqos": {
30
+ "types": "./dist/swqos/index.d.ts",
31
+ "import": "./dist/swqos/index.mjs",
32
+ "require": "./dist/swqos/index.js"
33
+ },
34
+ "./trading": {
35
+ "types": "./dist/trading/index.d.ts",
36
+ "import": "./dist/trading/index.mjs",
37
+ "require": "./dist/trading/index.js"
38
+ },
39
+ "./perf": {
40
+ "types": "./dist/perf/index.d.ts",
41
+ "import": "./dist/perf/index.mjs",
42
+ "require": "./dist/perf/index.js"
43
+ }
44
+ },
45
+ "files": [
46
+ "dist",
47
+ "src"
48
+ ],
49
+ "scripts": {
50
+ "build": "tsup src/index.ts src/perf/index.ts --format cjs,esm --dts --clean",
51
+ "dev": "tsup src/index.ts src/perf/index.ts --format cjs,esm --dts --watch",
52
+ "test": "vitest run",
53
+ "test:watch": "vitest",
54
+ "test:coverage": "vitest run --coverage",
55
+ "lint": "eslint src --ext .ts",
56
+ "lint:fix": "eslint src --ext .ts --fix",
57
+ "typecheck": "tsc --noEmit",
58
+ "prepublishOnly": "npm run build"
59
+ },
60
+ "keywords": [
61
+ "solana",
62
+ "trading",
63
+ "dex",
64
+ "blockchain",
65
+ "defi",
66
+ "pumpfun",
67
+ "raydium",
68
+ "meteora",
69
+ "swqos"
70
+ ],
71
+ "author": "Sol Trade SDK Team",
72
+ "license": "MIT",
73
+ "repository": {
74
+ "type": "git",
75
+ "url": "https://github.com/0xfnzero/sol-trade-sdk-ts"
76
+ },
77
+ "dependencies": {
78
+ "@matrixai/quic": "^2.0.9",
79
+ "@solana/spl-token": "^0.4.6",
80
+ "@solana/web3.js": "^1.91.0",
81
+ "bn.js": "^5.2.1",
82
+ "borsh": "^0.7.0",
83
+ "bs58": "^5.0.0",
84
+ "selfsigned": "^5.5.0",
85
+ "tweetnacl": "^1.0.3"
86
+ },
87
+ "devDependencies": {
88
+ "@types/bn.js": "^5.1.5",
89
+ "@types/node": "^20.11.0",
90
+ "@typescript-eslint/eslint-plugin": "^7.0.0",
91
+ "@typescript-eslint/parser": "^7.0.0",
92
+ "eslint": "^8.56.0",
93
+ "tsup": "^8.0.0",
94
+ "typescript": "^5.3.0",
95
+ "vitest": "^1.2.0"
96
+ },
97
+ "engines": {
98
+ "node": ">=18.0.0"
99
+ },
100
+ "sideEffects": false
101
+ }
@@ -0,0 +1,354 @@
1
+ /**
2
+ * Comprehensive Test Suite for Sol Trade SDK - TypeScript
3
+ * Tests all modules with performance benchmarks.
4
+ */
5
+
6
+ import { describe, it, expect, beforeEach } from 'vitest';
7
+
8
+ // Import all modules
9
+ import {
10
+ GasFeeStrategy,
11
+ GasFeeStrategyType,
12
+ createGasFeeStrategy,
13
+ SwqosType,
14
+ TradeType,
15
+ } from '../index';
16
+
17
+ import {
18
+ LRUCache,
19
+ TTLCache,
20
+ ShardedCache,
21
+ blockhashCache,
22
+ accountCache,
23
+ priceCache,
24
+ } from '../cache/cache';
25
+
26
+ import {
27
+ WorkerPool,
28
+ RateLimiter,
29
+ MultiRateLimiter,
30
+ ConnectionPool,
31
+ ObjectPool,
32
+ } from '../pool/pool';
33
+
34
+ import {
35
+ computeFee,
36
+ ceilDiv,
37
+ calculateWithSlippageBuy,
38
+ calculateWithSlippageSell,
39
+ getBuyTokenAmountFromSolAmount,
40
+ getSellSolAmountFromTokenAmount,
41
+ } from '../calc';
42
+
43
+ // ===== Gas Fee Strategy Tests =====
44
+
45
+ describe('GasFeeStrategy', () => {
46
+ let strategy: GasFeeStrategy;
47
+
48
+ beforeEach(() => {
49
+ strategy = new GasFeeStrategy();
50
+ });
51
+
52
+ it('should create a gas fee strategy', () => {
53
+ expect(strategy).toBeDefined();
54
+ });
55
+
56
+ it('should set and get a strategy', () => {
57
+ strategy.set(
58
+ SwqosType.Jito,
59
+ TradeType.Buy,
60
+ GasFeeStrategyType.Normal,
61
+ 200000,
62
+ 100000,
63
+ 0.001
64
+ );
65
+
66
+ const value = strategy.get(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal);
67
+ expect(value).toBeDefined();
68
+ expect(value?.cuLimit).toBe(200000);
69
+ expect(value?.cuPrice).toBe(100000);
70
+ expect(value?.tip).toBe(0.001);
71
+ });
72
+
73
+ it('should set global fee strategy', () => {
74
+ const globalStrategy = createGasFeeStrategy();
75
+
76
+ // Set global fee strategy first
77
+ globalStrategy.setGlobalFeeStrategy(
78
+ 200000, 200000, // buy/sell CU limit
79
+ 100000, 100000, // buy/sell CU price
80
+ 100000, 100000 // buy/sell tip
81
+ );
82
+
83
+ const jitoValue = globalStrategy.get(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal);
84
+ expect(jitoValue).toBeDefined();
85
+ expect(jitoValue?.cuLimit).toBe(200000);
86
+ });
87
+
88
+ it('should update buy tip for all strategies', () => {
89
+ strategy.set(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal, 200000, 100000, 0.001);
90
+ strategy.set(SwqosType.Jito, TradeType.Sell, GasFeeStrategyType.Normal, 200000, 100000, 0.002);
91
+
92
+ strategy.updateBuyTip(0.005);
93
+
94
+ const buyValue = strategy.get(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal);
95
+ const sellValue = strategy.get(SwqosType.Jito, TradeType.Sell, GasFeeStrategyType.Normal);
96
+
97
+ expect(buyValue?.tip).toBe(0.005);
98
+ expect(sellValue?.tip).toBe(0.002);
99
+ });
100
+
101
+ it('should delete a strategy', () => {
102
+ strategy.set(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal, 200000, 100000, 0.001);
103
+ strategy.delete(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal);
104
+
105
+ const value = strategy.get(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal);
106
+ expect(value).toBeUndefined();
107
+ });
108
+
109
+ it('should resolve conflicts when setting Normal strategy', () => {
110
+ strategy.set(
111
+ SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.LowTipHighCuPrice,
112
+ 200000, 100000, 0.0005
113
+ );
114
+ strategy.set(
115
+ SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal,
116
+ 200000, 100000, 0.001
117
+ );
118
+
119
+ const low = strategy.get(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.LowTipHighCuPrice);
120
+ const normal = strategy.get(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal);
121
+
122
+ expect(low).toBeUndefined();
123
+ expect(normal).toBeDefined();
124
+ });
125
+ });
126
+
127
+ // ===== Cache Tests =====
128
+
129
+ describe('LRUCache', () => {
130
+ it('should set and get values', () => {
131
+ const cache = new LRUCache<string, number>(3, 60000);
132
+
133
+ cache.set('a', 1);
134
+ cache.set('b', 2);
135
+ cache.set('c', 3);
136
+
137
+ expect(cache.get('a')).toBe(1);
138
+ expect(cache.get('b')).toBe(2);
139
+ expect(cache.get('c')).toBe(3);
140
+ });
141
+
142
+ it('should evict LRU entries', () => {
143
+ const cache = new LRUCache<string, number>(2, 60000);
144
+
145
+ cache.set('a', 1);
146
+ cache.set('b', 2);
147
+ cache.set('c', 3); // Should evict 'a'
148
+
149
+ expect(cache.get('a')).toBeUndefined();
150
+ expect(cache.get('b')).toBe(2);
151
+ expect(cache.get('c')).toBe(3);
152
+ });
153
+
154
+ it('should track statistics', () => {
155
+ const cache = new LRUCache<string, number>(10, 60000);
156
+
157
+ cache.set('a', 1);
158
+ cache.get('a'); // hit
159
+ cache.get('b'); // miss
160
+
161
+ const stats = cache.getStats();
162
+ expect(stats.hits).toBe(1);
163
+ expect(stats.misses).toBe(1);
164
+ expect(stats.hitRate).toBeCloseTo(0.5);
165
+ });
166
+ });
167
+
168
+ describe('TTLCache', () => {
169
+ it('should expire entries', async () => {
170
+ const cache = new TTLCache<string, number>(100); // 100ms
171
+
172
+ cache.set('a', 1);
173
+ expect(cache.get('a')).toBe(1);
174
+
175
+ await new Promise(resolve => setTimeout(resolve, 150));
176
+ expect(cache.get('a')).toBeUndefined();
177
+ });
178
+ });
179
+
180
+ describe('ShardedCache', () => {
181
+ it('should distribute keys across shards', () => {
182
+ const cache = new ShardedCache<string, number>(4, 100, 60000);
183
+
184
+ for (let i = 0; i < 10; i++) {
185
+ cache.set(`key_${i}`, i);
186
+ }
187
+
188
+ for (let i = 0; i < 10; i++) {
189
+ expect(cache.get(`key_${i}`)).toBe(i);
190
+ }
191
+ });
192
+ });
193
+
194
+ // ===== Pool Tests =====
195
+
196
+ describe('WorkerPool', () => {
197
+ it('should execute tasks', async () => {
198
+ const pool = new WorkerPool(4);
199
+
200
+ const result = await pool.submit(async () => 42);
201
+ expect(result).toBe(42);
202
+
203
+ const stats = pool.getStats();
204
+ expect(stats.tasksCompleted).toBe(1);
205
+ });
206
+
207
+ it('should execute batch tasks', async () => {
208
+ const pool = new WorkerPool(4);
209
+
210
+ const tasks = [1, 2, 3, 4, 5].map(n => async () => n * 2);
211
+ const results = await pool.submitBatch(tasks);
212
+
213
+ expect(results).toEqual([2, 4, 6, 8, 10]);
214
+ });
215
+ });
216
+
217
+ describe('RateLimiter', () => {
218
+ it('should allow burst', () => {
219
+ const limiter = new RateLimiter(100, 10);
220
+
221
+ // Should allow burst
222
+ for (let i = 0; i < 10; i++) {
223
+ expect(limiter.allow()).toBe(true);
224
+ }
225
+
226
+ // Should be rate limited
227
+ expect(limiter.allow()).toBe(false);
228
+ });
229
+ });
230
+
231
+ describe('MultiRateLimiter', () => {
232
+ it('should have separate limits per key', () => {
233
+ const limiter = new MultiRateLimiter(10, 5);
234
+
235
+ // Exhaust key1
236
+ for (let i = 0; i < 5; i++) {
237
+ limiter.allow('key1');
238
+ }
239
+
240
+ expect(limiter.allow('key1')).toBe(false);
241
+ expect(limiter.allow('key2')).toBe(true);
242
+ });
243
+ });
244
+
245
+ // ===== Calculation Tests =====
246
+
247
+ describe('Calculations', () => {
248
+ it('should compute fee correctly', () => {
249
+ const fee = computeFee(1000000n, 100n, 10000n); // 1%
250
+ expect(fee).toBe(10000n);
251
+ });
252
+
253
+ it('should perform ceiling division', () => {
254
+ expect(ceilDiv(10n, 3n)).toBe(4n);
255
+ expect(ceilDiv(9n, 3n)).toBe(3n);
256
+ expect(ceilDiv(11n, 3n)).toBe(4n);
257
+ });
258
+
259
+ it('should calculate with slippage for buy', () => {
260
+ const result = calculateWithSlippageBuy(1000n, 100n); // 1%
261
+ expect(result).toBe(1010n);
262
+ });
263
+
264
+ it('should calculate with slippage for sell', () => {
265
+ const result = calculateWithSlippageSell(1000n, 100n); // 1%
266
+ expect(result).toBe(990n);
267
+ });
268
+
269
+ it('should calculate PumpFun buy output', () => {
270
+ const tokens = getBuyTokenAmountFromSolAmount(
271
+ 1000000n, // 0.001 SOL
272
+ 30000000000n,
273
+ 1073000000000000n,
274
+ false, // hasCreator
275
+ 793000000000000n
276
+ );
277
+ expect(tokens > 0n).toBe(true);
278
+ });
279
+
280
+ it('should calculate PumpFun sell output', () => {
281
+ const sol = getSellSolAmountFromTokenAmount(
282
+ 1000000000n, // 1 million tokens
283
+ 30000000000n,
284
+ 1073000000000000n,
285
+ 1000000000n
286
+ );
287
+ expect(sol > 0n).toBe(true);
288
+ });
289
+ });
290
+
291
+ // ===== Performance Benchmarks =====
292
+
293
+ describe('Performance Benchmarks', () => {
294
+ it('LRU cache should be fast', () => {
295
+ const cache = new LRUCache<string, number>(10000, 60000);
296
+
297
+ // Set performance
298
+ const setStart = performance.now();
299
+ for (let i = 0; i < 10000; i++) {
300
+ cache.set(`key_${i}`, i);
301
+ }
302
+ const setTime = performance.now() - setStart;
303
+
304
+ // Get performance
305
+ const getStart = performance.now();
306
+ for (let i = 0; i < 10000; i++) {
307
+ cache.get(`key_${i}`);
308
+ }
309
+ const getTime = performance.now() - getStart;
310
+
311
+ console.log(`\nLRU Cache - Set: ${setTime.toFixed(2)}ms, Get: ${getTime.toFixed(2)}ms`);
312
+
313
+ expect(setTime).toBeLessThan(500); // Under 500ms for 10k ops
314
+ expect(getTime).toBeLessThan(500);
315
+ });
316
+
317
+ it('Calculations should be fast', () => {
318
+ const start = performance.now();
319
+ for (let i = 0; i < 100000; i++) {
320
+ getBuyTokenAmountFromSolAmount(
321
+ 1000000n,
322
+ 30000000000n,
323
+ 1073000000000000n,
324
+ false,
325
+ 793000000000000n
326
+ );
327
+ }
328
+ const elapsed = performance.now() - start;
329
+
330
+ console.log(`\nCalculations - 100k ops: ${elapsed.toFixed(2)}ms`);
331
+ expect(elapsed).toBeLessThan(1000); // Under 1 second
332
+ });
333
+
334
+ it('Gas strategy should be fast', () => {
335
+ const strategy = new GasFeeStrategy();
336
+
337
+ const start = performance.now();
338
+ for (let i = 0; i < 10000; i++) {
339
+ strategy.set(
340
+ SwqosType.Jito,
341
+ TradeType.Buy,
342
+ GasFeeStrategyType.Normal,
343
+ 200000,
344
+ 100000,
345
+ 0.001
346
+ );
347
+ strategy.get(SwqosType.Jito, TradeType.Buy, GasFeeStrategyType.Normal);
348
+ }
349
+ const elapsed = performance.now() - start;
350
+
351
+ console.log(`\nGas Strategy - 10k set/get: ${elapsed.toFixed(2)}ms`);
352
+ expect(elapsed).toBeLessThan(500);
353
+ });
354
+ });