# Track Specification: Package Enhancement - Add Helper Modules and ABIs

## Overview

This track enhances the `test-uniswap-position-quoter` package to become a complete, self-contained swap calculation library by integrating helper modules and ABIs from the `serverless-strategy-tx-processor` project. The enhancement will eliminate the need for consuming projects (like Cortex) to implement their own data extraction and contract management logic.

**Track Type:** Feature Enhancement  
**Priority:** High  
**Estimated Complexity:** Large  
**Breaking Change:** Yes (v2.0.0)

## Functional Requirements

### 1. ABI Integration

**Requirement:** Copy and integrate 22 ABI files from `serverless-strategy-tx-processor` into the package.

**ABIs to Include:**
- **Pool ABIs (7):** IUniswapV3Pool, IQuickSwapV3Pool, AlgebraIntegralPool, AlgebraV3UniDirectionalPool, LimitPool, MachineXV3Pool, AerodromV3Pool
- **Factory ABIs (4):** UniswapV3Factory, QuickSwapFactory, AlgebraIntegralFactory, LimitPoolFactory
- **Quoter ABIs (8):** QuoterV2, QuickSwapQuoterV2, AlgebraIntegralCustomRouter, QuoterV2AlgebraIntegral19, QuoterV2Shadow, QuoterV2Lynex, QuoterV2Thick, QuoterV2Aerodrom
- **Vault ABIs (3):** SinglePositionLiquidityManager, MultiPositionLiquidityManager, SinglePostionVaultOld, MultiPositionLiquidityManagerOld
- **Steer ABIs (1):** SteerPeriphery

**Acceptance Criteria:**
- All 22 ABI files are copied to `src/abis/` with proper subdirectory organization
- TypeScript type definitions are generated for all ABIs
- ABIs are exported from `src/abis/index.ts`
- Package build includes ABI files in distribution

### 2. Helper Module: AbiManager

**Requirement:** Port `AbiManager` class for protocol-specific ABI resolution.

**Responsibilities:**
- Resolve pool ABIs based on protocol (9 protocols supported)
- Resolve factory ABIs based on protocol
- Resolve quoter ABIs based on protocol
- Resolve vault ABIs (multi/single position, upgraded/old variants)
- Resolve SteerPeriphery ABI

**Acceptance Criteria:**
- `AbiManager` class is implemented in `src/helpers/AbiManager.ts`
- All protocol-specific ABI resolution methods work correctly
- Unit tests cover all 9 protocols
- Integration with `ProtocolDetector` for protocol identification

### 3. Helper Module: ProtocolDetector

**Requirement:** Port `ProtocolDetector` class for identifying DEX protocols from beacon names.

**Responsibilities:**
- Detect Uniswap V3/V4 protocols
- Detect Algebra variants (Integral, Integral 1.9, UniDirectional)
- Detect PoolShark (LimitPool)
- Detect ThickV2
- Detect Shadow
- Detect Aerodrome
- Detect MachineX V3
- Provide unified `getProtocol()` method

**Acceptance Criteria:**
- `ProtocolDetector` class is implemented in `src/helpers/ProtocolDetector.ts`
- All protocol detection methods work correctly
- Unit tests cover all supported protocols
- Edge cases (unknown protocols) are handled gracefully

### 4. Helper Module: ContractFactory

**Requirement:** Create `ContractFactory` class for ethers.js contract instantiation.

**Responsibilities:**
- Create pool contracts for all protocols
- Create quoter contracts for all protocols
- Create vault contracts with upgrade detection
- Create factory contracts for all protocols
- Create SteerPeriphery contracts
- Handle protocol-specific contract creation logic

**Acceptance Criteria:**
- `ContractFactory` class is implemented in `src/helpers/ContractFactory.ts`
- All contract creation methods work with ethers.js signers
- Unit tests cover all contract types and protocols
- Error handling for invalid addresses and missing ABIs

### 5. Helper Module: PositionExtractor

**Requirement:** Port `PositionExtractor` class for extracting position data from execution results and vault contracts.

**Responsibilities:**
- Extract new positions from `executionResult.valuesArray[1]`
- Query current vault positions for multi-position vaults
- Query current vault positions for single-position vaults
- Convert raw position data to `Position[]` format

**Acceptance Criteria:**
- `PositionExtractor` class is implemented in `src/helpers/PositionExtractor.ts`
- Handles both multi-position and single-position vaults
- Unit tests cover various execution result formats
- Edge cases (empty positions, malformed data) are handled

### 6. Helper Module: BalanceQuerier

**Requirement:** Port `BalanceQuerier` class for querying vault token balances.

**Responsibilities:**
- Query balances via SteerPeriphery for most protocols
- Query balances directly from vault for PoolShark, Blackhole, Aerodrome
- Handle protocol-specific balance query logic
- Return balances as `{ token0: BigNumber, token1: BigNumber }`

**Acceptance Criteria:**
- `BalanceQuerier` class is implemented in `src/helpers/BalanceQuerier.ts`
- Supports both SteerPeriphery and direct vault queries
- Unit tests cover all protocol-specific balance handling
- Error handling for failed queries

### 7. Helper Module: PoolStateQuerier

**Requirement:** Port `PoolStateQuerier` class for querying pool state (slot0/globalState).

**Responsibilities:**
- Query `slot0()` for Uniswap-based protocols
- Query `globalState()` for Algebra-based protocols
- Extract `sqrtPriceX96` from both formats
- Query `tickSpacing()` for ThickV2
- Handle protocol-specific state query logic

**Acceptance Criteria:**
- `PoolStateQuerier` class is implemented in `src/helpers/PoolStateQuerier.ts`
- Supports both Uniswap and Algebra pool state formats
- Unit tests cover all protocol-specific state handling
- Error handling for failed queries

### 8. Helper Module: ProtocolConfig

**Requirement:** Port `ProtocolConfig` module for protocol-specific configuration keys.

**Responsibilities:**
- Map beacon names to protocol config keys
- Provide factory and quoter config keys for each protocol
- Support fallback to default Uniswap config

**Acceptance Criteria:**
- `ProtocolConfig` module is implemented in `src/helpers/ProtocolConfig.ts`
- `PROTOCOL_CONFIG_MAP` is ported from serverless
- `getProtocolConfigKeys()` function works for all protocols
- Unit tests cover all protocol mappings

### 9. SwapCalculator Orchestrator

**Requirement:** Create high-level `SwapCalculator` class that orchestrates all helpers and existing routers.

**Responsibilities:**
- Accept high-level parameters (signer, vault address, beacon name, execution result, etc.)
- Orchestrate all helper modules to extract data
- Create required contracts via `ContractFactory`
- Detect protocol via `ProtocolDetector`
- Extract positions via `PositionExtractor`
- Query balances via `BalanceQuerier`
- Query pool state via `PoolStateQuerier`
- Use existing `CustomRouterFactory` to create protocol-specific router
- Call router's `getSwapAmount()` with prepared data
- Apply slippage to calculated `sqrtPrice`
- Handle `skipSwap` and `specifySwap` flags
- Implement fallback logic for unsupported networks
- Return comprehensive swap result

**Interface:**
```typescript
class SwapCalculator {
  async calculateSwapForVault(params: SwapCalculationParams): Promise<SwapCalculationResult>
}

interface SwapCalculationParams {
  signer: ethers.Signer
  vaultAddress: string
  beaconName: string
  token0: string
  token1: string
  fee?: number
  quoterAddress: string
  steerPeripheryAddress: string
  executionResult: any
  slippage: number
  chainName: string
  maxIterations?: number
  ratioErrorTolerance?: Fraction
}

interface SwapCalculationResult {
  amount: string
  zeroForOne: boolean
  sqrtPrice: string
  usedForking: boolean
  skipSwap: boolean
  specifySwap: boolean
  newPositions?: Position[]
}
```

**Acceptance Criteria:**
- `SwapCalculator` class is implemented in `src/SwapCalculator.ts`
- All helper modules are properly orchestrated
- Integration with existing `CustomRouterFactory` works
- Handles all 9 supported protocols
- Unit tests cover all orchestration logic
- Integration tests cover end-to-end scenarios
- Error handling for all failure modes
- Fallback logic works for unsupported networks

### 10. API and Documentation

**Requirement:** Export all new modules and provide comprehensive documentation.

**Acceptance Criteria:**
- `SwapCalculator` is exported from `src/index.ts`
- All helper modules are exported (for advanced usage)
- All new types are exported
- Existing exports remain unchanged (backward compatible exports)
- JSDoc documentation for all public APIs
- README updated with v2.0.0 features
- Usage examples for both high-level and granular APIs
- Migration guide from v1.x to v2.0.0

## Non-Functional Requirements

### Performance
- Swap calculation should complete in <5 seconds for typical scenarios
- No significant performance degradation compared to v1.x for existing use cases
- Bundle size increase should be <500KB

### Code Quality
- Test coverage >80% for all new code
- All code follows existing project style (ESLint/Prettier)
- No TypeScript errors or warnings
- All dependencies are properly declared

### Compatibility
- Breaking change: v2.0.0 (major version bump)
- Node.js >=16.x
- ethers.js v5.x (existing dependency)
- Compatible with all 9 supported protocols

## Acceptance Criteria

### Phase 1: ABI Integration
- [ ] All 22 ABI files are copied and organized
- [ ] TypeScript types are generated
- [ ] ABIs are exported and accessible
- [ ] Package builds successfully with ABIs

### Phase 2: Helper Modules
- [ ] All 7 helper modules are implemented
- [ ] Unit tests pass for all helpers
- [ ] Test coverage >80% for helpers
- [ ] All protocol-specific logic works correctly

### Phase 3: SwapCalculator Orchestrator
- [ ] `SwapCalculator` class is implemented
- [ ] All helpers are properly orchestrated
- [ ] Integration with existing routers works
- [ ] Unit and integration tests pass
- [ ] Test coverage >80%

### Phase 4: API and Documentation
- [ ] All modules are exported correctly
- [ ] JSDoc documentation is complete
- [ ] README is updated with v2.0.0 features
- [ ] Migration guide is provided

### Phase 5: Release
- [ ] Package version is 2.0.0
- [ ] CHANGELOG is updated
- [ ] Package is published to npm
- [ ] GitHub release is created

## Out of Scope

The following items are explicitly **not** included in this track:

1. **Network Configuration Management:** The package will not manage network-specific addresses (quoters, factories, peripheries). Consuming projects must provide these addresses.

2. **Forking Service:** The package will not include forking infrastructure. Consuming projects must provide configured ethers.js signers (forked or live).

3. **Effect-based Architecture:** The package will remain Promise-based. Effect integration is the responsibility of consuming projects (e.g., Cortex).

4. **New Protocol Support:** Only the 9 existing protocols are supported. Adding new protocols is a separate track.

5. **Performance Optimization:** No performance optimization beyond maintaining existing performance levels.

6. **UI/CLI Tools:** No user interface or command-line tools will be added.

## Dependencies

### Internal Dependencies
- Existing `CustomRouterFactory` and protocol-specific routers
- Existing type definitions (`Position`, `Fraction`, etc.)
- Existing build and test infrastructure

### External Dependencies
- `ethers` v5.x (existing)
- `@steerprotocol/sdk` (existing, for protocol detection)
- No new external dependencies should be added

### Source Dependencies
- ABIs from `serverless-strategy-tx-processor/src/functions/strategy-execution/sdk/artifacts/abis/`
- Helper logic from `serverless-strategy-tx-processor/src/functions/strategy-execution/sdk/classes/tasks/execution-utils/strategy-jobs/helpers/custom-router/`

## Success Metrics

1. **Completeness:** All 22 ABIs and 7 helper modules are integrated
2. **Test Coverage:** >80% code coverage for all new code
3. **API Usability:** Cortex integration code reduced from ~300 lines to ~30 lines
4. **Documentation:** Complete JSDoc and README with examples
5. **Release:** Successfully published to npm as v2.0.0
6. **Adoption:** At least one consuming project (Cortex) successfully migrated

## Notes

- This is a **breaking change** requiring a major version bump to v2.0.0
- The package will maintain a **layered API**: high-level `SwapCalculator` for simple use cases, and exported helpers for advanced use cases
- All logic is ported from battle-tested code in `serverless-strategy-tx-processor`
- The enhancement makes the package **self-contained** and **reusable** across multiple projects
