diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..5917573 --- /dev/null +++ b/.env.example @@ -0,0 +1,14 @@ +# ===== SOLANA ===== +SOL_PRIVATE_KEY= +SOL_RPC=https://api.mainnet-beta.solana.com +JUP_API_KEY= + +# ===== EVM ===== +EVM_PRIVATE_KEY=0x... +EVM_RPC=https://mainnet.base.org +EVM_CHAIN=base +OX_API_KEY= + +# ===== GROQ ===== +GROQ_API_KEY= +GROQ_MODEL=llama-3.1-8b-instant diff --git a/.gitignore b/.gitignore index 65ca4be..837f7f8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,28 +1,3 @@ -.nvmrc -stores node_modules -ui/**/node_modules -ui/**/dist -ui/**/dist-ssr - -# IDE / OS noise -.idea/ +.env .DS_Store - -# Test artifacts -test-results/ - -# Local planning / scratch (intentionally untracked) -progress.md - -# Local chain/node data, configs, secrets (intentionally untracked) -onchain/ - -# Rust/Solana build artifacts (may include generated keypairs) -target/ -**/target/ - -.claude -.codex -training/ -llama.cpp/ diff --git a/README.md b/README.md index 3bedecb..04aef16 100644 --- a/README.md +++ b/README.md @@ -1,1068 +1,267 @@ -# Intercom Swap - -This repo is a fork of upstream **Intercom** (Trac-Systems/intercom): a reference implementation of the Intercom stack on Trac Network for an internet of agents. - -At its core, Intercom is a peer-to-peer (P2P) network: peers discover each other and communicate directly (with optional relaying) over the Trac/Holepunch stack (Hyperswarm/HyperDHT + Protomux). There is no central server required for sidechannel messaging. - -This fork adds a non-custodial swap harness: - -- Negotiate via **request-for-quote (RFQ)** messages over **Intercom sidechannels** (P2P). -- Settle **BTC over Lightning** <> **USDT on Solana** using a shared Solana escrow program (HTLC-style). - -Links: -- Upstream Intercom: `https://github.com/Trac-Systems/intercom` -- This fork: `https://github.com/TracSystems/intercom-swap` - -## Architecture (High-Level) -Intercom Swap is a local-first P2P system with one core runtime and multiple optional control/settlement paths. - -```text - Humans + Autonomous Agents - | - +--------------+--------------+ - | | - Structured control Natural language - (UI + tool calls) (optional prompting) - | | - +--------------+--------------+ - v - Intercom runtime peer - (identity + local state store) - | - +-----------------+-------------------+ - | | - v v - P2P coordination fabric Optional app extension - - Sidechannels (RFQ + swap) - Local-first contracts/features - - Subnet replication - Trac Network tx path (TNK gas) - | - +--------------+--------------+ - | | - v v - Lightning settlement Solana settlement - (BTC leg) (USDT leg) -``` +# ๐Ÿง  INTERCOM SWAP BY PAK EKO ๐Ÿš€ -Key idea: -- Intercom handles coordination and agent communication. -- Settlement happens on Lightning + Solana. -- Contract usage on Trac Network is optional and extensible. +CLI-based **AI Multi-Agent Swap Engine** +๐Ÿ”ฅ REAL swap on MAINNET +๐Ÿ”ฅ Dexscreener-powered analysis +๐Ÿ”ฅ Risk engine + Agent pipeline --- -## What Intercom Is - -Intercom is a Trac stack for autonomous agents: -- **Sidechannels**: fast, ephemeral P2P messaging (Hyperswarm + Noise). -- **Features**: integrate non-agent services/tools into the same network. -- **Contracts (optional)**: deterministic state + optional chat. -- **MSB (optional)**: value-settled transactions. - -This fork keeps Intercom intact and layers swap + ops tooling on top. - ---- +## ๐Ÿ“ TRAC ADDRESS -## Table Of Contents - -- [Run Strategy Matrix](#run-strategy-matrix) -- [Install And Operate From `SKILL.md`](#install-and-operate-from-skillmd) -- [How To Use `SKILL.md` With An Agent](#how-to-use-skillmd-with-an-agent) -- [Conceptual Flow (BTC(LN) <> USDT(Solana))](#conceptual-flow-btcln--usdtsolana) -- [External APIs / RPCs (Defaults)](#external-apis--rpcs-defaults) -- [Command Surface (Scripts = "Function Calls")](#command-surface-scripts--function-calls) -- [Start Intercom Peers (`run-swap-*`)](#start-intercom-peers-run-swap-) -- [SC-Bridge Control (`swapctl`)](#sc-bridge-control-swapctl) -- [RFQ Bots (`rfq-maker` / `rfq-taker`)](#rfq-bots-rfq-maker--rfq-taker) -- [Recovery (`swaprecover`)](#recovery-swaprecover) -- [Solana Wallet Tooling (`solctl`)](#solana-wallet-tooling-solctl) -- [Solana Escrow Program Tooling (`escrowctl`)](#solana-escrow-program-tooling-escrowctl) -- [Lightning Operator Tooling (`lnctl`)](#lightning-operator-tooling-lnctl) -- [Optional LND Local Lifecycle (`lndctl` / `lndpw`)](#optional-lnd-local-lifecycle-lndctl--lndpw) -- [Prompt Router (Optional)](#prompt-router-optional) -- [Tests (Mandatory)](#tests-mandatory) -- [Secrets + Repo Hygiene](#secrets--repo-hygiene) +``` +trac1jwh8vrc50x7r8ysfx0v7d2k2qlkv999zkjl5w6sg7rktmmf6qhysp3w76d +``` --- -## Run Strategy Matrix - -Choose one path before running commands. Do not mix paths in a single instance. +## โšก OVERVIEW -| Goal | Path | Typical Network | Data Isolation Rule | -|---|---|---|---| -| Validate code and workflows | Test path | LN regtest + Solana local/devnet | test stores + test receipts DB + test promptd port | -| Upgrade an existing deployment | Upgrade path | same as current deployment | keep backup, preserve current stores, rerun tests | -| Operate with real funds | Mainnet path | LN mainnet + Solana mainnet | separate mainnet stores/receipts/ports; never reuse test data | -| Human-first operation | Collin path | any | Collin talks to one promptd instance at a time | -| Agent-first automation | Headless path | any | prefer deterministic scripts/tool calls over free-form prompting | +INTERCOM SWAP BY PAK EKO is a CLI tool designed for: -Minimal rule set: -- Always decide `test` vs `mainnet` first. -- Keep test and mainnet fully separated (store names, DB paths, ports, audit dirs). -- For mainnet, use public DHT bootstraps (local DHT is test-only). -- Run tests before first live settlement. +- ๐Ÿ’ฑ Real on-chain token swaps (MAINNET) +- ๐Ÿค– Multi-agent execution pipeline: + - Scout โ†’ intent parsing + - Analyst โ†’ market analysis (Dexscreener) + - RiskGate โ†’ safety checks + - Executor โ†’ on-chain swap +- ๐Ÿ“Š Real-time token analysis +- ๐Ÿ›ก๏ธ Built-in risk scoring system --- -## Install And Operate From `SKILL.md` +## ๐Ÿง  AGENT PIPELINE -`SKILL.md` is the canonical **installer + runbook** for this repo. If you are an agent, treat it as the source of truth for: -- installation steps -- runtime requirements (Pear, Node) -- first-run decisions (sidechannels, invites, PoW) -- operations (LN/Solana, recovery, tests) - -### Recommended Models (For Install/Upgrades) - -Installation and large merges are easiest with a top-tier coding model. +``` +USER INPUT + โ†“ +Scout (parse intent) + โ†“ +Analyst (Dexscreener data) + โ†“ +RiskGate (liquidity, volume, age, etc) + โ†“ +Executor (Jupiter swap โ†’ MAINNET) +``` -Recommended: -- OpenAI: **GPT-5.3+** (Codex, `xhigh`) -- Anthropic: **Claude Opus 4.6+** +--- -OpenClaw can use and control this stack autonomously (install/upgrade via `SKILL.md`, ops via scripts and optional `promptd` tool calls, including backend worker tools `intercomswap_tradeauto_*`). +## ๐Ÿš€ FEATURES -Local/open-weight models can work too, but use a high-grade one. +- โœ… CLI UI (Pro Max Interactive) +- โœ… Real swap via Jupiter Aggregator +- โœ… Token CA / Mint support +- โœ… Dexscreener integration +- โœ… Risk scoring engine +- โœ… Dry-run preview before execution +- โœ… AI-style agent workflow --- -## How To Use `SKILL.md` With An Agent +## ๐Ÿ“ฆ INSTALLATION -Example prompts (copy/paste): - -1. Install -```text -Install this repo using SKILL.md. Run all tests (unit + e2e). Report what you ran and any failures. +### 1. Clone repository +```bash +git clone https://github.com/pakeko78/intercom-swap-by-pakeko +cd intercom-swap-by-pakeko ``` -2. Install + staging tests -```text -Install this repo using SKILL.md. Run unit + local e2e. Then run a smoke test on test networks (LN regtest + Solana devnet) if supported. Report results. +### 2. Install dependencies +```bash +npm install ``` -2b. Decide and execute one run path first -```text -Read SKILL.md and pick exactly one run path (test / upgrade / mainnet / collin / headless). Explain why that path matches the goal, then execute it end-to-end. -``` +--- -3. Update workflow -```text -Pull the latest version of this fork, resolve merge conflicts, and run all tests (unit + e2e). If testnet smoke tests exist, run them too. Only then proceed to mainnet checks. -``` +## โš™๏ธ ENV SETUP -3b. Switch to mainnet (fresh instance) -```text -Create a clean mainnet instance: do NOT reuse any test stores or receipts DBs. Wipe/rotate test data only, keep mainnet keys separate. Then bring up mainnet peer + promptd + Collin and run a mainnet readiness checklist (funding + LN channel ready + Solana RPC reachable). +```bash +cp .env.example .env +nano .env ``` -4. Mainnet start -```text -Install this repo using SKILL.md, run all tests (unit + e2e), then run the mainnet bring-up checklist and start maker+taker peers on mainnet (with user-provided Solana RPC + Solana keypairs + LN node configuration). Report the exact commands run and any failures. -``` +Fill this: -5. Enable Collin prompting (LLM mode) -```text -Enable LLM prompting for Collin. Tell me exactly what config you need (OpenAI-compatible base_url, api_key or token file, model, max_tokens, temperature) and where it must be stored (gitignored). Validate by running a prompt that posts an Offer and confirm it appears in the UI. ``` - -6. Operator support mode -```text -Iโ€™m operating Collin and Iโ€™m stuck: โ€œโ€. Explain what it means and the exact next click/command to fix it. Do not guess; inspect the repo and logs. +SOL_PRIVATE_KEY=YOUR_PRIVATE_KEY +SOL_RPC=https://api.mainnet-beta.solana.com ``` --- -## Conceptual Flow (BTC(LN) <> USDT(Solana)) - -```text -Rendezvous sidechannel(s) (any; examples: 0000intercom, 0000intercomswapbtcusdt, my-swap-room) - | - | swap.svc_announce (service + offers[]) [periodic rebroadcast; sidechannels have no history] - | Offer (optional) -> RFQ (manual or backend-auto-from-offer) -> QUOTE -> QUOTE_ACCEPT - | - pre-filter by app_hash + fee caps + refund window - v -per-trade invite-only swap: - | - | TERMS (binding: fees, mint, refund_after_unix, ...) - | ACCEPT - | LN_INVOICE (payment_hash) - | SOL_ESCROW_CREATED (escrow PDA + vault ATA) - v -Settlement (BTC over Lightning <> USDT on Solana) - 1) Maker creates + posts LN invoice (receiver inbound liquidity check must pass) - 2) Taker runs LN route precheck and posts `ln_route_precheck_ok` (swap.status) - 3) Maker escrows USDT (Solana) only after taker precheck is OK - 4) Taker verifies escrow on-chain (hard rule: no escrow, no pay) - 5) Taker pays LN invoice -> learns preimage - 6) Taker claims USDT on Solana using preimage - 7) Refund path after sol_refund_after_unix if LN payment never happens -``` - -## External APIs / RPCs (Defaults) +## ๐Ÿ” PRIVATE KEY FORMAT -This stack touches a few external endpoints. Defaults are chosen so local e2e is easy, and live ops are configurable: +Supported formats: -- Price oracle (HTTP): by default uses public exchange APIs (no keys): `binance,coinbase,gate,kucoin,okx,bitstamp,kraken`. - - Enabled on peers via `--price-oracle 1` (included in `scripts/run-swap-*.sh`). - - Configure providers via `--price-providers ""`. -- Solana (JSON-RPC over HTTP): bots/tools default to local validator `http://127.0.0.1:8899`. - - Configure via `--solana-rpc-url ""` (comma-separated failover pool). -- Bitcoin/LN: the BTC leg is **Lightning** (CLN or LND). - - Local e2e uses docker regtest stacks under `dev/` (includes `bitcoind`). - - Mainnet uses your local LN node (CLN via `bitcoind` RPC, or LND via `neutrino` or `bitcoind` backend). - - This repo does not require a separate public Bitcoin explorer API by default. +- โœ… Base58 string +- โœ… JSON array (Solana format) -If any of your HTTP/RPC endpoints require auth headers (Bearer/API tokens), see **Authenticated API Endpoints** near the end of this README. +โš ๏ธ SECURITY WARNING: +- NEVER use your main wallet +- Always use burner wallet --- -## Command Surface (Scripts = "Function Calls") - -After installation, day-to-day operation should be done by invoking scripts (macOS/Linux `.sh`, Windows `.ps1`). The `.mjs` files are the canonical CLIs; wrappers exist to keep invocation stable and tool-call friendly. - -### Script Index - -| Area | macOS/Linux | Windows | Canonical | Purpose | -|---|---|---|---|---| -| Bootstrap | `scripts/bootstrap.sh` | n/a | bash | Install Pear runtime + deps | -| Start peer (maker/service) | `scripts/run-swap-maker.sh` | `scripts/run-swap-maker.ps1` | shell | Start a peer with SC-Bridge + price oracle and join an RFQ channel | -| Start peer (taker/client) | `scripts/run-swap-taker.sh` | `scripts/run-swap-taker.ps1` | shell | Start a peer with SC-Bridge + price oracle and join an RFQ channel; pins `SWAP_INVITER_KEYS` for `swap:*` | -| Peer lifecycle supervisor | `scripts/peermgr.sh` | `scripts/peermgr.ps1` | `scripts/peermgr.mjs` | Start/stop/restart background peers (headless) without keeping a terminal open | -| SC-Bridge control | `scripts/swapctl.sh` | `scripts/swapctl.ps1` | `scripts/swapctl.mjs` | Sidechannel ops + signed message helpers | -| SC-Bridge control (token auto) | `scripts/swapctl-peer.sh` | `scripts/swapctl-peer.ps1` | wrapper | Same as `swapctl`, but reads token from `onchain/sc-bridge/.token` | -| RFQ maker bot | `scripts/rfq-maker-peer.sh` | `scripts/rfq-maker-peer.ps1` | `scripts/rfq-maker.mjs` | Quote RFQs; optionally run full swap state machine | -| RFQ taker bot | `scripts/rfq-taker-peer.sh` | `scripts/rfq-taker-peer.ps1` | `scripts/rfq-taker.mjs` | Send RFQ; accept quote; optionally run full swap state machine | -| RFQ bot control | `scripts/rfqbotmgr.sh` | `scripts/rfqbotmgr.ps1` | `scripts/rfqbotmgr.mjs` | Start/stop/restart RFQ bot instances without stopping the peer | -| Recovery | `scripts/swaprecover.sh` | `scripts/swaprecover.ps1` | `scripts/swaprecover.mjs` | List/show receipts; claim/refund escrows | -| Solana wallet ops | `scripts/solctl.sh` | `scripts/solctl.ps1` | `scripts/solctl.mjs` | Keypairs, balances, ATA, token transfers | -| Solana escrow ops | `scripts/escrowctl.sh` | `scripts/escrowctl.ps1` | `scripts/escrowctl.mjs` | Program config, fee vaults, escrow inspection | -| Solana program ops (maintainers) | `scripts/solprogctl.sh` | `scripts/solprogctl.ps1` | `scripts/solprogctl.mjs` | Build/deploy the Solana program | -| Lightning ops | `scripts/lnctl.sh` | `scripts/lnctl.ps1` | `scripts/lnctl.mjs` | Addresses, channels, invoices, payments | -| LND local lifecycle (optional) | `scripts/lndctl.sh` | `scripts/lndctl.ps1` | `scripts/lndctl.mjs` | Generate `lnd.conf`, start/stop, create/unlock wallet | -| LND password helper (optional) | `scripts/lndpw.sh` | `scripts/lndpw.ps1` | shell | Write an LND wallet password file (no trailing newline) | - ---- - -### Start Intercom Peers (`run-swap-*`) - -| Function call | What it does | Parameters | -|---|---|---| -| `scripts/run-swap-maker.sh [storeName] [scBridgePort] [rfqChannel] [...extra peer flags]` | Starts a maker/service peer, enables SC-Bridge + price oracle, joins the RFQ channel | Positional args; optional env: `SIDECHANNEL_POW` (default `1`), `SIDECHANNEL_POW_DIFFICULTY` (default `12`) | -| `SWAP_INVITER_KEYS="" scripts/run-swap-taker.sh [storeName] [scBridgePort] [rfqChannel] [...extra peer flags]` | Starts a taker/client peer and pins inviter key(s) for `swap:*` invite-only channels | Requires `SWAP_INVITER_KEYS`; same optional env vars as maker | - -Notes: -| Item | Details | -|---|---| -| Token files | Created under `onchain/sc-bridge/.token` (gitignored). | -| RFQ channel | Any sidechannel works. Many operators use a dedicated rendezvous (example: `0000intercomswapbtcusdt`) to reduce noise, but `0000intercom` works too. | -| Subnet channel | Keep `--subnet-channel` consistent across peers (mismatches can prevent connections). | +## โ–ถ๏ธ RUN CLI ---- - -### Peer Lifecycle Supervisor (`peermgr`) - -`peermgr` is a local supervisor for starting/stopping `pear run` peers in the background (so you donโ€™t need to keep a terminal open). - -Notes: -- It enforces: **never run the same peer store twice**. -- It stores state + logs under `onchain/peers/` (gitignored). -- It always starts the peer in **headless mode** (`--terminal 0`). +```bash +npm run cli +``` -#### Commands +or: -| Command | What it does | -|---|---| -| `scripts/peermgr.sh start --name --store --sc-port --sidechannels ` | Start a peer and join one or more extra sidechannels on startup | -| `scripts/peermgr.sh stop --name ` | Stop the peer process | -| `scripts/peermgr.sh restart --name ` | Restart using the last saved config | -| `scripts/peermgr.sh status [--name ]` | Show state + PID + liveness | +```bash +node src/cli/index.js +``` --- -### SC-Bridge Control (`swapctl`) - -`swapctl` is the SC-Bridge client CLI. It controls a **running peer** over WebSocket, and (when needed) signs locally using the peer keypair file (SC-Bridge never signs). - -#### Connection - -| Flag | Required | Meaning | -|---|---:|---| -| `--url ws://127.0.0.1:` | yes | SC-Bridge websocket URL | -| `--token ` | yes | SC-Bridge token (from `onchain/sc-bridge/.token`) | -| `--peer-keypair ` | signing only | Peer `keypair.json` (usually `stores//db/keypair.json`) for commands that create signed payloads | - -#### Token Convenience Wrapper (Recommended) - -| Wrapper | What it does | -|---|---| -| `scripts/swapctl-peer.sh ` | Reads `onchain/sc-bridge/.token` and calls `swapctl` with `--url/--token` | -| `scripts/swapctl-peer.ps1 ` | Same for Windows | - -#### Command Reference - -##### Introspection +## ๐ŸŽฎ CLI MENU -| Command | What it does | Important flags | -|---|---|---| -| `info` | Peer info (pubkey, joined channels, SC-Bridge status) | none | -| `stats` | Peer runtime stats | none | -| `price-get` | Price snapshot from the peer's price feature | none | -| `watch` | Stream messages for debugging/observability | `--channels `, `--kinds `, `--trade-id `, `--pretty 0/1`, `--raw 0/1` | - -##### Sidechannel I/O - -| Command | What it does | Flags | -|---|---|---| -| `join` | Join a sidechannel | `--channel `; optional: `--invite `, `--welcome ` | -| `leave` | Leave a sidechannel | `--channel ` | -| `open` | Request others to open a channel (via the entry channel) | `--channel --via `; optional: `--invite <...>`, `--welcome <...>` | -| `send` | Send plaintext or JSON to a channel | `--channel ` and one of: `--text ` or `--json `; optional: `--invite <...>`, `--welcome <...>` | - -##### Service Presence (Directory Beacon) - -| Command | What it does | Flags | -|---|---|---| -| `svc-announce` | Broadcast a signed service announcement | Required: `--channels --name