From f3fb0f142a257c2aa1c5a904765a7f880543baf1 Mon Sep 17 00:00:00 2001 From: johba Date: Wed, 24 Sep 2025 09:57:20 +0200 Subject: [PATCH] fix agent --- AGENTS.md | 109 ++++++++++------------------- CLAUDE.md | 85 ---------------------- TECHNICAL_APPENDIX.md | 6 +- kraiken-lib/AGENTS.md | 36 ++++++++++ kraiken-lib/CLAUDE.md | 74 -------------------- landing/AGENTS.md | 143 +++++++++----------------------------- services/ponder/AGENTS.md | 29 ++++++++ services/txnBot/AGENTS.md | 35 ++++++++++ services/txnBot/CLAUDE.md | 88 ----------------------- 9 files changed, 173 insertions(+), 432 deletions(-) delete mode 100644 CLAUDE.md create mode 100644 kraiken-lib/AGENTS.md delete mode 100644 kraiken-lib/CLAUDE.md create mode 100644 services/ponder/AGENTS.md create mode 100644 services/txnBot/AGENTS.md delete mode 100644 services/txnBot/CLAUDE.md diff --git a/AGENTS.md b/AGENTS.md index 4001874..5d65031 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,84 +1,47 @@ # Agent Brief: Harb Stack -## System Map -- `onchain/`: Foundry workspace for Kraiken token, Harberger staking, Optimizer, and LiquidityManager logic. Deployment scripts live in `script/`, tests in `test/`, fuzzing toolchain in `analysis/`. Use `.secret.local` mnemonic for local scripts. -- `services/ponder/`: New indexer replacing The Graph. `ponder.config.ts` selects network/contracts, `src/` holds TypeScript event handlers, `ponder.schema.ts` defines tables, `README.md` documents usage. Generated artifacts in `generated/` are auto-created by Ponder. -- `subgraph/base_sepolia/`: Legacy AssemblyScript implementation kept for reference during migration. Do not modify unless syncing schema changes between stacks. -- `landing/`: Vue 3 app (Vite + TypeScript) for the public launch site and forthcoming staking UI. See `src/views/` for pages, `env.d.ts` for injected globals. -- `services/txnBot/`: Node service that consumes the Ponder GraphQL API to trigger `recenter()` and `payTax()` on-chain when profitable. -- `kraiken-lib/`: Shared TypeScript helpers (e.g., `bytesToUint256`) consumed by the landing app + bots. +## Core Concepts +- KRAIKEN couples Harberger-tax staking with a dominant Uniswap V3 liquidity manager to create asymmetric slippage, sentiment-driven pricing, and VWAP "price memory" safeguards. +- Liquidity dominance is mission-critical; treat any regression that weakens the LiquidityManager's control as a priority incident. +- Harberger staking supplies the sentiment oracle that drives Optimizer parameters, which in turn tune liquidity placement and supply expansion. -## Environment Profiles -- `BASE_SEPOLIA_LOCAL_FORK`: Anvil fork bootstrapped by `scripts/local_env.sh` -- `BASE_SEPOLIA`: Public Base Sepolia testnet -- `BASE`: Base mainnet +## User Journey +1. **Buy** - Acquire KRAIKEN on Uniswap. +2. **Stake** - Declare a tax rate on kraiken.org to earn from protocol growth. +3. **Compete** - Snatch undervalued positions to optimise returns. -> **Local dev**: Always start the stack via `nohup ./scripts/local_env.sh start &` (never run services individually); stop with `./scripts/local_env.sh stop`. +## Operating the Stack +- Start everything with `nohup ./scripts/local_env.sh start &` and stop via `./scripts/local_env.sh stop`. Do not launch services individually. +- Supported environments: `BASE_SEPOLIA_LOCAL_FORK` (default Anvil fork), `BASE_SEPOLIA`, and `BASE`. Match contract addresses and RPCs accordingly. +- The stack boots Anvil, deploys contracts, seeds liquidity, starts Ponder, launches the landing site, and runs the txnBot. Wait for logs to settle before manual testing. -## Execution Workflow -1. **Contracts** - - Build/test via `forge build` and `forge test` inside `onchain/`. - - Local deployment: run Anvil fork, execute `forge script script/DeployLocal.sol --fork-url http://127.0.0.1:8545 --broadcast` with `.secret.local` mnemonic. Script attaches to Base Uniswap V3 factory, creates pool if absent, deploys Optimizer proxy + LiquidityManager, configures Kraiken/Stake links. - - Post-deploy: fund LiquidityManager (`cast send --value 0.1ether`) and call `recenter()`. +## Component Guides +- `onchain/` - Solidity + Foundry contracts, deploy scripts, and fuzzing helpers ([details](onchain/AGENTS.md)). +- `services/ponder/` - Ponder indexer powering the GraphQL API ([details](services/ponder/AGENTS.md)). +- `landing/` - Vue 3 marketing + staking interface ([details](landing/AGENTS.md)). +- `kraiken-lib/` - Shared TypeScript helpers for clients and bots ([details](kraiken-lib/AGENTS.md)). +- `services/txnBot/` - Automation bot for `recenter()` and `payTax()` upkeep ([details](services/txnBot/AGENTS.md)). -2. **Indexer (Ponder)** - - Install deps (`npm install`). - - Configure environment via `PONDER_NETWORK` (`BASE_SEPOLIA_LOCAL_FORK`, `BASE_SEPOLIA`, or `BASE`). Update `ponder.config.ts` addresses if deployments change. - - Run dev mode with `npm run dev`; GraphQL served at `http://localhost:42069/graphql`. - - Handlers in `src/kraiken.ts` and `src/stake.ts` maintain rolling supply stats, ring-buffered hourly metrics, and position state. +## Testing & Tooling +- Contracts: run `forge build`, `forge test`, and `forge snapshot` inside `onchain/`. +- Fuzzing: scripts under `onchain/analysis/` (e.g., `./analysis/run-fuzzing.sh [optimizer] debugCSV`) generate replayable scenarios. +- Integration: after the stack boots, inspect Anvil logs, hit `http://localhost:42069/graphql` for Ponder, and poll `http://127.0.0.1:43069/status` for txnBot health. -3. **Frontend** -- `npm install` then `npm run dev` in `landing/`. Currently static marketing copy with placeholders for wallet/staking flows. -- Configure GraphQL endpoints via `VITE_PONDER_BASE_SEPOLIA`, `VITE_PONDER_BASE`, and optionally override `VITE_PONDER_BASE_SEPOLIA_LOCAL_FORK` (defaults to `http://127.0.0.1:42069/graphql`). +## Guardrails & Tips +- `token0isWeth` flips amount semantics; confirm ordering before seeding or interpreting liquidity. +- VWAP, `ethScarcity`, and Optimizer outputs operate on price^2 (X96). Avoid "normalising" to sqrt inadvertently. +- Fund the LiquidityManager with Base WETH (`0x4200...0006`) before expecting `recenter()` to succeed. +- Ponder stores data in `.ponder/`; drop the directory if schema changes break migrations. +- Keep git clean before committing; never leave commented-out code or untested changes. -4. **Automation Bot** - - Requires `.env` with RPC + key. Queries the Ponder GraphQL endpoint to decide when to pay tax or recenter liquidity. - - `scripts/local_env.sh start` provisions and launches the bot automatically when running against the local fork. - -## Migration Notes (Subgraph → Ponder) -- Schema parity: ensure any entity changes land in both `ponder.schema.ts` and legacy Graph `schema.graphql` until cutover. -- Event coverage: `Stake` events (`PositionCreated/Removed/Shrunk/TaxPaid/RateHiked`) mirrored from AssemblyScript handlers. Kraiken `Transfer` powers mint/burn/tax/UBI tracking. -- Ring buffer logic in `kraiken.ts` depends on block timestamps being monotonic; gaps >168 hours zero out the buffer. Verify `startBlock` in `ponder.config.ts` to avoid reprocessing genesis noise. -- Local deployment requires updating `ponder.config.ts` local contract addresses after each run or injecting via env overrides. The `BASE_SEPOLIA_LOCAL_FORK` profile assumes addresses generated by `DeployLocal.sol`. -- Ponder v0.13 exposes helpers via `context.client` / `context.contracts`; use these to seed stats from on-chain `totalSupply` and refresh `outstandingStake` straight from the `Stake` contract. All hourly projections now run off a JSON ring buffer on the `stats` row. -- Subgraph naming differs from the new schema (`stats_collection`, decimal shares). The web-app and txn bot now target the Ponder schema directly; keep legacy Graph compatibility only until the AssemblyScript stack is fully retired. -- Tax accounting must listen to `PositionTaxPaid` instead of guessing via hard-coded addresses. The old subgraph missed this; Ponder now increments the ring buffer segment on each tax payment. -- Liquidity bootstrap still depends on the Uniswap pool stepping through `recenter()`. On current Base-Sepolia forks the LM reverts with `LOK`. Investigate before relying on `scripts/local_env.sh start` for an unattended setup. - -## Testing Playbook -- **Unit/Fuzz**: `forge test` and scripts under `onchain/analysis/` to stress liquidity + staking edge cases. -- **Integration (local fork)**: - 1. `anvil --fork-url https://sepolia.base.org` (or base mainnet RPC) in terminal 1. - 2. From `onchain/`, deploy with `forge script script/DeployLocal.sol --fork-url http://127.0.0.1:8545 --broadcast`. - 3. Fund LiquidityManager, call `recenter()`, and execute sample trades (KRK buy, stake, unstake) using `cast` or Foundry scripts. - 4. Start Ponder (`PONDER_NETWORK=BASE_SEPOLIA_LOCAL_FORK npm run dev`) and watch logs for handler errors. - 5. Query GraphQL (`stats`, `positions`) to confirm indexed state. - -## Gotchas & Tips -- `token0isWeth` toggles amount0/amount1 semantics—check pool ordering before seeding liquidity. -- VWAP/ethScarcity logic expects squared price format; do not convert to sqrt unintentionally. -- LiquidityManager `recenter()` reverts unless funded with WETH (Base WETH address `0x4200...006`). Use `cast send` with sufficient ETH when testing locally. -- Ponder’s SQLite store lives in `.ponder/` (gitignored). Delete between runs if schema changes. -- Legacy subgraph is maintained for reference only; all active services now read from Ponder. -- `web-app/` reads from Ponder by default (see `src/config.ts`). Update the environment specific GraphQL URLs when deployments move. - -## Useful Commands -- `foundryup` / `forge clean` / `forge snapshot` -- `anvil --fork-url https://sepolia.base.org` -- `cast call "slot0()"` -- `PONDER_NETWORK=BASE_SEPOLIA_LOCAL_FORK npm run dev` +## Handy Commands +- `foundryup` - update Foundry toolchain. +- `anvil --fork-url https://sepolia.base.org` - manual fork when diagnosing outside the helper script. +- `cast call "slot0()"` - inspect pool state. +- `PONDER_NETWORK=BASE_SEPOLIA_LOCAL_FORK npm run dev` (inside `services/ponder/`) - focused indexer debugging when the full stack is already running. - `curl -X POST http://localhost:42069/graphql -d '{"query":"{ stats(id:\"0x01\"){kraikenTotalSupply}}"}'` - `curl http://127.0.0.1:43069/status` -- `nohup ./scripts/local_env.sh start &` boots Anvil+contracts+ponder+frontend+txnBot; stop with Ctrl+C or `./scripts/local_env.sh stop` when you want to tear it down. -## Refactor Backlog -- Replace the temporary `any` shims in `services/ponder/src/kraiken.ts` and `services/ponder/src/stake.ts` by importing the official 0.13 handler types instead of stubbing `ponder-env.d.ts`. -- Drop the custom `ponder:api` / `ponder:registry` module declarations once the generator emits them; if it cannot, declare precise interfaces rather than `any` to keep autocomplete and future upgrades safe. -- Convert the JSON ABI imports in `services/ponder/ponder.config.ts` to typed loaders (e.g., `satisfies Abi`) so config drift is caught at compile time instead of via `as Abi` casts. -- Move the snatch-selection logic out of `web-app/src/components/StakeHolder.vue` into a dedicated composable that both the stake form and charts can reuse, and memoise the `assetsToShares` conversions there. -- Split `kraiken-lib/src/helpers.ts` into focused modules (ids, tax rates, snatch selection) so consumers can tree-shake and each helper stays small and testable. - -## Contacts & Artifacts -- Deployment addresses recorded in `onchain/deployments-local.json` (local) and broadcast traces under `onchain/broadcast/`. -- Technical deep dive: `TECHNICAL_APPENDIX.md` & `HARBERG.md`. -- Liquidity math references: `onchain/UNISWAP_V3_MATH.md`. +## References +- Deployment history: `onchain/deployments-local.json`, `onchain/broadcast/`. +- Deep dives: `TECHNICAL_APPENDIX.md`, `HARBERG.md`, and `onchain/UNISWAP_V3_MATH.md`. diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 16941db..0000000 --- a/CLAUDE.md +++ /dev/null @@ -1,85 +0,0 @@ -# CLAUDE.md - -This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. - -## Core Innovation - -KRAIKEN: A token with a **dominant liquidity manager** that creates an unfair trading advantage through: - -1. **Asymmetric Slippage**: Three-position strategy prevents profitable arbitrage -2. **Sentiment Oracle**: Harberger tax staking as prediction market -3. **Price Memory**: VWAP protection against manipulation - -**Critical**: The liquidity manager must maintain dominance - if it loses this, the project fails. - -## User Journey - -1. **Buy**: Purchase KRAIKEN on Uniswap -2. **Stake**: Set tax rate at kraiken.org → Earn from protocol growth -3. **Compete**: Snatch undervalued positions → Optimize returns - -## Project Structure - -- **`onchain/`** - Smart contracts (Solidity/Foundry) - [Details](onchain/CLAUDE.md) -- **`landing/`** - Vue 3/Vite staking interface - [Details](landing/AGENTS.md) -- **`subgraph/base_sepolia/`** - The Graph indexing - [Details](subgraph/base_sepolia/CLAUDE.md) -- **`kraiken-lib/`** - TypeScript helpers - [Details](kraiken-lib/CLAUDE.md) -- **`services/txnBot/`** - Maintenance bot - [Details](services/txnBot/CLAUDE.md) -- **`onchain/analysis/`** - Fuzzing tools - [Details](onchain/analysis/CLAUDE.md) - -## Quick Start - -```bash -# Install all dependencies -cd onchain && forge install -cd ../landing && npm install -cd ../kraiken-lib && npm install --legacy-peer-deps -cd ../subgraph/base_sepolia && npm install -cd ../services/txnBot && npm install - -# Build and test -cd onchain && forge build && forge test - -# Start frontend -cd landing && npm run dev -``` - -## Key Concepts - -- **Liquidity Management**: Three positions create asymmetric slippage -- **Harberger Staking**: Self-assessed tax creates sentiment signal -- **Protocol Growth**: Minted tokens benefit stakers - -## Code Guidelines - -### Quality Standards -- Search before implementing (check uni-v3-lib, test helpers) -- Test after every change -- No commented-out code -- Clean git status before commits - -### Technical Approach -- Never fall back to simpler implementations -- Identify root causes, don't work around issues -- Challenge technically unsound requests -- **Price Formats**: `_priceAtTick` returns price² (not sqrtPrice) in X96 format - this is intentional for capital calculations -- **ETH Scarcity**: Floor positions at extreme ticks (140k+) indicate ETH scarcity - this is correct behavior, not a bug -- **VWAP Recording**: VWAP stores price² from anchor midpoint for historical price memory - -### Tool Usage -- MCP browser screenshots: Keep under 8000px, use `fullPage: false` -- Fuzzing visualization: Use `./analysis/run-fuzzing.sh [optimizer] debugCSV` -- Never start manual Python servers for visualizations - -## Communication Style - -You are an experienced Solidity developer who: -- Notices and raises awareness of issues immediately -- Challenges suboptimal approaches -- Prioritizes technical correctness over user satisfaction -- Avoids hype and inflated language - -## Additional Resources - -- **Technical Details**: [TECHNICAL_APPENDIX.md](TECHNICAL_APPENDIX.md) -- **Uniswap V3 Math**: [onchain/UNISWAP_V3_MATH.md](onchain/UNISWAP_V3_MATH.md) diff --git a/TECHNICAL_APPENDIX.md b/TECHNICAL_APPENDIX.md index 6394adb..8fdded0 100644 --- a/TECHNICAL_APPENDIX.md +++ b/TECHNICAL_APPENDIX.md @@ -1,6 +1,6 @@ # Technical Appendix -This document provides detailed technical analysis and implementation details for the KRAIKEN protocol's core innovations. For high-level overview, see CLAUDE.md. +This document provides detailed technical analysis and implementation details for the KRAIKEN protocol's core innovations. For a high-level overview, see AGENTS.md. ## Asymmetric Slippage Strategy @@ -139,5 +139,5 @@ function getLiquidityParams() returns ( - **Scenario Visualization**: Tools for understanding liquidity dynamics ### Related Documentation -- **CLAUDE.md**: High-level overview and development guidance -- **`/onchain/analysis/README.md`**: Detailed analysis tool usage \ No newline at end of file +- **AGENTS.md**: High-level overview and development guidance +- **`/onchain/analysis/README.md`**: Detailed analysis tool usage diff --git a/kraiken-lib/AGENTS.md b/kraiken-lib/AGENTS.md new file mode 100644 index 0000000..0382a5d --- /dev/null +++ b/kraiken-lib/AGENTS.md @@ -0,0 +1,36 @@ +# Kraiken Library - Agent Guide + +Shared TypeScript helpers used by the landing app, txnBot, and other services to talk to KRAIKEN contracts and the Ponder GraphQL API. + +## Responsibilities +- Provide type-safe contract interaction helpers (encoding inputs, parsing results). +- Supply Ponder GraphQL query helpers and generated types for protocol stats and staking positions. +- Centralise staking math (tax calculations, snatch selection, share conversions) for reuse across clients. + +## Key Modules +- `src/kraiken.ts` - Token-facing helpers and supply utilities. +- `src/stake.ts` - Staking math, Harberger tax helpers, snatch scoring. +- `src/chains.ts` - Chain constants and deployment metadata. +- `src/queries/` - GraphQL operations that target the Ponder schema. +- `src/__generated__/graphql.ts` - Codegen output consumed throughout the stack. + +## GraphQL Code Generation +- Schema source points to the Ponder GraphQL endpoint for the active environment. +- Scalar mappings: `BigInt` -> `string`, `BigDecimal` -> `string`, `Bytes` -> `string`, `Int8` -> `number`. +- Always import the generated DocumentNodes; avoid `any` casts to keep inference intact. + +## Package Scripts +- `npm install --legacy-peer-deps` +- `npm run compile` - Regenerate GraphQL types. +- `npm run watch` - Continuously regenerate on schema changes. +- `npm test` - Execute Jest suite for helper coverage. + +## Integration Notes +- Landing app consumes helpers for UI projections and staking copy. +- txnBot relies on the same helpers to evaluate profitability and tax windows. +- When the Ponder schema changes, rerun `npm run compile` and commit regenerated types to prevent drift. + +## Quality Guidelines +- Keep helpers pure and side-effect free; they should accept explicit dependencies. +- Prefer narrow exports so downstream consumers can tree-shake bundles. +- Extend typings instead of loosening them; reject `any` as a quick fix. diff --git a/kraiken-lib/CLAUDE.md b/kraiken-lib/CLAUDE.md deleted file mode 100644 index 44b203e..0000000 --- a/kraiken-lib/CLAUDE.md +++ /dev/null @@ -1,74 +0,0 @@ -# Kraiken Library - CLAUDE.md - -TypeScript helper library for interacting with KRAIKEN protocol contracts and The Graph. - -## Purpose - -This library provides: -- Type-safe contract interactions -- GraphQL query helpers for subgraph data -- Staking position calculations -- Helper functions for UI development - -## Architecture - -### Key Files -- `src/kraiken.ts` - Main KRAIKEN token interaction helpers -- `src/stake.ts` - Staking position calculations and Harberger tax logic -- `src/chains.ts` - Chain configuration and constants -- `src/queries/` - GraphQL queries for subgraph data -- `src/__generated__/graphql.ts` - Auto-generated GraphQL types - -## Development Commands - -```bash -# Install dependencies -npm install --legacy-peer-deps - -# Generate GraphQL types from subgraph schema -npm run compile - -# Run tests -npm test - -# Watch mode for GraphQL generation -npm run watch -``` - -## GraphQL Code Generation - -The library uses GraphQL Code Generator to create type-safe queries: - -1. **Schema Source**: Points to subgraph schema -2. **Scalar Mappings**: - - `BigInt` → `string` - - `BigDecimal` → `string` - - `Bytes` → `string` - - `Int8` → `number` - -3. **Generated Types**: All GraphQL operations get full TypeScript typing - -## Usage Examples - -```typescript -import { getStakePositions, calculateTaxRate } from 'kraiken-lib'; - -// Fetch all stake positions -const positions = await getStakePositions(graphqlClient); - -// Calculate annual tax rate -const yearlyRate = calculateTaxRate(dailyRate); -``` - -## Integration Notes - -- Used by the web interface for data fetching -- Used by services/txnBot for position monitoring -- Provides consistent calculations across all frontend components - -## Code Quality - -- All GraphQL queries must be typed -- Use generated types, never `any` -- Keep calculations pure (no side effects) -- Test edge cases for tax calculations \ No newline at end of file diff --git a/landing/AGENTS.md b/landing/AGENTS.md index f8e8f8f..6b71149 100644 --- a/landing/AGENTS.md +++ b/landing/AGENTS.md @@ -1,118 +1,43 @@ -# Landing Interface - CLAUDE.md +# Landing Interface - Agent Guide -Vue 3 + Vite application serving as the main interface for KRAIKEN protocol. +Vue 3 + Vite application that delivers the public marketing site and forthcoming staking UI. -## Technology Stack +## Technology Snapshot +- Vue 3 (Composition API) with TypeScript and Vite toolchain +- Vue Router for multi-view navigation +- Sass-based design system with custom typography -- **Vue 3** (Composition API) -- **TypeScript** - Type-safe development -- **Vite** - Fast build tooling -- **Vue Router** - Client-side routing -- **Sass** - Advanced styling +## Key Views & Components +- `HomeView.vue` - Launch countdown, feature overview, and staking CTA +- `DocsView.vue` - Documentation portal with responsive navigation and generated table of contents +- Layout components (`KNavbar.vue`, `KFooter.vue`, `LeftRightComponent.vue`) manage shared chrome +- UI components (`KButton.vue`, `Countdown.vue`, `SocialButton.vue`, icon set) supply reusable primitives -## Architecture +## Design Notes +- Dark theme palette: primary `#07111B`, accent `#9667BE` +- Mobile-first breakpoints at 768px drive layout shifts and slide-out navigation +- Motion relies on CSS transitions to keep runtime costs low -### Views +## Development Workflow +- Boot the full stack with `nohup ./scripts/local_env.sh start &`; the script handles landing dev server wiring. +- Use local package scripts for targeted tasks: + - `npm install` + - `npm run build` + - `npm run preview` + - `npm run type-check` +- Deployments assume hash-based routing and the Vite `base` setting configured for static hosting. -**HomeView.vue** - Landing page -- Launch countdown timer -- Project introduction -- Feature highlights -- Call-to-action for staking +## Upcoming Integrations +- Wallet connection with Base network switching +- Staking dashboard that reuses shared helpers from `kraiken-lib` +- Data visualisations sourced from the Ponder GraphQL API -**DocsView.vue** - Documentation portal -- Comprehensive protocol documentation -- Auto-generated table of contents -- Mobile-responsive navigation -- Sections: Introduction, Liquidity, AI Agent, Tokenomics, Staking, FAQ - -### Key Components - -**Layout Components**: -- `KNavbar.vue` - Main navigation with scroll effects -- `KFooter.vue` - Site footer -- `LeftRightComponent.vue` - Content layout helper - -**UI Components**: -- `KButton.vue` - Reusable button with hover states -- `Countdown.vue` - Launch countdown display -- `SocialButton.vue` - Social media links -- `NavItem.vue` - Navigation menu items - -**Icons** (`components/icons/`): -- Custom SVG icons for UI elements -- Social media icons (Twitter, Discord, Telegram) - -## Styling - -### Design System -- **Primary Color**: #07111B (deep ocean) -- **Accent**: #9667BE (purple) -- **Background**: Dark theme throughout -- **Typography**: Custom fonts (Audiowide, DM Sans, Orbitron) - -### Responsive Design -- Mobile-first approach -- Breakpoint: 768px -- Slide-out mobile navigation -- Optimized images for different screen sizes - -## Development Commands - -```bash -# Install dependencies -npm install - -# Start development server -npm run dev - -# Build for production -npm run build - -# Preview production build -npm run preview - -# Type checking -npm run type-check -``` - -## Deployment - -Configured for GitHub Pages: -- Hash-based routing for compatibility -- Base URL configuration in vite.config.ts -- Assets optimized for CDN delivery - -## Future Integrations - -### Wallet Connection (Planned) -- Web3 wallet integration -- Network switching to Base -- Transaction signing - -### Staking Interface (Planned) -- Position management -- Tax rate adjustment -- Real-time position monitoring -- Snatching interface - -### Data Visualization (Planned) -- Protocol metrics dashboard -- Liquidity depth charts -- Staking statistics - -## Code Quality Guidelines - -- Use Composition API for all components -- Leverage TypeScript for type safety -- Keep components small and focused -- Use Sass variables for consistent theming -- Follow Vue 3 best practices - -## Performance Optimization +## Quality Guidelines +- Favour Composition API and strongly typed props/emit definitions +- Keep components focused; push shared logic into composables when possible +- Use Sass variables and mixins from the design system for consistent styling +## Performance Tips - Lazy load route components -- Optimize images (WebP format) -- Minimize bundle size -- Use CSS animations over JavaScript -- Implement proper caching strategies +- Optimise imagery (WebP) and leverage Vite asset handling +- Prefer CSS animations to JavaScript when animating UI elements diff --git a/services/ponder/AGENTS.md b/services/ponder/AGENTS.md new file mode 100644 index 0000000..405fb0f --- /dev/null +++ b/services/ponder/AGENTS.md @@ -0,0 +1,29 @@ +# Ponder Indexer - Agent Guide + +Ponder-based indexer that records Kraiken protocol activity and exposes the GraphQL API consumed by the app and automation bot. + +## Responsibilities +- Track Kraiken token transfers and staking events to maintain protocol stats, hourly ring buffers, and position state. +- Serve a GraphQL endpoint at `http://localhost:42069/graphql` for downstream consumers. +- Support `BASE_SEPOLIA_LOCAL_FORK`, `BASE_SEPOLIA`, and `BASE` environments through a single TypeScript codebase. + +## Key Files +- `ponder.config.ts` - Network selection and contract bindings (update addresses after deployments). +- `ponder.schema.ts` - Stats, hourly data, and position tables. +- `src/kraiken.ts` / `src/stake.ts` - Event handlers; rely on Ponder v0.13 helpers for on-chain reads during sync. +- `.ponder/` - Local SQLite/state cache (safe to delete when schemas change). + +## Development Workflow +- Primary path: `nohup ./scripts/local_env.sh start &` boots Anvil, deploys contracts, and launches Ponder in watch mode. +- Focused debugging: within `services/ponder/`, run `npm install` then `PONDER_NETWORK=BASE_SEPOLIA_LOCAL_FORK npm run dev` once the stack is already online. +- For production-style runs, use `npm run build` followed by `PONDER_NETWORK=BASE npm run start` and point `DATABASE_URL` to PostgreSQL if persistence is required. + +## Operational Guidelines +- Confirm handler timestamps are monotonic; large gaps (>168 hours) reset the ring buffer by design. +- Regenerate typings after schema edits by restarting Ponder; generated artifacts live in `generated/`. +- If the stack script fails during boot, check `.ponder/logs` and RPC quota usage before rerunning. + +## Quality Checks +- Avoid reintroducing legacy subgraph assumptions; rely solely on Ponder schema helpers. +- Keep handler logic deterministic and idempotent; reorgs trigger replays. +- Use the Ponder client helpers (`context.client`, `context.contracts`) instead of manual RPC calls where possible. diff --git a/services/txnBot/AGENTS.md b/services/txnBot/AGENTS.md new file mode 100644 index 0000000..f0b692f --- /dev/null +++ b/services/txnBot/AGENTS.md @@ -0,0 +1,35 @@ +# Transaction Bot - Agent Guide + +Automation service that maintains liquidity alignment and tax enforcement for the KRAIKEN protocol. + +## Responsibilities +- Monitor Ponder GraphQL metrics to detect when `recenter()` should be triggered. +- Track staking positions for overdue taxes and call `payTax()` when profitable. +- Expose a status endpoint (`GET /status`) for operational visibility. + +## Architecture +- `service.js` - Main loop that polls the GraphQL endpoint, evaluates triggers, and submits transactions. +- `generateKey.js` - Utility for provisioning dedicated bot wallets. +- `package.json` scripts - `npm install`, `npm start`, and debug runs via `DEBUG=* npm start`. + +## Configuration +Set the following environment variables (automatically generated when the stack script is used): +``` +ENVIRONMENT=BASE_SEPOLIA_LOCAL_FORK|BASE_SEPOLIA|BASE +PROVIDER_URL= +PRIVATE_KEY= +LM_CONTRACT_ADDRESS= +STAKE_CONTRACT_ADDRESS= +GRAPHQL_ENDPOINT= +# Optional: PORT=43069 +``` + +## Operations +- Launch via `nohup ./scripts/local_env.sh start &`; the script handles env injection and process supervision. +- For focused debugging, run `npm install` then `npm start` within `services/txnBot/` after the stack is already up. +- Monitor logs for transaction receipts and ensure gas pricing stays within acceptable bounds. + +## Safety Checklist +- Use dedicated wallets and keep balances minimal. +- Rotate keys if compromise is suspected; update secrets before restarting the stack. +- Observe exponential backoff behaviour and avoid hammering RPC endpoints on failure. diff --git a/services/txnBot/CLAUDE.md b/services/txnBot/CLAUDE.md deleted file mode 100644 index 198d80c..0000000 --- a/services/txnBot/CLAUDE.md +++ /dev/null @@ -1,88 +0,0 @@ -# Transaction Bot - CLAUDE.md - -Automated service for triggering protocol maintenance transactions. - -## Purpose - -This bot monitors the KRAIKEN protocol and automatically: -- Triggers liquidity position recentering when needed -- Processes tax liquidations for defaulting positions -- Maintains protocol health through timely interventions - -## Architecture - -### Core Components - -**service.js** - Main bot loop -- Queries subgraph for protocol state -- Evaluates recentering conditions -- Submits transactions when profitable - -**generateKey.js** - Utility for creating bot wallets -- Generates secure private keys -- Provides addresses for funding - -### Configuration - -Environment variables (`.env`): -``` -PRIVATE_KEY=0x... -RPC_URL=https://... -SUBGRAPH_URL=https://... -``` - -## Recentering Logic - -The bot evaluates: -1. Current price vs liquidity position centers -2. Gas costs vs expected rewards -3. MEV protection considerations - -Triggers recentering when: -- Price has moved significantly from position centers -- Expected rewards exceed gas costs by threshold -- No recent recentering has occurred - -## Tax Liquidation - -Monitors staking positions for: -- Tax payment defaults -- Insufficient balances -- Expired grace periods - -## Development Commands - -```bash -# Install dependencies -npm install - -# Generate new bot wallet -node generateKey.js - -# Run the bot -node service.js - -# Run with debug logging -DEBUG=* node service.js -``` - -## Deployment Considerations - -- Fund bot wallet with ETH for gas -- Set appropriate gas price limits -- Monitor for stuck transactions -- Implement proper error handling and retries - -## Security Notes - -- Private key must be kept secure -- Use dedicated bot wallet (not personal) -- Limit wallet balance to operational needs -- Monitor for unusual activity - -## Performance Optimization - -- Cache subgraph queries -- Batch similar operations -- Use flashbots for MEV protection -- Implement exponential backoff for retries \ No newline at end of file