chore: sync submodule state (parent ref update)

Made-with: Cursor
This commit is contained in:
defiQUG
2026-03-02 12:14:09 -08:00
parent 50ab378da9
commit 5efe36b1e0
1100 changed files with 155024 additions and 8674 deletions

View File

@@ -0,0 +1,54 @@
# External Protocol Integration (Connext, Raiden, Statechannels.org)
This document describes how external payment-channel and state-channel protocols complement the in-repo PaymentChannelManager and GenericStateChannelManager.
---
## When to use what
| Use case | In this repo | External option |
|----------|--------------|-----------------|
| Same-chain, direct A↔B payments | **PaymentChannelManager** | — |
| Same-chain payments + attested state (stateHash) | **GenericStateChannelManager** | — |
| Cross-chain or routed payments | — | **Connext** |
| Payment channel network (many nodes, path finding) | — | **Raiden** |
| Full state channel framework (arbitrary state machines) | — | **Statechannels.org** |
| Chain-138 visibility on Mainnet | Transaction Mirror + MainnetTether (unchanged) | — |
---
## Connext (cross-chain and routed payments)
- **Site / docs**: [Connext](https://connext.network/) · [Docs](https://docs.connext.network/)
- **Capabilities**: Multi-chain transfers, xcalls, liquidity pools, virtual/routed payments.
- **When to use**: Cross-chain transfers, or when you want routed liquidity instead of direct A↔B channels.
- **Integration**: Use the Connext SDK in the frontend or a backend; link from the Channels UI (“Pay via Connext” / “Cross-chain transfer”). Does not replace PaymentChannelManager; use both as needed.
---
## Raiden (payment channel network)
- **Site / docs**: [Raiden Network](https://raiden.network/) · [Developer docs](https://docs.raiden.network/)
- **Capabilities**: Payment channel network on Ethereum, path finding, multi-hop transfers.
- **When to use**: Same-chain payments when you need a network of channels (many participants, routing) rather than single A↔B channels.
- **Integration**: Link from docs/UI for users who need channel networks; our PaymentChannelManager remains for simple direct channels.
---
## Statechannels.org (general state channels)
- **Site / docs**: [Statechannels.org](https://statechannels.org/) · [Docs](https://docs.statechannels.org/)
- **Capabilities**: General state channel framework: arbitrary state, state transition rules, dispute resolution.
- **When to use**: Applications that need full state channels (e.g. turn-based games, complex conditional flows), not just payment balances.
- **Integration**: Document and link from the Channels UI (“State channels (advanced)”) so users can use Statechannels.org for general state; our contracts cover payment channels and optional generic state (stateHash) settlement.
---
## Summary
- **This repo**: Payment channels (PaymentChannelManager) and optional generic state channels (GenericStateChannelManager with stateHash).
- **Connext**: Cross-chain and routed payments; link from the app.
- **Raiden**: Same-chain payment channel network; link for users who need routing.
- **Statechannels.org**: Full state channel framework; link for users who need arbitrary state machines.
All three external options are optional; our contracts are sufficient for direct payment channels and for stateHash-committed settlement on Mainnet and Chain-138.

View File

@@ -0,0 +1,18 @@
# Future Work (Channels)
Possible extensions beyond the current payment and generic state channel managers.
## Virtual channels
Virtual channels (hub, ledger channels, guarantees) allow many parties to interact without each pair opening a separate on-chain channel. For design and references:
- [State Channels blog Virtual channels](https://blog.statechannels.org/virtual-channels/)
- Nitro / Statechannels.org protocols
Current codebase does not implement virtual channels; this is listed as future work.
## Other directions
- **ERC20 payment channels**: Separate manager or token parameter with safe transfers (see PRE_DEPLOYMENT_RECOMMENDATIONS.md).
- **Connext / Raiden / Statechannels SDK**: Optional in-app flows or embedded guides (see EXTERNAL_PROTOCOL_INTEGRATION.md).
- **Upgradeability**: Deploy behind a transparent proxy if contract upgrades are required later.

View File

@@ -0,0 +1,79 @@
# Gaps and Additional Tasks (Payment and State Channels)
This document lists gaps in the current implementation, additional tasks, and code that is still needed. Use it with the Todos list to prioritize work.
---
## 1. Frontend and config
| # | Task | Gap / need | Priority |
|---|------|------------|----------|
| 1.1 | Add GenericStateChannelManager to frontend config | Deployment doc references `CONTRACT_ADDRESSES.mainnet.GENERIC_STATE_CHANNEL_MANAGER` and chain138; [contracts.ts](../frontend-dapp/src/config/contracts.ts) has no `GENERIC_STATE_CHANNEL_MANAGER`. Add optional addresses for mainnet and chain138. | High |
| 1.2 | GenericStateChannelManager ABI and UI | No [frontend-dapp/src/abis/GenericStateChannelManager.ts](frontend-dapp/src/abis/) ABI; no UI to open/fund/close state channels (with stateHash). Add ABI and a "State channels" section or tab (open, fund, close with stateHash, list channels). | Medium |
| 1.3 | Channels UI: cooperative close and submit close | Current UI has open, fund, finalize close only. No form for cooperative close or submit close (require off-chain signatures → v,r,s). Add optional forms (nonce, balanceA, balanceB, sig inputs) or a short guide + link to sign state off-chain. | Medium |
| 1.4 | Admin panel and Chain 138 | [AdminPanel](frontend-dapp/src/pages/AdminPanel.tsx) restricts to mainnet (`chainId === 1`). Channels and Channel Admin are unreachable on Chain 138. Either allow Chain 138 in the admin panel or add a separate Channels page that works on both Mainnet and Chain 138. | Medium |
---
## 2. Contract security (pre-deployment recommendations)
| # | Task | Gap / need | Priority |
|---|------|------------|----------|
| 2.1 | ReentrancyGuard | [PRE_DEPLOYMENT_RECOMMENDATIONS.md](PRE_DEPLOYMENT_RECOMMENDATIONS.md) suggests ReentrancyGuard on `closeChannelCooperative`, `finalizeClose` (and any path that does `_transfer`). Not implemented in PaymentChannelManager or GenericStateChannelManager. | High |
| 2.2 | Signature malleability (ECDSA) | Recommendations suggest EIP-2 check (reject `s > secp256k1n/2`) or OpenZeppelin ECDSA to avoid malleability and zero-address edge cases. Current contracts use raw `ecrecover` without these checks. | Medium |
---
## 3. Off-chain services
| # | Task | Gap / need | Priority |
|---|------|------------|----------|
| 3.1 | Watchtower service | [WATCHTOWER_AND_INDEXER.md](WATCHTOWER_AND_INDEXER.md) describes design only; no `services/watchtower/` implementation. Implement a small service (e.g. Node/TS) that subscribes to `ChallengeSubmitted`, holds latest state per channel, and calls `challengeClose` before deadline when needed. | Low |
| 3.2 | Indexer for channels | No indexer or subgraph for `ChannelOpened` / `ChannelClosed`. Frontend enumerates via `getChannelCount` + `getChannelIdByIndex`; no "my channels" or filter-by-participant. Add indexer (custom service or The Graph subgraph) and optional API for channels by participant. | Low |
---
## 4. Testing
| # | Task | Gap / need | Priority |
|---|------|------------|----------|
| 4.1 | E2E tests for GenericStateChannelManager | Only unit tests exist for [GenericStateChannelManager](test/channels/GenericStateChannelManager.t.sol). Add full e2e (e.g. `test/e2e/GenericStateChannelsE2E.t.sol`): cooperative close with stateHash, unilateral close, challenge (newest state wins) with stateHash. | Medium |
| 4.2 | Gas report in docs | PRE_DEPLOYMENT suggests gas snapshot. Run `forge test --gas-report` for channel and e2e tests and add results to deployment or PRE_DEPLOYMENT doc (or a GAS_REPORT.md). | Low |
| 4.3 | Fork / testnet e2e | Document or automate running e2e on Mainnet fork and (if available) Chain-138 testnet to catch chain-specific issues. | Low |
---
## 5. Deployment and ops
| # | Task | Gap / need | Priority |
|---|------|------------|----------|
| 5.1 | Chain-138 verification | [PAYMENT_CHANNELS_DEPLOYMENT.md](../deployment/PAYMENT_CHANNELS_DEPLOYMENT.md) mentions `--verify`; Chain-138 may need a different block explorer and env (e.g. Blockscout, `BLOCKSCOUT_API_KEY`). Document chain-specific verification steps or add to deployment script. | Medium |
| 5.2 | Incident response runbook | PRE_DEPLOYMENT suggests documenting how to pause, unpause, replace admin (multisig). Add a short runbook (section in PRE_DEPLOYMENT or [docs/operations/](operations/)): when to pause, how to unpause, how to change admin. | Low |
---
## 6. Documentation and future work
| # | Task | Gap / need | Priority |
|---|------|------------|----------|
| 6.1 | Virtual channels as future work | Virtual channels (hub, ledger channels, guarantees) are documented as external (Statechannels.org/Nitro). Add a short "Future work" section in [README.md](README.md) or a [FUTURE_WORK.md](FUTURE_WORK.md) that lists virtual channels and links to [State Channels blog](https://blog.statechannels.org/virtual-channels/). | Low |
| 6.2 | SUPPORTED_CHAINS for Chain 138 | [contracts.ts](frontend-dapp/src/config/contracts.ts) exports `SUPPORTED_CHAINS = { mainnet }`. If the dApp should support Chain 138 for channels, add chain 138 to wagmi chains and to SUPPORTED_CHAINS. | Medium (if targeting Chain 138 in UI) |
---
## 7. Optional / later
| # | Task | Gap / need | Priority |
|---|------|------------|----------|
| 7.1 | ERC20 payment channels | Current managers are ETH-only. PRE_DEPLOYMENT notes: if ERC20 is needed, add PaymentChannelManagerERC20 or extend with token parameter and safe transfers. | Optional |
| 7.2 | Connext / Raiden / Statechannels SDK integration | Frontend only links out to Connext, Raiden, Statechannels.org. No in-app "Pay via Connext" or "Open state channel (Statechannels.org)" flow. Optional: minimal SDK integration or embedded guide. | Optional |
| 7.3 | Upgradeability | Contracts are not proxy-based. Optional: deploy behind transparent proxy if upgradeability is required later. | Optional |
---
## Summary (actionable order)
- **High:** 1.1 (config), 2.1 (ReentrancyGuard).
- **Medium:** 1.2 (GenericStateChannel ABI + UI), 1.3 (cooperative/submit close UI), 1.4 (Chain 138 in admin or separate page), 2.2 (ECDSA), 4.1 (GenericStateChannel e2e), 5.1 (Chain-138 verify), 6.2 (SUPPORTED_CHAINS).
- **Low:** 3.1 (watchtower), 3.2 (indexer), 4.2 (gas report), 4.3 (fork/testnet e2e), 5.2 (incident runbook), 6.1 (virtual channels future work).
- **Optional:** 7.1 (ERC20), 7.2 (SDK integration), 7.3 (upgradeability).

View File

@@ -0,0 +1,9 @@
# Gas Report (Channels)
From: `forge test --match-path 'test/channels/*.t.sol' --gas-report`
PaymentChannelManager: Deployment ~1.26M. openChannel ~132173k, fundChannel ~57k, closeChannelCooperative ~67k, submitClose ~139k, challengeClose ~3365k, finalizeClose ~3158k.
GenericStateChannelManager: Deployment ~1.28M. openChannel ~176k, fundChannel ~57k, closeChannelCooperative ~68k, submitClose ~162k.
Re-run the command above for current numbers. E2E tests add full-flow gas; see test output.

View File

@@ -0,0 +1,83 @@
# Payment Channels Architecture
This document describes how payment channels combine with the existing Mainnet Tether and Transaction Mirror on Mainnet and Chain-138.
---
## Overview
- **MainnetTether** and **TransactionMirror** are unchanged. They anchor Chain-138 state proofs and mirror Chain-138 transactions to Mainnet.
- **PaymentChannelManager** is a new contract deployed on both Ethereum Mainnet and Chain-138. It manages payment channels (open, fund, cooperative close, unilateral close with challenge window).
- Channel open/close/update transactions on **Chain-138** are normal on-chain txs: they are mirrored by the existing Transaction Mirroring Service and reflected in state anchored by the State Anchoring Service. No changes to those services or contracts are required.
---
## Architecture Diagram
```mermaid
flowchart LR
subgraph mainnet [Ethereum Mainnet]
MT[MainnetTether]
TM[TransactionMirror]
PC_M[PaymentChannelManager]
end
subgraph chain138 [Chain 138]
PC_138[PaymentChannelManager]
end
subgraph offchain [Off-chain]
Anchor[State Anchoring Service]
MirrorSvc[Transaction Mirroring Service]
Watchtower[Watchtower optional]
end
Chain138 -->|state proofs| Anchor --> MT
Chain138 -->|tx data| MirrorSvc --> TM
PC_138 -->|anchored via| MT
PC_138 -->|mirrored via| TM
PC_M -->|optional Connext| Connext
PC_138 -->|optional Connext| Connext
```
---
## Data Flow
### Same-chain (Mainnet or Chain-138)
1. **Open**: Party A calls `openChannel(participantB)` with `value` (ETH). Optionally party B calls `fundChannel(channelId)` with `value`.
2. **Off-chain updates**: Parties exchange signed state (channelId, nonce, balanceA, balanceB) off-chain. No on-chain tx until close.
3. **Cooperative close**: Either party calls `closeChannelCooperative(channelId, nonce, balanceA, balanceB, vA, rA, sA, vB, rB, sB)`. Contract verifies both signatures and pays out.
4. **Unilateral close**: One party calls `submitClose(...)` with a signed state. Contract enters Dispute and sets a challenge deadline. The other party can call `challengeClose(...)` with a newer state (higher nonce) before the deadline. After the deadline, anyone can call `finalizeClose(channelId)` to distribute according to the last submitted state.
### Chain-138 and Mainnet visibility
- Every channel tx on Chain-138 (open, fund, submitClose, challengeClose, finalizeClose) is a normal transaction. The existing **Transaction Mirroring Service** mirrors these to **TransactionMirror** on Mainnet, so they appear on Etherscan (Mainnet).
- The **State Anchoring Service** anchors Chain-138 state (including contract state of PaymentChannelManager) to **MainnetTether** at intervals. So the state of channels on Chain-138 is reflected in the anchored state roots.
### Optional external protocol (Connext)
- For cross-chain or routed payments, the dApp can integrate **Connext** (or similar). See [EXTERNAL_PROTOCOL_INTEGRATION.md](EXTERNAL_PROTOCOL_INTEGRATION.md). Custom PaymentChannelManager remains for same-chain, direct A↔B channels.
---
## Disputes and security
- **Newest state wins**: In Dispute, only a state with `nonce` strictly greater than the current `disputeNonce` is accepted. This enforces the standard payment-channel guarantee.
- **Challenge window**: Configurable (e.g. 24h). Participants (or a watchtower) must respond before the deadline to submit a newer state.
- **Liveness**: If a participant is offline and the other submits an old state, the offline participant must have a watchtower or come online before the deadline to challenge. See watchtower documentation.
---
## Contracts and config
| Contract | Chain(s) | Purpose |
|----------|----------|---------|
| MainnetTether | Mainnet | Anchor Chain-138 state proofs |
| TransactionMirror | Mainnet | Mirror Chain-138 tx data |
| PaymentChannelManager | Mainnet, Chain-138 | Payment channels (one deployment per chain) |
Frontend config (`contracts.ts`):
- `CONTRACT_ADDRESSES.mainnet.PAYMENT_CHANNEL_MANAGER`
- `CONTRACT_ADDRESSES.chain138.PAYMENT_CHANNEL_MANAGER`
Set these after deploying PaymentChannelManager to each chain. See [PAYMENT_CHANNELS_DEPLOYMENT.md](../deployment/PAYMENT_CHANNELS_DEPLOYMENT.md).

View File

@@ -0,0 +1,83 @@
# Pre-Deployment Recommendations and Suggestions
Use this checklist and recommendations before deploying PaymentChannelManager to Mainnet or Chain-138.
---
## 1. Security
| Recommendation | Details |
|----------------|--------|
| **Admin = multisig** | Set `CHANNEL_ADMIN` to a Gnosis Safe (or other multisig). Avoid EOA for production. |
| **Challenge window** | 24h (86400s) is a reasonable default. Shorter (e.g. 1h) increases griefing risk for honest offline users; longer increases exposure to stale-state attacks. Document the tradeoff for operators. |
| **Reentrancy** | Current design: state updates then external transfers. Consider adding a simple reentrancy guard (e.g. OpenZeppelin `ReentrancyGuard`) on `closeChannelCooperative`, `finalizeClose`, and any other entry that does `_transfer`. |
| **Signature replay** | State is bound to `(channelId, nonce, balanceA, balanceB)`. No cross-chain replay if each chain has its own contract. Same-chain replay is prevented by nonce and status (channel closed). |
| **ecrecover edge cases** | Contract uses `ecrecover` without checking for zero address or signature malleability. For maximum safety, consider EIP-2 malleability check (reject `s > secp256k1n/2`) or use a library (e.g. OpenZeppelin ECDSA). |
---
## 2. Operational
| Recommendation | Details |
|----------------|--------|
| **Deploy order** | Deploy to testnet (or Mainnet fork + Chain-138 testnet) first. Run full e2e tests (see test/e2e/PaymentChannelsE2E.t.sol). |
| **Verification** | Verify on block explorer after deploy (`--verify` in Forge script). Ensures users can read the contract. |
| **Frontend config** | After deploy, set `CONTRACT_ADDRESSES.mainnet.PAYMENT_CHANNEL_MANAGER` and/or `CONTRACT_ADDRESSES.chain138.PAYMENT_CHANNEL_MANAGER` in the dApp. |
| **Monitoring** | Monitor `ChannelOpened`, `ChannelClosed`, `ChallengeSubmitted`. Alert on unexpected pause or admin change. |
| **Watchtower** | If users may be offline during the challenge window, document or run a watchtower (see WATCHTOWER_AND_INDEXER.md). |
---
## 3. Testing
| Recommendation | Details |
|----------------|--------|
| **Unit tests** | Already in `test/channels/PaymentChannelManager.t.sol`. Run before every deploy: `forge test --match-path test/channels/`. |
| **E2E tests** | Run full e2e: `forge test --match-path test/e2e/PaymentChannelsE2E.t.sol`. Covers happy path, unilateral close, challenge, and edge cases. |
| **Fork / testnet** | Run e2e on a fork of the target chain (and Chain-138 testnet if available) to catch env-specific issues. |
| **Gas snapshot** | See [GAS_REPORT.md](GAS_REPORT.md). Run `forge test --gas-report --match-path test/channels/` and e2e paths to refresh. |
---
## 4. Contract behavior and limits
| Item | Current behavior | Suggestion |
|------|------------------|------------|
| **ETH only** | v1 holds only ETH. | If you need ERC20 later, add a separate PaymentChannelManagerERC20 or extend with a token parameter and safe transfer. |
| **No upgradeability** | Contract is not proxy-based. | If you expect to change logic, consider deploying behind a transparent proxy and an initial implementation; otherwise keep immutable for simplicity. |
| **Unbounded channel list** | `_channelIds.length` grows with channels. | `getChannelCount` and enumeration are O(1) and O(n) per read; acceptable for moderate channel counts. For very high volume, an indexer is recommended. |
| **Pause** | Pause blocks only `openChannel` and `fundChannel`; `closeChannelCooperative`, `submitClose`, `challengeClose`, and `finalizeClose` are allowed when paused. | In-flight channels can always settle; new channels are disabled when paused. |
---
## 5. Documentation and runbooks
| Recommendation | Details |
|----------------|--------|
| **Runbook** | Keep [PAYMENT_CHANNELS_DEPLOYMENT.md](../deployment/PAYMENT_CHANNELS_DEPLOYMENT.md) updated with actual deployed addresses and any chain-specific steps. |
| **Incident response** | Document: how to pause (admin), how to unpause, how to replace admin (multisig), and when to use each. |
| **User-facing docs** | Explain challenge window and liveness (must respond or run watchtower before deadline). Link Connext (or other) for cross-chain from the Channels UI. |
---
## 6. Optional improvements (post-MVP)
- **ReentrancyGuard** on close/finalize paths.
- **ECDSA** (or equivalent) for signatures to avoid malleability and zero-address edge cases.
- **Events** for admin changes and challenge-window updates (already present).
- **Indexer** for “my channels” and filtering by participant (see WATCHTOWER_AND_INDEXER.md).
- **Watchtower** service for users who may be offline during disputes.
---
## 7. Deployment checklist (summary)
- [ ] Unit tests pass: `forge test --match-path test/channels/`
- [ ] E2E tests pass: `forge test --match-path test/e2e/PaymentChannelsE2E.t.sol` and `test/e2e/GenericStateChannelsE2E.t.sol`
- [ ] Admin set to multisig address
- [ ] Challenge window chosen and documented
- [ ] Deploy to testnet (or fork) and re-run e2e
- [ ] Deploy to target chain (Mainnet / Chain-138)
- [ ] Verify contract on block explorer
- [ ] Update frontend config with manager address(es)
- [ ] Document addresses and any chain-specific notes in deployment doc

36
docs/channels/README.md Normal file
View File

@@ -0,0 +1,36 @@
# Payment and State Channels
Documentation for on-chain payment channels, optional generic state channels, and external protocol integration.
---
## Index
| Doc | Description |
|-----|-------------|
| [STATE_CHANNELS_VS_PAYMENT_CHANNELS.md](STATE_CHANNELS_VS_PAYMENT_CHANNELS.md) | Definitions: state vs payment channels; what this repo provides. |
| [PAYMENT_CHANNELS_ARCHITECTURE.md](PAYMENT_CHANNELS_ARCHITECTURE.md) | Architecture: Mainnet/Chain-138, tether and mirror, data flow. |
| [EXTERNAL_PROTOCOL_INTEGRATION.md](EXTERNAL_PROTOCOL_INTEGRATION.md) | When to use Connext, Raiden, Statechannels.org; links and integration notes. |
| [PRE_DEPLOYMENT_RECOMMENDATIONS.md](PRE_DEPLOYMENT_RECOMMENDATIONS.md) | Security, ops, testing, and deployment checklist. |
| [WATCHTOWER_AND_INDEXER.md](WATCHTOWER_AND_INDEXER.md) | Optional watchtower and indexer for channels. |
| [GAPS_AND_ADDITIONAL_TASKS.md](GAPS_AND_ADDITIONAL_TASKS.md) | Gaps, additional tasks, and code still needed (checklist and priorities). |
| [GAS_REPORT.md](GAS_REPORT.md) | Gas costs from channel unit tests. |
| [FUTURE_WORK.md](FUTURE_WORK.md) | Future work: virtual channels, ERC20, upgradeability. |
---
## Deployment
| Doc | Description |
|-----|-------------|
| [../deployment/PAYMENT_CHANNELS_DEPLOYMENT.md](../deployment/PAYMENT_CHANNELS_DEPLOYMENT.md) | Deploy PaymentChannelManager (and optional GenericStateChannelManager) to Mainnet and Chain-138. |
| [../operations/CHANNEL_INCIDENT_RUNBOOK.md](../operations/CHANNEL_INCIDENT_RUNBOOK.md) | Incident runbook: pause, unpause, replace admin. |
---
## Contracts (this repo)
- **PaymentChannelManager** Payment channels: open, fund, cooperative/unilateral close, challenge window (newest state wins). ETH only. Deploy via `script/DeployPaymentChannelManager.s.sol`.
- **GenericStateChannelManager** (optional) State channels: same flow but settlement includes a `stateHash` so off-chain state (e.g. game, attestation) is attested when closing. Deploy via `script/DeployGenericStateChannelManager.s.sol`.
External protocols (Connext, Raiden, Statechannels.org) are linked from the dApp and from [EXTERNAL_PROTOCOL_INTEGRATION.md](EXTERNAL_PROTOCOL_INTEGRATION.md).

View File

@@ -0,0 +1,45 @@
# State Channels vs Payment Channels
This repo implements **payment channels** and (optionally) a **generic state channel** for committed state. Here is how they relate and when to use each.
---
## Definitions
### Payment channels
- **State** = two participants balances (and a nonce).
- **Off-chain**: Parties exchange signed balance updates; no on-chain tx until close.
- **Settlement**: On-chain contract distributes ETH according to the last signed (balanceA, balanceB).
- **Use cases**: Payments, micropayments, streaming, simple value transfer.
### State channels (general)
- **State** = arbitrary application state (e.g. game board, escrow conditions, multi-step agreement).
- **Off-chain**: Parties exchange signed state updates; state transition rules are agreed by the app.
- **Settlement**: On-chain contract verifies that the final state was signed by both and (if value is involved) distributes accordingly.
- **Use cases**: Turn-based games, conditional payments, complex protocols.
**Payment channels are a subset of state channels** where the only state is the two balances.
---
## What this repo provides
| Component | Type | State | Use when |
|-----------|------|--------|----------|
| **PaymentChannelManager** | Payment channel | (balanceA, balanceB, nonce) | Same-chain payments, micropayments, streaming. |
| **GenericStateChannelManager** | State channel (optional) | stateHash + (balanceA, balanceB, nonce) | You need to commit to an off-chain state (e.g. game, attestation) and still settle balances; stateHash proves what was agreed. |
| **External protocols** | Various | Depends (Connext, Raiden, Statechannels.org) | Cross-chain, routed payments, or full state-channel frameworks. |
We do **not** implement a full general-purpose state channel VM (arbitrary transitions verified on-chain). For that, use or integrate [Statechannels.org](https://statechannels.org/) or similar (see [EXTERNAL_PROTOCOL_INTEGRATION.md](EXTERNAL_PROTOCOL_INTEGRATION.md)).
---
## Do you need both?
- **Payments only** → **PaymentChannelManager** is enough.
- **Payments + proof of agreed state** (e.g. hash of game result or attestation) → use **GenericStateChannelManager** so settlement commits to a `stateHash` as well as balances.
- **Arbitrary state transitions verified on-chain** → use an external state channel framework (Statechannels.org, etc.) and link from our docs/UI.
See [README.md](README.md) for the full index of channel docs and [EXTERNAL_PROTOCOL_INTEGRATION.md](EXTERNAL_PROTOCOL_INTEGRATION.md) for external options.

View File

@@ -0,0 +1,64 @@
# Watchtower and Indexer
Optional off-chain components for payment channels: watchtower (dispute response) and indexer (channel listing).
---
## Watchtower
### Purpose
When a channel is in **Dispute**, the party that did not initiate the close has a limited time (challenge window) to submit a **newer** signed state via `challengeClose`. If they are offline, a malicious counterparty could submit an old state and wait for the deadline, then `finalizeClose` and take more than their share.
A **watchtower** watches the chain for `ChallengeSubmitted` (and channel close activity) for channels where a designated participant is involved. If it sees a close that uses an older state than the one the watchtower holds, it submits `challengeClose` with the latest signed state before the deadline.
### Design
- **Inputs**: RPC URL, list of (channelId, latest signed state: nonce, balanceA, balanceB, sigs) for channels the user cares about, and a key that can sign txs (or the watchtower runs on behalf of the user and has delegated authority).
- **Logic**: Subscribe to or poll PaymentChannelManager for `ChallengeSubmitted` and `ChannelClosed`. For each channel in the list, if `ChallengeSubmitted` shows a dispute with `nonce` less than the watchtowers latest nonce, call `challengeClose` with the stored state before `disputeDeadline`.
- **Security**: The key that signs `challengeClose` must be secure (env var, HSM, or user-backed key). Prefer a dedicated key with no other funds.
### Implementation options
- **Small service**: e.g. `services/watchtower/` in this repo: Node.js or Python script that uses ethers/web3.py, reads config from env, and runs a loop or event subscription.
- **Separate repo**: Standalone watchtower service that supports this contracts ABI and events.
No watchtower implementation is included in this repo; this doc is the specification. Deploy and run a watchtower only if users need automated dispute response.
---
## Indexer
### Purpose
The frontend “Channels” tab lists channels by calling `getChannelCount` and `getChannelIdByIndex`, then `getChannel` for each. That works for a small number of channels. For many channels or for filtering by participant, an **indexer** can:
- Index `ChannelOpened` and `ChannelClosed` (and optionally `ChallengeSubmitted`).
- Expose an API: e.g. “channels where address X is participantA or participantB”, “channels in status Open/Dispute”.
### Design
- **Events**: `ChannelOpened(channelId, participantA, participantB, depositA, depositB)`, `ChannelClosed(channelId, balanceA, balanceB, cooperative)`, `ChallengeSubmitted(channelId, nonce, balanceA, balanceB, newDeadline)`.
- **Storage**: DB (e.g. Postgres) with tables for channels and events, keyed by chain and channelId.
- **API**: REST or GraphQL: e.g. `GET /channels?chainId=138&participant=0x...`.
### Implementation options
- **Existing Chain-138 / Mainnet indexer**: If the project already has an indexer for the chain, add handlers for PaymentChannelManager events and expose channel queries.
- **Subgraph (The Graph)**: Create a subgraph for PaymentChannelManager and query channels by participant.
- **Custom service**: Small service that subscribes to logs, writes to DB, and serves HTTP.
Document the indexer API and deployment in ops/deployment docs when one is added. Until then, the frontend uses on-chain `getChannelCount` + `getChannelIdByIndex` + `getChannel` only.
---
## Implementation status
- **Watchtower**: A minimal implementation lives in `services/watchtower/`. It subscribes to `ChallengeSubmitted` on PaymentChannelManager and calls `challengeClose` with a newer state from a JSON file before the dispute deadline. See `services/watchtower/README.md`.
- **Indexer**: No indexer or subgraph is implemented yet. Channels are enumerated on-chain by the frontend. To add "channels by participant", implement a custom indexer or The Graph subgraph as described above and expose an API (e.g. `GET /channels?participant=0x...`).
---
## Transaction mirroring (no change)
Channel transactions on **Chain-138** are normal txs. The existing **Transaction Mirroring Service** mirrors them to **TransactionMirror** on Mainnet. No change to that service or contract is required. State anchoring of Chain-138 (including PaymentChannelManager state) is already done by the **State Anchoring Service** and **MainnetTether**.